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): durable Widget collection subscriptions (#20507)

Arvin Xua293857cb57f
diff --git a/apps/server/src/router-hono/workflows/goal/handlers/sweep.ts b/apps/server/src/router-hono/workflows/goal/handlers/sweep.ts
index bb05ac9b15d..447b5f6c0bd 100644
--- a/apps/server/src/router-hono/workflows/goal/handlers/sweep.ts
+++ b/apps/server/src/router-hono/workflows/goal/handlers/sweep.ts
@@ -7,6 +7,9 @@ import { appEnv } from '@/envs/app';
import { qstashClient } from '@/libs/qstash';
import { advanceGoal } from '@/server/services/goal/advanceGoal';
import { GOAL_ADVANCE_PATH } from '@/server/services/goal/scheduler';
+import { GoalSubscriptionService } from '@/server/services/goal/subscriptions';
+
+let subscriptionAfter: string | undefined;
const log = debug('lobe-server:workflows:goal:sweep');
@@ -44,6 +47,12 @@ export async function sweep(c: Context) {
const { dryRun = false, limit = 200, staleAfterMs = DEFAULT_STALE_AFTER_MS } = body ?? {};
const db = await getServerDB();
+ if (!dryRun)
+ subscriptionAfter = await GoalSubscriptionService.reconcile(
+ db,
+ subscriptionAfter,
+ Math.min(limit, 100),
+ );
const stalled = await GoalModel.listStalled(db, {
limit,
staleBefore: new Date(Date.now() - staleAfterMs),
diff --git a/apps/server/src/routers/lambda/__tests__/integration/widget.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/widget.integration.test.ts
index a07d13a10c0..83512574359 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/widget.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/widget.integration.test.ts
@@ -420,13 +420,16 @@ describe('widget + dashboard routers integration', () => {
await owner.publish({ versionId: v2.id, widgetId: widget.id });
// a v2 run starts, then a newer one finishes first and owns the snapshot
- const startedEarly = await WidgetModel.startRun(db, await widgetRow(), {
+ const reserved = await WidgetModel.startRun(db, await widgetRow(), {
trigger: 'schedule',
});
- await db
+ // Re-read after backdating: completion is fenced on the `startedAt` the
+ // worker holds, so the late worker must hold the row as it now stands.
+ const [startedEarly] = await db
.update(widgetRuns)
.set({ startedAt: new Date(Date.now() - 60_000) })
- .where(eq(widgetRuns.id, startedEarly.id));
+ .where(eq(widgetRuns.id, reserved.id))
+ .returning();
runSandbox.mockResolvedValueOnce(ok({ type: 'stat', value: 10 }));
await owner.run({ widgetId: widget.id });
const current = await widgetRow();
@@ -584,11 +587,20 @@ describe('widget + dashboard routers integration', () => {
],
type: 'series' as const,
};
+ const persistedModel = new WidgetModel(db, ownerId);
+ const version = await persistedModel.createVersion(widget.id, {
+ ...statScript,
+ outputType: 'series',
+ sourceType: 'agent',
+ });
+ await persistedModel.publishVersion(widget.id, version!.id);
+ const first = await persistedModel.startRun(widget.id, { trigger: 'manual' });
+ const second = await persistedModel.startRun(widget.id, { trigger: 'schedule' });
const record = (runId: string) =>
recordWidgetMetrics(db, widget, { observedAt: new Date(), output, runId });
// a manual refresh and a scheduled run report the same window at once
- const results = await Promise.all([record('run-a'), record('run-b')]);
+ const results = await Promise.all([record(first!.id), record(second!.id)]);
expect(results.map((r) => r.pointsWritten).sort()).toEqual([0, 2]);
const [metric] = await db
diff --git a/apps/server/src/routers/lambda/__tests__/metric.test.ts b/apps/server/src/routers/lambda/__tests__/metric.test.ts
index f876697fe26..bb82bff200c 100644
--- a/apps/server/src/routers/lambda/__tests__/metric.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/metric.test.ts
@@ -60,6 +60,13 @@ vi.mock('@/database/models/project', () => ({
return { findById: vi.fn().mockResolvedValue(null) };
}),
}));
+// Goal Widget bindings have their own integration suite; this router test keeps
+// to its mocked models, so a goal subject reads as having no bindings.
+vi.mock('@/server/services/goal/subscriptions', () => ({
+ GoalSubscriptionService: class {
+ list = async () => [];
+ },
+}));
vi.mock('@/database/models/task', () => ({
TaskModel: vi.fn(function () {
return { findById: vi.fn().mockResolvedValue(null) };
diff --git a/apps/server/src/routers/lambda/goal/index.procedures.test.ts b/apps/server/src/routers/lambda/goal/index.procedures.test.ts
index 1cad5dcf63d..888db1e62da 100644
--- a/apps/server/src/routers/lambda/goal/index.procedures.test.ts
+++ b/apps/server/src/routers/lambda/goal/index.procedures.test.ts
@@ -30,17 +30,21 @@ function expected(): Array<
['advance', 'mutation', 13],
['answerClarifications', 'mutation', 13],
['bindOperationTopic', 'mutation', 8],
+ ['bindSubscription', 'mutation', 13],
['bindTopic', 'mutation', 13],
['close', 'mutation', 13],
['create', 'mutation', 13],
['createConversationGoal', 'mutation', 8],
['decide', 'mutation', 13],
['delete', 'mutation', 13],
+ ['disableSubscription', 'mutation', 13],
+ ['enableSubscription', 'mutation', 13],
['events', 'query', 12],
['eventsOperation', 'query', 9],
['graph', 'query', 12],
['graphOperation', 'query', 9],
['list', 'query', 12],
+ ['listSubscriptions', 'query', 12],
['metricState', 'query', 12],
['metricStateOperation', 'query', 9],
['pause', 'mutation', 13],
@@ -48,6 +52,7 @@ function expected(): Array<
['pendingForIsland', 'query', 11],
['planContext', 'query', 12],
['planContextOperation', 'query', 9],
+ ['rebindSubscription', 'mutation', 13],
['recordObservation', 'mutation', 13],
['removeEdge', 'mutation', 13],
['removeMetricCriteria', 'mutation', 13],
@@ -70,6 +75,7 @@ function expected(): Array<
['supervision', 'query', 12],
['tick', 'mutation', 13],
['updateRequirement', 'mutation', 13],
+ ['updateSubscription', 'mutation', 13],
['wake', 'mutation', 13],
];
}
diff --git a/apps/server/src/routers/lambda/goal/index.ts b/apps/server/src/routers/lambda/goal/index.ts
index 8ef0e739f64..8b03d11ee14 100644
--- a/apps/server/src/routers/lambda/goal/index.ts
+++ b/apps/server/src/routers/lambda/goal/index.ts
@@ -6,6 +6,7 @@ import { creationRouter } from './creation';
import { lifecycleRouter } from './lifecycle';
import { planningRouter } from './planning';
import { readRouter } from './reads';
+import { subscriptionRouter } from './subscriptions';
export const goalRouter = mergeRouters(
lifecycleRouter,
@@ -13,6 +14,7 @@ export const goalRouter = mergeRouters(
creationRouter,
configurationRouter,
readRouter,
+ subscriptionRouter,
router({
...goalGraphEditProcedures,
}),
diff --git a/apps/server/src/routers/lambda/goal/subscriptions.ts b/apps/server/src/routers/lambda/goal/subscriptions.ts
new file mode 100644
index 00000000000..03c202c3dcf
--- /dev/null
+++ b/apps/server/src/routers/lambda/goal/subscriptions.ts
@@ -0,0 +1,55 @@
+import { z } from 'zod';
+
+import { router } from '@/libs/trpc/lambda';
+import {
+ bindSubscriptionSchema,
+ updateSubscriptionSchema,
+} from '@/server/services/goal/subscriptions';
+
+import { goalProcedure, goalWriteProcedure } from '../goalProcedures';
+
+const revisionInput = z.object({
+ bindingRevision: z.number().int().positive(),
+ id: z.string().uuid(),
+});
+
+/** A Goal's durable bindings to Widget metric collections. */
+export const subscriptionRouter = router({
+ bindSubscription: goalWriteProcedure
+ .input(bindSubscriptionSchema)
+ .mutation(async ({ ctx, input }) => ({
+ data: await ctx.goalSubscriptionService.bind(input),
+ success: true,
+ })),
+ disableSubscription: goalWriteProcedure.input(revisionInput).mutation(async ({ ctx, input }) => ({
+ data: await ctx.goalSubscriptionService.setEnabled(input.id, input.bindingRevision, false),
+ success: true,
+ })),
+ enableSubscription: goalWriteProcedure.input(revisionInput).mutation(async ({ ctx, input }) => ({
+ data: await ctx.goalSubscriptionService.setEnabled(input.id, input.bindingRevision, true),
+ success: true,
+ })),
+ listSubscriptions: goalProcedure
+ .input(z.object({ goalId: z.string().min(1) }))
+ .query(async ({ ctx, input }) => ({
+ data: await ctx.goalSubscriptionService.list(input.goalId),
+ success: true,
+ })),
+ rebindSubscription: goalWriteProcedure
+ .input(
+ bindSubscriptionSchema.extend({
+ bindingRevision: z.number().int().positive(),
+ id: z.string().uuid(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => ({
+ data: await ctx.goalSubscriptionService.bind(input, input),
+ success: true,
+ })),
+ updateSubscription: goalWriteProcedure
+ .input(updateSubscriptionSchema)
+ .mutation(async ({ ctx, input }) => ({
+ data: await ctx.goalSubscriptionService.update(input),
+ success: true,
+ })),
+});
diff --git a/apps/server/src/routers/lambda/goalProcedures.ts b/apps/server/src/routers/lambda/goalProcedures.ts
index b47fe8b74f0..88ebfd8500d 100644
--- a/apps/server/src/routers/lambda/goalProcedures.ts
+++ b/apps/server/src/routers/lambda/goalProcedures.ts
@@ -6,6 +6,7 @@ import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceA
import { GoalModel } from '@/database/models/goal';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { GoalService } from '@/server/services/goal';
+import { GoalSubscriptionService } from '@/server/services/goal/subscriptions';
/** Procedures and helpers shared by `goalRouter` and its spread-in procedure groups. */
export const goalProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>
@@ -21,6 +22,11 @@ export const goalProcedure = wsCompatProcedure.use(serverDatabase).use(async (op
opts.ctx.userId,
opts.ctx.workspaceId ?? undefined,
),
+ goalSubscriptionService: new GoalSubscriptionService(
+ opts.ctx.serverDB,
+ opts.ctx.userId,
+ opts.ctx.workspaceId ?? undefined,
+ ),
},
}),
);
diff --git a/apps/server/src/routers/lambda/metric.ts b/apps/server/src/routers/lambda/metric.ts
index 138775dee69..d8bd966a02f 100644
--- a/apps/server/src/routers/lambda/metric.ts
+++ b/apps/server/src/routers/lambda/metric.ts
@@ -14,6 +14,7 @@ import { WidgetModel } from '@/database/models/widget';
import type { LobeChatDatabase } from '@/database/type';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { GoalSubscriptionService } from '@/server/services/goal/subscriptions';
import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';
@@ -275,11 +276,27 @@ export const metricRouter = router({
input.subjectId,
input.keys,
);
+ // Tracking Goals use the exact Widget series and history read by boards.
+ // Alias only the contract key; identity and values remain authoritative.
+ const bindings =
+ input.subjectType === 'goal'
+ ? await new GoalSubscriptionService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ).list(input.subjectId)
+ : [];
+ const mapped = input.keys.flatMap((key) => {
+ const binding = bindings.find((item) => item.subscription.binding.criterionKey === key);
+ if (binding) return binding.metric ? [{ ...binding.metric, key }] : [];
+ const own = series.find((item) => item.key === key);
+ return own ? [own] : [];
+ });
const firstPoints = await ctx.metricModel.firstPointsByMetricIds(
- series.map((item) => item.id),
+ mapped.map((item) => item.id),
);
const data = await Promise.all(
- series.map(async (item) => ({
+ mapped.map(async (item) => ({
config: item.config,
firstPoint: firstPoints.get(item.id) ?? null,
id: item.id,
diff --git a/apps/server/src/services/goal/GoalService/__tests__/acceptance.test.ts b/apps/server/src/services/goal/GoalService/__tests__/acceptance.test.ts
index ad713d27ca7..9ab013a5aeb 100644
--- a/apps/server/src/services/goal/GoalService/__tests__/acceptance.test.ts
+++ b/apps/server/src/services/goal/GoalService/__tests__/acceptance.test.ts
@@ -220,6 +220,37 @@ describe('GoalService', () => {
});
});
+ it('re-checks measured acceptance in the same transaction as the achieved write', async () => {
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({
+ requirement: 'A runnable minimal training loop with evidence',
+ title: 'Reproduce Ornith training',
+ tasks: ['Implement minimal training loop'],
+ });
+ const created = await service.tick(graph.goal.id);
+ await taskModel.updateStatus(created.taskId!, 'completed');
+ await service.tick(graph.goal.id);
+ await service.tick(graph.goal.id);
+ const acceptanceTask = await service.tick(graph.goal.id);
+ await taskModel.updateStatus(acceptanceTask.taskId!, 'completed');
+ await service.tick(graph.goal.id);
+
+ // Evidence changes after the pre-check: only the read inside the final
+ // transaction (the one handed a `db`) sees the below-target observation.
+ const internals = service as unknown as {
+ evaluateMetricCriteria: (graph: unknown, db?: unknown) => Promise<unknown>;
+ };
+ const evaluate = internals.evaluateMetricCriteria;
+ vi.spyOn(internals, 'evaluateMetricCriteria').mockImplementation(async (graph, db) =>
+ db ? { allMet: false, criteria: [] } : evaluate(graph),
+ );
+
+ const result = await service.tick(graph.goal.id);
+ expect(result).toMatchObject({ outcome: 'no_progress' });
+ expect((await service.graph(graph.goal.id)).goal.status).not.toBe('achieved');
+ });
+
it('does not mark a required goal achieved when only its initial Task is complete', async () => {
const service = new GoalService(serverDB, userId);
const taskModel = new TaskModel(serverDB, userId);
diff --git a/apps/server/src/services/goal/GoalService/completion.ts b/apps/server/src/services/goal/GoalService/completion.ts
index 8cac6497dd9..4e531263744 100644
--- a/apps/server/src/services/goal/GoalService/completion.ts
+++ b/apps/server/src/services/goal/GoalService/completion.ts
@@ -10,6 +10,7 @@ import type {
import { experimentOwner } from '@lobechat/utils/goalGraph';
import { GoalGraphModel } from '@/database/models/goalGraph';
+import { GoalRepository } from '@/database/repositories/goal';
import {
GOAL_ACCEPTANCE_TASK_TITLE,
@@ -41,6 +42,16 @@ export const settleTerminalAcceptance = async (
const goalId = graph.goal.id;
if (move.outcome === 'achieved') {
+ // Re-read the numeric clauses right before the terminal transition: bindings,
+ // provenance and freshness can change between the verdict and here, and the
+ // earlier verdict is not a lease.
+ const measurementChanged: GoalTickResult = {
+ goalId,
+ message: 'Measured acceptance changed before the Goal could be achieved; re-evaluating',
+ outcome: 'no_progress',
+ };
+ const numeric = await ctx.evaluateMetricCriteria(await ctx.requireGraph(goalId));
+ if (!numeric.allMet) return measurementChanged;
// The map must agree with the verdict: only task nodes get resolved as
// Tasks complete, so without this the seeded problem nodes would read
// "active / unanswered" forever on an achieved goal.
@@ -54,7 +65,24 @@ export const settleTerminalAcceptance = async (
// the ask for good. Failing here leaves the goal open for the next tick,
// and the write is idempotent per acceptance.
await ctx.requestSignOff(graph);
- await ctx.transitionStatus(graph.goal, 'achieved', 'Goal-level acceptance passed');
+ // The final verdict and the terminal write commit together: the evidence
+ // locks taken by the re-read are held until `achieved` lands, so a rebind,
+ // disable or newer below-target observation cannot slip in between.
+ const achieved = await ctx.db.transaction(async (tx) => {
+ const model = new GoalRepository(tx, ctx.userId, ctx.workspaceId);
+ const current = await model.lockById(goalId);
+ if (!current || current.status !== graph.goal.status) return false;
+ if (!(await ctx.evaluateMetricCriteria({ ...graph, goal: current }, tx)).allMet) return false;
+ await model.updateStatus(goalId, 'achieved');
+ await new GoalGraphModel(tx, ctx.userId, ctx.workspaceId, {
+ id: GOAL_COORDINATOR_ACTOR_ID,
+ type: 'system',
+ })
+ .recordGoalStatus(goalId, current.status, 'achieved', 'Goal-level acceptance passed')
+ .catch((error) => console.error('[GoalService] failed to record goal status:', error));
+ return true;
+ });
+ if (!achieved) return measurementChanged;
effects.push({ type: 'goal_status', detail: 'achieved' });
return { goalId, message: move.message, outcome: 'achieved' };
}
diff --git a/apps/server/src/services/goal/GoalService/decisions.ts b/apps/server/src/services/goal/GoalService/decisions.ts
index 4d7f5ca9519..b6c020e0b52 100644
--- a/apps/server/src/services/goal/GoalService/decisions.ts
+++ b/apps/server/src/services/goal/GoalService/decisions.ts
@@ -16,9 +16,9 @@ import type {
import { experimentOwner } from '@lobechat/utils/goalGraph';
import { TRPCError } from '@trpc/server';
-import { GoalModel } from '@/database/models/goal';
import { GoalGraphModel } from '@/database/models/goalGraph';
import { TaskModel } from '@/database/models/task';
+import { GoalRepository } from '@/database/repositories/goal';
import { collectStrandedDependents, GOAL_ACCEPTANCE_TASK_TITLE } from '../decideNextMove';
import { answeredProblem, GoalManagerService, problemKey } from '../manager';
@@ -263,10 +263,10 @@ export const decide = async (
// Serialized with `close`, which commits under this row lock: a goal that
// ended while this answer was being written is left ended.
await ctx.db.transaction(async (tx) => {
- const current = await new GoalModel(tx, ctx.userId, ctx.workspaceId).lockById(goalId);
+ const current = await new GoalRepository(tx, ctx.userId, ctx.workspaceId).lockById(goalId);
if (!current || GOAL_ENDED_STATUSES.has(current.status)) return;
if (current.status === nextStatus) return;
- await new GoalModel(tx, ctx.userId, ctx.workspaceId).updateStatus(goalId, nextStatus);
+ await new GoalRepository(tx, ctx.userId, ctx.workspaceId).updateStatus(goalId, nextStatus);
await new GoalGraphModel(tx, ctx.userId, ctx.workspaceId, {
id: GOAL_COORDINATOR_ACTOR_ID,
type: 'system',
@@ -427,7 +427,7 @@ export const openFailureDecision = async (
gate: FailureGateOptions = {},
): Promise<GoalTickResult> => {
return ctx.db.transaction(async (tx) => {
- const currentGoal = await new GoalModel(tx, ctx.userId, ctx.workspaceId).lockById(
+ const currentGoal = await new GoalRepository(tx, ctx.userId, ctx.workspaceId).lockById(
graph.goal.id,
);
const service = ctx.inTransaction(tx);
diff --git a/apps/server/src/services/goal/GoalService/index.ts b/apps/server/src/services/goal/GoalService/index.ts
index 5facb1cf454..379134c8636 100644
--- a/apps/server/src/services/goal/GoalService/index.ts
+++ b/apps/server/src/services/goal/GoalService/index.ts
@@ -1,11 +1,11 @@
import { GOAL_COORDINATOR_ACTOR_ID } from '@lobechat/const/goal';
import { AgentModel } from '@/database/models/agent';
-import { GoalModel } from '@/database/models/goal';
import { GoalGraphModel } from '@/database/models/goalGraph';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
import { WorkModel } from '@/database/models/work';
+import { GoalRepository } from '@/database/repositories/goal';
import type { LobeChatDatabase } from '@/database/type';
import { TaskService } from '../../task';
@@ -121,7 +121,7 @@ export class GoalService {
/** What the goal tells the person through the inbox: gates, sign-off, findings. */
private readonly briefs: GoalBriefService;
private readonly releaseReview: GoalReleaseReview;
- private readonly goalModel: GoalModel;
+ private readonly goalModel: GoalRepository;
/**
* Graph writes attributed to the person who asked for them: seeding a goal,
* adding a node or edge by hand, resolving a decision gate.
@@ -147,7 +147,7 @@ export class GoalService {
this.acceptanceService = new AcceptanceService(db, userId, workspaceId);
this.agentModel = new AgentModel(db, userId, workspaceId);
this.briefs = new GoalBriefService(db, userId, workspaceId);
- this.goalModel = new GoalModel(db, userId, workspaceId);
+ this.goalModel = new GoalRepository(db, userId, workspaceId);
this.releaseReview = new GoalReleaseReview(db, userId, workspaceId, {
briefs: this.briefs,
decide: (...args) => this.decide(...args),
diff --git a/apps/server/src/services/goal/GoalService/lifecycle.ts b/apps/server/src/services/goal/GoalService/lifecycle.ts
index 3c4ca2b0466..6ab1f267f46 100644
--- a/apps/server/src/services/goal/GoalService/lifecycle.ts
+++ b/apps/server/src/services/goal/GoalService/lifecycle.ts
@@ -1,10 +1,10 @@
import type { GoalGraphSnapshot, GoalItem, GoalStatus, TaskItem } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
-import { GoalModel } from '@/database/models/goal';
import { GoalGraphModel } from '@/database/models/goalGraph';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
+import { GoalRepository } from '@/database/repositories/goal';
import { GoalAssignmentService } from '../assignment';
import { GOAL_ACCEPTANCE_TASK_TITLE, TERMINAL_NODE_STATUSES } from '../decideNextMove';
@@ -54,7 +54,7 @@ export const deleteGoal = async (ctx: GoalServiceContext, goalId: string) => {
if (managed || supervised) {
// Fence new claims before cancellation, then read the latest claimed turn.
await ctx.db.transaction(async (db) => {
- const model = new GoalModel(db, ctx.userId, ctx.workspaceId);
+ const model = new GoalRepository(db, ctx.userId, ctx.workspaceId);
const current = await model.lockById(goalId);
if (current && current.status !== 'paused') {
await model.updateStatus(goalId, 'paused');
@@ -101,7 +101,7 @@ export const deleteGoal = async (ctx: GoalServiceContext, goalId: string) => {
if (managed || supervised) {
return ctx.db.transaction(async (db) => {
- const model = new GoalModel(db, ctx.userId, ctx.workspaceId);
+ const model = new GoalRepository(db, ctx.userId, ctx.workspaceId);
const current = await model.lockById(goalId);
if (
current &&
@@ -284,7 +284,7 @@ export const resume = async (ctx: GoalServiceContext, goalId: string) => {
// Tasks back to `backlog` and they would dispatch again. Reopening an ended
// goal still works — that resume reads the ended status itself.
return ctx.db.transaction(async (tx) => {
- const model = new GoalModel(tx, ctx.userId, ctx.workspaceId);
+ const model = new GoalRepository(tx, ctx.userId, ctx.workspaceId);
const current = await model.lockById(goalId);
if (!current) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
// Only `start` launches a draft: it settles the creating run's planning
@@ -325,7 +325,7 @@ export const close = async (
// the close cannot start a Task after the scan below. The pause is the
// person's, so no measurement lifts it if the close is refused later on.
await ctx.db.transaction(async (db) => {
- const model = new GoalModel(db, ctx.userId, ctx.workspaceId);
+ const model = new GoalRepository(db, ctx.userId, ctx.workspaceId);
const current = await model.lockById(goalId);
// Only a goal that can still dispatch needs fencing.
if (!current || ['paused', 'achieved', 'failed', 'canceled'].includes(current.status)) return;
@@ -428,7 +428,7 @@ export const close = async (
// would leave that run spending on a goal reading "ended".
const reason = to === 'achieved' ? 'marked achieved by user' : 'canceled by user';
const goal = await ctx.db.transaction(async (db) => {
- const model = new GoalModel(db, ctx.userId, ctx.workspaceId);
+ const model = new GoalRepository(db, ctx.userId, ctx.workspaceId);
const current = await model.lockById(goalId);
if (!current) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
if (!['paused', 'achieved', 'failed', 'canceled'].includes(current.status)) {
diff --git a/apps/server/src/services/goal/GoalService/measurement.ts b/apps/server/src/services/goal/GoalService/measurement.ts
index 771baadf128..8efe6c9e377 100644
--- a/apps/server/src/services/goal/GoalService/measurement.ts
+++ b/apps/server/src/services/goal/GoalService/measurement.ts
@@ -8,8 +8,9 @@ import type {
} from '@lobechat/types';
import { TRPCError } from '@trpc/server';
-import { GoalModel } from '@/database/models/goal';
import { MetricModel } from '@/database/models/metric';
+import { GoalRepository } from '@/database/repositories/goal';
+import type { LobeChatDatabase } from '@/database/type';
import {
compareMetric,
@@ -18,6 +19,7 @@ import {
needsMetricCriteria,
} from '../decideNextMove';
import { GoalManagerService } from '../manager';
+import { GoalSubscriptionService } from '../subscriptions';
import { GoalSupervisorService } from '../supervisor';
import { GoalWaitService } from '../wait';
import type { GoalServiceContext } from './types';
@@ -238,7 +240,7 @@ const updateMetricCriteria = async (
// their list from the same snapshot would otherwise race, resurrecting a
// removed clause or dropping a newly declared one.
await ctx.db.transaction(async (tx) => {
- const model = new GoalModel(tx, ctx.userId, ctx.workspaceId);
+ const model = new GoalRepository(tx, ctx.userId, ctx.workspaceId);
const goal = await model.lockById(goalId);
if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
const next = edit(goal.config?.acceptance?.metrics ?? []);
@@ -338,9 +340,11 @@ export const setAcceptanceCriteria = async (
export const evaluateMetricCriteria = async (
ctx: GoalServiceContext,
graph: GoalGraphSnapshot,
+ /** Pass a transaction to hold the evidence locks until the caller commits. */
+ db: LobeChatDatabase = ctx.db,
): Promise<GoalMetricCriteriaState> => {
const declared = graph.goal.config?.acceptance?.metrics ?? [];
- const metricModel = new MetricModel(ctx.db, ctx.userId, ctx.workspaceId);
+ const metricModel = new MetricModel(db, ctx.userId, ctx.workspaceId);
// Two queries for the whole contract, not two per clause: this runs on
// every terminal tick, and a goal carrying a large acceptance payload would
@@ -360,10 +364,22 @@ export const evaluateMetricCriteria = async (
}),
);
+ // A clause bound to a Widget subscription reads that subscription's accepted
+ // observation (fresh, provenance-checked); an unbound clause keeps reading the
+ // series' latest point.
+ const subscriptions = await new GoalSubscriptionService(db, ctx.userId, ctx.workspaceId).criteria(
+ graph.goal.id,
+ declared.map((criterion) => criterion.key),
+ );
const criteria = declared.map((criterion) => {
const op = criterion.op ?? 'gte';
const seriesId = seriesByKey.get(criterion.key)?.id;
- const point = seriesId ? latestByMetricId.get(seriesId) : undefined;
+ const subscription = subscriptions.get(criterion.key);
+ const point = subscription?.bound
+ ? subscription.point
+ : seriesId
+ ? latestByMetricId.get(seriesId)
+ : undefined;
const value = point?.value ?? null;
return {
key: criterion.key,
diff --git a/apps/server/src/services/goal/GoalService/reads.ts b/apps/server/src/services/goal/GoalService/reads.ts
index 704334f5eba..d533cd7b9b2 100644
--- a/apps/server/src/services/goal/GoalService/reads.ts
+++ b/apps/server/src/services/goal/GoalService/reads.ts
@@ -24,7 +24,19 @@ export const graph = async (ctx: GoalServiceContext, goalId: string) => {
ctx.resolveSpend(graph),
new GoalReportStore(ctx.db, ctx.userId, ctx.workspaceId).state(graph),
]);
- return { ...graph, acceptances, assignees, deliveredAt, report, runHeartbeats, spend };
+ // Numeric clauses read through the Goal's Widget subscriptions when bound, so
+ // the page shows the same verdict the coordinator acts on.
+ const metricCriteria = await ctx.evaluateMetricCriteria(graph);
+ return {
+ ...graph,
+ acceptances,
+ assignees,
+ deliveredAt,
+ metricCriteria,
+ report,
+ runHeartbeats,
+ spend,
+ };
};
/**
diff --git a/apps/server/src/services/goal/GoalService/rollout.ts b/apps/server/src/services/goal/GoalService/rollout.ts
index 57c2f688011..704710c45c7 100644
--- a/apps/server/src/services/goal/GoalService/rollout.ts
+++ b/apps/server/src/services/goal/GoalService/rollout.ts
@@ -12,8 +12,8 @@ import {
import type { GoalGraphSnapshot, GoalTickResult } from '@lobechat/types';
import { type ExpertiseCarrier, ExpertiseModel } from '@/database/models/expertise';
-import { GoalModel } from '@/database/models/goal';
import { GoalGraphModel } from '@/database/models/goalGraph';
+import { GoalRepository } from '@/database/repositories/goal';
import { BatchPlanSkillService } from '../batchPlanSkill';
import { TERMINAL_NODE_STATUSES } from '../decideNextMove';
@@ -92,7 +92,7 @@ export const openPatternBreakGate = async (
// the rest find the break already open and reuse its gate instead of
// opening a second assay and decision that would re-park the goal later.
const claim = await ctx.db.transaction(async (tx) => {
- const goalModel = new GoalModel(tx, ctx.userId, ctx.workspaceId);
+ const goalModel = new GoalRepository(tx, ctx.userId, ctx.workspaceId);
const locked = await goalModel.lockById(goalId);
const current = locked?.config?.rolloutState;
if (!locked || !current) return undefined;
@@ -260,7 +260,7 @@ export const restartRolloutLoop = async (
: { type: 'user' };
const committed = await ctx.db.transaction(async (tx) => {
- const goalModel = new GoalModel(tx, ctx.userId, ctx.workspaceId);
+ const goalModel = new GoalRepository(tx, ctx.userId, ctx.workspaceId);
const current = (await goalModel.lockById(goalId))?.config?.rolloutState;
if (current?.phase !== 'pattern_break') return undefined;
const resolved = await new GoalGraphModel(tx, ctx.userId, ctx.workspaceId).resolveDecision(
diff --git a/apps/server/src/services/goal/GoalService/tick.ts b/apps/server/src/services/goal/GoalService/tick.ts
index 70f0b8e57db..ec9aa50dce5 100644
--- a/apps/server/src/services/goal/GoalService/tick.ts
+++ b/apps/server/src/services/goal/GoalService/tick.ts
@@ -15,6 +15,7 @@ import { GoalProbeDistill, needsProbeDistill } from '../probeDistill';
import { resolveMaxConcurrentTasks } from '../recoveryPolicy';
import { withoutGoalReport } from '../report';
import { GoalReportService } from '../reportService';
+import { GoalSubscriptionService } from '../subscriptions';
import { GoalSupervisorService } from '../supervisor';
import {
type GoalTickOptions,
@@ -87,6 +88,10 @@ export const tickOnce = async (
message: `Goal is a draft; start it with lh goal start ${goalId}`,
outcome: 'no_progress',
};
+ // An unmanaged Goal consumes its subscriptions' pending wakes here; a managed
+ // one hands them to its planner's turn.
+ if (!graph.goal.config?.manager)
+ await new GoalSubscriptionService(ctx.db, ctx.userId, ctx.workspaceId).acknowledge(goalId);
if (graph.goal.config?.manager) {
// The system's own planner leads whenever the Goal has one: a main Agent is
// the fallback for problems that planner cannot express, not a replacement
@@ -212,6 +217,17 @@ export const tickOnce = async (
ctx.workspaceId,
).reconsiderAcceptance(graph, move.message);
if (replanning) return observe(replanning);
+ const subscriptions = await new GoalSubscriptionService(
+ ctx.db,
+ ctx.userId,
+ ctx.workspaceId,
+ ).list(goalId);
+ if (subscriptions.some((entry) => entry.subscription.enabled)) {
+ // A measured shortfall is an observation wait, not a user's pause.
+ // The Widget schedule continues, and its durable pending effect or
+ // cyclic window scan requests the next coordinator evaluation.
+ return observe({ goalId, message: move.message, outcome: 'waiting_external' });
+ }
await ctx.setPauseReason(goalId, 'measured_acceptance');
await ctx.transitionStatus(graph.goal, 'paused', move.message);
effects.push({ type: 'goal_status', detail: 'paused' });
diff --git a/apps/server/src/services/goal/__tests__/subscriptionPolicy.test.ts b/apps/server/src/services/goal/__tests__/subscriptionPolicy.test.ts
new file mode 100644
index 00000000000..79685edc3c7
--- /dev/null
+++ b/apps/server/src/services/goal/__tests__/subscriptionPolicy.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ freshObservation,
+ subscriptionPolicySchema,
+ subscriptionWakes,
+} from '../subscriptionPolicy';
+
+const policy = { maxAgeMs: 1000, maxFutureSkewMs: 10 };
+const now = 100_000;
+
+describe('Widget subscription eligibility and planning cadence', () => {
+ it('rejects stale, future and invalid time observations at evaluation time', () => {
+ expect(freshObservation(new Date(now - 1000), policy, now)).toBe(true);
+ expect(freshObservation(new Date(now - 1001), policy, now)).toBe(false);
+ expect(freshObservation(new Date(now + 11), policy, now)).toBe(false);
+ expect(freshObservation('invalid', policy, now)).toBe(false);
+ expect(freshObservation(new Date(now), policy, now + 1001)).toBe(false);
+ });
+
+ it('does not plan per sample inside the observation window and wakes without arrivals at its boundary', () => {
+ const condition = { type: 'observation_window' as const, intervalMs: 1000 };
+ const lastWake = new Date(now).toISOString();
+ for (let n = 1; n < 1000; n += 10)
+ expect(subscriptionWakes(condition, 100, 0, lastWake, now + n)).toBe(false);
+ expect(subscriptionWakes(condition, undefined, undefined, lastWake, now + 1000)).toBe(true);
+ });
+
+ it('rounds thresholds to the authoritative numeric scale', () => {
+ expect(
+ subscriptionWakes(
+ { type: 'threshold', target: 0.1234567, op: 'eq' },
+ 0.123457,
+ undefined,
+ undefined,
+ now,
+ ),
+ ).toBe(true);
+ expect(
+ subscriptionWakes({ type: 'change', minimumAbsoluteChange: 2 }, 1, undefined, undefined, now),
+ ).toBe(false);
+ });
+
+ it('rejects invalid durable policies', () => {
+ for (const maxAgeMs of [0, -1, Infinity, NaN])
+ expect(
+ subscriptionPolicySchema.safeParse({
+ freshnessPolicy: { ...policy, maxAgeMs },
+ wakeCondition: { type: 'each_valid_run' },
+ }).success,
+ ).toBe(false);
+ expect(
+ subscriptionPolicySchema.safeParse({
+ freshnessPolicy: policy,
+ wakeCondition: { type: 'observation_window', intervalMs: 0 },
+ }).success,
+ ).toBe(false);
+ });
+});
diff --git a/apps/server/src/services/goal/__tests__/subscriptions.integration.test.ts b/apps/server/src/services/goal/__tests__/subscriptions.integration.test.ts
new file mode 100644
index 00000000000..7b1c64060ca
--- /dev/null
+++ b/apps/server/src/services/goal/__tests__/subscriptions.integration.test.ts
@@ -0,0 +1,585 @@
+// @vitest-environment node
+import { randomUUID } from 'node:crypto';
+
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq, sql } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { MetricModel } from '@/database/models/metric';
+import { WidgetModel } from '@/database/models/widget';
+import { GoalRepository } from '@/database/repositories/goal';
+import {
+ goals,
+ goalSubscriptions,
+ metricPoints,
+ users,
+ widgetRuns,
+ widgets,
+ workspaceMembers,
+ workspaces,
+} from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { executeWidgetRun } from '../../widget/executeRun';
+import { widgetRunLeaseMs } from '../../widget/lease';
+import { recordWidgetMetrics } from '../../widget/metrics';
+import { scheduleGoalAdvance } from '../scheduler';
+import { GoalSubscriptionService } from '../subscriptions';
+
+vi.mock('../scheduler', () => ({ scheduleGoalAdvance: vi.fn() }));
+
+let db: LobeChatDatabase;
+let owner: string;
+let other: string;
+let service: GoalSubscriptionService;
+let model: WidgetModel;
+const policy = {
+ freshnessPolicy: { maxAgeMs: 60_000, maxFutureSkewMs: 0 },
+ wakeCondition: { type: 'each_valid_run' as const },
+};
+
+beforeEach(async () => {
+ db = await getTestDB();
+ owner = `subscription-${randomUUID()}`;
+ other = `subscription-${randomUUID()}`;
+ await db.insert(users).values([{ id: owner }, { id: other }]);
+ service = new GoalSubscriptionService(db, owner);
+ model = new WidgetModel(db, owner);
+});
+afterEach(async () => {
+ await db.delete(users).where(sql`${users.id} IN (${owner}, ${other})`);
+ vi.restoreAllMocks();
+});
+
+const fixture = async () => {
+ const widget = await model.create({
+ title: 'Authoritative collection',
+ schedulePattern: '* * * * *',
+ });
+ const version = await model.createVersion(widget.id, {
+ outputType: 'stat',
+ runtime: 'node',
+ script: 'console.log(JSON.stringify({type:"stat",value:7}))',
+ sourceType: 'agent',
+ });
+ await model.publishVersion(widget.id, version!.id);
+ const run = await model.startRun(widget.id, { trigger: 'manual' });
+ await executeWidgetRun(
+ db,
+ { run: run!, widget, version: version! },
+ {
+ runner: {
+ run: async () => ({
+ durationMs: 1,
+ exitCode: 0,
+ stderr: '',
+ stdout: '{"type":"stat","value":7}',
+ timedOut: false,
+ }),
+ },
+ },
+ );
+ const metric = await new MetricModel(db, owner).findByKey('widget', widget.id, 'value');
+ const [goal] = await db
+ .insert(goals)
+ .values({
+ userId: owner,
+ title: 'Collection goal',
+ status: 'running',
+ config: { acceptance: { metrics: [{ key: 'followers', target: 8 }] } },
+ })
+ .returning();
+ const sub = await service.bind({
+ ...policy,
+ goalId: goal.id,
+ widgetId: widget.id,
+ metricId: metric!.id,
+ criterionKey: 'followers',
+ confirmedVersionId: version!.id,
+ confirmedContentHash: version!.contentHash,
+ });
+ const enabled = await service.update({
+ ...policy,
+ id: sub.id,
+ bindingRevision: sub.bindingRevision,
+ enabled: true,
+ });
+ return { widget, version: version!, metric: metric!, goal, sub: enabled };
+};
+const reserve = async (f: Awaited<ReturnType<typeof fixture>>) =>
+ (await model.startRun(f.widget.id, { trigger: 'manual' }))!;
+const finish = async (
+ f: Awaited<ReturnType<typeof fixture>>,
+ run: Awaited<ReturnType<typeof reserve>>,
+ status: 'succeeded' | 'failed' | 'timeout' | 'partial' = 'succeeded',
+ value = 8,
+) =>
+ WidgetModel.finishRun(
+ db,
+ run.id,
+ {
+ status,
+ output: { type: 'stat', value, ...(status === 'partial' && { meta: { complete: false } }) },
+ },
+ async (tx, completed) => {
+ await recordWidgetMetrics(tx as unknown as LobeChatDatabase, f.widget, {
+ runId: run.id,
+ manifest: f.version.manifest,
+ observedAt: completed.finishedAt!,
+ output: { type: 'stat', value },
+ });
+ },
+ );
+
+describe('durable Widget to Goal subscriptions', () => {
+ it('defaults disabled, rejects foreign owners and duplicate criterion mapping', async () => {
+ const f = await fixture();
+ await expect(new GoalSubscriptionService(db, other).list(f.goal.id)).rejects.toThrow();
+ await expect(
+ service.bind({
+ ...policy,
+ goalId: f.goal.id,
+ widgetId: f.widget.id,
+ metricId: null,
+ criterionKey: 'followers',
+ confirmedVersionId: f.version.id,
+ confirmedContentHash: f.version.contentHash,
+ }),
+ ).rejects.toThrow();
+ const result = await service.bind({
+ ...policy,
+ goalId: f.goal.id,
+ widgetId: f.widget.id,
+ metricId: null,
+ confirmedVersionId: f.version.id,
+ confirmedContentHash: f.version.contentHash,
+ });
+ expect(result.enabled).toBe(false);
+ expect((await service.criterion(f.goal.id, 'followers')).point).toBeUndefined();
+ });
+
+ it('persists early observations, dedupes duplicate hints, stops at running barriers and reconciles missed completions after restart', async () => {
+ const f = await fixture();
+ const early = await reserve(f);
+ await service.consume(f.sub.id); // early hint while producer still running
+ expect((await service.criterion(f.goal.id, 'followers')).point).toBeUndefined();
+ await finish(f, early);
+ await service.consume(f.sub.id);
+ const first = (await service.list(f.goal.id))[0].subscription.cursor;
+ expect(first.pendingWake).toBe(true);
+ await service.consume(f.sub.id); // duplicate
+ expect((await service.list(f.goal.id))[0].subscription.cursor).toEqual(first);
+ const slow = await reserve(f);
+ const fast = await reserve(f);
+ await finish(f, fast, 'succeeded', 9);
+ await service.consume(f.sub.id); // out-of-order finalization cannot skip slow
+ expect((await service.list(f.goal.id))[0].subscription.cursor.run?.runId).toBe(early.id);
+ await finish(f, slow, 'failed');
+ await GoalSubscriptionService.reconcile(db); // fresh instance, lost notification
+ expect((await service.list(f.goal.id))[0].subscription.cursor.run?.runId).toBe(fast.id);
+ expect((await service.criterion(f.goal.id, 'followers')).point?.value).toBe(9);
+ });
+
+ it.each(['deleted', 'republished'] as const)(
+ 'isolates a %s source during Goal scans and still consumes healthy bindings',
+ async (unavailable) => {
+ const invalid = await fixture();
+ const healthy = await fixture();
+ await db
+ .update(goalSubscriptions)
+ .set({
+ goalId: invalid.goal.id,
+ binding: { ...healthy.sub.binding, criterionKey: undefined },
+ })
+ .where(eq(goalSubscriptions.id, healthy.sub.id));
+ const run = await reserve(healthy);
+ await finish(healthy, run);
+ if (unavailable === 'deleted') {
+ await db.update(widgets).set({ isDeleted: true }).where(eq(widgets.id, invalid.widget.id));
+ } else {
+ const version = await model.createVersion(invalid.widget.id, {
+ outputType: 'stat',
+ runtime: 'node',
+ sourceType: 'agent',
+ script: 'console.log(JSON.stringify({type:"stat",value:999}))',
+ });
+ await model.publishVersion(invalid.widget.id, version!.id);
+ }
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ await expect(GoalSubscriptionService.forGoal(db, invalid.goal.id)).resolves.toBeUndefined();
+ expect(error).toHaveBeenCalled();
+ expect((await service.criterion(invalid.goal.id, 'followers')).point).toBeUndefined();
+ const [stored] = await db
+ .select()
+ .from(goalSubscriptions)
+ .where(eq(goalSubscriptions.id, healthy.sub.id));
+ expect(stored.cursor.run?.runId).toBe(run.id);
+ },
+ );
+
+ it('passes an abandoned running preview without accepting it or blocking collection', async () => {
+ const f = await fixture();
+ const preview = (await model.startRun(f.widget.id, { trigger: 'preview' }))!;
+ const run = await reserve(f);
+ await finish(f, run, 'succeeded', 9);
+ await service.consume(f.sub.id);
+ expect((await service.criterion(f.goal.id, 'followers')).point?.value).toBe(9);
+ expect((await service.list(f.goal.id))[0].subscription.cursor.run?.runId).toBe(run.id);
+ const [storedPreview] = await db.select().from(widgetRuns).where(eq(widgetRuns.id, preview.id));
+ expect(storedPreview.status).toBe('running');
+ });
+
+ it('expires abandoned manual reservations, preserves live barriers and rejects late completion', async () => {
+ const f = await fixture();
+ const abandoned = await reserve(f);
+ const later = await reserve(f);
+ await finish(f, later, 'succeeded', 9);
+ await service.consume(f.sub.id);
+ // An active manual worker still owns the contiguous-prefix barrier.
+ expect((await service.criterion(f.goal.id, 'followers')).point).toBeUndefined();
+ const expiredAt = new Date(Date.now() - widgetRunLeaseMs(f.version.manifest) - 1000);
+ await db
+ .update(widgetRuns)
+ .set({ startedAt: expiredAt })
+ .where(eq(widgetRuns.id, abandoned.id));
+ // Restart / missing-notification recovery uses the durable scanner, not a new execution.
+ await GoalSubscriptionService.reconcile(db);
+ const [expired] = await db.select().from(widgetRuns).where(eq(widgetRuns.id, abandoned.id));
+ expect(expired.status).toBe('timeout');
+ expect(expired.error?.code).toBe('MANUAL_RUN_LEASE_EXPIRED');
+ expect((await service.criterion(f.goal.id, 'followers')).point?.value).toBe(9);
+ expect((await service.list(f.goal.id))[0].subscription.cursor.run?.runId).toBe(later.id);
+ await expect(
+ WidgetModel.finishRun(db, abandoned.id, {
+ expectedStartedAt: expiredAt,
+ status: 'succeeded',
+ output: { type: 'stat', value: 999 },
+ }),
+ ).resolves.toBeUndefined();
+ await service.consume(f.sub.id);
+ expect((await service.criterion(f.goal.id, 'followers')).point?.value).toBe(9);
+ });
+
+ it.each([false, true])('detects change with split consumption = %s', async (split) => {
+ const f = await fixture();
+ await service.update({
+ ...policy,
+ id: f.sub.id,
+ bindingRevision: f.sub.bindingRevision,
+ enabled: true,
+ wakeCondition: { type: 'change', minimumAbsoluteChange: 5 },
+ });
+ const first = await reserve(f);
+ await finish(f, first, 'succeeded', 0);
+ if (split) await service.consume(f.sub.id);
+ const second = await reserve(f);
+ await finish(f, second, 'succeeded', 10);
+ await service.consume(f.sub.id);
+ const cursor = (await service.list(f.goal.id))[0].subscription.cursor;
+ expect(cursor.pendingWake).toBe(true);
+ expect(cursor.run?.runId).toBe(second.id);
+ expect((await service.criterion(f.goal.id, 'followers')).point?.value).toBe(10);
+ });
+
+ it.each(['failed', 'timeout', 'partial'] as const)(
+ 'does not achieve from %s sampling',
+ async (status) => {
+ const f = await fixture();
+ const run = await reserve(f);
+ await finish(f, run, status, 999);
+ await service.consume(f.sub.id);
+ expect((await service.criterion(f.goal.id, 'followers')).point).toBeUndefined();
+ expect((await service.list(f.goal.id))[0].latestRun?.status).toBe(status);
+ },
+ );
+
+ it('rolls back run success and metric points on publication failure', async () => {
+ const f = await fixture();
+ const run = await reserve(f);
+ await expect(
+ WidgetModel.finishRun(
+ db,
+ run.id,
+ { status: 'succeeded', output: { type: 'stat', value: 999 } },
+ async (tx, completed) => {
+ await recordWidgetMetrics(tx as unknown as LobeChatDatabase, f.widget, {
+ runId: run.id,
+ observedAt: completed.finishedAt!,
+ output: { type: 'stat', value: 999 },
+ });
+ throw new Error('storage failed');
+ },
+ ),
+ ).rejects.toThrow('storage failed');
+ const [stored] = await db.select().from(widgetRuns).where(eq(widgetRuns.id, run.id));
+ expect(stored.status).toBe('running');
+ expect(
+ await db.select().from(metricPoints).where(eq(metricPoints.actorId, run.id)),
+ ).toHaveLength(0);
+ await service.consume(f.sub.id);
+ expect((await service.criterion(f.goal.id, 'followers')).point).toBeUndefined();
+ });
+
+ it('re-evaluates freshness at acceptance and refuses future, stale or older observations', async () => {
+ const f = await fixture();
+ const run = await reserve(f);
+ await finish(f, run);
+ await service.consume(f.sub.id);
+ const point = (await service.criterion(f.goal.id, 'followers')).point!;
+ expect(point.value).toBe(8);
+ await db
+ .update(metricPoints)
+ .set({ observedAt: new Date(Date.now() - 120_000) })
+ .where(eq(metricPoints.id, point.id));
+ expect((await service.criterion(f.goal.id, 'followers')).point).toBeUndefined();
+ await db
+ .update(metricPoints)
+ .set({ observedAt: new Date(Date.now() + 120_000) })
+ .where(eq(metricPoints.id, point.id));
+ expect((await service.criterion(f.goal.id, 'followers')).point).toBeUndefined();
+ });
+
+ it.each(['paused', 'canceled', 'achieved'] as const)(
+ 'atomically stops %s Goal consumption while shared Widget collection continues',
+ async (status) => {
+ const f = await fixture();
+ const second = await db
+ .insert(goals)
+ .values({ userId: owner, title: 'Other Goal', status: 'running' })
+ .returning();
+ const otherBinding = await service.bind({
+ ...policy,
+ goalId: second[0].id,
+ widgetId: f.widget.id,
+ metricId: f.metric.id,
+ confirmedVersionId: f.version.id,
+ confirmedContentHash: f.version.contentHash,
+ });
+ await service.update({ ...policy, id: otherBinding.id, bindingRevision: 1, enabled: true });
+ await new GoalRepository(db, owner).updateStatus(f.goal.id, status);
+ const stopped = (await service.list(f.goal.id))[0].subscription;
+ expect(stopped.enabled).toBe(false);
+ expect(stopped.cursor.pendingWake).toBeUndefined();
+ expect(stopped.bindingRevision).toBe(f.sub.bindingRevision + 1);
+ const run = await reserve(f);
+ await finish(f, run);
+ await GoalSubscriptionService.forWidget(db, f.widget.id);
+ expect((await service.list(second[0].id))[0].subscription.cursor.run?.runId).toBe(run.id);
+ const [stillShared] = await db.select().from(widgets).where(eq(widgets.id, f.widget.id));
+ expect(stillShared.schedulePattern).toBe('* * * * *');
+ },
+ );
+
+ it('keeps bindings through a review gate and consumes once the Goal runs again', async () => {
+ const f = await fixture();
+ await db.update(goals).set({ status: 'review' }).where(eq(goals.id, f.goal.id));
+ const run = await reserve(f);
+ await finish(f, run, 'succeeded', 9);
+ await GoalSubscriptionService.forWidget(db, f.widget.id);
+ const gated = (await service.list(f.goal.id))[0].subscription;
+ expect(gated.enabled).toBe(true);
+ expect(gated.bindingRevision).toBe(f.sub.bindingRevision);
+ await db.update(goals).set({ status: 'running' }).where(eq(goals.id, f.goal.id));
+ await service.consume(f.sub.id, f.sub.bindingRevision);
+ expect((await service.criterion(f.goal.id, 'followers')).point?.value).toBe(9);
+ });
+
+ it('explicit rebind fences old callbacks and establishes a non-replay baseline', async () => {
+ const f = await fixture();
+ const run = await reserve(f);
+ await finish(f, run);
+ await service.consume(f.sub.id);
+ const rebound = await service.bind(
+ {
+ ...policy,
+ goalId: f.goal.id,
+ widgetId: f.widget.id,
+ metricId: f.metric.id,
+ criterionKey: 'followers',
+ confirmedVersionId: f.version.id,
+ confirmedContentHash: f.version.contentHash,
+ },
+ { id: f.sub.id, bindingRevision: f.sub.bindingRevision },
+ );
+ expect(rebound.enabled).toBe(false);
+ expect(rebound.cursor.observation).toBeUndefined();
+ await service.consume(rebound.id, f.sub.bindingRevision);
+ expect((await service.criterion(f.goal.id, 'followers')).point).toBeUndefined();
+ await expect(
+ service.update({
+ ...policy,
+ id: rebound.id,
+ bindingRevision: f.sub.bindingRevision,
+ enabled: true,
+ }),
+ ).rejects.toThrow('Binding revision');
+ await expect(
+ new MetricModel(db, owner).update(f.metric.id, { unit: 'different account' }),
+ ).rejects.toThrow('immutable');
+ });
+
+ it('preserves PostgreSQL submillisecond tuples and does not regress progress from older points', async () => {
+ const f = await fixture();
+ const run = await reserve(f);
+ await finish(f, run);
+ await db.execute(
+ sql`UPDATE widget_runs SET created_at = '2100-01-01T00:00:00.123456Z'::timestamptz WHERE id = ${run.id}::uuid`,
+ );
+ await db.execute(
+ sql`UPDATE metric_points SET observed_at = clock_timestamp() - interval '10 seconds' WHERE actor_id = ${run.id}`,
+ );
+ await service.consume(f.sub.id);
+ const cursor = (await service.list(f.goal.id))[0].subscription.cursor;
+ expect(cursor.run?.createdAt).toBe('2100-01-01T00:00:00.123456Z');
+ const later = await reserve(f);
+ await finish(f, later, 'succeeded', 1);
+ await db.execute(
+ sql`UPDATE widget_runs SET created_at = '2100-01-01T00:00:00.123457Z'::timestamptz WHERE id = ${later.id}::uuid`,
+ );
+ await db.execute(
+ sql`UPDATE metric_points SET observed_at = clock_timestamp() - interval '20 seconds' WHERE actor_id = ${later.id}`,
+ );
+ await service.consume(f.sub.id);
+ expect((await service.criterion(f.goal.id, 'followers')).point?.value).toBe(8);
+ expect((await service.list(f.goal.id))[0].subscription.cursor.run?.runId).toBe(later.id);
+ });
+
+ it('rejects preview runs and soft-deleted source access after binding', async () => {
+ const f = await fixture();
+ const preview = (await model.startRun(f.widget.id, { trigger: 'preview' }))!;
+ await finish(f, preview, 'succeeded', 999);
+ await service.consume(f.sub.id);
+ expect((await service.criterion(f.goal.id, 'followers')).point).toBeUndefined();
+ const run = await reserve(f);
+ await finish(f, run);
+ await service.consume(f.sub.id);
+ await db.update(widgets).set({ isDeleted: true }).where(eq(widgets.id, f.widget.id));
+ expect((await service.criterion(f.goal.id, 'followers')).point).toBeUndefined();
+ expect((await service.list(f.goal.id))[0].sourceAvailable).toBe(false);
+ });
+
+ it('rejects changed script/account semantics on the existing metric key', async () => {
+ const f = await fixture();
+ const changed = await model.createVersion(f.widget.id, {
+ outputType: 'stat',
+ runtime: 'node',
+ sourceType: 'agent',
+ script: 'console.log(JSON.stringify({type:"stat",value:999}))',
+ });
+ await model.publishVersion(f.widget.id, changed!.id);
+ expect((await service.criterion(f.goal.id, 'followers')).point).toBeUndefined();
+ const run = await reserve(f);
+ const failed = await executeWidgetRun(
+ db,
+ { run, widget: f.widget, version: changed! },
+ {
+ runner: {
+ run: async () => ({
+ durationMs: 1,
+ exitCode: 0,
+ stderr: '',
+ stdout: '{"type":"stat","value":999}',
+ timedOut: false,
+ }),
+ },
+ },
+ );
+ expect(failed?.status).toBe('failed');
+ expect(failed?.error?.code).toBe('METRIC_PUBLICATION_FAILED');
+ expect(
+ await db.select().from(metricPoints).where(eq(metricPoints.actorId, run.id)),
+ ).toHaveLength(0);
+ });
+
+ it('buffers frequent samples and atomically commits a retryable current-wait wake', async () => {
+ const f = await fixture();
+ const state = {
+ consumed: true,
+ token: 'current-wait',
+ topicId: 'tpc_test',
+ turns: 1,
+ snapshot: 'test',
+ startedAt: new Date().toISOString(),
+ wait: { until: new Date(Date.now() + 120_000).toISOString() },
+ };
+ await db
+ .update(goals)
+ .set({ config: { ...f.goal.config, manager: {}, managerState: state } })
+ .where(eq(goals.id, f.goal.id));
+ const run = await reserve(f);
+ await finish(f, run);
+ await service.consume(f.sub.id);
+ let [stored] = await db.select().from(goals).where(eq(goals.id, f.goal.id));
+ expect(stored.config?.managerState?.wait?.wake).toBeUndefined();
+ const cursor = (await service.list(f.goal.id))[0].subscription.cursor;
+ expect(cursor.pendingWake).toBe(true);
+ await db
+ .update(goalSubscriptions)
+ .set({ cursor: { ...cursor, lastWakeAt: new Date(Date.now() - 61_000).toISOString() } })
+ .where(eq(goalSubscriptions.id, f.sub.id));
+ vi.mocked(scheduleGoalAdvance).mockRejectedValueOnce(new Error('lost dispatch'));
+ await expect(service.consume(f.sub.id)).rejects.toThrow('lost dispatch');
+ [stored] = await db.select().from(goals).where(eq(goals.id, f.goal.id));
+ const wake = stored.config?.managerState?.wait?.wake;
+ expect(wake?.eventId).toContain(`:${f.sub.bindingRevision}:${run.id}`);
+ await new GoalSubscriptionService(db, owner).consume(f.sub.id); // restart / retry
+ [stored] = await db.select().from(goals).where(eq(goals.id, f.goal.id));
+ expect(stored.config?.managerState?.wait?.wake).toEqual(wake);
+ });
+
+ it('creates an observation-window fallback wake without new samples', async () => {
+ const f = await fixture();
+ const row = await service.update({
+ ...policy,
+ id: f.sub.id,
+ bindingRevision: f.sub.bindingRevision,
+ enabled: true,
+ wakeCondition: { type: 'observation_window', intervalMs: 1000 },
+ });
+ await db
+ .update(goalSubscriptions)
+ .set({ cursor: { ...row.cursor, lastWakeAt: new Date(Date.now() - 2000).toISOString() } })
+ .where(eq(goalSubscriptions.id, row.id));
+ await db
+ .update(goals)
+ .set({
+ config: {
+ ...f.goal.config,
+ manager: {},
+ managerState: {
+ consumed: true,
+ token: 'window',
+ topicId: 'tpc_test',
+ turns: 1,
+ snapshot: 'test',
+ startedAt: new Date().toISOString(),
+ wait: { until: new Date(Date.now() + 120_000).toISOString() },
+ },
+ },
+ })
+ .where(eq(goals.id, f.goal.id));
+ await service.consume(row.id, row.bindingRevision);
+ const [goal] = await db.select().from(goals).where(eq(goals.id, f.goal.id));
+ expect(goal.config?.managerState?.wait?.wake?.cause).toBe('event');
+ expect((await service.criterion(f.goal.id, 'followers')).point).toBeUndefined();
+ });
+
+ it('checks workspace membership and both actor and Goal owner read access', async () => {
+ const ws = `ws-${randomUUID()}`;
+ await db
+ .insert(workspaces)
+ .values({ id: ws, name: 'Subscriptions', slug: ws, primaryOwnerId: owner });
+ try {
+ await db.insert(workspaceMembers).values({ workspaceId: ws, userId: owner, role: 'owner' });
+ const [goal] = await db
+ .insert(goals)
+ .values({ userId: owner, workspaceId: ws, title: 'Workspace Goal', status: 'running' })
+ .returning();
+ await expect(new GoalSubscriptionService(db, other, ws).list(goal.id)).rejects.toThrow();
+ await db.insert(workspaceMembers).values({ workspaceId: ws, userId: other, role: 'member' });
+ expect(await new GoalSubscriptionService(db, other, ws).list(goal.id)).toEqual([]);
+ } finally {
+ await db.delete(workspaces).where(eq(workspaces.id, ws));
+ }
+ });
+});
diff --git a/apps/server/src/services/goal/assignment.ts b/apps/server/src/services/goal/assignment.ts
index 86c907ee1c0..8cbcc968d55 100644
--- a/apps/server/src/services/goal/assignment.ts
+++ b/apps/server/src/services/goal/assignment.ts
@@ -4,9 +4,9 @@ import { TRPCError } from '@trpc/server';
import { and, eq, inArray, notInArray, sql } from 'drizzle-orm';
import { AgentModel } from '@/database/models/agent';
-import { GoalModel } from '@/database/models/goal';
import { GoalGraphModel } from '@/database/models/goalGraph';
import { TaskModel } from '@/database/models/task';
+import { GoalRepository } from '@/database/repositories/goal';
import { agents, tasks } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
import { assertAgentUsableBy } from '@/database/utils/agent-access';
@@ -66,7 +66,7 @@ const pinsModel = (config: unknown, model?: Partial<ModelConfig>) => {
*/
export class GoalAssignmentService {
private agentModel: AgentModel;
- private goalModel: GoalModel;
+ private goalModel: GoalRepository;
private graphModel: GoalGraphModel;
private taskModel: TaskModel;
@@ -76,7 +76,7 @@ export class GoalAssignmentService {
private workspaceId?: string,
) {
this.agentModel = new AgentModel(db, userId, workspaceId);
- this.goalModel = new GoalModel(db, userId, workspaceId);
+ this.goalModel = new GoalRepository(db, userId, workspaceId);
this.graphModel = new GoalGraphModel(db, userId, workspaceId);
this.taskModel = new TaskModel(db, userId, workspaceId);
}
@@ -189,12 +189,14 @@ export class GoalAssignmentService {
): Promise<GoalItem> => {
if (modelConfig) {
// The owner never changes, so the availability check needs no lock.
- const owner = await new GoalModel(this.db, this.userId, this.workspaceId).findById(goalId);
+ const owner = await new GoalRepository(this.db, this.userId, this.workspaceId).findById(
+ goalId,
+ );
if (!owner) throw goalNotFound();
await assertGoalModelRunnable(this.db, owner, slot, modelConfig);
}
return this.db.transaction(async (tx) => {
- const model = new GoalModel(tx, this.userId, this.workspaceId);
+ const model = new GoalRepository(tx, this.userId, this.workspaceId);
const current = await model.lockById(goalId);
if (!current) throw goalNotFound();
// Reads inside the transaction go through it, not around it.
@@ -291,7 +293,7 @@ export class GoalAssignmentService {
*/
handOver = (
goalId: string,
- write: (model: GoalModel, current: GoalItem) => Promise<GoalItem | undefined>,
+ write: (model: GoalRepository, current: GoalItem) => Promise<GoalItem | undefined>,
/**
* Moves the goal's Tasks along with the handoff, under the same lock, so a
* Task-model write or a coordinator claim cannot land between the handoff
@@ -304,7 +306,7 @@ export class GoalAssignmentService {
) => Promise<string[]>,
): Promise<{ goal: GoalItem; movedTaskIds: string[]; previous: GoalItem }> =>
this.db.transaction(async (tx) => {
- const model = new GoalModel(tx, this.userId, this.workspaceId);
+ const model = new GoalRepository(tx, this.userId, this.workspaceId);
const previous = await model.lockById(goalId);
if (!previous) throw goalNotFound();
const updated = await write(model, previous);
@@ -493,7 +495,7 @@ export class GoalAssignmentService {
*/
syncBoundTask = (goalId: string, taskId: string) =>
this.db.transaction(async (tx) => {
- const current = await new GoalModel(tx, this.userId, this.workspaceId).lockById(goalId);
+ const current = await new GoalRepository(tx, this.userId, this.workspaceId).lockById(goalId);
if (!current) return;
const scoped = new GoalAssignmentService(tx, this.userId, this.workspaceId);
const task = await scoped.taskModelFor(current).findById(taskId);
diff --git a/apps/server/src/services/goal/manager/conversation.ts b/apps/server/src/services/goal/manager/conversation.ts
index 2ac0b9d905c..e7410797db6 100644
--- a/apps/server/src/services/goal/manager/conversation.ts
+++ b/apps/server/src/services/goal/manager/conversation.ts
@@ -6,9 +6,9 @@ import { eq, sql } from 'drizzle-orm';
import { TopicTrigger } from '@/const/topic';
import { AgentOperationModel } from '@/database/models/agentOperation';
-import { GoalModel } from '@/database/models/goal';
import { GoalGraphModel } from '@/database/models/goalGraph';
import { TopicModel } from '@/database/models/topic';
+import { GoalRepository } from '@/database/repositories/goal';
import { goals } from '@/database/schemas/goal';
import { TERMINAL_GOAL_STATUSES as finishedGoalStatuses } from '../goalTraceRecorder';
@@ -40,7 +40,7 @@ export const adoptConversationTurn = async (
run: { operationId: string; topicId: string },
) =>
ctx.db.transaction(async (db) => {
- const model = new GoalModel(db, ctx.userId, ctx.workspaceId);
+ const model = new GoalRepository(db, ctx.userId, ctx.workspaceId);
const goal = await model.lockById(goalId);
if (!goal?.config?.manager) throw new Error('Goal has no main Agent policy to adopt a turn');
if (goal.config.managerState) throw new Error('Goal already has a planning turn');
@@ -117,7 +117,7 @@ export const moveConversationTo = async (
agentId: string,
): Promise<GoalManagerState | undefined> =>
ctx.db.transaction(async (db) => {
- const model = new GoalModel(db, ctx.userId, ctx.workspaceId);
+ const model = new GoalRepository(db, ctx.userId, ctx.workspaceId);
const goal = await model.lockById(goalId);
const state = goal?.config?.managerState;
if (!goal || !state || !state.consumed || goal.agentId !== agentId) return;
@@ -170,7 +170,7 @@ export const bindTopic = async (
turnToken?: string;
}> =>
ctx.db.transaction(async (db) => {
- const model = new GoalModel(db, ctx.userId, ctx.workspaceId);
+ const model = new GoalRepository(db, ctx.userId, ctx.workspaceId);
const goal = await model.lockById(goalId);
if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
if (finishedGoalStatuses.has(goal.status))
diff --git a/apps/server/src/services/goal/manager/index.ts b/apps/server/src/services/goal/manager/index.ts
index 1bb1b884081..72bb288e331 100644
--- a/apps/server/src/services/goal/manager/index.ts
+++ b/apps/server/src/services/goal/manager/index.ts
@@ -13,11 +13,11 @@ import { TRPCError } from '@trpc/server';
import { TopicTrigger } from '@/const/topic';
import { AgentOperationModel } from '@/database/models/agentOperation';
-import { GoalModel } from '@/database/models/goal';
import { GoalGraphModel } from '@/database/models/goalGraph';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
import { TopicModel } from '@/database/models/topic';
+import { GoalRepository } from '@/database/repositories/goal';
import type { LobeChatDatabase } from '@/database/type';
import { AiAgentService } from '@/server/services/aiAgent';
import { readDeviceDispatchRoute } from '@/server/services/aiAgent/helpers/heteroErrors';
@@ -126,7 +126,7 @@ export class GoalManagerService {
private pause = async (goalId: string, message: string): Promise<GoalTickResult> => {
await this.db.transaction(async (db) => {
- const model = new GoalModel(db, this.userId, this.workspaceId);
+ const model = new GoalRepository(db, this.userId, this.workspaceId);
const goal = await model.lockById(goalId);
if (goal && activeStatuses.has(goal.status)) {
await model.updateStatus(goalId, 'paused');
@@ -242,7 +242,9 @@ export class GoalManagerService {
if (!this.eligible(graph)) return null;
if (!graph.goal.config?.managerState) return this.startTurn(graph, undefined, reason);
const changed = await this.db.transaction(async (db) => {
- const goal = await new GoalModel(db, this.userId, this.workspaceId).lockById(graph.goal.id);
+ const goal = await new GoalRepository(db, this.userId, this.workspaceId).lockById(
+ graph.goal.id,
+ );
const state = goal?.config?.managerState;
if (
!goal ||
@@ -330,7 +332,7 @@ export class GoalManagerService {
return this.wait(goal.id, 'Waiting for main Agent CLI planning turn');
}
const failed = await this.db.transaction(async (db) => {
- const fresh = await new GoalModel(db, this.userId, this.workspaceId).lockById(goal.id);
+ const fresh = await new GoalRepository(db, this.userId, this.workspaceId).lockById(goal.id);
const current = fresh?.config?.managerState;
if (current?.token !== state.token || current.consumed) return;
const settled: GoalManagerState = {
@@ -359,7 +361,10 @@ export class GoalManagerService {
await saveManagerState(db, goal.id, { ...settled, ...cleared });
const message = `${decision.reason}. Resume with: lh goal resume ${goal.id}`;
if (activeStatuses.has(fresh!.status)) {
- await new GoalModel(db, this.userId, this.workspaceId).updateStatus(goal.id, 'paused');
+ await new GoalRepository(db, this.userId, this.workspaceId).updateStatus(
+ goal.id,
+ 'paused',
+ );
await this.graph(db).recordGoalStatus(goal.id, fresh!.status, 'paused', message);
}
return { ...decision, reason: message };
@@ -497,7 +502,7 @@ export class GoalManagerService {
message: `Main Agent turn deferred until ${state.retryAfter} after a failed turn`,
};
const claimed = await this.db.transaction(async (db) => {
- const model = new GoalModel(db, this.userId, this.workspaceId);
+ const model = new GoalRepository(db, this.userId, this.workspaceId);
const fresh = await model.lockById(goal.id);
// `managerSnapshot` does not cover the goal agent, so a handoff landing
// between the caller's graph read and this lock would otherwise dispatch
@@ -641,7 +646,7 @@ export class GoalManagerService {
}),
});
await this.db.transaction(async (db) => {
- const fresh = await new GoalModel(db, this.userId, this.workspaceId).lockById(goal.id);
+ const fresh = await new GoalRepository(db, this.userId, this.workspaceId).lockById(goal.id);
if (fresh?.config?.managerState?.token === claimed.token) {
await saveManagerState(db, goal.id, {
...fresh.config.managerState,
@@ -683,7 +688,7 @@ export class GoalManagerService {
*/
confirmTurnExit = async (goalId: string) =>
this.db.transaction(async (db) => {
- const fresh = await new GoalModel(db, this.userId, this.workspaceId).lockById(goalId);
+ const fresh = await new GoalRepository(db, this.userId, this.workspaceId).lockById(goalId);
const state = fresh?.config?.managerState;
if (!state || state.consumed) return false;
const operation = await turnOperation(
@@ -705,7 +710,7 @@ export class GoalManagerService {
*/
private recordUnstartedDispatch = async (goalId: string, token: string, settle: boolean) =>
this.db.transaction(async (db) => {
- const fresh = await new GoalModel(db, this.userId, this.workspaceId).lockById(goalId);
+ const fresh = await new GoalRepository(db, this.userId, this.workspaceId).lockById(goalId);
if (fresh?.config?.managerState?.token !== token) return false;
await saveManagerState(db, goalId, {
...fresh.config.managerState,
diff --git a/apps/server/src/services/goal/manager/submit.ts b/apps/server/src/services/goal/manager/submit.ts
index e8542d200be..8bfbd93e732 100644
--- a/apps/server/src/services/goal/manager/submit.ts
+++ b/apps/server/src/services/goal/manager/submit.ts
@@ -4,10 +4,10 @@ import { TRPCError } from '@trpc/server';
import type { z } from 'zod';
import { AgentOperationModel } from '@/database/models/agentOperation';
-import { GoalModel } from '@/database/models/goal';
import { GoalGraphModel } from '@/database/models/goalGraph';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
+import { GoalRepository } from '@/database/repositories/goal';
import type { LobeChatDatabase } from '@/database/type';
import { GoalBriefService } from '../goalBriefs';
@@ -86,7 +86,7 @@ const declareBatch = async (
canarySize: plan.tasks.length,
createdByAgentId: agentId,
goalId: goal.id,
- goalModel: new GoalModel(db, ctx.userId, ctx.workspaceId),
+ goalModel: new GoalRepository(db, ctx.userId, ctx.workspaceId),
planSkillOwner: {
db,
goalTitle: goal.title,
@@ -117,7 +117,7 @@ export const submitPlan = async (
const plan = goalPlanSchema.parse(input);
const armed = plan.action === 'wait' ? GoalWaitService.arm(plan.until) : undefined;
const result = await ctx.db.transaction(async (db) => {
- const model = new GoalModel(db, ctx.userId, ctx.workspaceId);
+ const model = new GoalRepository(db, ctx.userId, ctx.workspaceId);
const goal = await model.lockById(goalId);
const state = goal?.config?.managerState;
if (!goal || !state)
diff --git a/apps/server/src/services/goal/probeDistill.ts b/apps/server/src/services/goal/probeDistill.ts
index a7f6cab7fa5..daba250a8d0 100644
--- a/apps/server/src/services/goal/probeDistill.ts
+++ b/apps/server/src/services/goal/probeDistill.ts
@@ -2,8 +2,8 @@ import { GOAL_COORDINATOR_ACTOR_ID } from '@lobechat/const/goal';
import type { GoalGraphSnapshot, GoalRolloutState, GoalTickResult } from '@lobechat/types';
import debug from 'debug';
-import { GoalModel } from '@/database/models/goal';
import { GoalGraphModel } from '@/database/models/goalGraph';
+import { GoalRepository } from '@/database/repositories/goal';
import type { LobeChatDatabase } from '@/database/type';
import { BatchPlanSkillService } from './batchPlanSkill';
@@ -87,7 +87,7 @@ export class GoalProbeDistill {
if (state.phase !== 'plan_distill') {
const entered = await this.db.transaction(async (tx) => {
- const goalModel = new GoalModel(tx, this.userId, this.workspaceId);
+ const goalModel = new GoalRepository(tx, this.userId, this.workspaceId);
const current = (await goalModel.lockById(goalId))?.config?.rolloutState;
if (
current?.phase !== 'probe' ||
@@ -143,7 +143,7 @@ export class GoalProbeDistill {
/** No main Agent can rewrite the plan: the gate judges the probes on it as written. */
private skip = async (goalId: string) =>
this.db.transaction(async (tx) => {
- const goalModel = new GoalModel(tx, this.userId, this.workspaceId);
+ const goalModel = new GoalRepository(tx, this.userId, this.workspaceId);
const current = (await goalModel.lockById(goalId))?.config?.rolloutState;
if (current?.phase !== 'plan_distill' || current.pendingDistill) return;
log('probe distill: no main Agent turn; judging the gate on the plan as written');
@@ -169,7 +169,7 @@ export class GoalProbeDistill {
const goalId = graph.goal.id;
const policy = graph.goal.config?.rollout;
const reopened = await this.db.transaction(async (tx) => {
- const goalModel = new GoalModel(tx, this.userId, this.workspaceId);
+ const goalModel = new GoalRepository(tx, this.userId, this.workspaceId);
const current = (await goalModel.lockById(goalId))?.config?.rolloutState;
// Another advance landed it first; what it decided is next either way.
if (current?.phase !== 'plan_distill' || !current.pendingDistill) return [];
diff --git a/apps/server/src/services/goal/releaseReview.ts b/apps/server/src/services/goal/releaseReview.ts
index 16b916e3bb9..62341221c62 100644
--- a/apps/server/src/services/goal/releaseReview.ts
+++ b/apps/server/src/services/goal/releaseReview.ts
@@ -19,8 +19,8 @@ import type {
import { TRPCError } from '@trpc/server';
import debug from 'debug';
-import { GoalModel } from '@/database/models/goal';
import { GoalGraphModel } from '@/database/models/goalGraph';
+import { GoalRepository } from '@/database/repositories/goal';
import type { LobeChatDatabase } from '@/database/type';
import { BatchPlanSkillService } from './batchPlanSkill';
@@ -190,7 +190,7 @@ export class GoalReleaseReview {
// Same claim as the pattern break: overlapping advances can both see the
// passed gate, and only the first may open the question.
const claim = await this.db.transaction(async (tx) => {
- const goalModel = new GoalModel(tx, this.userId, this.workspaceId);
+ const goalModel = new GoalRepository(tx, this.userId, this.workspaceId);
const locked = await goalModel.lockById(goalId);
const current = locked?.config?.rolloutState;
if (!locked || !current) return undefined;
@@ -298,7 +298,7 @@ export class GoalReleaseReview {
graph.goal.config?.rolloutState?.releaseGateAcceptanceId,
);
await this.db.transaction(async (tx) => {
- const goalModel = new GoalModel(tx, this.userId, this.workspaceId);
+ const goalModel = new GoalRepository(tx, this.userId, this.workspaceId);
const current = (await goalModel.lockById(goalId))?.config?.rolloutState;
if (current?.phase !== 'release_review' || current.releaseReviewNodeId !== gateNodeId)
return;
@@ -324,7 +324,7 @@ export class GoalReleaseReview {
optionId: ReleaseOption,
resolution?: string,
): Promise<string> => {
- const goal = await new GoalModel(this.db, this.userId, this.workspaceId).findByNode(
+ const goal = await new GoalRepository(this.db, this.userId, this.workspaceId).findByNode(
subjectNodeId,
);
if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
@@ -393,7 +393,7 @@ export class GoalReleaseReview {
message: 'Revising the recipe needs a correction',
});
const moved = await this.db.transaction(async (tx) => {
- const goalModel = new GoalModel(tx, this.userId, this.workspaceId);
+ const goalModel = new GoalRepository(tx, this.userId, this.workspaceId);
const locked = await goalModel.lockById(goalId);
const current = locked?.config?.rolloutState;
if (
@@ -509,7 +509,7 @@ export class GoalReleaseReview {
const planSkill = version === undefined ? undefined : state.planSkill;
const reopened: string[] = [];
const applied = await this.db.transaction(async (tx) => {
- const goalModel = new GoalModel(tx, this.userId, this.workspaceId);
+ const goalModel = new GoalRepository(tx, this.userId, this.workspaceId);
const current = (await goalModel.lockById(goalId))?.config?.rolloutState;
if (current?.phase !== 'plan_revision' || !current.pendingRevision?.revisedRecipe)
return false;
@@ -592,7 +592,7 @@ export class GoalReleaseReview {
resolution: string | undefined,
) => {
const resolved = await this.db.transaction(async (tx) => {
- const goalModel = new GoalModel(tx, this.userId, this.workspaceId);
+ const goalModel = new GoalRepository(tx, this.userId, this.workspaceId);
const current = (await goalModel.lockById(goalId))?.config?.rolloutState;
if (current?.phase !== 'release_review') return undefined;
const answered = await new GoalGraphModel(tx, this.userId, this.workspaceId).resolveDecision(
@@ -644,7 +644,7 @@ export class GoalReleaseReview {
const wave = roster.slice(released, released + waveSize);
if (!wave.length) {
- await new GoalModel(this.db, this.userId, this.workspaceId).updateRolloutState(goalId, {
+ await new GoalRepository(this.db, this.userId, this.workspaceId).updateRolloutState(goalId, {
...state,
phase: 'done',
});
@@ -657,7 +657,7 @@ export class GoalReleaseReview {
// advance read it.
const created: GoalAdvanceEffect[] = [];
const message = await this.db.transaction(async (tx) => {
- const goalModel = new GoalModel(tx, this.userId, this.workspaceId);
+ const goalModel = new GoalRepository(tx, this.userId, this.workspaceId);
const current = (await goalModel.lockById(goalId))?.config?.rolloutState;
if (
!current ||
diff --git a/apps/server/src/services/goal/reportService.ts b/apps/server/src/services/goal/reportService.ts
index a4d552e90eb..3abf8b012aa 100644
--- a/apps/server/src/services/goal/reportService.ts
+++ b/apps/server/src/services/goal/reportService.ts
@@ -8,10 +8,10 @@ import {
import type { GoalGraphSnapshot, GoalReportDispatch, GoalReportTrigger } from '@lobechat/types';
import { AgentModel } from '@/database/models/agent';
-import { GoalModel } from '@/database/models/goal';
import { GoalGraphModel } from '@/database/models/goalGraph';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
+import { GoalRepository } from '@/database/repositories/goal';
import type { LobeChatDatabase } from '@/database/type';
import { TaskService } from '../task';
@@ -59,7 +59,7 @@ export class GoalReportService {
// Claim the result under the goal row lock, so two coordinators reading the
// same ended acceptance dispatch exactly one wrap-up.
const claimed = await this.db.transaction(async (tx) => {
- const model = new GoalModel(tx, this.userId, this.workspaceId);
+ const model = new GoalRepository(tx, this.userId, this.workspaceId);
const goal = await model.lockById(goalId);
if (!goal || goal.config?.report?.acceptanceKey === decision.key) return undefined;
@@ -211,7 +211,7 @@ export class GoalReportService {
patch: Partial<GoalReportDispatch>,
) =>
this.db.transaction(async (tx) => {
- const model = new GoalModel(tx, this.userId, this.workspaceId);
+ const model = new GoalRepository(tx, this.userId, this.workspaceId);
const goal = await model.lockById(goalId);
const current = goal?.config?.report;
// A newer result may have claimed the receipt meanwhile; leave it alone.
diff --git a/apps/server/src/services/goal/start.ts b/apps/server/src/services/goal/start.ts
index ad8366d6bfd..e044c7c3250 100644
--- a/apps/server/src/services/goal/start.ts
+++ b/apps/server/src/services/goal/start.ts
@@ -3,8 +3,8 @@ import type { GoalGraphSnapshot, GoalItem, GoalRolloutVariantAxis } from '@lobec
import { TRPCError } from '@trpc/server';
import { AgentOperationModel } from '@/database/models/agentOperation';
-import { GoalModel } from '@/database/models/goal';
import { GoalGraphModel } from '@/database/models/goalGraph';
+import { GoalRepository } from '@/database/repositories/goal';
import type { LobeChatDatabase } from '@/database/type';
import { GoalManagerService } from './manager';
@@ -120,7 +120,7 @@ export class GoalStartService {
start = async (goalId: string, input: StartGoalInput = {}): Promise<GoalItem> =>
this.db.transaction(async (tx) => {
const db = tx as unknown as LobeChatDatabase;
- const goalModel = new GoalModel(db, this.userId, this.workspaceId);
+ const goalModel = new GoalRepository(db, this.userId, this.workspaceId);
const goal = await goalModel.lockById(goalId);
if (!goal) return refuse('Goal not found');
if (goal.status !== 'draft')
@@ -292,7 +292,7 @@ export class GoalStartService {
canarySize: probes.length,
createdByAgentId: goal.agentId ?? undefined,
goalId: goal.id,
- goalModel: new GoalModel(db, this.userId, this.workspaceId),
+ goalModel: new GoalRepository(db, this.userId, this.workspaceId),
planSkillOwner: {
db,
goalTitle: goal.title,
diff --git a/apps/server/src/services/goal/subscriptionPolicy.ts b/apps/server/src/services/goal/subscriptionPolicy.ts
new file mode 100644
index 00000000000..e123a13e366
--- /dev/null
+++ b/apps/server/src/services/goal/subscriptionPolicy.ts
@@ -0,0 +1,104 @@
+import type {
+ GoalSubscriptionFreshnessPolicy,
+ GoalSubscriptionWakeCondition,
+} from '@lobechat/types';
+import { toMetricScale } from '@lobechat/types';
+import { z } from 'zod';
+
+export const subscriptionPolicySchema = z.object({
+ freshnessPolicy: z
+ .object({
+ maxAgeMs: z.number().finite().positive(),
+ maxFutureSkewMs: z.number().finite().nonnegative(),
+ })
+ .strict(),
+ wakeCondition: z.discriminatedUnion('type', [
+ z
+ .object({
+ minimumPlanningIntervalMs: z.number().finite().positive().optional(),
+ type: z.literal('each_valid_run'),
+ })
+ .strict(),
+ z
+ .object({
+ minimumPlanningIntervalMs: z.number().finite().positive().optional(),
+ type: z.literal('observation_window'),
+ intervalMs: z.number().finite().positive(),
+ })
+ .strict(),
+ z
+ .object({
+ minimumPlanningIntervalMs: z.number().finite().positive().optional(),
+ type: z.literal('threshold'),
+ op: z.enum(['gte', 'lte', 'gt', 'lt', 'eq']),
+ target: z.number().finite(),
+ })
+ .strict(),
+ z
+ .object({
+ minimumPlanningIntervalMs: z.number().finite().positive().optional(),
+ type: z.literal('change'),
+ minimumAbsoluteChange: z.number().finite().nonnegative(),
+ })
+ .strict(),
+ ]),
+});
+
+export const freshObservation = (
+ observedAt: string | Date,
+ policy: GoalSubscriptionFreshnessPolicy,
+ now: number,
+) => {
+ const age = now - new Date(observedAt).getTime();
+ return Number.isFinite(age) && age <= policy.maxAgeMs && age >= -policy.maxFutureSkewMs;
+};
+
+export const subscriptionWakes = (
+ condition: GoalSubscriptionWakeCondition,
+ value: number | undefined,
+ previous: number | undefined,
+ lastWakeAt: string | undefined,
+ now: number,
+) => {
+ switch (condition.type) {
+ case 'each_valid_run': {
+ return true;
+ }
+ case 'observation_window': {
+ return now >= (lastWakeAt ? Date.parse(lastWakeAt) : now) + condition.intervalMs;
+ }
+ case 'change': {
+ return (
+ value !== undefined &&
+ previous !== undefined &&
+ Math.abs(value - previous) >= condition.minimumAbsoluteChange
+ );
+ }
+ case 'threshold': {
+ if (value === undefined) return false;
+ value = toMetricScale(value);
+ const target = toMetricScale(condition.target);
+ switch (condition.op) {
+ case 'gte': {
+ return value >= target;
+ }
+ case 'lte': {
+ return value <= target;
+ }
+ case 'gt': {
+ return value > target;
+ }
+ case 'lt': {
+ return value < target;
+ }
+ case 'eq': {
+ return value === target;
+ }
+ }
+ }
+ }
+};
+
+export const planningInterval = (condition: GoalSubscriptionWakeCondition) =>
+ condition.minimumPlanningIntervalMs ??
+ (condition.type === 'observation_window' ? condition.intervalMs : 60_000);
diff --git a/apps/server/src/services/goal/subscriptions.ts b/apps/server/src/services/goal/subscriptions.ts
new file mode 100644
index 00000000000..663c8cdd9df
--- /dev/null
+++ b/apps/server/src/services/goal/subscriptions.ts
@@ -0,0 +1,813 @@
+import type { GoalSubscriptionCursor } from '@lobechat/types';
+import { isRecord } from '@lobechat/utils/object';
+import { TRPCError } from '@trpc/server';
+import { and, asc, desc, eq, inArray, isNull, sql } from 'drizzle-orm';
+import pMap from 'p-map';
+import { z } from 'zod';
+
+import { AgentModel } from '@/database/models/agent';
+import { GoalModel } from '@/database/models/goal';
+import { GoalGraphModel } from '@/database/models/goalGraph';
+import { MetricModel } from '@/database/models/metric';
+import { ProjectModel } from '@/database/models/project';
+import { WidgetModel } from '@/database/models/widget';
+import { goals } from '@/database/schemas/goal';
+import { type GoalSubscriptionRow, goalSubscriptions } from '@/database/schemas/goalSubscription';
+import { metricPoints, metrics } from '@/database/schemas/metric';
+import { widgetRuns, widgets, widgetVersions } from '@/database/schemas/widget';
+import { workspaceMembers } from '@/database/schemas/workspace';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { widgetRunLeaseMs } from '../widget/lease';
+import { WIDGET_SANDBOX_MAX_TIMEOUT_MS } from '../widget/sandbox/types';
+import { scheduleGoalAdvance } from './scheduler';
+import {
+ freshObservation,
+ planningInterval,
+ subscriptionPolicySchema,
+ subscriptionWakes,
+} from './subscriptionPolicy';
+
+/** How many bindings one list read resolves at a time. */
+const SUBSCRIPTION_READ_CONCURRENCY = 4;
+
+export const bindSubscriptionSchema = subscriptionPolicySchema.extend({
+ goalId: z.string().min(1),
+ widgetId: z.string().uuid(),
+ confirmedVersionId: z.string().uuid(),
+ metricId: z.string().min(1).nullable(),
+ criterionKey: z.string().min(1).max(255).optional(),
+ // Read back the immutable version hash and explicitly confirm it.
+ confirmedContentHash: z.string().length(64),
+});
+export const updateSubscriptionSchema = subscriptionPolicySchema.extend({
+ id: z.string().uuid(),
+ bindingRevision: z.number().int().positive(),
+ enabled: z.boolean(),
+});
+
+const instant = (column: typeof widgetRuns.createdAt | typeof metricPoints.observedAt) =>
+ sql<string>`to_char(${column} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`;
+const unavailable = () =>
+ new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Subscription source unavailable or confirmation obsolete',
+ });
+
+/** Existing runs and points are the only observation storage. */
+export class GoalSubscriptionService {
+ constructor(
+ private readonly db: LobeChatDatabase,
+ private readonly userId: string,
+ private readonly workspaceId?: string,
+ ) {}
+
+ private async goal(db: LobeChatDatabase, id: string, manage = false) {
+ const goal = await new GoalModel(db, this.userId, this.workspaceId).lockById(id);
+ if (!goal) throw unavailable();
+ if (
+ goal.projectId &&
+ !(await new ProjectModel(db, this.userId, this.workspaceId).findById(goal.projectId))
+ )
+ throw unavailable();
+ if (
+ goal.agentId &&
+ !(await new AgentModel(db, this.userId, this.workspaceId).existsById(goal.agentId))
+ )
+ throw unavailable();
+ if (this.workspaceId) {
+ const [member] = await db
+ .select()
+ .from(workspaceMembers)
+ .where(
+ and(
+ eq(workspaceMembers.workspaceId, this.workspaceId),
+ eq(workspaceMembers.userId, this.userId),
+ isNull(workspaceMembers.deletedAt),
+ ),
+ )
+ .for('share');
+ if (goal.userId !== this.userId) {
+ const [ownerMember] = await db
+ .select()
+ .from(workspaceMembers)
+ .where(
+ and(
+ eq(workspaceMembers.workspaceId, this.workspaceId),
+ eq(workspaceMembers.userId, goal.userId),
+ isNull(workspaceMembers.deletedAt),
+ ),
+ )
+ .for('share');
+ if (!ownerMember) throw unavailable();
+ }
+ if (!member || (manage && goal.userId !== this.userId && member.role !== 'owner'))
+ throw unavailable();
+ }
+ return goal;
+ }
+
+ private async source(
+ db: LobeChatDatabase,
+ sub: Pick<GoalSubscriptionRow, 'widgetId' | 'metricId' | 'confirmedVersionId' | 'binding'>,
+ owner: string,
+ ) {
+ const model = new WidgetModel(db, owner, this.workspaceId);
+ const widget = await model.findById(sub.widgetId);
+ const readableByActor = await new WidgetModel(db, this.userId, this.workspaceId).findById(
+ sub.widgetId,
+ );
+ const version = await model.findVersion(sub.widgetId, sub.confirmedVersionId);
+ if (
+ !widget ||
+ !readableByActor ||
+ !version ||
+ widget.workspaceId !== (this.workspaceId ?? null) ||
+ version.workspaceId !== widget.workspaceId ||
+ version.userId !== widget.userId ||
+ widget.publishedVersionId !== version.id ||
+ version.contentHash !== sub.binding.semanticsHash
+ )
+ throw unavailable();
+ if (sub.metricId)
+ await db
+ .select({ id: metrics.id })
+ .from(metrics)
+ .where(eq(metrics.id, sub.metricId))
+ .for('share');
+ const metric = sub.metricId
+ ? await new MetricModel(db, owner, this.workspaceId).findById(sub.metricId)
+ : undefined;
+ if (
+ sub.metricId &&
+ (!metric ||
+ metric.userId !== widget.userId ||
+ metric.subjectType !== 'widget' ||
+ metric.subjectId !== widget.id ||
+ metric.key !== sub.binding.metric?.key ||
+ metric.kind !== sub.binding.metric?.kind ||
+ metric.unit !== sub.binding.metric?.unit ||
+ !isRecord(metric.metadata) ||
+ metric.metadata.widgetContentHash !== version.contentHash)
+ )
+ throw unavailable();
+ return { widget, version, metric };
+ }
+
+ private async baseline(db: LobeChatDatabase, widgetId: string): Promise<GoalSubscriptionCursor> {
+ await db.select({ id: widgets.id }).from(widgets).where(eq(widgets.id, widgetId)).for('update');
+ const [last] = await db
+ .select({ createdAt: instant(widgetRuns.createdAt), runId: widgetRuns.id })
+ .from(widgetRuns)
+ .where(eq(widgetRuns.widgetId, widgetId))
+ .orderBy(desc(widgetRuns.createdAt), desc(widgetRuns.id))
+ .limit(1);
+ return { lastWakeAt: new Date().toISOString(), ...(last && { run: last }) };
+ }
+
+ bind = async (
+ raw: z.infer<typeof bindSubscriptionSchema>,
+ rebind?: { id: string; bindingRevision: number },
+ ) => {
+ const input = bindSubscriptionSchema.parse(raw);
+ return this.db.transaction(async (tx) => {
+ const db = tx as unknown as LobeChatDatabase;
+ const goal = await this.goal(db, input.goalId, true);
+ const widget = await new WidgetModel(db, goal.userId, this.workspaceId).findById(
+ input.widgetId,
+ );
+ const metric = input.metricId
+ ? await new MetricModel(db, goal.userId, this.workspaceId).findById(input.metricId)
+ : undefined;
+ if (
+ !widget ||
+ (input.metricId && !metric) ||
+ (input.criterionKey && !metric) ||
+ (!metric && ['threshold', 'change'].includes(input.wakeCondition.type))
+ )
+ throw unavailable();
+ const binding = {
+ criterionKey: input.criterionKey,
+ semanticsHash: input.confirmedContentHash,
+ ...(metric && { metric: { key: metric.key, kind: metric.kind, unit: metric.unit } }),
+ };
+ await db
+ .select({ id: widgets.id })
+ .from(widgets)
+ .where(eq(widgets.id, input.widgetId))
+ .for('update');
+ await this.source(db, { ...input, binding }, goal.userId);
+ const existing = await db
+ .select()
+ .from(goalSubscriptions)
+ .where(eq(goalSubscriptions.goalId, goal.id));
+ if (
+ input.criterionKey &&
+ existing.some((s) => s.id !== rebind?.id && s.binding.criterionKey === input.criterionKey)
+ )
+ throw new TRPCError({ code: 'CONFLICT', message: 'Criterion already bound' });
+ const cursor = await this.baseline(db, input.widgetId);
+ const values = {
+ binding,
+ cursor,
+ enabled: false,
+ confirmedVersionId: input.confirmedVersionId,
+ metricId: input.metricId,
+ widgetId: input.widgetId,
+ freshnessPolicy: input.freshnessPolicy,
+ wakeCondition: input.wakeCondition,
+ updatedAt: new Date(),
+ };
+ if (rebind) {
+ const [row] = await db
+ .update(goalSubscriptions)
+ .set({ ...values, bindingRevision: rebind.bindingRevision + 1 })
+ .where(
+ and(
+ eq(goalSubscriptions.id, rebind.id),
+ eq(goalSubscriptions.goalId, goal.id),
+ eq(goalSubscriptions.bindingRevision, rebind.bindingRevision),
+ ),
+ )
+ .returning();
+ if (!row) throw new TRPCError({ code: 'CONFLICT', message: 'Binding revision changed' });
+ return row;
+ }
+ const [row] = await db
+ .insert(goalSubscriptions)
+ .values({ ...values, goalId: goal.id, userId: goal.userId, workspaceId: goal.workspaceId })
+ .returning();
+ return row;
+ });
+ };
+
+ update = async (raw: z.infer<typeof updateSubscriptionSchema>) => {
+ const input = updateSubscriptionSchema.parse(raw);
+ return this.db.transaction(async (tx) => {
+ const db = tx as unknown as LobeChatDatabase;
+ const [sub] = await db
+ .select()
+ .from(goalSubscriptions)
+ .where(eq(goalSubscriptions.id, input.id));
+ if (!sub) throw unavailable();
+ const goal = await this.goal(db, sub.goalId, true);
+ await db
+ .select({ id: widgets.id })
+ .from(widgets)
+ .where(eq(widgets.id, sub.widgetId))
+ .for('update');
+ if (input.enabled) await this.source(db, sub, goal.userId);
+ if (!sub.metricId && ['threshold', 'change'].includes(input.wakeCondition.type))
+ throw unavailable();
+ // Every explicit activation starts after all already reserved runs; resume
+ // cannot silently reuse pre-pause evidence. Revision fences all old callbacks.
+ const cursor =
+ input.enabled && !sub.enabled ? await this.baseline(db, sub.widgetId) : sub.cursor;
+ const [row] = await db
+ .update(goalSubscriptions)
+ .set({
+ enabled: input.enabled,
+ cursor,
+ wakeCondition: input.wakeCondition,
+ freshnessPolicy: input.freshnessPolicy,
+ bindingRevision: input.bindingRevision + 1,
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(goalSubscriptions.id, input.id),
+ eq(goalSubscriptions.bindingRevision, input.bindingRevision),
+ ),
+ )
+ .returning();
+ if (!row) throw new TRPCError({ code: 'CONFLICT', message: 'Binding revision changed' });
+ return row;
+ });
+ };
+
+ setEnabled = async (id: string, bindingRevision: number, enabled: boolean) => {
+ const [sub] = await this.db
+ .select()
+ .from(goalSubscriptions)
+ .where(eq(goalSubscriptions.id, id));
+ if (!sub) throw unavailable();
+ return this.update({
+ id,
+ bindingRevision,
+ enabled,
+ wakeCondition: sub.wakeCondition,
+ freshnessPolicy: sub.freshnessPolicy,
+ });
+ };
+
+ /** Stable Dashboard handoff: no projections or copied Goal points. */
+ list = async (goalId: string) =>
+ this.db.transaction(async (tx) => {
+ const db = tx as unknown as LobeChatDatabase;
+ const goal = await this.goal(db, goalId);
+ const rows = await db
+ .select()
+ .from(goalSubscriptions)
+ .where(eq(goalSubscriptions.goalId, goalId))
+ .orderBy(asc(goalSubscriptions.id));
+ // Bounded: each binding reads its source, up to 200 trend points and its
+ // runs, and a Goal may carry many bindings on one transaction connection.
+ return pMap(
+ rows,
+ async (subscription) => {
+ const source = await this.source(db, subscription, goal.userId).catch(() => undefined);
+ const model = new MetricModel(db, goal.userId, this.workspaceId);
+ const trend = source?.metric
+ ? await model.listPoints(source.metric.id, { limit: 200 })
+ : undefined;
+ const [latestRun] = source
+ ? await db
+ .select()
+ .from(widgetRuns)
+ .where(
+ and(
+ eq(widgetRuns.widgetId, subscription.widgetId),
+ sql`${widgetRuns.trigger} <> 'preview'`,
+ ),
+ )
+ .orderBy(desc(widgetRuns.createdAt), desc(widgetRuns.id))
+ .limit(1)
+ : [];
+ const [latestSuccessfulRun] = source
+ ? await db
+ .select()
+ .from(widgetRuns)
+ .where(
+ and(
+ eq(widgetRuns.widgetId, subscription.widgetId),
+ eq(widgetRuns.versionId, subscription.confirmedVersionId),
+ eq(widgetRuns.status, 'succeeded'),
+ sql`${widgetRuns.trigger} <> 'preview'`,
+ ),
+ )
+ .orderBy(desc(widgetRuns.createdAt), desc(widgetRuns.id))
+ .limit(1)
+ : [];
+ const [latestFailureRun] = source
+ ? await db
+ .select()
+ .from(widgetRuns)
+ .where(
+ and(
+ eq(widgetRuns.widgetId, subscription.widgetId),
+ sql`${widgetRuns.status} IN ('failed', 'timeout', 'partial')`,
+ sql`${widgetRuns.trigger} <> 'preview'`,
+ ),
+ )
+ .orderBy(desc(widgetRuns.createdAt), desc(widgetRuns.id))
+ .limit(1)
+ : [];
+ const point = source ? await this.acceptedPoint(db, subscription) : undefined;
+ const clause = goal.config?.acceptance?.metrics?.find(
+ (c) => c.key === subscription.binding.criterionKey,
+ );
+ const eligible =
+ subscription.enabled &&
+ ['planning', 'running'].includes(goal.status) &&
+ !!point &&
+ Number.isFinite(point.value) &&
+ freshObservation(point.observedAt, subscription.freshnessPolicy, Date.now());
+ const progress = clause
+ ? {
+ criterionKey: clause.key,
+ value: point?.value ?? null,
+ observedAt: point?.observedAt,
+ eligible,
+ target: clause.target,
+ op: clause.op ?? 'gte',
+ met:
+ eligible &&
+ subscriptionWakes(
+ { type: 'threshold', op: clause.op ?? 'gte', target: clause.target },
+ point?.value,
+ undefined,
+ undefined,
+ Date.now(),
+ ),
+ }
+ : undefined;
+ return {
+ subscription,
+ widget: source?.widget,
+ metric: source?.metric,
+ trend: trend?.points ?? [],
+ latestRun,
+ latestSuccessfulRun,
+ latestFailureRun,
+ progress,
+ latestSuccessfulObservation: point,
+ fresh:
+ !!point &&
+ freshObservation(point.observedAt, subscription.freshnessPolicy, Date.now()),
+ sourceAvailable: !!source,
+ goal: {
+ id: goal.id,
+ status: goal.status,
+ managerState: goal.config?.managerState,
+ acceptance: goal.config?.acceptance,
+ },
+ };
+ },
+ { concurrency: SUBSCRIPTION_READ_CONCURRENCY },
+ );
+ });
+
+ private async acceptedPoint(db: LobeChatDatabase, sub: GoalSubscriptionRow) {
+ if (!sub.metricId || !sub.cursor.observation) return undefined;
+ const [point] = await db
+ .select()
+ .from(metricPoints)
+ .innerJoin(widgetRuns, sql`${widgetRuns.id}::text = ${metricPoints.actorId}`)
+ .where(
+ and(
+ eq(metricPoints.id, sub.cursor.observation.pointId),
+ eq(metricPoints.metricId, sub.metricId),
+ eq(metricPoints.userId, widgetRuns.userId),
+ sql`${metricPoints.workspaceId} IS NOT DISTINCT FROM ${widgetRuns.workspaceId}`,
+ eq(metricPoints.actorType, 'system'),
+ eq(metricPoints.sourceType, 'probe'),
+ eq(widgetRuns.widgetId, sub.widgetId),
+ eq(widgetRuns.versionId, sub.confirmedVersionId),
+ eq(widgetRuns.status, 'succeeded'),
+ sql`${widgetRuns.trigger} <> 'preview'`,
+ sql`COALESCE(${widgetRuns.output}->'meta'->>'complete', 'true') <> 'false'`,
+ ),
+ );
+ return point?.metric_points;
+ }
+
+ /** Numeric acceptance reads only the committed, still fresh authoritative point. */
+ criterion = async (goalId: string, key: string) =>
+ this.db.transaction(async (tx) => {
+ const db = tx as unknown as LobeChatDatabase;
+ const goal = await this.goal(db, goalId);
+ const rows = await db
+ .select()
+ .from(goalSubscriptions)
+ .where(
+ and(
+ eq(goalSubscriptions.goalId, goalId),
+ sql`${goalSubscriptions.binding}->>'criterionKey' = ${key}`,
+ ),
+ )
+ .for('update');
+ if (!rows.length) return { bound: false as const, point: undefined };
+ const sub = rows[0];
+ if (
+ rows.length !== 1 ||
+ sub.userId !== goal.userId ||
+ sub.workspaceId !== goal.workspaceId ||
+ !sub.enabled ||
+ !['planning', 'running'].includes(goal.status)
+ )
+ return { bound: true as const, point: undefined };
+ await db
+ .select({ id: widgets.id })
+ .from(widgets)
+ .where(eq(widgets.id, sub.widgetId))
+ .for('update');
+ const source = await this.source(db, sub, goal.userId).catch(() => undefined);
+ if (!source) return { bound: true as const, point: undefined };
+ const point = await this.acceptedPoint(db, sub);
+ return {
+ bound: true as const,
+ point:
+ point &&
+ Number.isFinite(point.value) &&
+ freshObservation(point.observedAt, sub.freshnessPolicy, Date.now())
+ ? point
+ : undefined,
+ };
+ });
+
+ criteria = async (goalId: string, keys: string[]) => {
+ const empty = () =>
+ new Map<string, Awaited<ReturnType<GoalSubscriptionService['criterion']>>>();
+ if (!keys.length) return empty();
+ // Every graph read lands here: a Goal with no bindings must not pay the
+ // access checks and locks below.
+ if (!(await this.hasBindings(goalId))) return empty();
+ return this.db.transaction(async (tx) => {
+ const db = tx as unknown as LobeChatDatabase;
+ await this.goal(db, goalId);
+ const rows = await db
+ .select()
+ .from(goalSubscriptions)
+ .where(eq(goalSubscriptions.goalId, goalId));
+ const ids = [
+ ...new Set(
+ rows
+ .filter((sub) => sub.binding.criterionKey && keys.includes(sub.binding.criterionKey))
+ .map((sub) => sub.widgetId),
+ ),
+ ].sort();
+ // All bound sources lock in one global order, including final achievement.
+ // Two Goals with inverse clause orders cannot deadlock on shared Widgets.
+ if (ids.length)
+ await db
+ .select({ id: widgets.id })
+ .from(widgets)
+ .where(inArray(widgets.id, ids))
+ .orderBy(asc(widgets.id))
+ .for('update');
+ const service = new GoalSubscriptionService(db, this.userId, this.workspaceId);
+ const result = new Map<string, Awaited<ReturnType<GoalSubscriptionService['criterion']>>>();
+ for (const key of keys) result.set(key, await service.criterion(goalId, key));
+ return result;
+ });
+ };
+
+ /** Unmanaged Goals acknowledge the same durable pending coordination effect on tick. */
+ acknowledge = async (goalId: string) => {
+ // Runs on every unmanaged tick; nothing to acknowledge without an enabled binding.
+ if (!(await this.hasBindings(goalId, { enabledOnly: true }))) return;
+ return this.db.transaction(async (tx) => {
+ const db = tx as unknown as LobeChatDatabase;
+ const goal = await this.goal(db, goalId);
+ if (goal.config?.manager || !['planning', 'running'].includes(goal.status)) return;
+ const rows = await db
+ .select()
+ .from(goalSubscriptions)
+ .where(and(eq(goalSubscriptions.goalId, goalId), eq(goalSubscriptions.enabled, true)))
+ .for('update');
+ const now = Date.now();
+ for (const sub of rows) {
+ if (
+ !sub.cursor.pendingWake ||
+ now <
+ Date.parse(sub.cursor.lastWakeAt ?? new Date(now).toISOString()) +
+ planningInterval(sub.wakeCondition)
+ )
+ continue;
+ await db
+ .update(goalSubscriptions)
+ .set({
+ cursor: { ...sub.cursor, pendingWake: false, lastWakeAt: new Date(now).toISOString() },
+ updatedAt: new Date(),
+ })
+ .where(eq(goalSubscriptions.id, sub.id));
+ }
+ });
+ };
+
+ /** Cheap pre-check, no locks: whether the Goal has any (enabled) binding at all. */
+ private hasBindings = async (goalId: string, options?: { enabledOnly?: boolean }) => {
+ const [row] = await this.db
+ .select({ id: goalSubscriptions.id })
+ .from(goalSubscriptions)
+ .where(
+ options?.enabledOnly
+ ? and(eq(goalSubscriptions.goalId, goalId), eq(goalSubscriptions.enabled, true))
+ : eq(goalSubscriptions.goalId, goalId),
+ )
+ .limit(1);
+ return Boolean(row);
+ };
+
+ consume = async (id: string, revision?: number) => {
+ const wake = await this.db.transaction(async (tx) => {
+ const db = tx as unknown as LobeChatDatabase;
+ const [hint] = await db.select().from(goalSubscriptions).where(eq(goalSubscriptions.id, id));
+ if (!hint) return;
+ const goal = await this.goal(db, hint.goalId);
+ if (goal.userId !== hint.userId || goal.workspaceId !== hint.workspaceId) throw unavailable();
+ // Widget lock closes late-reservation gaps; consistent goal→widget→subscription order.
+ await db
+ .select({ id: widgets.id })
+ .from(widgets)
+ .where(eq(widgets.id, hint.widgetId))
+ .for('update');
+ const [sub] = await db
+ .select()
+ .from(goalSubscriptions)
+ .where(eq(goalSubscriptions.id, id))
+ .for('update');
+ if (!sub?.enabled || (revision !== undefined && revision !== sub.bindingRevision)) return;
+ if (!['planning', 'running'].includes(goal.status)) {
+ // A review gate only defers consumption: the answer returns the Goal to
+ // `running` with its bindings intact. Only a stopped Goal releases them.
+ if (['paused', 'canceled', 'achieved', 'failed'].includes(goal.status))
+ await db
+ .update(goalSubscriptions)
+ .set({
+ enabled: false,
+ bindingRevision: sub.bindingRevision + 1,
+ updatedAt: new Date(),
+ })
+ .where(eq(goalSubscriptions.id, id));
+ return;
+ }
+ const source = await this.source(db, sub, goal.userId);
+ const cursor = { ...sub.cursor };
+ const now = Date.now();
+ let previousValue = (await this.acceptedPoint(db, sub))?.value;
+ let shouldWake =
+ cursor.pendingWake === true ||
+ (sub.wakeCondition.type === 'observation_window' &&
+ subscriptionWakes(sub.wakeCondition, undefined, undefined, cursor.lastWakeAt, now));
+ const runs = await db
+ .select({ run: widgetRuns, position: instant(widgetRuns.createdAt) })
+ .from(widgetRuns)
+ .where(
+ and(
+ eq(widgetRuns.widgetId, sub.widgetId),
+ cursor.run
+ ? sql`(${widgetRuns.createdAt}, ${widgetRuns.id}) > (${cursor.run.createdAt}::timestamptz, ${cursor.run.runId}::uuid)`
+ : undefined,
+ ),
+ )
+ .orderBy(asc(widgetRuns.createdAt), asc(widgetRuns.id))
+ .limit(100);
+ for (const { run, position } of runs) {
+ // Previews never publish eligible observations, even if their worker is lost.
+ if (run.trigger === 'preview') {
+ cursor.run = { createdAt: position, runId: run.id };
+ continue;
+ }
+ if (run.status === 'running') {
+ // Manual refreshes have no scheduler retry. Close abandoned reservations
+ // under the producer's Widget lock, with the same lease fence as completion.
+ if (run.trigger !== 'manual') break;
+ const [version] = await db
+ .select({ manifest: widgetVersions.manifest })
+ .from(widgetVersions)
+ .where(eq(widgetVersions.id, run.versionId));
+ // Same lease the producer runs under; only a missing version falls back to the cap.
+ const leaseMs = widgetRunLeaseMs(
+ version ? version.manifest : { timeoutMs: WIDGET_SANDBOX_MAX_TIMEOUT_MS },
+ );
+ if (now - run.startedAt.getTime() <= leaseMs) break;
+ const completed = await WidgetModel.finishRun(db, run.id, {
+ expectedStartedAt: run.startedAt,
+ status: 'timeout',
+ error: {
+ code: 'MANUAL_RUN_LEASE_EXPIRED',
+ message: 'Manual collection worker did not complete before its lease expired',
+ },
+ });
+ if (!completed) break;
+ cursor.run = { createdAt: position, runId: run.id };
+ continue;
+ }
+ let valid = false;
+ let value: number | undefined;
+ if (
+ run.userId === source.widget.userId &&
+ run.workspaceId === sub.workspaceId &&
+ run.versionId === sub.confirmedVersionId &&
+ run.status === 'succeeded' &&
+ run.output?.meta?.complete !== false
+ ) {
+ if (!sub.metricId)
+ valid = !!run.finishedAt && freshObservation(run.finishedAt, sub.freshnessPolicy, now);
+ else {
+ const points = await db
+ .select({ point: metricPoints, position: instant(metricPoints.observedAt) })
+ .from(metricPoints)
+ .where(
+ and(
+ eq(metricPoints.metricId, sub.metricId),
+ eq(metricPoints.actorId, run.id),
+ eq(metricPoints.actorType, 'system'),
+ eq(metricPoints.sourceType, 'probe'),
+ eq(metricPoints.userId, source.widget.userId),
+ sql`${metricPoints.workspaceId} IS NOT DISTINCT FROM ${sub.workspaceId}`,
+ cursor.observation
+ ? sql`(${metricPoints.observedAt}, ${metricPoints.id}) > (${cursor.observation.observedAt}::timestamptz, ${cursor.observation.pointId}::uuid)`
+ : undefined,
+ ),
+ )
+ .orderBy(asc(metricPoints.observedAt), asc(metricPoints.id));
+ for (const { point, position: observedAt } of points) {
+ if (
+ !Number.isFinite(point.value) ||
+ !freshObservation(observedAt, sub.freshnessPolicy, now)
+ )
+ continue;
+ cursor.observation = { observedAt, pointId: point.id };
+ value = point.value;
+ valid = true;
+ }
+ }
+ }
+ if (
+ valid &&
+ subscriptionWakes(sub.wakeCondition, value, previousValue, cursor.lastWakeAt, now)
+ )
+ shouldWake = true;
+ if (valid) previousValue = value;
+ cursor.run = { createdAt: position, runId: run.id };
+ }
+ cursor.pendingWake = shouldWake;
+ const state = goal.config?.managerState;
+ const graph = shouldWake
+ ? await new GoalGraphModel(db, goal.userId, this.workspaceId).getGraph(goal.id)
+ : undefined;
+ const readyAt =
+ Date.parse(cursor.lastWakeAt ?? new Date(now).toISOString()) +
+ planningInterval(sub.wakeCondition);
+ const ready = now >= readyAt;
+ if (
+ shouldWake &&
+ ready &&
+ state?.consumed &&
+ state.wait &&
+ !state.wait.wake &&
+ !graph?.decisions.some((d) => d.status === 'pending')
+ ) {
+ cursor.lastWakeAt = new Date(now).toISOString();
+ cursor.pendingWake = false;
+ const next = {
+ ...state,
+ wait: {
+ ...state.wait,
+ wake: {
+ at: cursor.lastWakeAt,
+ cause: 'event' as const,
+ eventId: `widget:${sub.id}:${sub.bindingRevision}:${cursor.run?.runId ?? 'window'}`,
+ reference: sub.widgetId,
+ summary: 'Widget observation boundary reached',
+ },
+ },
+ };
+ await db
+ .update(goals)
+ .set({
+ config: sql`jsonb_set(COALESCE(${goals.config}, '{}'::jsonb), '{managerState}', ${JSON.stringify(next)}::jsonb)`,
+ })
+ .where(eq(goals.id, goal.id));
+ }
+ await db
+ .update(goalSubscriptions)
+ .set({ cursor, updatedAt: new Date() })
+ .where(eq(goalSubscriptions.id, id));
+ // Durable wait.wake survives dispatch failure; sweep resends until advance consumes it.
+ return (state?.wait && (state.wait.wake || shouldWake)) ||
+ (!goal.config?.manager && shouldWake)
+ ? {
+ goalId: goal.id,
+ delay: state?.wait?.wake || ready ? 0 : Math.max(1, Math.ceil((readyAt - now) / 1000)),
+ }
+ : undefined;
+ });
+ if (wake)
+ await scheduleGoalAdvance({
+ ...wake,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ trigger: 'wake',
+ });
+ };
+
+ static async forWidget(db: LobeChatDatabase, widgetId: string) {
+ const subs = await db
+ .select()
+ .from(goalSubscriptions)
+ .where(and(eq(goalSubscriptions.widgetId, widgetId), eq(goalSubscriptions.enabled, true)))
+ .limit(100);
+ for (const sub of subs)
+ await new GoalSubscriptionService(db, sub.userId, sub.workspaceId ?? undefined)
+ .consume(sub.id, sub.bindingRevision)
+ .catch((error) =>
+ console.error('[goal:subscription] completion scan failed', sub.id, error),
+ );
+ }
+
+ static async forGoal(db: LobeChatDatabase, goalId: string) {
+ const subs = await db
+ .select()
+ .from(goalSubscriptions)
+ .where(and(eq(goalSubscriptions.goalId, goalId), eq(goalSubscriptions.enabled, true)));
+ for (const sub of subs)
+ await new GoalSubscriptionService(db, sub.userId, sub.workspaceId ?? undefined)
+ .consume(sub.id, sub.bindingRevision)
+ .catch((error) => console.error('[goal:subscription] Goal scan failed', sub.id, error));
+ }
+
+ /** Bounded cyclic pass. Stable UUID ordering; scheduling never depends on notification delivery. */
+ static async reconcile(db: LobeChatDatabase, after?: string, limit = 100) {
+ const rows = await db
+ .select()
+ .from(goalSubscriptions)
+ .where(
+ and(
+ eq(goalSubscriptions.enabled, true),
+ after ? sql`${goalSubscriptions.id} > ${after}::uuid` : undefined,
+ ),
+ )
+ .orderBy(asc(goalSubscriptions.id))
+ .limit(limit);
+ for (const sub of rows)
+ await new GoalSubscriptionService(db, sub.userId, sub.workspaceId ?? undefined)
+ .consume(sub.id, sub.bindingRevision)
+ .catch((error) => console.error('[goal:subscription] reconcile failed', sub.id, error));
+ return rows.length === limit ? rows.at(-1)?.id : undefined;
+ }
+}
+
+export type GoalSubscriptionRead = Awaited<ReturnType<GoalSubscriptionService['list']>>[number];
diff --git a/apps/server/src/services/goal/wait.ts b/apps/server/src/services/goal/wait.ts
index b74cd39f66b..face5bebc87 100644
--- a/apps/server/src/services/goal/wait.ts
+++ b/apps/server/src/services/goal/wait.ts
@@ -1,14 +1,17 @@
import type { GoalGraphSnapshot, GoalManagerState, GoalTickResult } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
-import { eq, sql } from 'drizzle-orm';
+import { and, eq, sql } from 'drizzle-orm';
import { z } from 'zod';
-import { GoalModel } from '@/database/models/goal';
import { GoalGraphModel } from '@/database/models/goalGraph';
+import { GoalRepository } from '@/database/repositories/goal';
import { goals } from '@/database/schemas/goal';
+import { goalSubscriptions } from '@/database/schemas/goalSubscription';
import type { LobeChatDatabase } from '@/database/type';
import { scheduleGoalAdvance } from './scheduler';
+import { planningInterval } from './subscriptionPolicy';
+import { GoalSubscriptionService } from './subscriptions';
export const goalWaitSchema = z.object({
until: z.string().datetime(),
@@ -44,14 +47,49 @@ export class GoalWaitService {
};
// The sweep also recovers lost callbacks after the deadline.
- schedule = (goalId: string, delay: number) =>
- scheduleGoalAdvance({
+ schedule = async (goalId: string, delay: number) => {
+ const bounded = await this.db.transaction(async (tx) => {
+ const db = tx as unknown as LobeChatDatabase;
+ const goal = await new GoalRepository(db, this.userId, this.workspaceId).lockById(goalId);
+ if (!goal || !['planning', 'running'].includes(goal.status)) return delay;
+ const subs = await db
+ .select()
+ .from(goalSubscriptions)
+ .where(and(eq(goalSubscriptions.goalId, goalId), eq(goalSubscriptions.enabled, true)));
+ const now = Date.now();
+ const windows = subs.flatMap((sub) =>
+ sub.wakeCondition.type === 'observation_window'
+ ? [
+ Math.max(
+ 1,
+ Math.ceil(
+ ((sub.cursor.lastWakeAt ? Date.parse(sub.cursor.lastWakeAt) : now) +
+ Math.max(sub.wakeCondition.intervalMs, planningInterval(sub.wakeCondition)) -
+ now) /
+ 1000,
+ ),
+ ),
+ ]
+ : [],
+ );
+ const nextDelay = Math.min(delay, ...windows);
+ const state = goal.config?.managerState;
+ if (state?.wait && !state.wait.wake) {
+ await this.save(db, goalId, {
+ ...state,
+ wait: { ...state.wait, armedUntil: new Date(now + nextDelay * 1000).toISOString() },
+ });
+ }
+ return nextDelay;
+ });
+ return scheduleGoalAdvance({
goalId,
userId: this.userId,
workspaceId: this.workspaceId,
trigger: 'wake',
- delay,
+ delay: bounded,
});
+ };
private save = async (db: LobeChatDatabase, goalId: string, state: GoalManagerState) => {
await db
@@ -64,9 +102,22 @@ export class GoalWaitService {
};
advance = async (graph: GoalGraphSnapshot): Promise<GoalTickResult | null> => {
- const state = graph.goal.config?.managerState;
+ await GoalSubscriptionService.forGoal(this.db, graph.goal.id);
+ // Re-read after the start-of-wait scan may have durably installed a wake.
+ const currentGoal = await new GoalRepository(this.db, this.userId, this.workspaceId).findById(
+ graph.goal.id,
+ );
+ const state = currentGoal?.config?.managerState;
const wait = state?.wait;
- if (!state?.consumed || !wait || wait.wake) return null;
+ if (!state?.consumed || !wait) return null;
+ if (wait.wake)
+ return graph.goal.config?.managerState?.wait?.wake
+ ? null
+ : {
+ goalId: graph.goal.id,
+ outcome: 'advanced',
+ message: 'Widget observation woke this wait',
+ };
if (Date.parse(wait.until) > Date.now()) {
await this.rearm(graph.goal.id, state.token);
return {
@@ -76,7 +127,9 @@ export class GoalWaitService {
};
}
await this.db.transaction(async (db) => {
- const goal = await new GoalModel(db, this.userId, this.workspaceId).lockById(graph.goal.id);
+ const goal = await new GoalRepository(db, this.userId, this.workspaceId).lockById(
+ graph.goal.id,
+ );
const current = goal?.config?.managerState;
if (
!goal ||
@@ -109,7 +162,7 @@ export class GoalWaitService {
*/
private rearm = async (goalId: string, token: string) => {
const delay = await this.db.transaction(async (db) => {
- const goal = await new GoalModel(db, this.userId, this.workspaceId).lockById(goalId);
+ const goal = await new GoalRepository(db, this.userId, this.workspaceId).lockById(goalId);
const current = goal?.config?.managerState;
const wait = current?.wait;
if (!goal || current?.token !== token || !wait || wait.wake) return;
@@ -125,7 +178,7 @@ export class GoalWaitService {
deliver = async (goalId: string, input: z.infer<typeof goalWakeEventSchema>) => {
const event = goalWakeEventSchema.parse(input);
const result = await this.db.transaction(async (db) => {
- const goal = await new GoalModel(db, this.userId, this.workspaceId).lockById(goalId);
+ const goal = await new GoalRepository(db, this.userId, this.workspaceId).lockById(goalId);
if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
const state = goal.config?.managerState;
const wait = state?.wait;
diff --git a/apps/server/src/services/widget/executeRun.ts b/apps/server/src/services/widget/executeRun.ts
index d9aa445c4a6..a676d1e462c 100644
--- a/apps/server/src/services/widget/executeRun.ts
+++ b/apps/server/src/services/widget/executeRun.ts
@@ -5,6 +5,7 @@ import { WidgetModel } from '@/database/models/widget';
import type { WidgetRow, WidgetRunRow, WidgetVersionRow } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
+import { GoalSubscriptionService } from '../goal/subscriptions';
import {
ForbiddenWidgetCredentialsError,
MissingWidgetEnvError,
@@ -32,8 +33,16 @@ export interface ExecuteWidgetRunDeps {
runner: WidgetSandboxRunner;
}
+/**
+ * A failure inside the run's metric publication. Only this is answered by
+ * recording the run as failed: any other `finishRun` failure is the worker
+ * dying mid-completion, and the run must stay `running` so its lease expires
+ * and recovery resumes it.
+ */
+class MetricPublicationError extends Error {}
+
export interface ExecuteWidgetRunParams {
- run: Pick<WidgetRunRow, 'id' | 'trigger'>;
+ run: Pick<WidgetRunRow, 'id' | 'trigger'> & Partial<Pick<WidgetRunRow, 'startedAt'>>;
version: Pick<
WidgetVersionRow,
'manifest' | 'outputType' | 'publishedByUserId' | 'runtime' | 'script' | 'userId'
@@ -188,36 +197,60 @@ export const executeWidgetRun = async (
const outcome = await runInSandbox(db, params, deps);
const finishedAt = new Date();
- const finished = await WidgetModel.finishRun(db, run.id, {
- durationMs: outcome.durationMs ?? null,
- error: outcome.error ?? null,
- exitCode: outcome.exitCode ?? null,
- finishedAt,
- output: outcome.output ?? null,
- status: outcome.status,
- stderr: outcome.stderr ? sanitizeStream(outcome.stderr, outcome.env) : null,
- stdout: outcome.stdout ? sanitizeStream(outcome.stdout, outcome.env) : null,
- });
-
- // Same "current run" rule as the snapshot: a stale run (old version, or
- // started before the snapshot's run) finishing late must not become the
- // newest trend point nor move `widgets.metric_id`.
- if (finished?.folded && outcome.status === 'succeeded' && outcome.output) {
- try {
- const { primaryMetricId } = await recordWidgetMetrics(db, widget, {
- manifest: version.manifest,
- observedAt: finishedAt,
- output: outcome.output,
- runId: run.id,
- });
- if (primaryMetricId && primaryMetricId !== widget.metricId) {
- // A newer run may have taken the snapshot while this one recorded metrics.
- await WidgetModel.linkMetric(db, widget.id, primaryMetricId, run.id);
- }
- } catch (error) {
- // The run itself succeeded; a trend write failure must not flip it.
- console.error('[widget:executeRun] failed to record metrics widget=%s', widget.id, error);
- }
+ let finished: Awaited<ReturnType<typeof WidgetModel.finishRun>>;
+ try {
+ finished = await WidgetModel.finishRun(
+ db,
+ run.id,
+ {
+ expectedStartedAt: run.startedAt,
+ durationMs: outcome.durationMs ?? null,
+ error: outcome.error ?? null,
+ exitCode: outcome.exitCode ?? null,
+ finishedAt,
+ output: outcome.output ?? null,
+ status: outcome.status,
+ stderr: outcome.stderr ? sanitizeStream(outcome.stderr, outcome.env) : null,
+ stdout: outcome.stdout ? sanitizeStream(outcome.stdout, outcome.env) : null,
+ },
+ async (tx) => {
+ if (!outcome.output) return;
+ const transactionalDB = tx as unknown as LobeChatDatabase;
+ try {
+ const { primaryMetricId } = await recordWidgetMetrics(transactionalDB, widget, {
+ manifest: version.manifest,
+ observedAt: finishedAt,
+ output: outcome.output,
+ runId: run.id,
+ });
+ if (primaryMetricId)
+ await WidgetModel.linkMetric(transactionalDB, widget.id, primaryMetricId, run.id);
+ } catch (cause) {
+ throw new MetricPublicationError('Widget metric publication failed', { cause });
+ }
+ },
+ );
+ } catch (error) {
+ if (!(error instanceof MetricPublicationError)) throw error;
+ console.error('[widget:executeRun] atomic metric publication failed', error);
+ // The failed transaction left no points or success. Persist the collection
+ // failure in existing history; consumers can handle it without guessing.
+ finished = await WidgetModel.finishRun(db, run.id, {
+ status: 'failed',
+ finishedAt,
+ expectedStartedAt: run.startedAt,
+ error: {
+ code: 'METRIC_PUBLICATION_FAILED',
+ message: 'Widget metric publication failed; check source semantics and storage',
+ },
+ });
+ }
+
+ if (finished && finished.run.trigger !== 'preview') {
+ // A completion is only a hint. The durable scanner also runs on wait/sweep.
+ await GoalSubscriptionService.forWidget(db, widget.id).catch((error) => {
+ console.error('[widget:executeRun] subscription scan failed', error);
+ });
}
log('run=%s widget=%s status=%s', run.id, widget.id, outcome.status);
diff --git a/apps/server/src/services/widget/lease.ts b/apps/server/src/services/widget/lease.ts
new file mode 100644
index 00000000000..8b5edc3d2e0
--- /dev/null
+++ b/apps/server/src/services/widget/lease.ts
@@ -0,0 +1,16 @@
+import type { WidgetManifest } from '@lobechat/types';
+
+import { clampSandboxTimeout, WIDGET_SANDBOX_REQUEST_OVERHEAD_MS } from './sandbox/types';
+
+/** Slack on top of the sandbox bounds before a reserved run counts as abandoned. */
+export const WIDGET_RUN_LEASE_MARGIN_MS = 60_000;
+/**
+ * How long a worker may hold a reserved run before another worker
+ * may take it over: the version's (clamped) script timeout, plus what the
+ * sandbox request may add on top, plus a margin for credential resolution
+ * and closing the run.
+ */
+export const widgetRunLeaseMs = (manifest?: Pick<WidgetManifest, 'timeoutMs'> | null) =>
+ clampSandboxTimeout(manifest?.timeoutMs) +
+ WIDGET_SANDBOX_REQUEST_OVERHEAD_MS +
+ WIDGET_RUN_LEASE_MARGIN_MS;
diff --git a/apps/server/src/services/widget/metrics.ts b/apps/server/src/services/widget/metrics.ts
index bc36e985c7b..ac952ee5837 100644
--- a/apps/server/src/services/widget/metrics.ts
+++ b/apps/server/src/services/widget/metrics.ts
@@ -1,6 +1,8 @@
import type { WidgetManifest, WidgetOutput } from '@lobechat/types';
+import { and, eq, sql } from 'drizzle-orm';
import { MetricModel } from '@/database/models/metric';
+import { metrics, widgetRuns, widgetVersions } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
export interface WidgetMetricScope {
@@ -72,6 +74,36 @@ export const recordWidgetMetrics = async (
): Promise<RecordWidgetMetricsResult> => {
const { manifest, output, observedAt, runId } = params;
const metricModel = new MetricModel(db, widget.userId, widget.workspaceId ?? undefined);
+ const [version] = await db
+ .select({ contentHash: widgetVersions.contentHash })
+ .from(widgetRuns)
+ .innerJoin(widgetVersions, eq(widgetVersions.id, widgetRuns.versionId))
+ .where(eq(widgetRuns.id, runId));
+ if (!version) throw new Error('Metric run has no persisted version');
+ const ensure = async (params: Parameters<MetricModel['ensure']>[0]) => {
+ const metric = await metricModel.ensure({
+ ...params,
+ metadata: { widgetContentHash: version.contentHash },
+ });
+ if (!metric) throw new Error('Metric scope unavailable');
+ // Legacy series may be adopted only while empty. A changed script/account/
+ // extraction must use a new key, even after explicitly rebinding a Goal.
+ const [confirmed] = await db
+ .update(metrics)
+ .set({ metadata: { widgetContentHash: version.contentHash } })
+ .where(
+ and(
+ eq(metrics.id, metric.id),
+ sql`(
+ ${metrics.metadata}->>'widgetContentHash' = ${version.contentHash}
+ OR (${metrics.metadata} IS NULL AND NOT EXISTS (SELECT 1 FROM metric_points WHERE metric_id = ${metric.id}))
+ )`,
+ ),
+ )
+ .returning();
+ if (!confirmed) throw new Error('Widget metric source changed: publish a new metric key');
+ return confirmed;
+ };
const kind = manifest?.metric?.kind ?? 'gauge';
const pointBase = {
@@ -86,7 +118,7 @@ export const recordWidgetMetrics = async (
);
if (value === undefined) return { pointsWritten: 0 };
- const metric = await metricModel.ensure({
+ const metric = await ensure({
key: manifest?.metric?.key ?? DEFAULT_STAT_KEY,
kind,
subjectId: widget.id,
@@ -107,10 +139,13 @@ export const recordWidgetMetrics = async (
for (const series of output.series) {
const points = series.points
.map((p) => ({ observedAt: parseTime(p.t), value: p.v }))
- .filter((p): p is { observedAt: Date; value: number } => !!p.observedAt);
+ .filter(
+ (p): p is { observedAt: Date; value: number } =>
+ !!p.observedAt && Number.isFinite(p.value),
+ );
if (points.length === 0) continue;
- const metric = await metricModel.ensure({
+ const metric = await ensure({
key: `${SERIES_KEY_PREFIX}${series.name}`,
kind,
subjectId: widget.id,
diff --git a/apps/server/src/services/widget/scheduler.ts b/apps/server/src/services/widget/scheduler.ts
index 7edd614ef96..9cf166d4c51 100644
--- a/apps/server/src/services/widget/scheduler.ts
+++ b/apps/server/src/services/widget/scheduler.ts
@@ -1,4 +1,4 @@
-import type { WidgetManifest, WidgetRunStatus } from '@lobechat/types';
+import type { WidgetRunStatus } from '@lobechat/types';
import debug from 'debug';
import pMap from 'p-map';
@@ -6,32 +6,23 @@ import { WidgetModel } from '@/database/models/widget';
import type { WidgetRow, WidgetRunRow, WidgetVersionRow } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
+import { GoalSubscriptionService } from '../goal/subscriptions';
import { executeWidgetRun, type ExecuteWidgetRunDeps } from './executeRun';
-import { clampSandboxTimeout, WIDGET_SANDBOX_REQUEST_OVERHEAD_MS } from './sandbox/types';
+import { widgetRunLeaseMs } from './lease';
import { nextScheduleOccurrence } from './schedule';
const log = debug('lobe-server:widget:scheduler');
+let subscriptionAfter: string | undefined;
const DEFAULT_TICK_LIMIT = 50;
const DEFAULT_INLINE_CONCURRENCY = 4;
const DEFAULT_DISPATCH_CONCURRENCY = 10;
-/** Slack on top of the sandbox bounds before a reserved run counts as abandoned. */
-export const WIDGET_RUN_LEASE_MARGIN_MS = 60_000;
+export { WIDGET_RUN_LEASE_MARGIN_MS, widgetRunLeaseMs } from './lease';
+
/** Reservations older than this are no longer resumed — that occurrence is long gone. */
const RESUME_HORIZON_MS = 24 * 60 * 60 * 1000;
-/**
- * How long a worker may hold a reserved scheduled run before another worker
- * may take it over: the version's (clamped) script timeout, plus what the
- * sandbox request may add on top, plus a margin for credential resolution
- * and closing the run.
- */
-export const widgetRunLeaseMs = (manifest?: Pick<WidgetManifest, 'timeoutMs'> | null) =>
- clampSandboxTimeout(manifest?.timeoutMs) +
- WIDGET_SANDBOX_REQUEST_OVERHEAD_MS +
- WIDGET_RUN_LEASE_MARGIN_MS;
-
/** The shortest lease any version can have — the coarse cut for the stale query. */
const MIN_LEASE_MS = widgetRunLeaseMs({ timeoutMs: 1 });
@@ -234,6 +225,7 @@ export const runWidgetSchedulerTick = async (
return { claimed: 0, dispatched: 0, due: due.length, resumed: 0, results: [] };
}
+ subscriptionAfter = await GoalSubscriptionService.reconcile(db, subscriptionAfter);
const stale = await findStaleRuns(db, now, { limit });
let dispatched = 0;
let resumed = 0;
diff --git a/docs/development/goal-widget-subscriptions.md b/docs/development/goal-widget-subscriptions.md
new file mode 100644
index 00000000000..e1e42d40f9e
--- /dev/null
+++ b/docs/development/goal-widget-subscriptions.md
@@ -0,0 +1,48 @@
+# Durable Widget subscriptions for Goals
+
+This runtime stacks on the schema and repair branches. It reuses `goal_subscriptions`, `widget_runs`, `metrics`, `metric_points` and the Goal's existing wait receipt. It adds no table or duplicated metric projection. Numeric observations are never copied into a Goal series.
+
+## API and scope
+
+`goal.bindSubscription`, `goal.listSubscriptions`, `goal.updateSubscription`, `goal.enableSubscription`, `goal.disableSubscription` and `goal.rebindSubscription` are authenticated workspace-compatible TRPC procedures. Writes require `agent:update`, Goal creator or workspace-owner management permission, live membership and read access for both the authenticated actor and Goal owner. Sources must share scope; version ownership must match its Widget; a numeric metric must belong to that Widget and match key, kind and unit.
+
+Bind/rebind require `confirmedVersionId` and the immutable version's `confirmedContentHash`. Bind defaults disabled; explicit enablement authorizes consumption. A criterion key is unique within its Goal, serialized under the Goal lock. A result-only subscription cannot bind a numeric criterion or use threshold/change policies. Mutations use `bindingRevision`; obsolete revisions conflict. Bind, rebind and re-enable baseline after every already-reserved run, including running reservations, deliberately excluding pre-authorization evidence.
+
+The service rechecks source access, soft deletion, version/hash, metric ownership/semantics and Goal state before consumption and numeric evaluation. Workspace membership and metric rows are held under share locks for transactional decisions. Final achievement re-evaluates numeric freshness under its existing Goal lock; bound Widget rows lock in UUID order to avoid inverse-clause deadlocks across Goals.
+
+## Producer and consumption protocol
+
+Both scheduled reservation (`claimDueRun`) and manual/preview reservation (`startRun`) serialize on the Widget row. They allocate `created_at` with PostgreSQL `clock_timestamp()` after that lock. A scanner holds the same lock; no pre-lock transaction timestamp can commit below its watermark. This is not a fixed-lookback repair.
+
+`WidgetModel.finishRun` accepts a transactional metric-publication callback. `executeWidgetRun` publishes the successful current run, snapshot, metric definitions/points and metric link within that transaction. A publication exception rolls back all of them, then closes the existing run as `failed` with `METRIC_PUBLICATION_FAILED`. If storage also prevents that failure write, the run remains running: scanners stop at that barrier instead of inventing success. Scheduled lease completions also compare the worker's `startedAt` to reject superseded workers.
+
+Subscription processing locks Goal, Widget and subscription, then reads `(created_at, UUID)` order. Positions are formatted by PostgreSQL with six fractional digits rather than round-tripped through JavaScript Dates. A bounded scan handles only a contiguous final prefix; a running row stops it. Preview, wrong-version, failed, timeout and partial rows are handled without numeric success. Successful observations require complete output, finite values, system/probe/run provenance, matching owner/workspace and fresh non-future timestamps. Observations advance only in `(observed_at, UUID)` order; older points cannot replace accepted progress.
+
+The cursor and pending/wake coordination effect commit together. `cursor.pendingWake` contains no sampled value: it remembers eligible early observations until a wait exists or an unmanaged Goal ticks. Managed Goals use their current durable `managerState.wait.wake`; unmanaged Goals acknowledge the pending effect in their coordinator tick. Notification arrival is only a hint. A failed queue dispatch is recoverable from those durable effects.
+
+Completion fanout, start-of-wait scans, Widget scheduler ticks and Goal sweeps invoke the same consumer. Reconciliation uses bounded cyclic UUID pages, resets to the start after a complete pass, and starts from the beginning after a process restart. The process-local page position is only an optimization; it is not the consumption watermark.
+
+## Cadence, stops and semantics
+
+The Widget owns collection cadence. `wakeCondition.minimumPlanningIntervalMs` independently bounds planning wakes; its default is one minute, or the observation-window interval for that policy. Matching observations remain pending inside the interval. Observation windows become eligible even with no arrivals. Existing durable wait timers are armed at the earlier collection-window boundary, and cyclic reconciliation repairs missed timers. A numeric shortfall on a subscribed unmanaged Goal stays an observation wait instead of becoming a user pause.
+
+Pause, cancellation, failure and achievement atomically disable enabled subscriptions, increment their revision and remove pending wakes in `GoalModel.update`; existing cursor observations remain available for historical reads. Explicit re-enable establishes a new non-replay baseline. Widget schedules, history, Dashboard output and other Goals' subscriptions are unaffected. Pending human decisions gate the managed wake receipt; existing coordinator budgets and turn/pause gates remain authoritative.
+
+Widget metric definitions retain a version content hash in their existing `metadata`. `ensure` rejects incompatible key-slot kind/unit, and publication rejects a different script/account/extraction hash on existing history. Widget metric kind/unit/metadata mutations through `update` are rejected. Empty legacy series may acquire a hash; populated untagged legacy series require a new key. This conservative policy includes the whole immutable content hash, so compatible presentational changes can also require a new metric key; it never silently reinterprets old history. Rebinding confirms a version, but cannot override series immutability.
+
+## Dashboard and Goal read handoff
+
+`goal.listSubscriptions({ goalId })`, exposed through `goalService.listSubscriptions`, returns `GoalSubscriptionRead` from `apps/server/src/services/goal/subscriptions.ts`:
+
+- `subscription`: Widget/metric/version identity, binding revision, enablement, typed policies and durable cursor;
+- `widget`, `metric`, `trend`: existing source rows and a bounded 200-point trend;
+- `latestRun`, `latestSuccessfulRun`, `latestFailureRun`: non-preview existing run history, including failed/timeout/partial health;
+- `latestSuccessfulObservation`, `fresh`, `sourceAvailable`: the accepted authoritative point and current eligibility information;
+- `progress`: criterion key, value/time, eligibility, target/operator and fresh comparison;
+- `goal`: Goal identity/status, acceptance contract and Manager wait/execution receipt.
+
+`metric.listSeriesWithPoints` maps Goal criterion keys to these same Widget metric IDs and history, preserving source identity and values. `goal.graph` also returns fresh `metricCriteria`. Bind/update/enable/disable/rebind client methods live in `src/services/goal.ts`. No Dashboard renderer is included. The subsequent Dashboard Task owns presentation, bindings UI/cache invalidation and visual same-source verification.
+
+## Validation status
+
+The branch has syntax parsing and whitespace checks only at authoring time. Regression suites and full product collection scenarios remain unexecuted while the host resource guard is red. This document describes intended source invariants, not a passing acceptance verdict. No migration was added: the only type additions are fields in existing typed JSON policies/cursors. Schema PR #20500 stays unchanged and its schema-only acceptance does not cover this runtime.
diff --git a/packages/database/src/models/__tests__/goalSubscription.test.ts b/packages/database/src/models/__tests__/goalSubscription.test.ts
new file mode 100644
index 00000000000..279a2fdd573
--- /dev/null
+++ b/packages/database/src/models/__tests__/goalSubscription.test.ts
@@ -0,0 +1,69 @@
+// @vitest-environment node
+import { randomUUID } from 'node:crypto';
+
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { goals, goalSubscriptions, users } from '../../schemas';
+import { GoalSubscriptionModel } from '../goalSubscription';
+import { WidgetModel } from '../widget';
+
+const db = await getTestDB();
+const owner = `subscription-model-${randomUUID()}`;
+beforeEach(async () => {
+ await db.insert(users).values({ id: owner });
+});
+afterEach(async () => {
+ await db.delete(users).where(eq(users.id, owner));
+});
+
+it('disables only the owning Goal bindings and preserves accepted history', async () => {
+ const widget = await new WidgetModel(db, owner).create({ title: 'Shared' });
+ const version = await new WidgetModel(db, owner).createVersion(widget.id, {
+ script: 'console.log(1)',
+ runtime: 'node',
+ sourceType: 'agent',
+ outputType: 'stat',
+ });
+ const roots = await db
+ .insert(goals)
+ .values([
+ { userId: owner, title: 'First' },
+ { userId: owner, title: 'Second' },
+ ])
+ .returning();
+ const cursor = { pendingWake: true, lastWakeAt: new Date().toISOString() };
+ const rows = await db
+ .insert(goalSubscriptions)
+ .values(
+ roots.map((goal) => ({
+ goalId: goal.id,
+ userId: owner,
+ widgetId: widget.id,
+ confirmedVersionId: version!.id,
+ enabled: true,
+ binding: { semanticsHash: version!.contentHash },
+ freshnessPolicy: { maxAgeMs: 60000, maxFutureSkewMs: 0 },
+ wakeCondition: { type: 'each_valid_run' as const },
+ cursor,
+ })),
+ )
+ .returning();
+ await new GoalSubscriptionModel(db).disableForGoal(roots[0].id);
+ await new GoalSubscriptionModel(db).disableForGoal(roots[0].id);
+ const [stopped] = await db
+ .select()
+ .from(goalSubscriptions)
+ .where(eq(goalSubscriptions.id, rows[0].id));
+ const [shared] = await db
+ .select()
+ .from(goalSubscriptions)
+ .where(eq(goalSubscriptions.id, rows[1].id));
+ expect(stopped.enabled).toBe(false);
+ expect(stopped.bindingRevision).toBe(2);
+ expect(stopped.cursor).toEqual({ lastWakeAt: cursor.lastWakeAt });
+ expect(shared.enabled).toBe(true);
+ expect(shared.bindingRevision).toBe(1);
+ expect(shared.cursor).toEqual(cursor);
+});
diff --git a/packages/database/src/models/__tests__/widget.subscriptionBarriers.test.ts b/packages/database/src/models/__tests__/widget.subscriptionBarriers.test.ts
new file mode 100644
index 00000000000..5029bab7079
--- /dev/null
+++ b/packages/database/src/models/__tests__/widget.subscriptionBarriers.test.ts
@@ -0,0 +1,97 @@
+// @vitest-environment node
+import { eq, sql } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { users, widgetRuns, widgets } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import type { CreateWidgetVersionInput } from '../widget';
+import { WidgetModel } from '../widget';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'widget-barrier-user';
+
+const script = (n: number): CreateWidgetVersionInput => ({
+ manifest: { network: { allow: ['api.github.com'] }, title: `v${n}` },
+ outputType: 'stat',
+ runtime: 'node',
+ script: `console.log(JSON.stringify({ type: 'stat', value: ${n} }))`,
+ sourceType: 'agent',
+ view: { size: 'sm' },
+});
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+/**
+ * The producer side of Goal Widget subscriptions: a run's completion and its
+ * metric publication commit together, and a reservation takes its timestamp
+ * only after the subscription scanner's Widget lock.
+ */
+describe('WidgetModel subscription producer barriers', () => {
+ const model = new WidgetModel(serverDB, userId);
+
+ it('keeps completion and metric publication atomic on failure', async () => {
+ const widget = await model.create({ title: 'Atomic metric publication' });
+ const version = await model.createVersion(widget.id, script(1));
+ await model.publishVersion(widget.id, version!.id);
+ const run = await model.startRun(widget.id, { trigger: 'manual' });
+ await expect(
+ WidgetModel.finishRun(
+ serverDB,
+ run!.id,
+ { status: 'succeeded', output: { type: 'stat', value: 1 } },
+ async () => {
+ throw new Error('metric storage failure');
+ },
+ ),
+ ).rejects.toThrow('metric storage failure');
+ const [stored] = await serverDB.select().from(widgetRuns).where(eq(widgetRuns.id, run!.id));
+ expect(stored.status).toBe('running');
+ expect((await model.findById(widget.id))?.lastRunId).toBeNull();
+ });
+
+ it.skipIf(process.env.TEST_SERVER_DB !== '1')(
+ 'allocates reservation timestamps after waiting for the scanner Widget lock',
+ async () => {
+ const widget = await model.create({ title: 'Delayed reservation' });
+ const version = await model.createVersion(widget.id, script(1));
+ await model.publishVersion(widget.id, version!.id);
+ let release!: () => void;
+ let locked!: () => void;
+ const held = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const ready = new Promise<void>((resolve) => {
+ locked = resolve;
+ });
+ let scannerTime = '';
+ const scanner = serverDB.transaction(async (tx) => {
+ await tx.select().from(widgets).where(eq(widgets.id, widget.id)).for('update');
+ locked();
+ await held;
+ const result = await tx.execute(sql`SELECT clock_timestamp()::text AS timestamp`);
+ scannerTime = result.rows[0].timestamp as string;
+ });
+ await ready;
+ // Begin while the scanner holds the row; without producer serialization
+ // this reservation completes before the scanner releases its watermark.
+ const reservation = model.startRun(widget.id, { trigger: 'manual' });
+ await serverDB.execute(sql`SELECT pg_sleep(0.05)`);
+ release();
+ await scanner;
+ const run = await reservation;
+ const result = await serverDB.execute(
+ sql`SELECT created_at > ${scannerTime}::timestamptz AS after_scan FROM widget_runs WHERE id = ${run!.id}::uuid`,
+ );
+ expect(result.rows[0].after_scan).toBe(true);
+ },
+ );
+});
diff --git a/packages/database/src/models/goalSubscription.ts b/packages/database/src/models/goalSubscription.ts
new file mode 100644
index 00000000000..c160e31c274
--- /dev/null
+++ b/packages/database/src/models/goalSubscription.ts
@@ -0,0 +1,22 @@
+import { and, eq, sql } from 'drizzle-orm';
+
+import { goalSubscriptions } from '../schemas/goalSubscription';
+import type { LobeChatDatabase } from '../type';
+
+/** Subscription binding lifecycle; callers authorize and lock the owning Goal. */
+export class GoalSubscriptionModel {
+ constructor(private readonly db: LobeChatDatabase) {}
+
+ /** Privileged primitive: call only after authorizing and locking the owning Goal. */
+ disableForGoal = async (goalId: string) => {
+ await this.db
+ .update(goalSubscriptions)
+ .set({
+ enabled: false,
+ bindingRevision: sql`${goalSubscriptions.bindingRevision} + 1`,
+ cursor: sql`${goalSubscriptions.cursor} - 'pendingWake'`,
+ updatedAt: new Date(),
+ })
+ .where(and(eq(goalSubscriptions.goalId, goalId), eq(goalSubscriptions.enabled, true)));
+ };
+}
diff --git a/packages/database/src/models/metric.ts b/packages/database/src/models/metric.ts
index 7887ed05b1a..0a3ab7eed35 100644
--- a/packages/database/src/models/metric.ts
+++ b/packages/database/src/models/metric.ts
@@ -92,7 +92,14 @@ export class MetricModel {
.returning();
if (inserted) return inserted;
- return this.findByKey(params.subjectType, params.subjectId, params.key);
+ const existing = await this.findByKey(params.subjectType, params.subjectId, params.key);
+ if (
+ existing?.subjectType === 'widget' &&
+ (existing.kind !== (params.kind ?? 'gauge') || existing.unit !== (params.unit ?? null))
+ ) {
+ throw new Error('Metric semantics changed: publish a new metric key');
+ }
+ return existing;
};
findById = async (id: string): Promise<MetricItem | undefined> => {
@@ -169,6 +176,14 @@ export class MetricModel {
};
update = async (id: string, patch: MetricPatch): Promise<MetricItem | undefined> => {
+ const current = await this.findById(id);
+ if (
+ current?.subjectType === 'widget' &&
+ ((patch.kind !== undefined && patch.kind !== current.kind) ||
+ (patch.unit !== undefined && patch.unit !== current.unit) ||
+ patch.metadata !== undefined)
+ )
+ throw new Error('Widget metric semantics are immutable: publish a new metric key');
const [row] = await this.db
.update(metrics)
.set(patch)
diff --git a/packages/database/src/models/widget.ts b/packages/database/src/models/widget.ts
index aded20236d6..72aa48d9e46 100644
--- a/packages/database/src/models/widget.ts
+++ b/packages/database/src/models/widget.ts
@@ -94,6 +94,8 @@ export interface FinishWidgetRunInput {
durationMs?: number | null;
error?: WidgetRunError | null;
exitCode?: number | null;
+ /** Fence an obsolete worker after a scheduled lease takeover. */
+ expectedStartedAt?: Date;
finishedAt?: Date;
output?: WidgetOutput | null;
sandboxId?: string | null;
@@ -757,6 +759,7 @@ export class WidgetModel {
.values({
// Millisecond precision on purpose: the lease is compared-and-set
// against the value a reader got back as a JS Date.
+ createdAt: sql`clock_timestamp()`,
startedAt: new Date(),
status: 'running',
trigger: 'schedule',
@@ -865,27 +868,36 @@ export class WidgetModel {
if (!versionId) throw new Error('Widget has no version to run');
if (!isUuid(versionId)) throw new Error('Version does not belong to this widget');
- const [version] = await db
- .select({ id: widgetVersions.id })
- .from(widgetVersions)
- .where(and(eq(widgetVersions.id, versionId), eq(widgetVersions.widgetId, widget.id)))
- .limit(1);
- if (!version) throw new Error('Version does not belong to this widget');
-
- const [run] = await db
- .insert(widgetRuns)
- .values({
- operationId: input.operationId ?? null,
- status: 'running',
- trigger: input.trigger,
- userId: widget.userId,
- versionId,
- widgetId: widget.id,
- workspaceId: widget.workspaceId,
- })
- .returning();
-
- return run;
+ return db.transaction(async (tx) => {
+ // Scanners and every reservation share this lock. Allocate the timestamp
+ // AFTER acquiring it: transaction-start timestamps can commit behind a cursor.
+ const [current] = await tx
+ .select()
+ .from(widgets)
+ .where(eq(widgets.id, widget.id))
+ .for('update');
+ if (!current || current.isDeleted) throw new Error('Widget unavailable');
+ const [version] = await tx
+ .select({ id: widgetVersions.id })
+ .from(widgetVersions)
+ .where(and(eq(widgetVersions.id, versionId), eq(widgetVersions.widgetId, widget.id)));
+ if (!version) throw new Error('Version does not belong to this widget');
+ const [run] = await tx
+ .insert(widgetRuns)
+ .values({
+ createdAt: sql`clock_timestamp()`,
+ startedAt: new Date(),
+ operationId: input.operationId ?? null,
+ status: 'running',
+ trigger: input.trigger,
+ userId: current.userId,
+ versionId,
+ widgetId: current.id,
+ workspaceId: current.workspaceId,
+ })
+ .returning();
+ return run;
+ });
}
/**
@@ -930,8 +942,20 @@ export class WidgetModel {
db: LobeChatDatabase,
runId: string,
input: FinishWidgetRunInput,
+ publishMetrics?: (tx: Transaction, run: WidgetRunRow) => Promise<void>,
): Promise<{ folded: boolean; run: WidgetRunRow } | undefined> {
return db.transaction(async (tx) => {
+ const [reservation] = await tx
+ .select({ widgetId: widgetRuns.widgetId })
+ .from(widgetRuns)
+ .where(eq(widgetRuns.id, runId));
+ if (!reservation) return undefined;
+ // Match reservation/scanner lock order, before touching the run row.
+ await tx
+ .select({ id: widgets.id })
+ .from(widgets)
+ .where(eq(widgets.id, reservation.widgetId))
+ .for('update');
const finishedAt = input.finishedAt ?? new Date();
const [run] = await tx
.update(widgetRuns)
@@ -948,7 +972,15 @@ export class WidgetModel {
stderr: input.stderr ?? null,
stdout: input.stdout ?? null,
})
- .where(and(eq(widgetRuns.id, runId), eq(widgetRuns.status, 'running')))
+ .where(
+ and(
+ eq(widgetRuns.id, runId),
+ eq(widgetRuns.status, 'running'),
+ input.expectedStartedAt
+ ? sql`date_trunc('milliseconds', ${widgetRuns.startedAt}) = ${input.expectedStartedAt.toISOString()}::timestamptz`
+ : undefined,
+ ),
+ )
.returning();
if (!run) return undefined;
@@ -980,6 +1012,9 @@ export class WidgetModel {
})
.where(eq(widgets.id, run.widgetId));
+ // Throwing rolls back completion and snapshot as well as all metric writes.
+ // A retry never observes a completed run with unfinished publication.
+ if (input.status === 'succeeded' && publishMetrics) await publishMetrics(tx, run);
return { folded: true, run };
});
}
diff --git a/packages/database/src/repositories/goal/__tests__/index.test.ts b/packages/database/src/repositories/goal/__tests__/index.test.ts
new file mode 100644
index 00000000000..594b6c68317
--- /dev/null
+++ b/packages/database/src/repositories/goal/__tests__/index.test.ts
@@ -0,0 +1,77 @@
+// @vitest-environment node
+import { randomUUID } from 'node:crypto';
+
+import { eq, sql } from 'drizzle-orm';
+import { afterEach, beforeEach, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { WidgetModel } from '../../../models/widget';
+import { goalSubscriptions, users } from '../../../schemas';
+import { GoalRepository } from '../index';
+
+const db = await getTestDB();
+const owner = `goal-repo-${randomUUID()}`;
+const other = `goal-repo-other-${randomUUID()}`;
+beforeEach(async () => {
+ await db.insert(users).values([{ id: owner }, { id: other }]);
+});
+afterEach(async () => {
+ await db.delete(users).where(sql`${users.id} IN (${owner}, ${other})`);
+});
+
+it('rolls back the Goal transition if disabling its subscriptions fails, then fences on retry', async () => {
+ const repo = new GoalRepository(db, owner);
+ const goal = await repo.create({ title: 'Atomic pause', status: 'running' });
+ const widget = await new WidgetModel(db, owner).create({ title: 'Shared' });
+ const version = await new WidgetModel(db, owner).createVersion(widget.id, {
+ script: 'console.log(1)',
+ runtime: 'node',
+ sourceType: 'agent',
+ outputType: 'stat',
+ });
+ const [sub] = await db
+ .insert(goalSubscriptions)
+ .values({
+ goalId: goal.id,
+ userId: owner,
+ widgetId: widget.id,
+ confirmedVersionId: version!.id,
+ enabled: true,
+ binding: { semanticsHash: version!.contentHash },
+ freshnessPolicy: { maxAgeMs: 60000, maxFutureSkewMs: 0 },
+ wakeCondition: { type: 'each_valid_run' },
+ cursor: { pendingWake: true },
+ })
+ .returning();
+ await expect(
+ new GoalRepository(db, other).updateStatus(goal.id, 'paused'),
+ ).resolves.toBeUndefined();
+ // Force the subscription write to reject while leaving the initial row valid.
+ await db.execute(
+ sql.raw(
+ `ALTER TABLE goal_subscriptions ADD CONSTRAINT test_goal_repo_fence CHECK (id <> '${sub.id}'::uuid OR binding_revision = 1)`,
+ ),
+ );
+ try {
+ await expect(repo.updateStatus(goal.id, 'paused')).rejects.toThrow();
+ expect((await repo.findById(goal.id))?.status).toBe('running');
+ const [unchanged] = await db
+ .select()
+ .from(goalSubscriptions)
+ .where(eq(goalSubscriptions.id, sub.id));
+ expect(unchanged.enabled).toBe(true);
+ expect(unchanged.bindingRevision).toBe(1);
+ expect(unchanged.cursor.pendingWake).toBe(true);
+ } finally {
+ await db.execute(sql`ALTER TABLE goal_subscriptions DROP CONSTRAINT test_goal_repo_fence`);
+ }
+ await repo.updateStatus(goal.id, 'paused');
+ expect((await repo.findById(goal.id))?.status).toBe('paused');
+ const [stopped] = await db
+ .select()
+ .from(goalSubscriptions)
+ .where(eq(goalSubscriptions.id, sub.id));
+ expect(stopped.enabled).toBe(false);
+ expect(stopped.bindingRevision).toBe(2);
+ expect(stopped.cursor.pendingWake).toBeUndefined();
+});
diff --git a/packages/database/src/repositories/goal/index.ts b/packages/database/src/repositories/goal/index.ts
new file mode 100644
index 00000000000..f6ad6c1fd52
--- /dev/null
+++ b/packages/database/src/repositories/goal/index.ts
@@ -0,0 +1,25 @@
+import { GoalModel } from '../../models/goal';
+import { GoalSubscriptionModel } from '../../models/goalSubscription';
+import type { LobeChatDatabase } from '../../type';
+
+/** Goal operations with atomic lifecycle fencing of the separate subscription aggregate. */
+export class GoalRepository extends GoalModel {
+ constructor(
+ private readonly database: LobeChatDatabase,
+ private readonly ownerId: string,
+ private readonly scope?: string,
+ ) {
+ super(database, ownerId, scope);
+ }
+
+ override update = async (...args: Parameters<GoalModel['update']>) =>
+ this.database.transaction(async (tx) => {
+ const db = tx as LobeChatDatabase;
+ const row = await new GoalModel(db, this.ownerId, this.scope).update(...args);
+ // Goal update holds the root lock before subscriptions, matching consumption.
+ if (row && ['paused', 'canceled', 'achieved', 'failed'].includes(row.status)) {
+ await new GoalSubscriptionModel(db).disableForGoal(row.id);
+ }
+ return row;
+ });
+}
diff --git a/packages/types/src/goalSubscription.ts b/packages/types/src/goalSubscription.ts
index dab4b38ead7..4a261d8b810 100644
--- a/packages/types/src/goalSubscription.ts
+++ b/packages/types/src/goalSubscription.ts
@@ -2,11 +2,15 @@ import type { GoalMetricComparison } from './goal';
import type { MetricKind } from './metric';
/** Planning policy; collection cadence remains owned by the Widget schedule. */
-export type GoalSubscriptionWakeCondition =
+export type GoalSubscriptionWakeCondition = (
| { type: 'each_valid_run' }
| { intervalMs: number; type: 'observation_window' }
| { op: GoalMetricComparison; target: number; type: 'threshold' }
- | { minimumAbsoluteChange: number; type: 'change' };
+ | { minimumAbsoluteChange: number; type: 'change' }
+) & {
+ /** Independent minimum time between planning wakes; defaults to one minute. */
+ minimumPlanningIntervalMs?: number;
+};
/** Strict eligibility for Goal evaluation, independent of card rendering. */
export interface GoalSubscriptionFreshnessPolicy {
@@ -32,6 +36,8 @@ export interface GoalSubscriptionCursor {
lastWakeAt?: string;
/** Last accepted observation in (observed_at, UUID) order for this binding. */
observation?: { observedAt: string; pointId: string };
+ /** Eligible observations await a durable Goal wait receipt; no values copied. */
+ pendingWake?: boolean;
/** Last completely handled run in (created_at, UUID) order; never a running run. */
run?: { createdAt: string; runId: string };
}
diff --git a/src/services/goal.ts b/src/services/goal.ts
index 9d2edff6b24..748333b0a34 100644
--- a/src/services/goal.ts
+++ b/src/services/goal.ts
@@ -4,6 +4,8 @@ import type {
GoalGraphSnapshot,
GoalMetricCriterion,
GoalNodeKind,
+ GoalSubscriptionFreshnessPolicy,
+ GoalSubscriptionWakeCondition,
GoalTickResult,
} from '@lobechat/types';
@@ -32,6 +34,37 @@ export interface GoalListParams {
/** Every graph method takes the `goals` row id. */
class GoalService {
+ enableSubscription = async (id: string, bindingRevision: number) =>
+ (await lambdaClient.goal.enableSubscription.mutate({ id, bindingRevision })).data;
+ disableSubscription = async (id: string, bindingRevision: number) =>
+ (await lambdaClient.goal.disableSubscription.mutate({ id, bindingRevision })).data;
+
+ listSubscriptions = async (goalId: string) =>
+ (await lambdaClient.goal.listSubscriptions.query({ goalId })).data;
+
+ bindSubscription = async (input: {
+ goalId: string;
+ widgetId: string;
+ metricId: string | null;
+ criterionKey?: string;
+ confirmedVersionId: string;
+ confirmedContentHash: string;
+ freshnessPolicy: GoalSubscriptionFreshnessPolicy;
+ wakeCondition: GoalSubscriptionWakeCondition;
+ }) => (await lambdaClient.goal.bindSubscription.mutate(input)).data;
+
+ rebindSubscription = async (
+ input: Parameters<GoalService['bindSubscription']>[0] & { id: string; bindingRevision: number },
+ ) => (await lambdaClient.goal.rebindSubscription.mutate(input)).data;
+
+ updateSubscription = async (input: {
+ id: string;
+ bindingRevision: number;
+ enabled: boolean;
+ freshnessPolicy: GoalSubscriptionFreshnessPolicy;
+ wakeCondition: GoalSubscriptionWakeCondition;
+ }) => (await lambdaClient.goal.updateSubscription.mutate(input)).data;
+
/**
* List goals. Each item is the execution-carrier task with the goal row
* attached plus subtree run statistics — see `GoalModel.list` on the server.