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.

πŸ› fix(goal): record why the coordinator parked a goal, and bound gate reads (#19151)

Arvin Xufe4c8b156abb
diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.ts
index 12a5ea86276..ccaa1f76130 100644
--- a/apps/server/src/routers/lambda/goal.ts
+++ b/apps/server/src/routers/lambda/goal.ts
@@ -1,4 +1,5 @@
import { goalStatuses } from '@lobechat/const/goal';
+import { MAX_GOAL_METRIC_CRITERIA } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
@@ -114,6 +115,7 @@ export const goalRouter = router({
target: z.number(),
}),
)
+ .max(MAX_GOAL_METRIC_CRITERIA)
.optional(),
})
.optional(),
@@ -212,13 +214,15 @@ export const goalRouter = router({
setMetricCriteria: goalWriteProcedure
.input(
idInput.extend({
- metrics: z.array(
- z.object({
- key: z.string().min(1).max(255),
- op: z.enum(['gte', 'lte', 'gt', 'lt', 'eq']).optional(),
- target: z.number(),
- }),
- ),
+ metrics: z
+ .array(
+ z.object({
+ key: z.string().min(1).max(255),
+ op: z.enum(['gte', 'lte', 'gt', 'lt', 'eq']).optional(),
+ target: z.number(),
+ }),
+ )
+ .max(MAX_GOAL_METRIC_CRITERIA),
}),
)
.mutation(async ({ ctx, input }) => {
diff --git a/apps/server/src/services/goal/decideNextMove.ts b/apps/server/src/services/goal/decideNextMove.ts
index 489c81b3ac7..20ec34615f1 100644
--- a/apps/server/src/services/goal/decideNextMove.ts
+++ b/apps/server/src/services/goal/decideNextMove.ts
@@ -113,6 +113,13 @@ export const frontierNeedsBudget = (
return needsBudget(tasksById.get(node.taskId) ?? null);
});
+/**
+ * Opening of the message the gate parks a goal with, and therefore of the
+ * reason recorded on its status trail. Shared so the recovery path that reads
+ * historical parks back cannot drift from the wording that wrote them.
+ */
+export const MEASURED_ACCEPTANCE_PAUSE_REASON = 'Measured acceptance not met';
+
/** Evaluate one numeric clause. Kept beside the gate that consumes it. */
export const compareMetric = (
rawValue: number,
@@ -409,7 +416,7 @@ const decideWithoutFrontier = (
return {
...base,
branch: 'measured_acceptance',
- message: `Measured acceptance not met: ${unmet
+ message: `${MEASURED_ACCEPTANCE_PAUSE_REASON}: ${unmet
.map((c) => `${c.key} ${c.op} ${c.target} (${c.value ?? 'no observation'})`)
.join(', ')}`,
outcome: 'no_progress',
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index 3079346801d..dbaf5306588 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -920,27 +920,136 @@ describe('GoalService', () => {
).toBe(true);
});
- it('leaves a deliberately paused goal alone when a stray sample lands', async () => {
- // `setBudget` only reopens a goal the budget actually stopped; the same
- // discipline applies here, or an unrelated measurement would restart a goal
- // somebody paused on purpose.
+ /** A goal parked by the gate, one clause short of acceptance. */
+ const parkedOnGate = async (service: GoalService) => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({
+ config: { acceptance: { metrics: [{ key: 'followers', target: 1000 }] } },
+ requirement: 'Grow the account',
+ tasks: ['Publish the first posts'],
+ title: 'Parked on a measurement',
+ });
+ 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);
+ return graph.goal.id;
+ };
+
+ it('reopens a goal parked before the pause marker existed', async () => {
+ // Rows parked by the parent implementation β€” and any parked by an old
+ // worker mid-deploy β€” carry no marker. Requiring one strictly would strand
+ // them until somebody pressed Resume by hand, so the transition's recorded
+ // actor stands in for it.
+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);
+ const service = new GoalService(serverDB, userId);
+ const goalModel = new GoalModel(serverDB, userId);
+ const goalId = await parkedOnGate(service);
+
+ // Exactly what a pre-marker row looks like.
+ const parked = (await goalModel.findById(goalId))!;
+ await goalModel.update(goalId, { config: { ...parked.config, pausedBy: undefined } });
+
+ const cleared = await service.recordObservation(goalId, { key: 'followers', value: 5000 });
+
+ expect(cleared.shouldAdvance).toBe(true);
+ expect((await goalModel.findById(goalId))?.status).toBe('running');
+ });
+
+ it('does not let an observation restart a goal the coordinator parked for another reason', async () => {
+ // The coordinator also parks goals that are deadlocked or out of budget.
+ // Those carry no marker either once they predate it, so the fallback has to
+ // read *why* it parked β€” not just that it was the coordinator.
vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);
const service = new GoalService(serverDB, userId);
const goalModel = new GoalModel(serverDB, userId);
const graph = await service.create({
- requirement: 'No measured gate here',
- tasks: ['Do the work'],
- title: 'Deliberately paused',
+ config: { acceptance: { metrics: [{ key: 'followers', target: 1000 }] } },
+ requirement: 'Deadlocked before the gate',
+ tasks: ['A', 'B'],
+ title: 'Parked with work outstanding',
});
- await service.tick(graph.goal.id);
- await service.pause(graph.goal.id);
+ const [a, b] = graph.nodes.filter((n) => n.kind === 'task');
+ const graphModel = new GoalGraphModel(serverDB, userId);
+ await graphModel.createEdge(graph.goal.id, a.id, b.id, 'depends_on');
+ await graphModel.createEdge(graph.goal.id, b.id, a.id, 'depends_on');
- const stray = await service.recordObservation(graph.goal.id, { key: 'followers', value: 10 });
+ await service.tick(graph.goal.id); // deadlock β†’ no_frontier β†’ paused
+ expect((await goalModel.findById(graph.goal.id))?.status).toBe('paused');
+
+ const satisfying = await service.recordObservation(graph.goal.id, {
+ key: 'followers',
+ value: 5000,
+ });
- expect(stray.shouldAdvance).toBe(false);
+ expect(satisfying.shouldAdvance).toBe(false);
expect((await goalModel.findById(graph.goal.id))?.status).toBe('paused');
});
+ it('leaves a deliberately paused goal alone even when the measurement lands', async () => {
+ // The hard case: same status, same terminal phase, same clauses as a goal
+ // the coordinator parked. Only the recorded pause reason tells them apart,
+ // and without it a satisfying sample would restart a goal somebody stopped
+ // on purpose β€” and run its acceptance work.
+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);
+ const service = new GoalService(serverDB, userId);
+ const goalModel = new GoalModel(serverDB, userId);
+ const goalId = await parkedOnGate(service);
+ await service.pause(goalId);
+
+ const satisfying = await service.recordObservation(goalId, { key: 'followers', value: 5000 });
+
+ expect(satisfying.shouldAdvance).toBe(false);
+ expect((await goalModel.findById(goalId))?.status).toBe('paused');
+ expect(
+ (await service.graph(goalId)).nodes.some((n) => n.title === 'Complete full Goal acceptance'),
+ ).toBe(false);
+ });
+
+ it('resumes a user-paused goal only through resume, and then it advances again', async () => {
+ // The other half: once the person lifts their own pause, the goal is the
+ // coordinator's again.
+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);
+ const service = new GoalService(serverDB, userId);
+ const goalId = await parkedOnGate(service);
+ await service.pause(goalId);
+ await service.recordObservation(goalId, { key: 'followers', value: 5000 });
+
+ await service.resume(goalId);
+
+ expect(await service.tick(goalId)).toMatchObject({ outcome: 'advanced' });
+ });
+
+ it('unblocks a parked goal when its last clause is dropped', async () => {
+ // `setMetricCriteria(id, [])` is the advertised way to clear the gate. It
+ // used to leave the goal parked on a gate that no longer existed, so the
+ // scheduled advance ticked straight back out as `goal_paused` and only a
+ // manual resume could move it.
+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);
+ const service = new GoalService(serverDB, userId);
+ const goalModel = new GoalModel(serverDB, userId);
+ const goalId = await parkedOnGate(service);
+ expect((await goalModel.findById(goalId))?.status).toBe('paused');
+
+ await service.setMetricCriteria(goalId, []);
+
+ expect((await goalModel.findById(goalId))?.status).toBe('running');
+ expect(await service.tick(goalId)).toMatchObject({ outcome: 'advanced' });
+ });
+
+ it('unblocks a parked goal when a clause is relaxed below the measurement', async () => {
+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);
+ const service = new GoalService(serverDB, userId);
+ const goalModel = new GoalModel(serverDB, userId);
+ const goalId = await parkedOnGate(service);
+ await service.recordObservation(goalId, { key: 'followers', value: 400 });
+ expect((await goalModel.findById(goalId))?.status).toBe('paused');
+
+ await service.setMetricCriteria(goalId, [{ key: 'followers', target: 100 }]);
+
+ expect((await goalModel.findById(goalId))?.status).toBe('running');
+ });
+
it('keeps the numeric gate when the delivery criteria are bound or rebound', async () => {
// Both writers used to rebuild `config.acceptance` from `criteriaIds`
// alone, so declaring criteria β€” at creation or later from the goal page β€”
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index 1355e0d8aff..288229ddb0f 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -10,6 +10,7 @@ import type {
GoalMetricCriterion,
GoalNodeKind,
GoalNodeStatus,
+ GoalPauseReason,
GoalStatus,
GoalTickResult,
MetricKind,
@@ -43,6 +44,7 @@ import {
GOAL_ACCEPTANCE_TASK_TITLE,
type GoalMove,
LEASE_EXPIRED_ERROR,
+ MEASURED_ACCEPTANCE_PAUSE_REASON,
needsMetricCriteria,
selectFrontier,
TERMINAL_NODE_STATUSES,
@@ -325,25 +327,92 @@ export class GoalService {
/**
* Whether the coordinator is worth waking: either the goal is already
- * running, or it was parked short of its measured acceptance and every
- * clause now holds.
+ * running, or the coordinator itself parked it on a measured gate that no
+ * longer holds it.
+ *
+ * The `pausedBy` marker is what makes this safe. A goal paused by a person
+ * looks exactly like one parked by the gate β€” same status, same terminal
+ * phase, same clauses β€” so without it an arriving measurement would restart
+ * a goal somebody deliberately stopped.
+ *
+ * "No longer holds it" covers both ways out: every clause now satisfied, and
+ * the clauses being dropped altogether (`setMetricCriteria(id, [])`), which
+ * otherwise left the goal parked on a gate that no longer existed.
*/
- private reopenIfMeasurementCleared = async (goalId: string): Promise<boolean> => {
+ private reopenIfMeasurementCleared = async (
+ goalId: string,
+ /**
+ * Whether the gate held the goal *before* the caller's edit, for callers
+ * that change the clauses themselves: dropping the last one erases the
+ * evidence, so the verdict is taken from the state that preceded it β€” the
+ * same way `setBudget` reads what was binding before it wrote.
+ */
+ parkedBeforeEdit?: boolean,
+ ): Promise<boolean> => {
const graph = await this.coordinatorGraph.getGraph(goalId);
if (!graph) return false;
if (graph.goal.status !== 'paused') return true;
- if (!needsMetricCriteria(graph)) return false;
+ if (!(parkedBeforeEdit ?? this.isParkedOnMeasuredGate(graph))) return false;
- const { allMet } = await this.evaluateMetricCriteria(graph);
- if (!allMet) return false;
+ if (needsMetricCriteria(graph)) {
+ const { allMet } = await this.evaluateMetricCriteria(graph);
+ if (!allMet) return false;
+ }
+ await this.setPauseReason(goalId, undefined);
await this.transitionStatus(graph.goal, 'running', 'a measurement cleared the acceptance gate');
return true;
};
+ /**
+ * Record (or clear) why the coordinator is holding this goal paused.
+ *
+ * Kept on the goal's JSONB config rather than derived from the event log:
+ * control flow should not depend on a capped audit trail, and the marker has
+ * to survive for as long as the pause does β€” which for a long-horizon goal
+ * is the whole wait.
+ */
+ private setPauseReason = async (goalId: string, reason: GoalPauseReason | undefined) => {
+ await this.goalModel.updatePauseReason(goalId, reason);
+ };
+
+ /**
+ * Whether the coordinator is the one holding this paused goal.
+ *
+ * The marker answers it outright. Goals parked before the marker existed β€”
+ * and any parked by an old worker mid-deploy β€” carry none, so fall back to
+ * who performed the transition: every status change records a goal-entity
+ * event, and the newest one is by definition the transition that produced
+ * the current status. A coordinator park is attributed to `system`, a user
+ * pause to `user`, so the two stay distinguishable without the marker.
+ *
+ * Absent both, the pause is left alone: a goal wrongly resumed spends money
+ * against an explicit human decision, while one left parked says so on its
+ * row and is one Resume away.
+ */
+ private isParkedOnMeasuredGate = (graph: GoalGraphSnapshot): boolean => {
+ if (graph.goal.status !== 'paused') return false;
+ if (graph.goal.config?.pausedBy) return graph.goal.config.pausedBy === 'measured_acceptance';
+
+ // Match the park this gate actually recorded, not merely "the coordinator
+ // paused it": it also parks goals that are blocked or out of budget, and an
+ // unrelated sample must not restart either. The newest goal-entity event is
+ // by definition the transition that produced the current status; if two
+ // share a millisecond and the read picks the other one, the result is a
+ // missed reopen rather than a wrongful one.
+ const lastTransition = graph.events.find((event) => event.entityType === 'goal');
+ return (
+ lastTransition?.actorType !== 'user' &&
+ !!lastTransition?.reason?.startsWith(MEASURED_ACCEPTANCE_PAUSE_REASON) &&
+ needsMetricCriteria(graph)
+ );
+ };
+
setMetricCriteria = async (goalId: string, metrics: GoalMetricCriterion[]) => {
- const goal = await this.goalModel.findById(goalId);
- if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ const before = await this.coordinatorGraph.getGraph(goalId);
+ if (!before) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ const parkedOnGate = this.isParkedOnMeasuredGate(before);
+ const goal = before.goal;
await this.goalModel.update(goalId, {
config: {
...goal.config,
@@ -354,7 +423,7 @@ export class GoalService {
},
});
// Relaxing or dropping a clause can clear a gate the goal is parked on.
- await this.reopenIfMeasurementCleared(goalId);
+ await this.reopenIfMeasurementCleared(goalId, parkedOnGate);
return this.graph(goalId);
};
@@ -535,6 +604,10 @@ export class GoalService {
pause = async (goalId: string) => {
const graph = await this.requireGraph(goalId);
+ // From here the pause is the person's, so no later measurement lifts it.
+ // Written even when the goal is already paused β€” that transition is a
+ // no-op, so this marker is the only record that the person took it over.
+ await this.setPauseReason(goalId, 'user');
const goal = await this.transitionStatus(graph.goal, 'paused', 'paused by user', 'user');
if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
return goal;
@@ -565,23 +638,39 @@ export class GoalService {
const declared = graph.goal.config?.acceptance?.metrics ?? [];
const metricModel = new MetricModel(this.db, this.userId, this.workspaceId);
- const criteria = await Promise.all(
- declared.map(async (criterion) => {
- const op = criterion.op ?? 'gte';
- const series = await metricModel.findByKey('goal', graph.goal.id, criterion.key);
- const point = series ? await metricModel.latestPoint(series.id) : undefined;
- const value = point?.value ?? null;
- return {
- key: criterion.key,
- met: value !== null && compareMetric(value, op, criterion.target),
- observedAt: point ? new Date(point.observedAt).getTime() : undefined,
- op,
- target: criterion.target,
- value,
- };
+ // 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
+ // otherwise pace the connection pool for unrelated requests. Only the
+ // declared keys are fetched β€” the same goal can accumulate any number of
+ // other sampled series, and none of them can gate acceptance.
+ const series = await metricModel.findByKeys(
+ 'goal',
+ graph.goal.id,
+ declared.map((criterion) => criterion.key),
+ );
+ const seriesByKey = new Map(series.map((item) => [item.key, item]));
+ const latestByMetricId = await metricModel.latestPointsByMetricIds(
+ declared.flatMap((criterion) => {
+ const id = seriesByKey.get(criterion.key)?.id;
+ return id ? [id] : [];
}),
);
+ 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 value = point?.value ?? null;
+ return {
+ key: criterion.key,
+ met: value !== null && compareMetric(value, op, criterion.target),
+ observedAt: point ? new Date(point.observedAt).getTime() : undefined,
+ op,
+ target: criterion.target,
+ value,
+ };
+ });
+
return { allMet: criteria.every((criterion) => criterion.met), criteria };
};
@@ -659,6 +748,7 @@ export class GoalService {
const status = graph.decisions.some((decision) => decision.status === 'pending')
? 'review'
: 'running';
+ await this.setPauseReason(goalId, undefined);
const goal = await this.transitionStatus(graph.goal, status, 'resumed by user', 'user');
return goal ?? graph.goal;
};
@@ -818,6 +908,7 @@ export class GoalService {
// the newest-first scan limit. `recordObservation` resumes it when a
// measurement actually clears the gate.
case 'measured_acceptance': {
+ await this.setPauseReason(goalId, 'measured_acceptance');
await this.transitionStatus(graph.goal, 'paused', move.message);
effects.push({ type: 'goal_status', detail: 'paused' });
return observe({ goalId, message: move.message, outcome: move.outcome });
diff --git a/packages/database/src/models/__tests__/goal.test.ts b/packages/database/src/models/__tests__/goal.test.ts
index e54c6161a20..475dd2deab0 100644
--- a/packages/database/src/models/__tests__/goal.test.ts
+++ b/packages/database/src/models/__tests__/goal.test.ts
@@ -57,6 +57,50 @@ describe('GoalModel', () => {
});
});
+ describe('updatePauseReason', () => {
+ it('patches only the marker, leaving a concurrent config edit intact', async () => {
+ // The coordinator writes this from a tick while the user edits budget and
+ // acceptance criteria on the same JSONB column from the goal page. A
+ // read-modify-write of the whole config would let whichever landed second
+ // discard the other's work.
+ const goal = await goalModel.create({
+ config: { acceptance: { metrics: [{ key: 'followers', target: 1000 }] } },
+ subjectType: 'standalone',
+ title: 'Concurrent config writers',
+ });
+
+ await goalModel.updatePauseReason(goal.id, 'measured_acceptance');
+
+ const parked = await goalModel.findById(goal.id);
+ expect(parked?.config).toMatchObject({
+ acceptance: { metrics: [{ key: 'followers', target: 1000 }] },
+ pausedBy: 'measured_acceptance',
+ });
+
+ await goalModel.updatePauseReason(goal.id, undefined);
+
+ const cleared = await goalModel.findById(goal.id);
+ expect(cleared?.config?.pausedBy).toBeUndefined();
+ expect(cleared?.config?.acceptance?.metrics).toEqual([{ key: 'followers', target: 1000 }]);
+ });
+
+ it('starts from an empty object when the goal has no config yet', async () => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'No config' });
+
+ await goalModel.updatePauseReason(goal.id, 'measured_acceptance');
+
+ expect((await goalModel.findById(goal.id))?.config?.pausedBy).toBe('measured_acceptance');
+ });
+
+ it('does not reach a goal owned by somebody else', async () => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Owned' });
+
+ await new GoalModel(serverDB, otherUserId).updatePauseReason(goal.id, 'measured_acceptance');
+
+ expect((await goalModel.findById(goal.id))?.config?.pausedBy).toBeUndefined();
+ });
+ });
+
describe('findByGraphTask', () => {
it('finds the goal whose graph owns a Task', async () => {
const task = await new TaskModel(serverDB, userId).create({ instruction: 'do the work' });
diff --git a/packages/database/src/models/__tests__/metric.test.ts b/packages/database/src/models/__tests__/metric.test.ts
index 10c3cac8206..db9dd05d301 100644
--- a/packages/database/src/models/__tests__/metric.test.ts
+++ b/packages/database/src/models/__tests__/metric.test.ts
@@ -124,6 +124,66 @@ describe('MetricModel', () => {
});
});
+ describe('findByKeys', () => {
+ it('fetches only the named series, not everything the subject has sampled', async () => {
+ await seed('declared.one');
+ await seed('declared.two');
+ await seed('sampled.noise');
+
+ const found = await model.findByKeys('goal', 'goal_metric_test', [
+ 'declared.one',
+ 'declared.two',
+ 'never.created',
+ ]);
+
+ expect(found.map((item) => item.key)).toEqual(['declared.one', 'declared.two']);
+ expect(await model.findByKeys('goal', 'goal_metric_test', [])).toEqual([]);
+ });
+
+ it('scopes to the owner', async () => {
+ await seed('declared.one');
+ expect(await otherModel.findByKeys('goal', 'goal_metric_test', ['declared.one'])).toEqual([]);
+ });
+ });
+
+ describe('latestPointsByMetricIds', () => {
+ it('returns one newest row per series in a single read', async () => {
+ const a = (await seed('a.metric'))!;
+ const b = (await seed('b.metric'))!;
+ for (const [series, at, value] of [
+ [a, '2026-09-01T00:00:00Z', 1],
+ [a, '2026-09-03T00:00:00Z', 3],
+ // Written last but observed earlier: newest means observed, not inserted.
+ [a, '2026-09-02T00:00:00Z', 2],
+ [b, '2026-09-01T00:00:00Z', 10],
+ ] as const) {
+ await model.addPoint(series.id, {
+ actorType: 'system',
+ observedAt: new Date(at),
+ sourceType: 'probe',
+ value,
+ });
+ }
+
+ const latest = await model.latestPointsByMetricIds([a.id, b.id]);
+ expect(latest.get(a.id)?.value).toBe(3);
+ expect(latest.get(b.id)?.value).toBe(10);
+ });
+
+ it('is empty for no ids and skips series outside the owner scope', async () => {
+ const series = (await seed())!;
+ await model.addPoint(series.id, {
+ actorType: 'user',
+ observedAt: new Date(),
+ sourceType: 'manual',
+ value: 1,
+ });
+
+ expect((await model.latestPointsByMetricIds([])).size).toBe(0);
+ expect((await otherModel.latestPointsByMetricIds([series.id])).size).toBe(0);
+ });
+ });
+
describe('listPoints', () => {
const day = (d: number, h = 0) => new Date(Date.UTC(2026, 8, d, h));
diff --git a/packages/database/src/models/goal.ts b/packages/database/src/models/goal.ts
index e783d7c9514..a7297761638 100644
--- a/packages/database/src/models/goal.ts
+++ b/packages/database/src/models/goal.ts
@@ -84,6 +84,27 @@ export class GoalModel {
return row?.goal;
};
+ /**
+ * Patch only `config.pausedBy`, leaving every other key in the column alone.
+ *
+ * The coordinator writes this marker from a tick while the user edits budget
+ * and acceptance criteria on the same JSONB column from the goal page. A
+ * read-modify-write of the whole config would let whichever landed second
+ * discard the other's work β€” the user's new criteria, or the marker a
+ * measured-acceptance goal needs to ever reopen.
+ */
+ updatePauseReason = async (id: string, reason: string | undefined): Promise<void> => {
+ await this.db
+ .update(goals)
+ .set({
+ config: reason
+ ? sql`jsonb_set(COALESCE(${goals.config}, '{}'::jsonb), '{pausedBy}', ${JSON.stringify(reason)}::jsonb)`
+ : sql`COALESCE(${goals.config}, '{}'::jsonb) - 'pausedBy'`,
+ updatedAt: new Date(),
+ })
+ .where(and(eq(goals.id, id), this.ownership()));
+ };
+
update = async (id: string, value: Partial<Omit<GoalItem, 'id' | 'userId'>>) => {
const [row] = await this.db
.update(goals)
diff --git a/packages/database/src/models/metric.ts b/packages/database/src/models/metric.ts
index aeebddd6595..03fef703ba0 100644
--- a/packages/database/src/models/metric.ts
+++ b/packages/database/src/models/metric.ts
@@ -1,5 +1,5 @@
import type { MetricConfig, MetricKind, MetricSubjectType } from '@lobechat/types';
-import { and, asc, desc, eq, gte, lte, sql } from 'drizzle-orm';
+import { and, asc, desc, eq, gte, inArray, lte, sql } from 'drizzle-orm';
import type { MetricItem, MetricPointItem, NewMetricPoint } from '../schemas/metric';
import { metricPoints, metrics } from '../schemas/metric';
@@ -124,6 +124,33 @@ export class MetricModel {
return row;
};
+ /**
+ * The named series of one subject. Distinct from {@link findBySubject}: a
+ * caller that already knows which keys it needs β€” an acceptance contract
+ * naming a handful β€” must not materialize every series the subject has ever
+ * sampled, which nothing bounds.
+ */
+ findByKeys = async (
+ subjectType: MetricSubjectType,
+ subjectId: string,
+ keys: string[],
+ ): Promise<MetricItem[]> => {
+ if (keys.length === 0) return [];
+
+ return this.db
+ .select()
+ .from(metrics)
+ .where(
+ and(
+ eq(metrics.subjectType, subjectType),
+ eq(metrics.subjectId, subjectId),
+ inArray(metrics.key, keys),
+ this.seriesOwnership(),
+ ),
+ )
+ .orderBy(asc(metrics.key));
+ };
+
findBySubject = async (
subjectType: MetricSubjectType,
subjectId: string,
@@ -199,6 +226,26 @@ export class MetricModel {
return row;
};
+ /**
+ * The latest observation of many series at once, keyed by metric id.
+ *
+ * `DISTINCT ON` keeps this one query however many series are asked for β€”
+ * the per-series `latestPoint` is fine for a single read, but a caller
+ * evaluating a whole acceptance contract would otherwise issue one query per
+ * clause and pace the connection pool with it.
+ */
+ latestPointsByMetricIds = async (metricIds: string[]): Promise<Map<string, MetricPointItem>> => {
+ if (metricIds.length === 0) return new Map();
+
+ const rows = await this.db
+ .selectDistinctOn([metricPoints.metricId])
+ .from(metricPoints)
+ .where(and(inArray(metricPoints.metricId, metricIds), this.pointOwnership()))
+ .orderBy(metricPoints.metricId, desc(metricPoints.observedAt));
+
+ return new Map(rows.map((row) => [row.metricId, row]));
+ };
+
/**
* Range read for charts. Without `bucket`, raw points in ascending time.
* With `bucket`, points are `date_trunc`-grouped and aggregated by the
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index efd34ce90a0..9395f2e5c84 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -73,6 +73,13 @@ export interface GoalMetricCriterion {
target: number;
}
+/**
+ * Upper bound on declared numeric clauses. Every clause is read on each
+ * terminal tick, and an unbounded list would let one goal's acceptance payload
+ * pace the coordinator (and its database pool) for everyone else.
+ */
+export const MAX_GOAL_METRIC_CRITERIA = 20;
+
export interface GoalAcceptancePolicy {
criteriaIds?: string[];
/**
@@ -84,6 +91,17 @@ export interface GoalAcceptancePolicy {
metrics?: GoalMetricCriterion[];
}
+/**
+ * Who a goal's current pause belongs to, recorded whenever one is taken.
+ *
+ * Runtime bookkeeping rather than policy: without it, an event that clears the
+ * coordinator's reason cannot tell a park it owns from a pause a person chose,
+ * and would restart a goal somebody deliberately stopped. A person's claim is
+ * stored explicitly rather than as the absence of a marker, because pausing an
+ * already-paused goal is a no-op that leaves no other trace of who asked.
+ */
+export type GoalPauseReason = 'measured_acceptance' | 'user';
+
export interface GoalConfig {
acceptance?: GoalAcceptancePolicy;
/**
@@ -93,6 +111,8 @@ export interface GoalConfig {
* before the first result came back. Null/undefined uses the default.
*/
maxConcurrentTasks?: number | null;
+ /** Who the current pause belongs to; cleared when the goal runs again. */
+ pausedBy?: GoalPauseReason;
recovery?: GoalRecoveryPolicy;
schedule?: GoalSchedulePolicy;
}