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): gate acceptance on measured criteria (#19133)

Arvin Xudbeb3b1bf242
diff --git a/apps/server/src/routers/lambda/__tests__/goal.metricCriteria.test.ts b/apps/server/src/routers/lambda/__tests__/goal.metricCriteria.test.ts
new file mode 100644
index 00000000000..6973fd0f19d
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/goal.metricCriteria.test.ts
@@ -0,0 +1,113 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => ({})),
+}));
+
+vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({
+ withScopedPermission: vi.fn(() => (opts: any) => opts.next({ ctx: opts.ctx })),
+}));
+
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
+ const { authedProcedure } = await import('@/libs/trpc/lambda');
+ return { wsCompatProcedure: authedProcedure };
+});
+
+const mockCreate = vi.fn();
+const mockSetMetricCriteria = vi.fn();
+const mockRecordObservation = vi.fn();
+const mockFindById = vi.fn();
+
+vi.mock('@/server/services/goal', () => ({
+ GoalService: vi.fn(() => ({
+ create: mockCreate,
+ recordObservation: mockRecordObservation,
+ setMetricCriteria: mockSetMetricCriteria,
+ })),
+}));
+
+vi.mock('@/database/models/goal', () => ({
+ GoalModel: vi.fn(() => ({ findById: mockFindById })),
+}));
+
+const mockScheduleGoalAdvance = vi.fn();
+vi.mock('@/server/services/goal/scheduler', () => ({
+ scheduleGoalAdvance: mockScheduleGoalAdvance,
+}));
+
+const { goalRouter } = await import('../goal');
+
+describe('goalRouter numeric acceptance', () => {
+ const ctx: any = { serverDB: {}, userId: 'user-1', workspaceId: null };
+ const caller = goalRouter.createCaller(ctx);
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockCreate.mockResolvedValue({ goal: { id: 'goal_1' } });
+ mockFindById.mockResolvedValue({ id: 'goal_1', userId: 'user-1' });
+ mockSetMetricCriteria.mockResolvedValue({ goal: { id: 'goal_1' } });
+ mockRecordObservation.mockResolvedValue({ point: {}, series: {}, shouldAdvance: true });
+ });
+
+ it('carries measured clauses through the create contract', async () => {
+ // Zod strips unknown keys, so a clause absent from the schema would reach
+ // the service as `undefined` and leave the gate unreachable in production
+ // while the service-level tests still passed.
+ await caller.create({
+ config: { acceptance: { metrics: [{ key: 'followers', target: 1_000_000 }] } },
+ title: 'Grow the account',
+ });
+
+ expect(mockCreate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ config: { acceptance: { metrics: [{ key: 'followers', target: 1_000_000 }] } },
+ }),
+ );
+ });
+
+ it('declares clauses after creation', async () => {
+ await caller.setMetricCriteria({
+ id: 'goal_1',
+ metrics: [{ key: 'churn', op: 'lte', target: 5 }],
+ });
+
+ expect(mockSetMetricCriteria).toHaveBeenCalledWith('goal_1', [
+ { key: 'churn', op: 'lte', target: 5 },
+ ]);
+ });
+
+ it('rejects a comparison the evaluator does not implement', async () => {
+ await expect(
+ caller.setMetricCriteria({
+ id: 'goal_1',
+ metrics: [{ key: 'churn', op: 'approx' as never, target: 5 }],
+ }),
+ ).rejects.toThrow();
+ expect(mockSetMetricCriteria).not.toHaveBeenCalled();
+ });
+
+ describe('recordObservation', () => {
+ it('wakes the coordinator when the measurement cleared the gate', async () => {
+ await caller.recordObservation({ id: 'goal_1', key: 'followers', value: 1200 });
+
+ expect(mockRecordObservation).toHaveBeenCalledWith('goal_1', {
+ key: 'followers',
+ value: 1200,
+ });
+ expect(mockScheduleGoalAdvance).toHaveBeenCalledWith(
+ expect.objectContaining({ goalId: 'goal_1', trigger: 'observe' }),
+ );
+ });
+
+ it('does not queue an advance a parked goal would tick straight back out of', async () => {
+ mockRecordObservation.mockResolvedValue({ point: {}, series: {}, shouldAdvance: false });
+
+ const result = await caller.recordObservation({ id: 'goal_1', key: 'followers', value: 400 });
+
+ expect(mockScheduleGoalAdvance).not.toHaveBeenCalled();
+ // `shouldAdvance` is coordination bookkeeping, not part of the response.
+ expect(result.data).not.toHaveProperty('shouldAdvance');
+ });
+ });
+});
diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.ts
index 769a45ded3f..12a5ea86276 100644
--- a/apps/server/src/routers/lambda/goal.ts
+++ b/apps/server/src/routers/lambda/goal.ts
@@ -103,6 +103,20 @@ export const goalRouter = router({
createdByAgentId: z.string().optional(),
config: z
.object({
+ acceptance: z
+ .object({
+ /** Numeric clauses gating acceptance; keyed by a series on this goal. */
+ metrics: z
+ .array(
+ z.object({
+ key: z.string().min(1).max(255),
+ op: z.enum(['gte', 'lte', 'gt', 'lt', 'eq']).optional(),
+ target: z.number(),
+ }),
+ )
+ .optional(),
+ })
+ .optional(),
// Bounds mirror `resolveMaxConcurrentTasks`, so a rejected value and
// a clamped one cannot disagree about what the cap may be.
maxConcurrentTasks: z.number().int().min(1).max(10).nullable().optional(),
@@ -194,6 +208,80 @@ export const goalRouter = router({
}
}),
+ /** Declare or clear the numeric clauses gating this goal's acceptance. */
+ 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(),
+ }),
+ ),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ const goal = await ctx.goalModel.findById(input.id);
+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ assertWorkspaceRowManageable(ctx, goal.userId, 'goal');
+ const data = await ctx.goalService.setMetricCriteria(input.id, input.metrics);
+ // Relaxing a clause can free a goal parked short of acceptance.
+ await scheduleGoalAdvance({
+ goalId: input.id,
+ trigger: 'observe',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+ return { data, message: 'Metric criteria updated', success: true };
+ } catch (error) {
+ mapGoalError(error, 'setMetricCriteria');
+ }
+ }),
+
+ /**
+ * Record a measurement against this goal and let the coordinator react.
+ *
+ * The graph otherwise only moves when a Task settles, but a long-horizon
+ * goal advances when the *world* changes β€” a follower count, a conversion
+ * rate. This is that entry point: it writes to the generic metrics layer
+ * (subject = this goal) and schedules an advance, so a goal whose numeric
+ * acceptance was the last thing outstanding closes on the observation
+ * instead of waiting up to a sweep window.
+ */
+ recordObservation: goalWriteProcedure
+ .input(
+ idInput.extend({
+ key: z.string().min(1).max(255),
+ kind: z.enum(['gauge', 'counter']).optional(),
+ observedAt: z.coerce.date().optional(),
+ title: z.string().optional(),
+ unit: z.string().optional(),
+ value: z.number(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ const { id, ...observation } = input;
+ const { shouldAdvance, ...data } = await ctx.goalService.recordObservation(id, observation);
+ // A goal parked short of its measured acceptance is only worth waking
+ // when the measurement actually cleared the gate; otherwise the advance
+ // would tick straight back out as `goal_paused`.
+ if (shouldAdvance) {
+ await scheduleGoalAdvance({
+ goalId: id,
+ trigger: 'observe',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+ }
+ return { data, message: 'Observation recorded', success: true };
+ } catch (error) {
+ mapGoalError(error, 'recordObservation');
+ }
+ }),
+
/**
* Run the coordinator now and report where it stopped.
*
diff --git a/apps/server/src/services/goal/decideNextMove.test.ts b/apps/server/src/services/goal/decideNextMove.test.ts
index 98496c76577..832c1dd115f 100644
--- a/apps/server/src/services/goal/decideNextMove.test.ts
+++ b/apps/server/src/services/goal/decideNextMove.test.ts
@@ -2,11 +2,13 @@ import type { GoalGraphNode, GoalGraphSnapshot, TaskItem } from '@lobechat/types
import { describe, expect, it } from 'vitest';
import {
+ compareMetric,
decideNextMove,
frontierNeedsBudget,
GOAL_ACCEPTANCE_TASK_TITLE,
LEASE_EXPIRED_ERROR,
needsBudget,
+ needsMetricCriteria,
selectFrontier,
VERIFICATION_FAILED_ERROR,
} from './decideNextMove';
@@ -48,16 +50,18 @@ const decide = (
budget?: Parameters<typeof decideNextMove>[0]['budget'];
concurrency?: number;
frontierTask?: TaskItem | null;
+ metricCriteria?: Parameters<typeof decideNextMove>[0]['metricCriteria'];
tasks?: TaskItem[];
} = {},
) => {
- const { budget, concurrency = 3, frontierTask, tasks } = extra;
+ const { budget, concurrency = 3, frontierTask, metricCriteria, tasks } = extra;
const listed = tasks ?? (frontierTask ? [frontierTask] : []);
return decideNextMove({
budget,
concurrency,
frontier: selectFrontier(snapshot),
graph: snapshot,
+ metricCriteria,
tasksById: new Map(listed.map((item) => [item.id, item])),
});
};
@@ -451,3 +455,92 @@ describe('frontierNeedsBudget', () => {
expect(withTasks(snapshot, [task({ id: 'task_1', status: 'running' })])).toBe(false);
});
});
+
+describe('needsMetricCriteria', () => {
+ const withCriteria = (nodes: GoalGraphNode[]) =>
+ graph({
+ goal: {
+ ...graph().goal,
+ config: { acceptance: { metrics: [{ key: 'followers', target: 1_000_000 }] } },
+ },
+ nodes,
+ });
+
+ it('only asks for criteria in the terminal phase of a goal that declares them', () => {
+ // Evaluating them is a database read per clause; a dispatch tick must not
+ // pay for it.
+ expect(needsMetricCriteria(withCriteria([node('a', { status: 'resolved' })]))).toBe(true);
+ expect(needsMetricCriteria(withCriteria([node('a', { status: 'active' })]))).toBe(false);
+ expect(needsMetricCriteria(withCriteria([]))).toBe(false);
+ expect(needsMetricCriteria(graph({ nodes: [node('a', { status: 'resolved' })] }))).toBe(false);
+ });
+});
+
+describe('compareMetric', () => {
+ it('evaluates each comparison', () => {
+ expect(compareMetric(10, 'gte', 10)).toBe(true);
+ expect(compareMetric(9, 'gte', 10)).toBe(false);
+ expect(compareMetric(10, 'gt', 10)).toBe(false);
+ expect(compareMetric(10, 'lte', 10)).toBe(true);
+ expect(compareMetric(11, 'lt', 10)).toBe(false);
+ expect(compareMetric(10, 'eq', 10)).toBe(true);
+ });
+
+ it('reads both operands at the scale observations are stored with', () => {
+ // `metric_points.value` is numeric(20, 6): recording 0.1234567 reads back
+ // as 0.123457, so a full-precision target would make the clause
+ // unsatisfiable and could flip gte/lte right at the boundary.
+ expect(compareMetric(0.123_457, 'eq', 0.123_456_7)).toBe(true);
+ expect(compareMetric(0.123_457, 'gte', 0.123_456_7)).toBe(true);
+ expect(compareMetric(0.123_457, 'lte', 0.123_456_7)).toBe(true);
+ // Differences the column can still represent are not rounded away.
+ expect(compareMetric(0.123_457, 'eq', 0.123_458)).toBe(false);
+ });
+});
+
+describe('measured acceptance', () => {
+ const terminal = graph({
+ goal: { ...graph().goal, requirement: 'Prove it' },
+ nodes: [node('a', { status: 'resolved' })],
+ });
+
+ it('holds the goal short of the delivery contract while a number is unmet', () => {
+ // The acceptance Task is never created: an unmet number is not something a
+ // verifier can talk its way past, so running it would only spend tokens to
+ // restate the gap.
+ const move = decide(terminal, {
+ metricCriteria: {
+ allMet: false,
+ criteria: [{ key: 'followers', met: false, op: 'gte', target: 1_000_000, value: 4200 }],
+ },
+ });
+
+ expect(move).toMatchObject({ branch: 'measured_acceptance', outcome: 'no_progress' });
+ expect(move.message).toContain('followers');
+ expect(move.message).toContain('4200');
+ });
+
+ it('names a clause that was never measured rather than reading it as satisfied', () => {
+ const move = decide(terminal, {
+ metricCriteria: {
+ allMet: false,
+ criteria: [{ key: 'followers', met: false, op: 'gte', target: 1_000_000, value: null }],
+ },
+ });
+
+ expect(move.message).toContain('no observation');
+ });
+
+ it('falls through to the delivery contract once every number holds', () => {
+ expect(
+ decide(terminal, {
+ metricCriteria: {
+ allMet: true,
+ criteria: [
+ { key: 'followers', met: true, op: 'gte', target: 1_000_000, value: 1_000_001 },
+ ],
+ },
+ }),
+ ).toMatchObject({ branch: 'terminal_acceptance', outcome: 'advanced' });
+ });
+});
diff --git a/apps/server/src/services/goal/decideNextMove.ts b/apps/server/src/services/goal/decideNextMove.ts
index 3ce4a6c309c..489c81b3ac7 100644
--- a/apps/server/src/services/goal/decideNextMove.ts
+++ b/apps/server/src/services/goal/decideNextMove.ts
@@ -1,11 +1,18 @@
import type {
FrontierCandidate,
GoalBudgetState,
+ GoalMetricCriteriaState,
GoalTickBranch,
GoalTickOutcome,
} from '@lobechat/agent-tracing';
import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';
-import type { GoalGraphNode, GoalGraphSnapshot, TaskItem } from '@lobechat/types';
+import type {
+ GoalGraphNode,
+ GoalGraphSnapshot,
+ GoalMetricComparison,
+ TaskItem,
+} from '@lobechat/types';
+import { toMetricScale } from '@lobechat/types';
export { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';
@@ -106,6 +113,48 @@ export const frontierNeedsBudget = (
return needsBudget(tasksById.get(node.taskId) ?? null);
});
+/** Evaluate one numeric clause. Kept beside the gate that consumes it. */
+export const compareMetric = (
+ rawValue: number,
+ op: GoalMetricComparison,
+ rawTarget: number,
+): boolean => {
+ // Both operands are read at the storage scale: the observation was already
+ // rounded on its way into `numeric(20, 6)`, so comparing it against a
+ // full-precision target would judge two different numbers β€” `eq 0.1234567`
+ // could never hold, and `gte` / `lte` could flip at the rounding boundary.
+ const value = toMetricScale(rawValue);
+ const target = toMetricScale(rawTarget);
+ switch (op) {
+ case 'eq': {
+ return value === target;
+ }
+ case 'gt': {
+ return value > target;
+ }
+ case 'gte': {
+ return value >= target;
+ }
+ case 'lt': {
+ return value < target;
+ }
+ case 'lte': {
+ return value <= target;
+ }
+ }
+};
+
+/**
+ * Whether this tick could read numeric acceptance criteria: the goal declares
+ * some, and every Task node is terminal so the coordinator is in its terminal
+ * phase. Keeps the extra reads off every dispatch tick.
+ */
+export const needsMetricCriteria = (graph: GoalGraphSnapshot): boolean => {
+ if (!graph.goal.config?.acceptance?.metrics?.length) return false;
+ const taskNodes = graph.nodes.filter((node) => node.kind === 'task');
+ return taskNodes.length > 0 && taskNodes.every((node) => TERMINAL_NODE_STATUSES.has(node.status));
+};
+
export interface GoalMoveInput {
/** Required only when {@link needsBudget} says the branch could dispatch or recover. */
budget?: GoalBudgetState;
@@ -113,6 +162,13 @@ export interface GoalMoveInput {
concurrency: number;
frontier: FrontierSelection;
graph: GoalGraphSnapshot;
+ /**
+ * Required only when {@link needsMetricCriteria} holds β€” the terminal phase
+ * of a goal that declares numeric acceptance clauses. Evaluating them is a
+ * database read, so it happens in `tick` and travels in, the same way the
+ * budget does.
+ */
+ metricCriteria?: GoalMetricCriteriaState;
/**
* The responsible Task of every candidate that has one, keyed by task id.
* A candidate whose task id is absent from the map has lost its row.
@@ -161,6 +217,7 @@ export const decideNextMove = ({
concurrency,
frontier,
graph,
+ metricCriteria,
tasksById,
}: GoalMoveInput): GoalMove => {
const { candidates, chosen } = frontier;
@@ -239,7 +296,7 @@ export const decideNextMove = ({
return move;
}
- if (!chosen) return decideWithoutFrontier(graph, candidates);
+ if (!chosen) return decideWithoutFrontier(graph, candidates, metricCriteria);
// Everything eligible is either running, parked on a person, or waiting for a
// slot. Report which, so the row does not read as stalled when it is simply
@@ -265,7 +322,7 @@ export const decideNextMove = ({
};
}
- return decideWithoutFrontier(graph, candidates);
+ return decideWithoutFrontier(graph, candidates, metricCriteria);
};
/** What one candidate wants, or why it cannot be acted on right now. */
@@ -313,6 +370,7 @@ const decideForCandidate = ({
const decideWithoutFrontier = (
graph: GoalGraphSnapshot,
candidates: FrontierCandidate[],
+ metricCriteria?: GoalMetricCriteriaState,
): GoalMove => {
const base = { candidates };
const taskNodes = graph.nodes.filter((node) => node.kind === 'task');
@@ -341,6 +399,23 @@ const decideWithoutFrontier = (
};
}
+ // Measured clauses gate the delivery contract, and are checked before it:
+ // an unmet number is not something a verifier can talk its way past, so
+ // creating (or re-running) the acceptance Task against it would only spend
+ // tokens to restate the gap. `no_progress` leaves the goal running β€” the
+ // next observation is what moves it, not another attempt.
+ if (metricCriteria && !metricCriteria.allMet) {
+ const unmet = metricCriteria.criteria.filter((criterion) => !criterion.met);
+ return {
+ ...base,
+ branch: 'measured_acceptance',
+ message: `Measured acceptance not met: ${unmet
+ .map((c) => `${c.key} ${c.op} ${c.target} (${c.value ?? 'no observation'})`)
+ .join(', ')}`,
+ outcome: 'no_progress',
+ };
+ }
+
const acceptanceTask = taskNodes.find((node) => node.title === GOAL_ACCEPTANCE_TASK_TITLE);
if (graph.goal.requirement && !acceptanceTask) {
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index 7d4648d82a2..3079346801d 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -8,6 +8,7 @@ import { AcceptanceModel } from '@/database/models/acceptance';
import { AgentOperationModel } from '@/database/models/agentOperation';
import { GoalModel } from '@/database/models/goal';
import { GoalGraphModel } from '@/database/models/goalGraph';
+import { MetricModel } from '@/database/models/metric';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
import {
@@ -19,6 +20,8 @@ import {
goalNodeDecisions,
goalNodes,
goals,
+ metricPoints,
+ metrics,
tasks,
taskTopics,
topics,
@@ -52,6 +55,8 @@ afterEach(async () => {
await serverDB.delete(goalEvents);
await serverDB.delete(goalNodes);
await serverDB.delete(goals);
+ await serverDB.delete(metricPoints);
+ await serverDB.delete(metrics);
await serverDB.delete(acceptances);
await serverDB.delete(agentOperations);
await serverDB.delete(taskTopics);
@@ -859,6 +864,164 @@ describe('GoalService', () => {
).toHaveLength(1);
});
+ it('parks a goal short of acceptance and reopens it when the measurement clears', async () => {
+ // The measured half of acceptance: "followers >= 1000" is not a document a
+ // verifier reads, it is a number. Until it holds, the acceptance Task must
+ // not be created β€” and the goal must not sit `running` reporting
+ // `no_progress`, or every sweep would re-tick it for the whole wait.
+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const goalModel = new GoalModel(serverDB, userId);
+ const graph = await service.create({
+ config: { acceptance: { metrics: [{ key: 'followers', target: 1000 }] } },
+ requirement: 'Grow the account',
+ tasks: ['Publish the first posts'],
+ title: 'Measured goal',
+ });
+ const created = await service.tick(graph.goal.id);
+ await taskModel.updateStatus(created.taskId!, 'completed');
+ await service.tick(graph.goal.id);
+
+ // Nothing measured yet β€” "never observed" is not "satisfied".
+ const unmeasured = await service.tick(graph.goal.id);
+ expect(unmeasured).toMatchObject({ outcome: 'no_progress' });
+ expect(unmeasured.message).toContain('no observation');
+ expect((await goalModel.findById(graph.goal.id))?.status).toBe('paused');
+ expect(
+ (await service.graph(graph.goal.id)).nodes.some(
+ (n) => n.title === 'Complete full Goal acceptance',
+ ),
+ ).toBe(false);
+
+ // A sample that is still short leaves it parked and is not worth an advance.
+ const short = await service.recordObservation(graph.goal.id, {
+ key: 'followers',
+ value: 400,
+ });
+ expect(short.shouldAdvance).toBe(false);
+ expect((await goalModel.findById(graph.goal.id))?.status).toBe('paused');
+
+ // The number lands: the goal reopens and falls through to its delivery
+ // contract.
+ const cleared = await service.recordObservation(graph.goal.id, {
+ key: 'followers',
+ value: 1200,
+ });
+ expect(cleared.shouldAdvance).toBe(true);
+ expect((await goalModel.findById(graph.goal.id))?.status).toBe('running');
+
+ const advanced = await service.tick(graph.goal.id);
+ expect(advanced).toMatchObject({ outcome: 'advanced' });
+ expect(
+ (await service.graph(graph.goal.id)).nodes.some(
+ (n) => n.title === 'Complete full Goal acceptance',
+ ),
+ ).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.
+ 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',
+ });
+ await service.tick(graph.goal.id);
+ await service.pause(graph.goal.id);
+
+ const stray = await service.recordObservation(graph.goal.id, { key: 'followers', value: 10 });
+
+ expect(stray.shouldAdvance).toBe(false);
+ expect((await goalModel.findById(graph.goal.id))?.status).toBe('paused');
+ });
+
+ 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 β€”
+ // silently dropped a live measured gate and let the goal be accepted
+ // without it.
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({
+ config: { acceptance: { metrics: [{ key: 'followers', target: 1000 }] } },
+ criteria: [{ title: 'Ship the launch post' }],
+ requirement: 'Grow the account',
+ tasks: ['Publish the first posts'],
+ title: 'Both halves of acceptance',
+ });
+
+ const created = await new GoalModel(serverDB, userId).findById(graph.goal.id);
+ expect(created?.config?.acceptance?.metrics).toEqual([{ key: 'followers', target: 1000 }]);
+ expect(created?.config?.acceptance?.criteriaIds).toHaveLength(1);
+
+ await service.setAcceptanceCriteria(graph.goal.id, []);
+
+ const rebound = await new GoalModel(serverDB, userId).findById(graph.goal.id);
+ expect(rebound?.config?.acceptance?.metrics).toEqual([{ key: 'followers', target: 1000 }]);
+ });
+
+ it('declares numeric clauses after creation without touching the criteria binding', async () => {
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({
+ criteria: [{ title: 'Ship the launch post' }],
+ requirement: 'Grow the account',
+ tasks: ['Publish the first posts'],
+ title: 'Late-declared gate',
+ });
+
+ await service.setMetricCriteria(graph.goal.id, [{ key: 'churn', op: 'lte', target: 5 }]);
+
+ const updated = await new GoalModel(serverDB, userId).findById(graph.goal.id);
+ expect(updated?.config?.acceptance).toMatchObject({
+ criteriaIds: expect.any(Array),
+ metrics: [{ key: 'churn', op: 'lte', target: 5 }],
+ });
+ expect(updated?.config?.acceptance?.criteriaIds).toHaveLength(1);
+ });
+
+ it('records what the measured decision read, not just its verdict', async () => {
+ // A replay has to see the number the live run saw β€” the same reason the
+ // deadline verdict travels with the budget.
+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const metricModel = new MetricModel(serverDB, userId);
+ const graph = await service.create({
+ config: { acceptance: { metrics: [{ key: 'churn', op: 'lte', target: 5 }] } },
+ requirement: 'Keep churn down',
+ tasks: ['Ship retention fixes'],
+ title: 'Traced measurement',
+ });
+ const created = await service.tick(graph.goal.id);
+ await taskModel.updateStatus(created.taskId!, 'completed');
+ await service.tick(graph.goal.id);
+
+ const series = (await metricModel.ensure({
+ key: 'churn',
+ subjectId: graph.goal.id,
+ subjectType: 'goal',
+ }))!;
+ await metricModel.addPoint(series.id, {
+ actorType: 'system',
+ observedAt: new Date('2026-09-01T00:00:00Z'),
+ sourceType: 'probe',
+ value: 9,
+ });
+
+ const observed: GoalTickObservation[] = [];
+ await service.tick(graph.goal.id, { onDecision: (o) => observed.push(o) });
+
+ expect(observed.at(-1)!.metricCriteria).toMatchObject({
+ allMet: false,
+ criteria: [{ key: 'churn', met: false, op: 'lte', target: 5, value: 9 }],
+ });
+ });
+
it('evolves a failed task into a durable decision gate', async () => {
const service = new GoalService(serverDB, userId);
const taskModel = new TaskModel(serverDB, userId);
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index da84583409d..1355e0d8aff 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -1,4 +1,4 @@
-import type { GoalAdvanceEffect } from '@lobechat/agent-tracing';
+import type { GoalAdvanceEffect, GoalMetricCriteriaState } from '@lobechat/agent-tracing';
import { buildGoalRequirement } from '@lobechat/builtin-tool-goal';
import { GOAL_COORDINATOR_ACTOR_ID } from '@lobechat/const/goal';
import type {
@@ -7,10 +7,12 @@ import type {
GoalGraphNode,
GoalGraphSnapshot,
GoalItem,
+ GoalMetricCriterion,
GoalNodeKind,
GoalNodeStatus,
GoalStatus,
GoalTickResult,
+ MetricKind,
TaskItem,
TaskTopicHandoff,
} from '@lobechat/types';
@@ -20,6 +22,7 @@ import { sql } from 'drizzle-orm';
import { AgentOperationModel } from '@/database/models/agentOperation';
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 { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
@@ -34,11 +37,13 @@ import { AcceptanceService } from '../verify/acceptanceService';
import { VerifyPlanGeneratorService } from '../verify/planGenerator';
import { GoalCriteriaGeneratorService, type GoalDecompositionDraft } from './criteriaGenerator';
import {
+ compareMetric,
decideNextMove,
frontierNeedsBudget,
GOAL_ACCEPTANCE_TASK_TITLE,
type GoalMove,
LEASE_EXPIRED_ERROR,
+ needsMetricCriteria,
selectFrontier,
TERMINAL_NODE_STATUSES,
} from './decideNextMove';
@@ -204,7 +209,10 @@ export class GoalService {
verifierType: 'agent',
})),
);
- config = { ...config, acceptance: { criteriaIds } };
+ // Merge, never replace: `acceptance` also carries the numeric clauses,
+ // and rebuilding the object from `criteriaIds` alone would drop a
+ // measured gate the caller asked for in the same call.
+ config = { ...config, acceptance: { ...config?.acceptance, criteriaIds } };
}
const goal = await this.goalModel.create({
@@ -255,11 +263,106 @@ export class GoalService {
* editing). The criteria rows themselves are edited through the verify
* criteria endpoints; this only rebinds which of them gate the goal.
*/
+ /**
+ * Declare (or clear) the numeric clauses that gate this goal's acceptance.
+ *
+ * Merged into `config.acceptance` so it cannot clobber the delivery criteria
+ * binding, and settable after creation because a long-horizon goal learns its
+ * real thresholds while it runs. Relaxing a clause can unblock a goal that is
+ * already parked short of acceptance β€” the same reason extending a deadline
+ * resumes a budget-stopped one β€” so the caller schedules an advance.
+ */
+ /**
+ * Write a measurement against this goal, and reopen it when that measurement
+ * is what it was waiting for.
+ *
+ * The gate parks the goal (see the `measured_acceptance` branch), and `tick`
+ * refuses to move a paused goal β€” so without the reopen here the observation
+ * would land and nothing would happen. Only a goal the gate actually stopped
+ * is reopened, and only once every clause holds: the same discipline
+ * `setBudget` uses, so a deliberate pause is never undone by a stray sample
+ * and a still-short measurement does not queue a no-op advance.
+ */
+ recordObservation = async (
+ goalId: string,
+ input: {
+ key: string;
+ kind?: MetricKind;
+ observedAt?: Date;
+ title?: string;
+ unit?: string;
+ value: number;
+ },
+ ) => {
+ const goal = await this.goalModel.findById(goalId);
+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+
+ const metricModel = new MetricModel(this.db, this.userId, this.workspaceId);
+ const series = await metricModel.ensure({
+ key: input.key,
+ kind: input.kind,
+ subjectId: goal.id,
+ subjectType: 'goal',
+ title: input.title,
+ unit: input.unit,
+ });
+ if (!series)
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: 'Metric series slot is owned by another scope',
+ });
+
+ const point = await metricModel.addPoint(series.id, {
+ actorId: this.userId,
+ actorType: 'user',
+ observedAt: input.observedAt ?? new Date(),
+ sourceType: 'manual',
+ value: input.value,
+ });
+
+ return { point, series, shouldAdvance: await this.reopenIfMeasurementCleared(goalId) };
+ };
+
+ /**
+ * 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.
+ */
+ private reopenIfMeasurementCleared = async (goalId: string): 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;
+
+ const { allMet } = await this.evaluateMetricCriteria(graph);
+ if (!allMet) return false;
+
+ await this.transitionStatus(graph.goal, 'running', 'a measurement cleared the acceptance gate');
+ return true;
+ };
+
+ 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' });
+ await this.goalModel.update(goalId, {
+ config: {
+ ...goal.config,
+ acceptance: {
+ ...goal.config?.acceptance,
+ metrics: metrics.length > 0 ? metrics : undefined,
+ },
+ },
+ });
+ // Relaxing or dropping a clause can clear a gate the goal is parked on.
+ await this.reopenIfMeasurementCleared(goalId);
+ return this.graph(goalId);
+ };
+
setAcceptanceCriteria = async (goalId: string, criteriaIds: string[]) => {
const goal = await this.goalModel.findById(goalId);
if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
await this.goalModel.update(goalId, {
- config: { ...goal.config, acceptance: { criteriaIds } },
+ config: { ...goal.config, acceptance: { ...goal.config?.acceptance, criteriaIds } },
});
// A terminal Goal-acceptance Task may already be dispatched β€” its
@@ -449,6 +552,39 @@ export class GoalService {
* cannot express, and a goal whose deadline passed must stop the same way a
* goal out of money does.
*/
+ /**
+ * Read every declared numeric clause against its series' latest observation.
+ *
+ * A missing series or a series with no points reads as `null` and fails its
+ * clause: "never measured" is not "satisfied". The measured value is carried
+ * out with the verdict so the trajectory records what the decision saw.
+ */
+ private evaluateMetricCriteria = async (
+ graph: GoalGraphSnapshot,
+ ): Promise<GoalMetricCriteriaState> => {
+ 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,
+ };
+ }),
+ );
+
+ return { allMet: criteria.every((criterion) => criterion.met), criteria };
+ };
+
private evaluateBudget = async (goal: GoalItem, graph: GoalGraphSnapshot) => {
const taskIds = graph.nodes.flatMap((node) => (node.taskId ? [node.taskId] : []));
const runs = await this.taskTopicModel.findWithHandoffByTaskIds(taskIds, 10_000);
@@ -607,12 +743,19 @@ export class GoalService {
? toBudgetState(graph.goal, await this.evaluateBudget(graph.goal, graph))
: undefined;
+ // Same shape as the budget: a database read the pure decision cannot do,
+ // taken only in the terminal phase of a goal that declares numeric clauses.
+ const metricCriteria = needsMetricCriteria(graph)
+ ? await this.evaluateMetricCriteria(graph)
+ : undefined;
+
const concurrency = resolveMaxConcurrentTasks(graph.goal);
const move = decideNextMove({
budget,
concurrency,
frontier,
graph,
+ metricCriteria,
tasksById,
});
// The scheduler may pick past the head of the frontier, so every arm below
@@ -631,6 +774,7 @@ export class GoalService {
branch: move.branch,
budget,
candidates: move.candidates,
+ metricCriteria,
chosenNodeId: move.chosenNodeId,
effects,
candidateTasks: frontier.eligible.flatMap(({ node }) => {
@@ -663,6 +807,22 @@ export class GoalService {
});
}
+ // The measured half of acceptance stopped the goal short of its delivery
+ // contract. Nothing to create and nothing to settle β€” the next
+ // observation is what moves it, which can be days away.
+ //
+ // Park it for the same reason `no_frontier` does: a `running` goal that
+ // always reports `no_progress` is picked by every sweep forever, and a
+ // long-horizon goal waiting on a measurement would sit in that state for
+ // its whole life β€” enough of them crowd genuinely stranded goals out of
+ // the newest-first scan limit. `recordObservation` resumes it when a
+ // measurement actually clears the gate.
+ case '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 });
+ }
+
case 'terminal_acceptance': {
return observe(await this.settleTerminalAcceptance(graph, move, effects));
}
diff --git a/apps/server/src/services/goal/replayCoordinator.test.ts b/apps/server/src/services/goal/replayCoordinator.test.ts
index 7e1742caeff..89044eebf38 100644
--- a/apps/server/src/services/goal/replayCoordinator.test.ts
+++ b/apps/server/src/services/goal/replayCoordinator.test.ts
@@ -169,6 +169,52 @@ describe('replayGoalAgainstCurrentCoordinator', () => {
expect(replayGoalAgainstCurrentCoordinator(exhausted).divergences).toEqual([]);
});
+
+ /**
+ * The measured gate stops in the terminal phase, exactly like the delivery
+ * contract does. If the replay could not tell the two apart, a regressed gate
+ * would be reported as a match β€” the one failure mode a regression harness
+ * must not have.
+ */
+ const measured = (branch: 'measured_acceptance' | 'terminal_acceptance'): GoalTrajectory => ({
+ ...trajectory,
+ advances: [
+ {
+ ...trajectory.advances[0],
+ ticks: [
+ tick(0, {
+ branch,
+ candidates: [],
+ metricCriteria: {
+ allMet: false,
+ criteria: [{ key: 'followers', met: false, op: 'gte', target: 1_000_000, value: 42 }],
+ },
+ outcome: 'no_progress',
+ }),
+ ],
+ },
+ ],
+ // No config on the replayed goal on purpose: the gate reads the recorded
+ // `metricCriteria` and nothing else, which is what makes it replayable
+ // from the trajectory alone.
+ graphBaseline: graphState({ nodes: [task('a', { status: 'resolved' })] }),
+ });
+
+ it('carries the recorded measured criteria into the decision', () => {
+ expect(
+ replayGoalAgainstCurrentCoordinator(measured('measured_acceptance')).divergences,
+ ).toEqual([]);
+ });
+
+ it('reports a gate that no longer fires instead of matching it', () => {
+ // A trajectory whose terminal tick was recorded as the plain delivery
+ // contract must not replay as an unmet gate, and vice versa.
+ expect(
+ replayGoalAgainstCurrentCoordinator(measured('terminal_acceptance')).divergences,
+ ).toMatchObject([
+ { field: 'branch', recorded: 'terminal_acceptance', replayed: 'measured_acceptance' },
+ ]);
+ });
});
describe('replaying trajectories recorded before the scheduler', () => {
diff --git a/apps/server/src/services/goal/replayCoordinator.ts b/apps/server/src/services/goal/replayCoordinator.ts
index e38f10a9f5b..f5152522e0b 100644
--- a/apps/server/src/services/goal/replayCoordinator.ts
+++ b/apps/server/src/services/goal/replayCoordinator.ts
@@ -65,6 +65,7 @@ export const coordinatorDecider: GoalDecider = (input): GoalDecision => {
concurrency: input.concurrency ?? DEFAULT_REPLAY_CONCURRENCY,
frontier,
graph,
+ metricCriteria: input.metricCriteria,
tasksById: toTasksById(input),
});
diff --git a/apps/server/src/services/goal/traceObservation.ts b/apps/server/src/services/goal/traceObservation.ts
index 531a3e54933..fe51bc1241d 100644
--- a/apps/server/src/services/goal/traceObservation.ts
+++ b/apps/server/src/services/goal/traceObservation.ts
@@ -4,6 +4,7 @@ import type {
GoalBudgetState,
GoalFrontierTaskState,
GoalGraphState,
+ GoalMetricCriteriaState,
GoalTickBranch,
GoalTickOutcome,
} from '@lobechat/agent-tracing';
@@ -27,6 +28,8 @@ export interface GoalTickObservation {
effects: GoalAdvanceEffect[];
graphState: GoalGraphState;
message: string;
+ /** Numeric acceptance clauses as they read, on terminal-phase decisions. */
+ metricCriteria?: GoalMetricCriteriaState;
outcome: GoalTickOutcome;
taskId?: string;
}
diff --git a/packages/agent-tracing/src/goal/index.ts b/packages/agent-tracing/src/goal/index.ts
index e6f6b191555..15355ddb240 100644
--- a/packages/agent-tracing/src/goal/index.ts
+++ b/packages/agent-tracing/src/goal/index.ts
@@ -36,6 +36,8 @@ export type {
GoalGraphDelta,
GoalGraphShape,
GoalGraphState,
+ GoalMetricCriteriaState,
+ GoalMetricCriterionState,
GoalTickBranch,
GoalTickOutcome,
GoalTickSnapshot,
diff --git a/packages/agent-tracing/src/goal/replay.ts b/packages/agent-tracing/src/goal/replay.ts
index cf1337afe84..1598d682e3e 100644
--- a/packages/agent-tracing/src/goal/replay.ts
+++ b/packages/agent-tracing/src/goal/replay.ts
@@ -4,6 +4,7 @@ import type {
GoalBudgetState,
GoalFrontierTaskState,
GoalGraphState,
+ GoalMetricCriteriaState,
GoalTickBranch,
GoalTrajectory,
} from './types';
@@ -20,6 +21,8 @@ export interface GoalDecisionInput {
/** @deprecated Legacy single-task shape; present only on older trajectories. */
frontierTask?: GoalFrontierTaskState;
graph: GoalGraphState;
+ /** Numeric acceptance clauses as the recorded tick read them. */
+ metricCriteria?: GoalMetricCriteriaState;
}
/**
@@ -80,6 +83,7 @@ export const replayGoalTrajectory = (
const graph: GoalGraphState = reconstructGraphAt(trajectory, advance.seq, tick.index);
const replayed = decide({
budget: tick.budget,
+ metricCriteria: tick.metricCriteria,
// A trajectory recorded before the scheduler existed has only the
// chosen candidate's task. Dropping it would replay every one of those
// ticks as `missing_task` and report divergences that never happened.
diff --git a/packages/agent-tracing/src/goal/types.ts b/packages/agent-tracing/src/goal/types.ts
index f9a9b03f0eb..295ba453625 100644
--- a/packages/agent-tracing/src/goal/types.ts
+++ b/packages/agent-tracing/src/goal/types.ts
@@ -16,7 +16,16 @@
/** What caused this advance. `unknown` covers traces written before a caller was labelled. */
export type GoalAdvanceTrigger =
- 'create' | 'decide' | 'settle' | 'sweep' | 'resume' | 'budget' | 'manual' | 'unknown';
+ | 'create'
+ | 'decide'
+ | 'settle'
+ | 'sweep'
+ | 'resume'
+ | 'budget'
+ | 'manual'
+ /** A measurement landed β€” the goal moves on observation, not only on work. */
+ | 'observe'
+ | 'unknown';
/** Which arm of the coordinator ran. One per `tick` return path. */
export type GoalTickBranch =
@@ -31,6 +40,13 @@ export type GoalTickBranch =
| 'plan_decomposition'
/** Every task node finished; the goal-level acceptance contract is next. */
| 'terminal_acceptance'
+ /**
+ * Every task node finished, but a declared numeric clause is unmet, so the
+ * delivery contract is not attempted. Distinct from `terminal_acceptance`
+ * on purpose: both stop in the terminal phase, and a replay that could not
+ * tell them apart would report a regressed gate as a match.
+ */
+ | 'measured_acceptance'
/** The chosen task node has no responsible task yet. */
| 'create_task'
/** Its task row is gone. */
@@ -145,6 +161,30 @@ export interface GoalBudgetState {
totalCost: number;
}
+/**
+ * One numeric acceptance clause as it read at decision time.
+ *
+ * The measured value travels with the verdict for the same reason
+ * `deadlinePassed` does: a replay must see the number the live run saw, not
+ * whatever the series holds when the trajectory is re-read.
+ */
+export interface GoalMetricCriterionState {
+ key: string;
+ met: boolean;
+ /** When the recorded value was observed; absent when nothing was measured. */
+ observedAt?: number;
+ op: string;
+ target: number;
+ /** Latest observation, or null when the series has no points (or no series). */
+ value: number | null;
+}
+
+/** The measured half of Goal acceptance, evaluated only in the terminal phase. */
+export interface GoalMetricCriteriaState {
+ allMet: boolean;
+ criteria: GoalMetricCriterionState[];
+}
+
/** A candidate's responsible task at decision time; drives every post-dispatch branch. */
export interface GoalFrontierTaskState {
error?: string | null;
@@ -210,6 +250,11 @@ export interface GoalTickSnapshot {
graphShape: GoalGraphShape;
index: number;
message: string;
+ /**
+ * Present only on terminal-phase decisions of a goal that declares numeric
+ * criteria β€” the one place the coordinator reads them.
+ */
+ metricCriteria?: GoalMetricCriteriaState;
outcome: GoalTickOutcome;
taskId?: string;
}
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index e600fe7ae25..efd34ce90a0 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -53,8 +53,35 @@ export interface GoalSchedulePolicy {
* records their ids so the terminal Goal-acceptance Task verifies against
* exactly these checks instead of re-deriving them from the requirement prose.
*/
+/** Comparison a measured value must satisfy. */
+export type GoalMetricComparison = 'gte' | 'lte' | 'gt' | 'lt' | 'eq';
+
+/**
+ * A numeric acceptance clause: "this series must read at least this much".
+ *
+ * The counterpart to a delivery contract judged by a verifier β€” "followers >=
+ * 1,000,000" is not a document someone reads, it is a number that gets
+ * measured. `key` addresses a series on the goal itself (subjectType `goal`,
+ * subjectId the goal id), so a criterion needs no id of its own and survives
+ * the series being re-created.
+ */
+export interface GoalMetricCriterion {
+ /** Metric series key on this goal, e.g. 'twitter.followers'. */
+ key: string;
+ /** Defaults to `gte` β€” the "reach this number" case. */
+ op?: GoalMetricComparison;
+ target: number;
+}
+
export interface GoalAcceptancePolicy {
criteriaIds?: string[];
+ /**
+ * Measured clauses that gate acceptance. Every one must hold before the
+ * Goal-level delivery acceptance is even attempted: an unmet number is not
+ * something a verifier can talk its way past, and running the acceptance
+ * agent against it would only spend tokens to restate the gap.
+ */
+ metrics?: GoalMetricCriterion[];
}
export interface GoalConfig {
diff --git a/packages/types/src/metric.ts b/packages/types/src/metric.ts
index 2fbaaca6e9b..9ac16d91b0c 100644
--- a/packages/types/src/metric.ts
+++ b/packages/types/src/metric.ts
@@ -10,6 +10,22 @@
*/
export type MetricSubjectType = 'goal' | 'task' | 'agent' | 'project' | 'workspace';
+/**
+ * Decimal places `metric_points.value` keeps β€” the column is `numeric(20, 6)`.
+ *
+ * Anything compared against a stored observation has to be read at this scale:
+ * the database has already rounded its side, so a full-precision threshold
+ * would make clauses like `eq 0.1234567` unsatisfiable and could flip `gte` /
+ * `lte` right at the rounding boundary.
+ */
+export const METRIC_VALUE_SCALE = 6;
+
+/** Round to the scale observations are persisted at. */
+export const toMetricScale = (value: number): number => {
+ const factor = 10 ** METRIC_VALUE_SCALE;
+ return Math.round(value * factor) / factor;
+};
+
/**
* Aggregation semantics of a series β€” the one thing a chart renderer cannot
* infer from the data: