Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(goal): let exploration revise a flawed protocol instead of only branching (#19375)

Arvin Xuf4a39da7d9ed
diff --git a/apps/server/src/services/goal/EXPLORATION.md b/apps/server/src/services/goal/EXPLORATION.md
index 982027d701a..752f3fb6209 100644
--- a/apps/server/src/services/goal/EXPLORATION.md
+++ b/apps/server/src/services/goal/EXPLORATION.md
@@ -11,15 +11,39 @@ lh goal create 'Compare three candidate explanations' \
```
The first Task produces a baseline. Its normal Task settlement creates a finding
-and schedules a Goal advance. The Goal model then chooses one of two actions:
+and schedules a Goal advance. The Goal model then chooses one of three actions:
- `expand`: choose a resolved historical experiment container and create one experiment.
`child --derived_from--> parent` records provenance; `depends_on` continues to
mean execution dependency. The child receives the selected parent's findings
and pins the parent's produced Work version references as inputs.
+- `revise`: rerun one experiment with a corrected protocol when it measured the
+ wrong thing — a wrong output shape, metric, threshold or evaluation procedure.
+ Without it the only move available is a sibling that inherits the same flawed
+ instrument, which reproduces the flaw rather than answering the question.
- `verify`: request the existing independent terminal acceptance Task. The
planner cannot declare the Goal achieved.
+A correction is a Task inside the experiment it corrects, not a new container, so
+it does not consume an experiment slot: fixing an instrument should not cost an
+exploration budget. `MAX_PROTOCOL_REVISIONS` bounds them per experiment, and
+`revisionsRemaining` reports the balance in the planner input so an exhausted
+allowance is visible before the choice is made rather than refused after it.
+Corrections carry a dedicated `revises` edge rather than `derived_from`: that kind
+is generic provenance, is writable through the public `addEdge` mutation, and
+already appears on hand-authored tasks, so reusing it would reinterpret unrelated
+provenance as a correction. `revises` is written only by the coordinator and is
+deliberately absent from the public vocabulary. Rolling this release back leaves
+any queued correction dispatchable but weaker: the previous coordinator resolves
+provenance through the containing experiment, so the rerun carries that
+experiment's branch parent instead of the experiment it corrects, or no history
+when the container is a root. The corrected protocol itself is in the Task
+description and survives, so the degradation is missing context rather than a
+wrong instruction; drain queued corrections before rolling back if that matters.
+An experiment reads as unresolved while a correction runs,
+so corrections are serial. A seed Task with no experiment container cannot hold
+one and reports no allowance; those goals expand first.
+
Retries remain attempts of the same Task, with their existing TaskTopics. They
do not create new experiment nodes. A bad experimental result may be useful
research evidence; the experiment's own contract should evaluate execution and
diff --git a/apps/server/src/services/goal/explorationPlanner.test.ts b/apps/server/src/services/goal/explorationPlanner.test.ts
index 9eb209b6ca3..3b6b3d7bd4d 100644
--- a/apps/server/src/services/goal/explorationPlanner.test.ts
+++ b/apps/server/src/services/goal/explorationPlanner.test.ts
@@ -38,10 +38,40 @@ describe('GoalExplorationPlanner', () => {
expect(generateObject).toHaveBeenCalledWith(
expect.objectContaining({ model: 'goal-model', provider: 'goal-provider' }),
{
- tracing: { scenario: 'goal_explore', promptVersion: 'v1', schemaName: 'goal_exploration' },
+ tracing: { scenario: 'goal_explore', promptVersion: 'v2', schemaName: 'goal_exploration' },
},
);
});
+ it('accepts a revision that reuses the parent title but keeps its corrected protocol', async () => {
+ generateObject.mockResolvedValue({
+ action: 'revise',
+ parentNodeId: 'exp-1',
+ title: '',
+ instruction: 'Emit a calibrated score instead of a boolean, then report AUC',
+ reason: 'The arms measured a hard verdict, which discards the ranking signal',
+ });
+ const plan = await planner.plan(input);
+ expect(plan.action).toBe('revise');
+ expect(plan.parentNodeId).toBe('exp-1');
+ });
+ it('rejects a revision that names no experiment or carries no corrected protocol', async () => {
+ generateObject.mockResolvedValue({
+ action: 'revise',
+ parentNodeId: '',
+ title: 'Fix',
+ instruction: 'Measure AUC',
+ reason: 'Wrong instrument',
+ });
+ await expect(planner.plan(input)).rejects.toThrow();
+ generateObject.mockResolvedValue({
+ action: 'revise',
+ parentNodeId: 'exp-1',
+ title: 'Fix',
+ instruction: ' ',
+ reason: 'Wrong instrument',
+ });
+ await expect(planner.plan(input)).rejects.toThrow();
+ });
it('rejects empty expansion instructions and unknown actions', async () => {
generateObject.mockResolvedValue({
action: 'expand',
diff --git a/apps/server/src/services/goal/explorationPlanner.ts b/apps/server/src/services/goal/explorationPlanner.ts
index 69c53f4b34a..df916610bd0 100644
--- a/apps/server/src/services/goal/explorationPlanner.ts
+++ b/apps/server/src/services/goal/explorationPlanner.ts
@@ -14,7 +14,7 @@ import { resolveGoalModelConfig } from './modelConfig';
const planSchema = z
.object({
- action: z.enum(['expand', 'verify']),
+ action: z.enum(['expand', 'revise', 'verify']),
parentNodeId: z.string(),
title: z.string().max(80),
instruction: z.string().max(12000),
@@ -30,6 +30,14 @@ const planSchema = z
message: 'An expansion requires a parent, title and instruction',
});
}
+ // A revision reuses its parent's container and title, so only the corrected
+ // protocol and the experiment it corrects are mandatory.
+ if (plan.action === 'revise' && (!plan.parentNodeId || !plan.instruction.trim())) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'A revision requires the experiment it corrects and a corrected instruction',
+ });
+ }
});
export type GoalExplorationPlan = z.infer<typeof planSchema>;
diff --git a/apps/server/src/services/goal/exploreGraph.test.ts b/apps/server/src/services/goal/exploreGraph.test.ts
new file mode 100644
index 00000000000..28a9e694ae9
--- /dev/null
+++ b/apps/server/src/services/goal/exploreGraph.test.ts
@@ -0,0 +1,139 @@
+import type { GoalGraphSnapshot } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { LobeChatDatabase } from '@/database/type';
+
+import { exploreGraph } from './exploreGraph';
+
+const { plan, claim, apply } = vi.hoisted(() => ({
+ apply: vi.fn(),
+ claim: vi.fn(),
+ plan: vi.fn(),
+}));
+vi.mock('@/database/models/goalExploration', () => ({
+ GoalExplorationModel: vi.fn(() => ({ apply, claim, fail: vi.fn() })),
+ goalExplorationSnapshot: () => 'snapshot',
+}));
+vi.mock('./explorationPlanner', () => ({
+ GoalExplorationPlanner: vi.fn(() => ({ plan })),
+}));
+
+const node = (id: string, kind: string, status = 'resolved') =>
+ ({ description: null, id, kind, status, title: id }) as any;
+
+const graph = (edges: any[] = []): GoalGraphSnapshot =>
+ ({
+ decisions: [],
+ edges,
+ events: [],
+ goal: {
+ config: { exploration: { instruction: 'search', maxExperiments: 5 } },
+ id: 'goal_1',
+ requirement: 'Answer the question',
+ title: 'Goal',
+ },
+ nodes: [node('parent', 'experiment'), node('child', 'experiment')],
+ workVersions: [],
+ }) as any;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ claim.mockResolvedValue({ token: 'token' });
+ plan.mockResolvedValue({
+ action: 'verify',
+ instruction: '',
+ parentNodeId: '',
+ reason: 'done',
+ title: '',
+ });
+ apply.mockResolvedValue({ outcome: 'verify' });
+});
+
+describe('exploreGraph', () => {
+ it('tells the planner which experiments a previous turn derived, and from what', async () => {
+ await exploreGraph({
+ db: {} as LobeChatDatabase,
+ effects: [],
+ graph: graph([{ kind: 'derived_from', sourceNodeId: 'child', targetNodeId: 'parent' }]),
+ userId: 'user',
+ });
+ const experiments = plan.mock.calls[0][0].experiments;
+ expect(experiments.find((item: any) => item.id === 'child').derivedFromId).toBe('parent');
+ expect(experiments.find((item: any) => item.id === 'parent').derivedFromId).toBeUndefined();
+ });
+
+ it('folds a correction’s results into the experiment it corrected', async () => {
+ const withCorrection = {
+ ...graph(),
+ edges: [{ kind: 'revises', sourceNodeId: 'fix', targetNodeId: 'parent' }],
+ nodes: [
+ node('parent', 'experiment'),
+ { ...node('fix', 'task'), description: null },
+ { ...node('rerun-result', 'finding'), description: 'AUC 0.71 on the same holdout' },
+ ],
+ } as any;
+ withCorrection.edges.push({
+ kind: 'produces',
+ sourceNodeId: 'fix',
+ targetNodeId: 'rerun-result',
+ });
+ await exploreGraph({
+ db: {} as LobeChatDatabase,
+ effects: [],
+ graph: withCorrection,
+ userId: 'user',
+ });
+ const parent = plan.mock.calls[0][0].experiments.find((item: any) => item.id === 'parent');
+ // Without this the next turn reads only the pre-correction evidence.
+ expect(parent.results.join('\n')).toContain('AUC 0.71');
+ expect(parent.revisionsRemaining).toBe(1);
+ });
+
+ it('reports the park instead of replanning when an allowance is spent', async () => {
+ plan.mockResolvedValue({
+ action: 'revise',
+ instruction: 'Try once more',
+ parentNodeId: 'parent',
+ reason: 'Still not measuring the right thing',
+ title: '',
+ });
+ apply.mockResolvedValue({ outcome: 'revision-limit', reason: 'allowance spent' });
+ const effects: any[] = [];
+ const result = await exploreGraph({
+ db: {} as LobeChatDatabase,
+ effects,
+ graph: graph(),
+ userId: 'user',
+ });
+ // `advanced` here would replan on identical input and burn the tick budget.
+ expect(result).toMatchObject({ message: 'allowance spent', outcome: 'no_progress' });
+ expect(effects).toContainEqual(
+ expect.objectContaining({ detail: 'paused: revision allowance spent' }),
+ );
+ });
+
+ it('reports a revision as its own advance so the corrected protocol is dispatched', async () => {
+ plan.mockResolvedValue({
+ action: 'revise',
+ instruction: 'Report AUC instead of a verdict',
+ parentNodeId: 'parent',
+ reason: 'The verdict discarded the ranking signal',
+ title: '',
+ });
+ apply.mockResolvedValue({ nodeId: 'retry', outcome: 'revised', parentNodeId: 'parent' });
+ const effects: any[] = [];
+ const result = await exploreGraph({
+ db: {} as LobeChatDatabase,
+ effects,
+ graph: graph(),
+ userId: 'user',
+ });
+ expect(result).toMatchObject({ nodeId: 'retry', outcome: 'advanced' });
+ expect(effects).toContainEqual(
+ expect.objectContaining({
+ detail: 'revised parent: The verdict discarded the ranking signal',
+ type: 'created_node',
+ }),
+ );
+ });
+});
diff --git a/apps/server/src/services/goal/exploreGraph.ts b/apps/server/src/services/goal/exploreGraph.ts
index a42d209d39a..1db119abdd3 100644
--- a/apps/server/src/services/goal/exploreGraph.ts
+++ b/apps/server/src/services/goal/exploreGraph.ts
@@ -1,7 +1,13 @@
import type { GoalAdvanceEffect } from '@lobechat/agent-tracing';
import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';
import type { GoalGraphSnapshot, GoalTickResult } from '@lobechat/types';
-import { experimentMembers, experimentOwner } from '@lobechat/utils/goalGraph';
+import {
+ experimentOwner,
+ experimentScope,
+ isProtocolRevision,
+ MAX_PROTOCOL_REVISIONS,
+ protocolRevisionCount,
+} from '@lobechat/utils/goalGraph';
import { GoalExplorationModel, goalExplorationSnapshot } from '@/database/models/goalExploration';
import type { LobeChatDatabase } from '@/database/type';
@@ -9,8 +15,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { GoalExplorationPlanner } from './explorationPlanner';
export const experimentResults = (graph: GoalGraphSnapshot, nodeId: string): string[] => {
- const members = experimentMembers(graph, nodeId);
- members.add(nodeId);
+ const members = experimentScope(graph, nodeId);
const findings = new Set(
graph.edges
.filter((edge) => members.has(edge.sourceNodeId) && edge.kind === 'produces')
@@ -50,18 +55,29 @@ export async function exploreGraph(params: {
node.kind === 'experiment' ||
(node.kind === 'task' &&
node.title !== GOAL_ACCEPTANCE_TASK_TITLE &&
- !experimentOwner(graph, node.id)),
+ !experimentOwner(graph, node.id) &&
+ !isProtocolRevision(graph, node.id)),
)
.map((node) => ({
id: node.id,
title: node.title,
status: node.status,
results: experimentResults(graph, node.id),
+ // Tells the planner which experiments a previous turn authored, so it can
+ // judge whether its own last move helped before repeating that direction.
+ derivedFromId: graph.edges.find(
+ (edge) => edge.sourceNodeId === node.id && edge.kind === 'derived_from',
+ )?.targetNodeId,
+ // An uncontained seed cannot hold a correction, so it reports none left
+ // rather than inviting a choice the apply step would refuse.
+ revisionsRemaining:
+ node.kind === 'experiment' || experimentOwner(graph, node.id)
+ ? Math.max(MAX_PROTOCOL_REVISIONS - protocolRevisionCount(graph, node.id), 0)
+ : 0,
inputVersionIds: graph.workVersions
.filter(
(version) =>
- (version.nodeId === node.id ||
- experimentMembers(graph, node.id).has(version.nodeId)) &&
+ experimentScope(graph, node.id).has(version.nodeId) &&
version.relation === 'produced' &&
version.work,
)
@@ -83,6 +99,18 @@ export async function exploreGraph(params: {
message: `Experiment limit reached (${policy.maxExperiments}); goal is not yet accepted. ${decision.reason}`,
};
}
+ if (result.outcome === 'revision-limit') {
+ effects.push({ detail: 'paused: revision allowance spent', type: 'goal_status' });
+ return { goalId, outcome: 'no_progress', message: result.reason };
+ }
+ if (result.outcome === 'revised') {
+ effects.push({
+ type: 'created_node',
+ nodeId: result.nodeId,
+ detail: `revised ${result.parentNodeId}: ${decision.reason}`,
+ });
+ return { goalId, nodeId: result.nodeId, outcome: 'advanced', message: decision.reason };
+ }
if (result.outcome === 'expanded') {
effects.push({
type: 'created_node',
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index 9a49cccba58..4854b978086 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -20,7 +20,7 @@ import type {
TaskTopicHandoff,
WorkVersionEventItem,
} from '@lobechat/types';
-import { experimentOwner } from '@lobechat/utils/goalGraph';
+import { experimentOwner, provenanceParentId } from '@lobechat/utils/goalGraph';
import { TRPCError } from '@trpc/server';
import { sql } from 'drizzle-orm';
@@ -1576,11 +1576,7 @@ export class GoalService {
let acceptanceId: string | undefined;
let task: TaskItem | undefined;
try {
- const parentId = graph.edges.find(
- (edge) =>
- edge.sourceNodeId === (experimentOwner(graph, frontier.id) ?? frontier.id) &&
- edge.kind === 'derived_from',
- )?.targetNodeId;
+ const parentId = provenanceParentId(graph, frontier.id);
const parent = graph.nodes.find((node) => node.id === parentId);
const description = [
frontier.description ?? frontier.title,
diff --git a/packages/database/src/models/__tests__/goalExploration.test.ts b/packages/database/src/models/__tests__/goalExploration.test.ts
index af464a86a9d..82b83c0f8f0 100644
--- a/packages/database/src/models/__tests__/goalExploration.test.ts
+++ b/packages/database/src/models/__tests__/goalExploration.test.ts
@@ -48,7 +48,153 @@ const expand = (parentNodeId: string) => ({
reason: 'The first result is promising',
});
+const revise = (
+ parentNodeId: string,
+ instruction = 'Emit a calibrated score, then report AUC',
+) => ({
+ action: 'revise' as const,
+ parentNodeId,
+ title: '',
+ instruction,
+ reason: 'The arms measured a hard verdict, which discards the ranking signal',
+});
+
+/** A resolved experiment container with one finished protocol and its produced Work. */
+async function seedExperiment(goalId: string, title = 'Three arms') {
+ const graph = (await graphModel.getGraph(goalId))!;
+ const experiment = await graphModel.createNode(goalId, {
+ kind: 'experiment',
+ questionId: graph.nodes.find((node) => node.kind === 'problem')!.id,
+ title,
+ });
+ const run = await graphModel.createNode(goalId, {
+ kind: 'task',
+ scopeId: experiment!.id,
+ status: 'resolved',
+ title: `${title} run 1`,
+ });
+ const task = await new TaskModel(db, userId).create({ instruction: 'baseline evidence' });
+ const work = await new WorkModel(db, userId).registerTask({
+ changeType: 'created',
+ taskId: task.id,
+ toolIdentifier: 'test',
+ toolName: 'createTask',
+ });
+ await graphModel.attachWorkVersion(goalId, run!.id, work!.currentVersionId!, 'produced');
+ return { experimentId: experiment!.id, versionId: work!.currentVersionId! };
+}
+
describe('GoalExplorationModel', () => {
+ it('reruns a corrected protocol inside the same experiment without spending a slot', async () => {
+ const { goalId } = await seed(2);
+ const { experimentId, versionId } = await seedExperiment(goalId);
+ const result = await model.apply(goalId, (await claim(goalId))!.token, revise(experimentId));
+ expect(result.outcome).toBe('revised');
+ const graph = (await graphModel.getGraph(goalId))!;
+ // No second container: the correction lives beside the protocol it replaces.
+ expect(graph.nodes.filter((node) => node.kind === 'experiment')).toHaveLength(1);
+ const revised = graph.nodes.find((node) => node.id === result.nodeId)!;
+ expect(revised.kind).toBe('task');
+ expect(revised.description).toBe('Emit a calibrated score, then report AUC');
+ expect(graph.workVersions).toContainEqual(
+ expect.objectContaining({
+ nodeId: result.nodeId,
+ relation: 'input',
+ workVersionId: versionId,
+ }),
+ );
+ expect(graph.events).toContainEqual(
+ expect.objectContaining({
+ actorType: 'system',
+ reason: `Revised ${experimentId}: The arms measured a hard verdict, which discards the ranking signal`,
+ }),
+ );
+ });
+
+ it('carries an earlier correction’s Work into the next one', async () => {
+ const { goalId } = await seed(2);
+ const { experimentId } = await seedExperiment(goalId);
+ const first = await model.apply(goalId, (await claim(goalId))!.token, revise(experimentId));
+ const task = await new TaskModel(db, userId).create({ instruction: 'rerun evidence' });
+ const work = await new WorkModel(db, userId).registerTask({
+ changeType: 'created',
+ taskId: task.id,
+ toolIdentifier: 'test',
+ toolName: 'createTask',
+ });
+ await graphModel.attachWorkVersion(goalId, first.nodeId!, work!.currentVersionId!, 'produced');
+ await graphModel.updateNodeStatus(goalId, first.nodeId!, 'resolved');
+ const second = await model.apply(
+ goalId,
+ (await claim(goalId))!.token,
+ revise(experimentId, 'attempt 3'),
+ );
+ // Without the correction in scope the second rerun would start from the original
+ // protocol's artefacts and never see what the first correction produced.
+ expect((await graphModel.getGraph(goalId))!.workVersions).toContainEqual(
+ expect.objectContaining({
+ nodeId: second.nodeId,
+ relation: 'input',
+ workVersionId: work!.currentVersionId,
+ }),
+ );
+ }, 20_000);
+
+ it('parks the goal when the planner asks past a spent allowance', async () => {
+ const { goalId } = await seed(4);
+ const { experimentId } = await seedExperiment(goalId);
+ for (const attempt of [1, 2]) {
+ const applied = await model.apply(
+ goalId,
+ (await claim(goalId))!.token,
+ revise(experimentId, `attempt ${attempt}`),
+ );
+ expect(applied.outcome).toBe('revised');
+ // An experiment reads as unresolved while a correction is still running, so
+ // each rerun must finish before the next correction can target it.
+ await graphModel.updateNodeStatus(goalId, applied.nodeId!, 'resolved');
+ }
+ const spent = await model.apply(goalId, (await claim(goalId))!.token, revise(experimentId));
+ expect(spent).toMatchObject({ outcome: 'revision-limit' });
+ expect((spent as { reason: string }).reason).toContain('already ran 2 corrected protocols');
+ // Leaving it running would let every sweep buy another identical planning call.
+ const goal = await new GoalModel(db, userId).findById(goalId);
+ expect(goal?.status).toBe('paused');
+ expect(goal?.config?.pausedBy).toBe('exploration_revision_limit');
+ });
+
+ it('does not charge ordinary branches to the correction budget', async () => {
+ const { goalId, parent } = await seed(9);
+ const { experimentId } = await seedExperiment(goalId);
+ // Ordinary expansions also write `derived_from` edges; counting the edge alone
+ // would refuse the very first correction.
+ for (const _ of [1, 2])
+ expect(
+ (await model.apply(goalId, (await claim(goalId))!.token, expand(parent.id))).outcome,
+ ).toBe('expanded');
+ expect(
+ (await model.apply(goalId, (await claim(goalId))!.token, revise(experimentId))).outcome,
+ ).toBe('revised');
+ });
+
+ it('refuses to correct a seed that has no experiment container', async () => {
+ const { goalId, parent } = await seed(9);
+ await expect(
+ model.apply(goalId, (await claim(goalId))!.token, revise(parent.id)),
+ ).rejects.toThrow(/experiment container/);
+ });
+
+ it('refuses to revise an experiment that never produced a result', async () => {
+ const { goalId } = await seed();
+ const unresolved = await graphModel.createNode(goalId, {
+ kind: 'task',
+ title: 'Still running',
+ status: 'active',
+ });
+ await expect(
+ model.apply(goalId, (await claim(goalId))!.token, revise(unresolved!.id)),
+ ).rejects.toThrow(/resolved experiment/);
+ });
it('branches from an older experiment and pins its produced version with an auditable reason', async () => {
const { goalId, parent } = await seed();
await graphModel.createNode(goalId, {
diff --git a/packages/database/src/models/goalExploration.ts b/packages/database/src/models/goalExploration.ts
index b5ce8ba9d32..820c9f62c42 100644
--- a/packages/database/src/models/goalExploration.ts
+++ b/packages/database/src/models/goalExploration.ts
@@ -2,7 +2,13 @@ import { createHash, randomUUID } from 'node:crypto';
import { GOAL_ACCEPTANCE_TASK_TITLE, GOAL_COORDINATOR_ACTOR_ID } from '@lobechat/const/goal';
import type { GoalExplorationDecision, GoalGraphSnapshot } from '@lobechat/types';
-import { experimentMembers, experimentOwner } from '@lobechat/utils/goalGraph';
+import {
+ experimentOwner,
+ experimentScope,
+ isProtocolRevision,
+ MAX_PROTOCOL_REVISIONS,
+ protocolRevisionCount,
+} from '@lobechat/utils/goalGraph';
import { and, eq } from 'drizzle-orm';
import { goals } from '../schemas/goal';
@@ -125,9 +131,13 @@ export class GoalExplorationModel {
const experiments = graph.nodes.filter(
(node) =>
node.kind === 'experiment' ||
+ // A standalone correction re-runs an existing question, so it must not
+ // read back as a new experiment: that would spend a slot and let the
+ // planner revise it as a fresh target with an empty correction budget.
(node.kind === 'task' &&
node.title !== GOAL_ACCEPTANCE_TASK_TITLE &&
- !experimentOwner(graph, node.id)),
+ !experimentOwner(graph, node.id) &&
+ !isProtocolRevision(graph, node.id)),
);
if (decision.action === 'verify') {
await tx
@@ -155,6 +165,66 @@ export class GoalExplorationModel {
);
return { outcome: 'verify' as const };
}
+ if (decision.action === 'revise') {
+ const target = experiments.find(
+ (node) => node.id === decision.parentNodeId && node.status === 'resolved',
+ );
+ if (!target) throw new Error('A revision must correct a resolved experiment in this goal');
+ // A spent allowance is a predictable policy answer, not a planner crash. Throwing
+ // here would pause the whole goal through the generic failure path, and resuming
+ // could produce the same choice again.
+ const spent = protocolRevisionCount(graph, target.id);
+ if (spent >= MAX_PROTOCOL_REVISIONS) {
+ // The planner asked for a correction after being told the allowance was
+ // gone, and nothing about the graph will change on its own. Leaving the
+ // goal running would let every sweep buy another identical planning call
+ // forever, so park it the way an exhausted experiment budget does.
+ const reason = `Experiment ${target.id} already ran ${spent} corrected protocols; the planner asked for another. Resume to replan.`;
+ await tx
+ .update(goals)
+ .set({
+ config: {
+ ...goal.config,
+ exploration: { ...policy, checkpoint: undefined },
+ pausedBy: 'exploration_revision_limit',
+ },
+ status: 'paused',
+ })
+ .where(eq(goals.id, goalId));
+ await graphModel.recordGoalStatus(goalId, 'running', 'paused', reason);
+ return { outcome: 'revision-limit' as const, reason };
+ }
+ // Correcting an instrument reuses the parent's container, so the graph keeps one
+ // question with successive protocols instead of a row of flawed siblings. An
+ // uncontained legacy seed has no such container: a correction there would be
+ // another root task, which the planner cannot see, which drops the previous
+ // correction's Work, and which an older release would read back as an
+ // experiment consuming a slot. Those goals expand first.
+ const container =
+ target.kind === 'experiment' ? target.id : experimentOwner(graph, target.id);
+ if (!container)
+ throw new Error('A revision needs an experiment container; expand this seed first');
+ const node = await graphModel.createNode(goalId, {
+ description: decision.instruction,
+ kind: 'task',
+ scopeId: container,
+ title: decision.title.trim() || target.title,
+ });
+ if (!node) throw new Error('Could not persist the revised protocol');
+ await graphModel.createEdge(goalId, node.id, target.id, 'revises');
+ const members = experimentScope(graph, container);
+ for (const version of graph.workVersions.filter(
+ (item) => members.has(item.nodeId) && item.relation === 'produced',
+ ))
+ // Preserve the existing version visibility checks; never turn a graph link into read permission.
+ await graphModel.attachWorkVersion(goalId, node.id, version.workVersionId, 'input');
+ await tx
+ .update(goals)
+ .set({ config: { ...goal.config, exploration: { ...policy, checkpoint: undefined } } })
+ .where(eq(goals.id, goalId));
+ await this.recordDecision(tx, goalId, `Revised ${target.id}: ${decision.reason}`);
+ return { outcome: 'revised' as const, nodeId: node.id, parentNodeId: target.id };
+ }
if (experiments.length >= policy.maxExperiments) {
await tx
.update(goals)
@@ -201,8 +271,7 @@ export class GoalExplorationModel {
});
if (!node) throw new Error('Could not persist exploration node');
await graphModel.createEdge(goalId, experiment.id, parent.id, 'derived_from');
- const parentMembers = experimentMembers(graph, parent.id);
- parentMembers.add(parent.id);
+ const parentMembers = experimentScope(graph, parent.id);
for (const version of graph.workVersions.filter(
(item) => parentMembers.has(item.nodeId) && item.relation === 'produced',
)) {
diff --git a/packages/prompts/src/chains/goalExplore.ts b/packages/prompts/src/chains/goalExplore.ts
index f987070b8d3..4af359a9aa9 100644
--- a/packages/prompts/src/chains/goalExplore.ts
+++ b/packages/prompts/src/chains/goalExplore.ts
@@ -1,5 +1,5 @@
/** Run-time graph expansion, distinct from initial goal decomposition. */
-export const GOAL_EXPLORE_PROMPT_VERSION = 'v1';
+export const GOAL_EXPLORE_PROMPT_VERSION = 'v2';
export const GOAL_EXPLORE_JSON_SCHEMA = {
name: 'goal_exploration',
strict: true,
@@ -7,7 +7,7 @@ export const GOAL_EXPLORE_JSON_SCHEMA = {
type: 'object' as const,
additionalProperties: false,
properties: {
- action: { type: 'string', enum: ['expand', 'verify'] },
+ action: { type: 'string', enum: ['expand', 'revise', 'verify'] },
parentNodeId: { type: 'string' },
title: { type: 'string', maxLength: 80 },
instruction: { type: 'string' },
@@ -24,6 +24,10 @@ export interface GoalExploreInput {
status: string;
results: string[];
inputVersionIds: string[];
+ /** Set when a previous exploration turn derived this experiment from another. */
+ derivedFromId?: string;
+ /** Corrected protocols this experiment may still take; 0 means revise is closed. */
+ revisionsRemaining: number;
}>;
instruction: string;
maxExperiments: number;
@@ -41,8 +45,13 @@ export const chainGoalExplore = (input: GoalExploreInput) => ({
'Return expand to propose one concrete new experiment. Select parentNodeId from a resolved experiment in the supplied history, including an older experiment when useful. Do not assume the most recent is best.',
'The new instruction must explain the specific change, the expected deliverable, and how to evaluate this experiment. A low-quality measured outcome can still be useful; do not require this single experiment to satisfy the entire Goal.',
'The selected parent results and version references will be injected by the server. Refer to them explicitly when proposing a variation.',
+ 'Return revise to correct an experiment that already produced results but measured the wrong thing: a wrong output format, metric, threshold, or evaluation procedure. A revision re-runs inside the same experiment with a corrected protocol and does not consume an experiment slot.',
+ 'Prefer revise over expand when the weakness is in how the result was measured rather than in which question was asked. Adding a sibling that inherits a flawed instrument reproduces the flaw.',
+ 'derivedFromId marks an experiment a previous turn derived from another. Compare such an experiment against its parent: if it did not improve on the parent, do not expand again in the same direction — revise the protocol or change the question.',
'Return verify only when the evidence warrants final acceptance; this requests independent verification, never declares the Goal achieved.',
'The experiment limit is a resource limit, not a success criterion. If more work is needed even at the limit, return expand; the coordinator will stop without claiming success.',
+ 'For revise, set parentNodeId to the experiment being corrected and put the corrected protocol in instruction; title may repeat the parent title.',
+ 'revisionsRemaining is how many corrected protocols an experiment may still take. Never return revise for an experiment whose revisionsRemaining is 0; expand or verify instead.',
'For verify, use empty strings for parentNodeId, title, and instruction. Always explain your reason using concrete results.',
'Write human-facing fields in the language of the goal.',
].join('\n'),
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index ec69ab01726..05a4b304c36 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -104,10 +104,20 @@ export interface GoalAcceptancePolicy {
* stored explicitly rather than as the absence of a marker, because pausing an
* already-paused goal is a no-op that leaves no other trace of who asked.
*/
-export type GoalPauseReason = 'measured_acceptance' | 'exploration_limit' | 'user';
+export type GoalPauseReason =
+ | 'measured_acceptance'
+ | 'exploration_limit'
+ /** The planner asked for a correction after its allowance was already spent. */
+ | 'exploration_revision_limit'
+ | 'user';
export interface GoalExplorationDecision {
- action: 'expand' | 'verify';
+ /**
+ * `expand` opens a sibling experiment for a new question; `revise` corrects the
+ * protocol of an experiment that already ran, so a flawed instrument is fixed in
+ * place instead of being inherited by another sibling.
+ */
+ action: 'expand' | 'revise' | 'verify';
instruction: string;
parentNodeId: string;
reason: string;
@@ -297,6 +307,13 @@ export type GoalEdgeKind =
| 'decomposes'
| 'depends_on'
| 'derived_from'
+ /**
+ * A corrected protocol replacing an earlier one inside the same experiment.
+ * Distinct from `derived_from`, which records generic provenance and is writable
+ * through the public graph mutation: reusing it would silently reinterpret any
+ * hand-authored task provenance as a correction.
+ */
+ | 'revises'
| 'investigates'
| 'produces'
| 'supports'
diff --git a/packages/utils/src/goalGraph.test.ts b/packages/utils/src/goalGraph.test.ts
index 98cfce2ff98..2b31a9d4c20 100644
--- a/packages/utils/src/goalGraph.test.ts
+++ b/packages/utils/src/goalGraph.test.ts
@@ -1,7 +1,14 @@
import type { GoalGraphNode, GoalGraphSnapshot, GoalNodeKind } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
-import { experimentMembers, experimentStatus, graphScopeIds } from './goalGraph';
+import {
+ experimentMembers,
+ experimentStatus,
+ graphScopeIds,
+ isProtocolRevision,
+ protocolRevisionCount,
+ provenanceParentId,
+} from './goalGraph';
const node = (
id: string,
@@ -80,3 +87,43 @@ describe('experiment containment', () => {
expect(experimentStatus(g, g.nodes[1])).toBe('active');
});
});
+
+describe('provenance and protocol revisions', () => {
+ const graph = {
+ edges: [
+ { kind: 'contains', sourceNodeId: 'exp', targetNodeId: 'run1' },
+ { kind: 'contains', sourceNodeId: 'exp', targetNodeId: 'fix1' },
+ { kind: 'derived_from', sourceNodeId: 'exp', targetNodeId: 'older' },
+ { kind: 'derived_from', sourceNodeId: 'hand', targetNodeId: 'older' },
+ { kind: 'contains', sourceNodeId: 'exp', targetNodeId: 'hand' },
+ { kind: 'revises', sourceNodeId: 'fix1', targetNodeId: 'exp' },
+ ],
+ nodes: [
+ { id: 'older', kind: 'experiment' },
+ { id: 'exp', kind: 'experiment' },
+ { id: 'run1', kind: 'task' },
+ { id: 'hand', kind: 'task' },
+ { id: 'fix1', kind: 'task' },
+ ],
+ } as any;
+
+ it('gives a corrected protocol its own parent rather than its container’s', () => {
+ // `fix1` corrects `exp`; reading the container would hand it `older` instead.
+ expect(provenanceParentId(graph, 'fix1')).toBe('exp');
+ // An ordinary member falls back to its container's branch parent.
+ expect(provenanceParentId(graph, 'run1')).toBe('older');
+ // A hand-authored provenance edge is preferred over the container's, and is
+ // still not treated as a correction.
+ expect(provenanceParentId(graph, 'hand')).toBe('older');
+ });
+
+ it('separates a correction from an ordinary branch when counting', () => {
+ expect(isProtocolRevision(graph, 'fix1')).toBe(true);
+ // `exp` also has a `derived_from` edge, but it is a branch, not a correction.
+ expect(isProtocolRevision(graph, 'exp')).toBe(false);
+ // A hand-authored task provenance edge is not a correction either.
+ expect(isProtocolRevision(graph, 'hand')).toBe(false);
+ expect(protocolRevisionCount(graph, 'exp')).toBe(1);
+ expect(protocolRevisionCount(graph, 'older')).toBe(0);
+ });
+});
diff --git a/packages/utils/src/goalGraph.ts b/packages/utils/src/goalGraph.ts
index 80d2f7898c3..15ef119a3de 100644
--- a/packages/utils/src/goalGraph.ts
+++ b/packages/utils/src/goalGraph.ts
@@ -70,3 +70,73 @@ export const graphScopeIds = (graph: Graph, scopeId?: string): Set<string> => {
graph.nodes.filter((node) => !experimentOwner(graph, node.id)).map((node) => node.id),
);
};
+
+/**
+ * How many corrected protocols one experiment may take. Bounding them keeps a planner
+ * that keeps "fixing" the same instrument from spending the goal's budget without ever
+ * changing the question.
+ */
+export const MAX_PROTOCOL_REVISIONS = 2;
+
+/** A node that replaces an earlier protocol, rather than opening a new branch. */
+export const isProtocolRevision = (graph: Graph, nodeId: string): boolean =>
+ graph.edges.some((edge) => edge.kind === 'revises' && edge.sourceNodeId === nodeId);
+
+/**
+ * Corrections already aimed at this experiment, following a standalone chain back to
+ * its origin so revising the latest attempt cannot hand the budget back.
+ */
+export const protocolRevisionCount = (graph: Graph, targetId: string): number => {
+ const revisions = graph.edges.filter((edge) => edge.kind === 'revises');
+ const seen = new Set<string>();
+ let cursor: string | undefined = targetId;
+ let count = 0;
+ while (cursor && !seen.has(cursor)) {
+ seen.add(cursor);
+ count += revisions.filter((edge) => edge.targetNodeId === cursor).length;
+ cursor = revisions.find((edge) => edge.sourceNodeId === cursor)?.targetNodeId;
+ }
+ return count;
+};
+
+/**
+ * The experiment whose results a node's run should carry.
+ *
+ * A corrected protocol has its own provenance edge, so it must be preferred over the
+ * container's: reading the container's would hand the run the results of the older
+ * experiment that container was itself branched from.
+ */
+export const provenanceParentId = (graph: Graph, nodeId: string): string | undefined =>
+ (
+ graph.edges.find(
+ (edge) =>
+ (edge.kind === 'revises' || edge.kind === 'derived_from') && edge.sourceNodeId === nodeId,
+ ) ??
+ graph.edges.find(
+ (edge) =>
+ edge.kind === 'derived_from' &&
+ edge.sourceNodeId === (experimentOwner(graph, nodeId) ?? nodeId),
+ )
+ )?.targetNodeId;
+
+/**
+ * Every node whose work belongs to this experiment: its container members plus the
+ * corrections aimed at it. A correction re-runs the same question, so its findings and
+ * produced versions are the experiment's evidence — without this the planner would
+ * keep reading the pre-correction result and never see what the rerun found.
+ */
+export const experimentScope = (graph: Graph, nodeId: string): Set<string> => {
+ const scope = experimentMembers(graph, nodeId);
+ scope.add(nodeId);
+ for (;;) {
+ const next = graph.edges.filter(
+ (edge) =>
+ edge.kind === 'revises' && scope.has(edge.targetNodeId) && !scope.has(edge.sourceNodeId),
+ );
+ if (!next.length) return scope;
+ for (const edge of next) {
+ scope.add(edge.sourceNodeId);
+ for (const member of experimentMembers(graph, edge.sourceNodeId)) scope.add(member);
+ }
+ }
+};