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): north-star metrics strip on the goal detail header (#19206)

Arvin Xu5bf3a37e378d
diff --git a/apps/server/src/routers/lambda/__tests__/goal.metricCriteria.test.ts b/apps/server/src/routers/lambda/__tests__/goal.metricCriteria.test.ts
index 6973fd0f19d..facf8fd6c55 100644
--- a/apps/server/src/routers/lambda/__tests__/goal.metricCriteria.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/goal.metricCriteria.test.ts
@@ -66,15 +66,31 @@ describe('goalRouter numeric acceptance', () => {
);
});
- it('declares clauses after creation', async () => {
+ it('declares clauses after creation, defaulting to replace mode', 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 },
- ]);
+ expect(mockSetMetricCriteria).toHaveBeenCalledWith(
+ 'goal_1',
+ [{ key: 'churn', op: 'lte', target: 5 }],
+ undefined,
+ );
+ });
+
+ it('passes merge mode through, so single-clause declares upsert server-side', async () => {
+ await caller.setMetricCriteria({
+ id: 'goal_1',
+ metrics: [{ key: 'churn', op: 'lte', target: 5 }],
+ mode: 'merge',
+ });
+
+ expect(mockSetMetricCriteria).toHaveBeenCalledWith(
+ 'goal_1',
+ [{ key: 'churn', op: 'lte', target: 5 }],
+ 'merge',
+ );
});
it('rejects a comparison the evaluator does not implement', async () => {
diff --git a/apps/server/src/routers/lambda/__tests__/metric.test.ts b/apps/server/src/routers/lambda/__tests__/metric.test.ts
index aefeb05f3ce..fd70c0fd9ee 100644
--- a/apps/server/src/routers/lambda/__tests__/metric.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/metric.test.ts
@@ -19,9 +19,12 @@ const mockModel = {
delete: vi.fn(),
ensure: vi.fn(),
findById: vi.fn(),
+ findByKeys: vi.fn(),
findBySubject: vi.fn(),
+ firstPointsByMetricIds: vi.fn(),
latestPoint: vi.fn(),
listPoints: vi.fn(),
+ recentPoints: vi.fn(),
update: vi.fn(),
};
@@ -143,16 +146,58 @@ describe('metricRouter', () => {
['listPoints', () => caller.listPoints({ id: 'mtr_1' })],
['addPoint', () => caller.addPoint({ id: 'mtr_1', value: 1 })],
['listSeries', () => caller.listSeries({ subjectId: 'goal_1', subjectType: 'goal' })],
+ [
+ 'listSeriesWithPoints',
+ () =>
+ caller.listSeriesWithPoints({ keys: ['k'], subjectId: 'goal_1', subjectType: 'goal' }),
+ ],
])('%s refuses a series whose subject the caller cannot see', async (_name, run) => {
mockGoalFindById.mockResolvedValue(undefined);
await expect(run()).rejects.toMatchObject({ code: 'NOT_FOUND' });
expect(mockModel.findBySubject).not.toHaveBeenCalled();
+ expect(mockModel.findByKeys).not.toHaveBeenCalled();
expect(mockModel.listPoints).not.toHaveBeenCalled();
expect(mockModel.addPoint).not.toHaveBeenCalled();
});
});
+ describe('listSeriesWithPoints', () => {
+ it('bundles named series, their recent windows and true first points in one call', async () => {
+ // The per-series alternative amplifies to 1+N RPCs on a polled surface;
+ // this is the whole read in one request, restricted to declared keys.
+ mockModel.findByKeys.mockResolvedValue([
+ { config: null, id: 'mtr_1', key: 'followers', kind: 'gauge', title: '粉丝', unit: null },
+ ]);
+ mockModel.firstPointsByMetricIds.mockResolvedValue(
+ new Map([['mtr_1', { metricId: 'mtr_1', value: 1200 }]]),
+ );
+ mockModel.recentPoints.mockResolvedValue([{ value: 8800 }]);
+
+ const result = await caller.listSeriesWithPoints({
+ keys: ['followers'],
+ subjectId: 'goal_1',
+ subjectType: 'goal',
+ });
+
+ expect(mockModel.findByKeys).toHaveBeenCalledWith('goal', 'goal_1', ['followers']);
+ expect(result.data).toEqual([
+ expect.objectContaining({
+ firstPoint: expect.objectContaining({ value: 1200 }),
+ key: 'followers',
+ points: [{ value: 8800 }],
+ }),
+ ]);
+ });
+
+ it('rejects an empty key list instead of scanning every series', async () => {
+ await expect(
+ caller.listSeriesWithPoints({ keys: [], subjectId: 'goal_1', subjectType: 'goal' }),
+ ).rejects.toThrow();
+ expect(mockModel.findByKeys).not.toHaveBeenCalled();
+ });
+ });
+
describe('updateSeries', () => {
it('clears nullable definition fields when passed null', async () => {
// Dropping a target back to "no target" is an edit, not an omission.
diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.ts
index ccaa1f76130..610e2a639b8 100644
--- a/apps/server/src/routers/lambda/goal.ts
+++ b/apps/server/src/routers/lambda/goal.ts
@@ -113,6 +113,7 @@ export const goalRouter = router({
key: z.string().min(1).max(255),
op: z.enum(['gte', 'lte', 'gt', 'lt', 'eq']).optional(),
target: z.number(),
+ title: z.string().max(255).optional(),
}),
)
.max(MAX_GOAL_METRIC_CRITERIA)
@@ -220,9 +221,12 @@ export const goalRouter = router({
key: z.string().min(1).max(255),
op: z.enum(['gte', 'lte', 'gt', 'lt', 'eq']).optional(),
target: z.number(),
+ title: z.string().max(255).optional(),
}),
)
.max(MAX_GOAL_METRIC_CRITERIA),
+ /** `merge` upserts by key server-side; `replace` (default) swaps the list. */
+ mode: z.enum(['merge', 'replace']).optional(),
}),
)
.mutation(async ({ ctx, input }) => {
@@ -230,7 +234,7 @@ export const goalRouter = router({
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);
+ const data = await ctx.goalService.setMetricCriteria(input.id, input.metrics, input.mode);
// Relaxing a clause can free a goal parked short of acceptance.
await scheduleGoalAdvance({
goalId: input.id,
diff --git a/apps/server/src/routers/lambda/metric.ts b/apps/server/src/routers/lambda/metric.ts
index 3a863f625bc..ebb0ffe2377 100644
--- a/apps/server/src/routers/lambda/metric.ts
+++ b/apps/server/src/routers/lambda/metric.ts
@@ -226,6 +226,54 @@ export const metricRouter = router({
}
}),
+ /**
+ * The chart bundle for a tracking surface, in one RPC: the named series of a
+ * subject, each with its recent point window and its true first observation.
+ *
+ * Exists because the per-series alternative amplifies: a polled surface
+ * calling listSeries + N x listPoints costs 1+N requests and ~3N queries
+ * for series that cannot even affect the view. Here the caller names its
+ * keys (a declared acceptance contract is capped), and the whole read is
+ * one request over K+2 bounded queries. `firstPoint` travels separately
+ * because the recent window silently rebases a progress baseline once
+ * history outgrows it.
+ */
+ listSeriesWithPoints: metricProcedure
+ .input(
+ subjectInput.extend({
+ keys: z.array(z.string().min(1).max(255)).min(1).max(50),
+ limit: z.number().int().min(2).max(1000).optional(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ try {
+ await assertSubjectVisible(ctx.serverDB, ctx, input.subjectType, input.subjectId);
+ const series = await ctx.metricModel.findByKeys(
+ input.subjectType,
+ input.subjectId,
+ input.keys,
+ );
+ const firstPoints = await ctx.metricModel.firstPointsByMetricIds(
+ series.map((item) => item.id),
+ );
+ const data = await Promise.all(
+ series.map(async (item) => ({
+ config: item.config,
+ firstPoint: firstPoints.get(item.id) ?? null,
+ id: item.id,
+ key: item.key,
+ kind: item.kind,
+ points: await ctx.metricModel.recentPoints(item.id, input.limit ?? 200),
+ title: item.title,
+ unit: item.unit,
+ })),
+ );
+ return { data, success: true };
+ } catch (error) {
+ mapMetricError(error, 'listSeriesWithPoints');
+ }
+ }),
+
listSeries: metricProcedure.input(subjectInput).query(async ({ input, ctx }) => {
try {
await assertSubjectVisible(ctx.serverDB, ctx, input.subjectType, input.subjectId);
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index a1260c9cda4..60764b32072 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -1223,6 +1223,38 @@ describe('GoalService', () => {
expect(rebound?.config?.acceptance?.metrics).toEqual([{ key: 'followers', target: 1000 }]);
});
+ it('merges a declared clause into the server-side list instead of replacing it', async () => {
+ // Two editors declaring from the same stale snapshot must not erase each
+ // other: merge upserts by key against the list as it stands on the server.
+ const service = new GoalService(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'],
+ title: 'Merge-mode goal',
+ });
+
+ // A "concurrent" declaration this client never saw.
+ await service.setMetricCriteria(
+ graph.goal.id,
+ [{ key: 'retention', op: 'gte', target: 80 }],
+ 'merge',
+ );
+ // This client merges its own clause from a snapshot that predates it.
+ await service.setMetricCriteria(
+ graph.goal.id,
+ [{ key: 'followers', target: 2000, title: '粉丝' }],
+ 'merge',
+ );
+
+ const metrics = (await goalModel.findById(graph.goal.id))?.config?.acceptance?.metrics;
+ expect(metrics).toHaveLength(2);
+ expect(metrics).toContainEqual({ key: 'retention', op: 'gte', target: 80 });
+ // Same-key merge upserts rather than duplicating.
+ expect(metrics).toContainEqual({ key: 'followers', target: 2000, title: '粉丝' });
+ });
+
it('declares numeric clauses after creation without touching the criteria binding', async () => {
const service = new GoalService(serverDB, userId);
const graph = await service.create({
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index 32d6567d79f..705e5fc6900 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -418,17 +418,32 @@ export class GoalService {
);
};
- setMetricCriteria = async (goalId: string, metrics: GoalMetricCriterion[]) => {
+ setMetricCriteria = async (
+ goalId: string,
+ metrics: GoalMetricCriterion[],
+ /**
+ * `merge` upserts by key into the list as it stands on the server —
+ * for callers declaring one clause, whose own snapshot may be stale.
+ * A client-built replacement array would silently drop whatever a
+ * concurrent editor or agent declared since that snapshot was read.
+ */
+ mode: 'merge' | 'replace' = 'replace',
+ ) => {
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;
+ const current = goal.config?.acceptance?.metrics ?? [];
+ const next =
+ mode === 'merge'
+ ? [...current.filter((item) => !metrics.some((m) => m.key === item.key)), ...metrics]
+ : metrics;
await this.goalModel.update(goalId, {
config: {
...goal.config,
acceptance: {
...goal.config?.acceptance,
- metrics: metrics.length > 0 ? metrics : undefined,
+ metrics: next.length > 0 ? next : undefined,
},
},
});
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index d06dbb5b3c0..a3d51aee7bc 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -646,6 +646,29 @@
"goalProcess.nodeStatus.resolved": "Done",
"goalProcess.nodeStatus.retired": "Retired",
"goalProcess.nodeStatus.waiting": "Waiting",
+ "goalProcess.northStar.declare.failed": "Failed to declare the metric",
+ "goalProcess.northStar.declare.keyLabel": "Metric key",
+ "goalProcess.northStar.declare.keyPlaceholder": "e.g. followers / security.open_issues",
+ "goalProcess.northStar.declare.opLabel": "Condition",
+ "goalProcess.northStar.declare.submit": "Declare",
+ "goalProcess.northStar.declare.targetLabel": "Target value",
+ "goalProcess.northStar.declare.title": "Declare metric",
+ "goalProcess.northStar.declare.titleLabel": "Display name (optional)",
+ "goalProcess.northStar.declare.titlePlaceholder": "e.g. Followers / Open security issues",
+ "goalProcess.northStar.emptyHint": "No measurable target declared yet — e.g. followers ≥ 10,000, or open security issues down to 0",
+ "goalProcess.northStar.lastObserved": "Last observed {{time}}",
+ "goalProcess.northStar.met": "Met",
+ "goalProcess.northStar.op.eq": "=",
+ "goalProcess.northStar.op.gt": ">",
+ "goalProcess.northStar.op.gte": "≥",
+ "goalProcess.northStar.op.lt": "<",
+ "goalProcess.northStar.op.lte": "≤",
+ "goalProcess.northStar.record.failed": "Failed to record the observation",
+ "goalProcess.northStar.record.submit": "Record",
+ "goalProcess.northStar.record.title": "Record observation",
+ "goalProcess.northStar.record.valueLabel": "Current value of {{key}}",
+ "goalProcess.northStar.staleWarning": "data may be outdated",
+ "goalProcess.northStar.unmeasured": "Never measured — the clause counts as unmet until a value lands",
"goalProcess.pause": "Pause",
"goalProcess.paused": "Paused — no new work will start",
"goalProcess.planning.description": "The coordinator is breaking the goal into executable tasks — they will appear here shortly.",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 243a16c36e3..bb1271fceb7 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -646,6 +646,29 @@
"goalProcess.nodeStatus.resolved": "已完成",
"goalProcess.nodeStatus.retired": "已退役",
"goalProcess.nodeStatus.waiting": "等待中",
+ "goalProcess.northStar.declare.failed": "声明指标失败",
+ "goalProcess.northStar.declare.keyLabel": "指标名(key)",
+ "goalProcess.northStar.declare.keyPlaceholder": "如 followers / security.open_issues",
+ "goalProcess.northStar.declare.opLabel": "判定条件",
+ "goalProcess.northStar.declare.submit": "声明",
+ "goalProcess.northStar.declare.targetLabel": "目标值",
+ "goalProcess.northStar.declare.title": "声明指标",
+ "goalProcess.northStar.declare.titleLabel": "显示名(可选)",
+ "goalProcess.northStar.declare.titlePlaceholder": "如 粉丝总数 / 未关闭安全 issue",
+ "goalProcess.northStar.emptyHint": "尚未声明可量测的目标指标——例如:粉丝数 ≥ 10,000、安全 issue 清零",
+ "goalProcess.northStar.lastObserved": "最近观测 {{time}}",
+ "goalProcess.northStar.met": "已达标",
+ "goalProcess.northStar.op.eq": "=",
+ "goalProcess.northStar.op.gt": ">",
+ "goalProcess.northStar.op.gte": "≥",
+ "goalProcess.northStar.op.lt": "<",
+ "goalProcess.northStar.op.lte": "≤",
+ "goalProcess.northStar.record.failed": "记录观测失败",
+ "goalProcess.northStar.record.submit": "记录",
+ "goalProcess.northStar.record.title": "记录观测",
+ "goalProcess.northStar.record.valueLabel": "{{key}} 的当前值",
+ "goalProcess.northStar.staleWarning": "数据可能已过期",
+ "goalProcess.northStar.unmeasured": "尚未测量——在第一个观测值到来前按未达标处理",
"goalProcess.pause": "暂停",
"goalProcess.paused": "已暂停,不会再开始新的任务",
"goalProcess.planning.description": "协调器正在把目标拆解为可执行任务,节点稍后会陆续出现",
diff --git a/packages/database/src/models/__tests__/metric.test.ts b/packages/database/src/models/__tests__/metric.test.ts
index db9dd05d301..175f479b795 100644
--- a/packages/database/src/models/__tests__/metric.test.ts
+++ b/packages/database/src/models/__tests__/metric.test.ts
@@ -146,6 +146,30 @@ describe('MetricModel', () => {
});
});
+ describe('firstPointsByMetricIds / recentPoints', () => {
+ it('returns the true first observation and the newest window ascending', async () => {
+ const s1 = (await seed('windowed'))!;
+ for (const [at, value] of [
+ ['2026-09-01T00:00:00Z', 0],
+ ['2026-09-02T00:00:00Z', 90],
+ ['2026-09-03T00:00:00Z', 95],
+ ] as const) {
+ await model.addPoint(s1.id, {
+ actorType: 'system',
+ observedAt: new Date(at),
+ sourceType: 'probe',
+ value,
+ });
+ }
+
+ // The window keeps the newest 2 ascending; the baseline read keeps 0.
+ expect((await model.recentPoints(s1.id, 2)).map((p) => p.value)).toEqual([90, 95]);
+ expect((await model.firstPointsByMetricIds([s1.id])).get(s1.id)?.value).toBe(0);
+ expect((await model.firstPointsByMetricIds([])).size).toBe(0);
+ expect(await otherModel.recentPoints(s1.id, 5)).toEqual([]);
+ });
+ });
+
describe('latestPointsByMetricIds', () => {
it('returns one newest row per series in a single read', async () => {
const a = (await seed('a.metric'))!;
diff --git a/packages/database/src/models/metric.ts b/packages/database/src/models/metric.ts
index 03fef703ba0..1d0eff515fd 100644
--- a/packages/database/src/models/metric.ts
+++ b/packages/database/src/models/metric.ts
@@ -234,6 +234,41 @@ export class MetricModel {
* evaluating a whole acceptance contract would otherwise issue one query per
* clause and pace the connection pool with it.
*/
+ /**
+ * The earliest observation of many series at once, keyed by metric id.
+ *
+ * The counterpart of {@link latestPointsByMetricIds}: progress baselines
+ * read "where the series started", and a windowed recent read silently
+ * rebases once history outgrows the window — the true first point has to
+ * travel separately.
+ */
+ firstPointsByMetricIds = 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, asc(metricPoints.observedAt));
+
+ return new Map(rows.map((row) => [row.metricId, row]));
+ };
+
+ /**
+ * The newest `limit` raw points of one series, ascending, without resolving
+ * the series row — for callers that already hold it and must not pay the
+ * per-series double read of {@link listPoints}.
+ */
+ recentPoints = async (metricId: string, limit: number): Promise<MetricPointItem[]> => {
+ const rows = await this.db
+ .select()
+ .from(metricPoints)
+ .where(and(eq(metricPoints.metricId, metricId), this.pointOwnership()))
+ .orderBy(desc(metricPoints.observedAt))
+ .limit(limit);
+ return rows.reverse();
+ };
+
latestPointsByMetricIds = async (metricIds: string[]): Promise<Map<string, MetricPointItem>> => {
if (metricIds.length === 0) return new Map();
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index d441ea3453d..1830deb1dd1 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1879,6 +1879,31 @@ export default {
'goalDetail.unnamedRun': 'Untitled run',
'goalDetail.viewPlan': 'View execution plan',
'goalProcess.frontier.title': 'Current tasks',
+ 'goalProcess.northStar.emptyHint':
+ 'No measurable target declared yet — e.g. followers >= 10,000, or open security issues down to 0',
+ 'goalProcess.northStar.met': 'Met',
+ 'goalProcess.northStar.unmeasured':
+ 'Never measured — the clause counts as unmet until a value lands',
+ 'goalProcess.northStar.lastObserved': 'Last observed {{time}}',
+ 'goalProcess.northStar.staleWarning': 'data may be outdated',
+ 'goalProcess.northStar.op.gte': '\u2265',
+ 'goalProcess.northStar.op.lte': '\u2264',
+ 'goalProcess.northStar.op.gt': '>',
+ 'goalProcess.northStar.op.lt': '<',
+ 'goalProcess.northStar.op.eq': '=',
+ 'goalProcess.northStar.declare.title': 'Declare metric',
+ 'goalProcess.northStar.declare.keyLabel': 'Metric key',
+ 'goalProcess.northStar.declare.titleLabel': 'Display name (optional)',
+ 'goalProcess.northStar.declare.titlePlaceholder': 'e.g. Followers / Open security issues',
+ 'goalProcess.northStar.declare.keyPlaceholder': 'e.g. followers / security.open_issues',
+ 'goalProcess.northStar.declare.opLabel': 'Condition',
+ 'goalProcess.northStar.declare.targetLabel': 'Target value',
+ 'goalProcess.northStar.declare.submit': 'Declare',
+ 'goalProcess.northStar.declare.failed': 'Failed to declare the metric',
+ 'goalProcess.northStar.record.title': 'Record observation',
+ 'goalProcess.northStar.record.valueLabel': 'Current value of {{key}}',
+ 'goalProcess.northStar.record.submit': 'Record',
+ 'goalProcess.northStar.record.failed': 'Failed to record the observation',
'goalProcess.frontier.add': 'Add task',
'goalProcess.frontier.needsYou': '{{count}} need you',
'goalProcess.frontier.advanceable': '{{count}} can advance',
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index 70d64edbead..cf2af7c773c 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -73,6 +73,8 @@ export interface GoalMetricCriterion {
/** Defaults to `gte` — the "reach this number" case. */
op?: GoalMetricComparison;
target: number;
+ /** Human-facing name shown on tracking surfaces; the key stays the address. */
+ title?: string;
}
/**
diff --git a/src/features/AgentGoals/GoalDetailPage.tsx b/src/features/AgentGoals/GoalDetailPage.tsx
index 9f43a3a73ed..fcec95175e8 100644
--- a/src/features/AgentGoals/GoalDetailPage.tsx
+++ b/src/features/AgentGoals/GoalDetailPage.tsx
@@ -33,6 +33,7 @@ import GoalDetailActions from './GoalDetailActions';
import { formatSpan, formatUsd, goalStatusKey, summarizeGoalBudget } from './goalPresentation';
import GoalRequirement from './GoalRequirement';
import GoalStatusGlyph from './GoalStatusGlyph';
+import NorthStarMetrics from './NorthStarMetrics';
import ProcessControl from './ProcessControl';
/**
@@ -372,6 +373,11 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
{goal.requirement && (
<GoalRequirement goalId={goal.id} requirement={goal.requirement} />
)}
+ {/* North-star strip beside the requirement document: the measured
+ clauses ARE half of the acceptance contract, so they read
+ with it — not squeezed between the title and the execution
+ metrics (review feedback, r1). */}
+ <NorthStarMetrics canEdit={canEdit} goalId={goalId} />
</Flexbox>
<ProcessControl
diff --git a/src/features/AgentGoals/NorthStarMetrics/DeclareMetricModal.tsx b/src/features/AgentGoals/NorthStarMetrics/DeclareMetricModal.tsx
new file mode 100644
index 00000000000..32c175e3437
--- /dev/null
+++ b/src/features/AgentGoals/NorthStarMetrics/DeclareMetricModal.tsx
@@ -0,0 +1,130 @@
+'use client';
+
+import type { GoalMetricComparison } from '@lobechat/types';
+import { Flexbox, Input } from '@lobehub/ui';
+import {
+ Button,
+ createModal,
+ type ModalInstance,
+ Select,
+ Text,
+ toast,
+ useModalContext,
+} from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useGoalStore } from '@/store/goal';
+
+/**
+ * Declare one measured acceptance clause: "this series must reach this
+ * number". The key doubles as the series name the probe / manual observations
+ * write to, so declaring is enough — the first observation creates the series.
+ */
+const DeclareMetricContent = memo<{ goalId: string }>(({ goalId }) => {
+ const { t } = useTranslation('chat');
+ const { close } = useModalContext();
+ const declareGoalMetric = useGoalStore((s) => s.declareGoalMetric);
+
+ const [key, setKey] = useState('');
+ const [title, setTitle] = useState('');
+ const [op, setOp] = useState<GoalMetricComparison>('gte');
+ const [target, setTarget] = useState('');
+ const [busy, setBusy] = useState(false);
+
+ const submit = async () => {
+ const trimmedKey = key.trim();
+ const parsedTarget = Number(target);
+ if (!trimmedKey || !Number.isFinite(parsedTarget) || busy) return;
+ setBusy(true);
+ try {
+ await declareGoalMetric(goalId, {
+ key: trimmedKey,
+ op,
+ target: parsedTarget,
+ title: title.trim() || undefined,
+ });
+ close();
+ } catch (error) {
+ // Keep the form open — a silent close would be indistinguishable from success.
+ console.error('[NorthStar] failed to declare metric:', error);
+ toast.error(t('goalProcess.northStar.declare.failed'));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <Flexbox gap={16} paddingBlock={'4px 8px'}>
+ <Flexbox gap={6}>
+ <Text fontSize={13} weight={500}>
+ {t('goalProcess.northStar.declare.keyLabel')}
+ </Text>
+ <Input
+ autoFocus
+ placeholder={t('goalProcess.northStar.declare.keyPlaceholder')}
+ value={key}
+ onChange={(e) => setKey(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox gap={6}>
+ <Text fontSize={13} weight={500}>
+ {t('goalProcess.northStar.declare.titleLabel')}
+ </Text>
+ <Input
+ placeholder={t('goalProcess.northStar.declare.titlePlaceholder')}
+ value={title}
+ onChange={(e) => setTitle(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox horizontal gap={12}>
+ <Flexbox flex={1} gap={6}>
+ <Text fontSize={13} weight={500}>
+ {t('goalProcess.northStar.declare.opLabel')}
+ </Text>
+ <Select
+ value={op}
+ options={(['gte', 'lte', 'gt', 'lt', 'eq'] as const).map((value) => ({
+ label: t(`goalProcess.northStar.op.${value}` as const),
+ value,
+ }))}
+ onChange={(value) => setOp(value as GoalMetricComparison)}
+ />
+ </Flexbox>
+ <Flexbox flex={1} gap={6}>
+ <Text fontSize={13} weight={500}>
+ {t('goalProcess.northStar.declare.targetLabel')}
+ </Text>
+ <Input
+ placeholder={'10000'}
+ value={target}
+ onChange={(e) => setTarget(e.target.value)}
+ onPressEnter={() => void submit()}
+ />
+ </Flexbox>
+ </Flexbox>
+ <Flexbox horizontal justify={'flex-end'}>
+ <Button
+ disabled={!key.trim() || !Number.isFinite(Number(target)) || target.trim() === ''}
+ loading={busy}
+ type={'primary'}
+ onClick={() => void submit()}
+ >
+ {t('goalProcess.northStar.declare.submit')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+DeclareMetricContent.displayName = 'DeclareMetricContent';
+
+export const openDeclareMetricModal = (goalId: string): ModalInstance =>
+ createModal({
+ content: <DeclareMetricContent goalId={goalId} />,
+ footer: null,
+ maskClosable: true,
+ title: t('goalProcess.northStar.declare.title', { ns: 'chat' }),
+ width: 'min(90%, 480px)',
+ });
diff --git a/src/features/AgentGoals/NorthStarMetrics/RecordObservationModal.tsx b/src/features/AgentGoals/NorthStarMetrics/RecordObservationModal.tsx
new file mode 100644
index 00000000000..98c8568ac13
--- /dev/null
+++ b/src/features/AgentGoals/NorthStarMetrics/RecordObservationModal.tsx
@@ -0,0 +1,93 @@
+'use client';
+
+import { Flexbox, Input } from '@lobehub/ui';
+import {
+ Button,
+ createModal,
+ type ModalInstance,
+ Text,
+ toast,
+ useModalContext,
+} from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useGoalStore } from '@/store/goal';
+
+/**
+ * Manually record one measurement against a declared clause. The probe Work is
+ * the automated writer; this is the human's entry for numbers only they can
+ * see — and the server advances the goal when the observation clears the gate.
+ */
+const RecordObservationContent = memo<{ goalId: string; metricKey: string; metricTitle?: string }>(
+ ({ goalId, metricKey, metricTitle }) => {
+ const { t } = useTranslation('chat');
+ const { close } = useModalContext();
+ const recordGoalObservation = useGoalStore((s) => s.recordGoalObservation);
+
+ const [value, setValue] = useState('');
+ const [busy, setBusy] = useState(false);
+
+ const submit = async () => {
+ const parsed = Number(value);
+ if (!Number.isFinite(parsed) || value.trim() === '' || busy) return;
+ setBusy(true);
+ try {
+ // The clause's display name rides along so the series created by the
+ // first observation carries it too.
+ await recordGoalObservation(goalId, { key: metricKey, title: metricTitle, value: parsed });
+ close();
+ } catch (error) {
+ console.error('[NorthStar] failed to record observation:', error);
+ toast.error(t('goalProcess.northStar.record.failed'));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <Flexbox gap={16} paddingBlock={'4px 8px'}>
+ <Flexbox gap={6}>
+ <Text fontSize={13} weight={500}>
+ {t('goalProcess.northStar.record.valueLabel', { key: metricKey })}
+ </Text>
+ <Input
+ autoFocus
+ placeholder={'42180'}
+ value={value}
+ onChange={(e) => setValue(e.target.value)}
+ onPressEnter={() => void submit()}
+ />
+ </Flexbox>
+ <Flexbox horizontal justify={'flex-end'}>
+ <Button
+ disabled={!Number.isFinite(Number(value)) || value.trim() === ''}
+ loading={busy}
+ type={'primary'}
+ onClick={() => void submit()}
+ >
+ {t('goalProcess.northStar.record.submit')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+RecordObservationContent.displayName = 'RecordObservationContent';
+
+export const openRecordObservationModal = (
+ goalId: string,
+ metricKey: string,
+ metricTitle?: string,
+): ModalInstance =>
+ createModal({
+ content: (
+ <RecordObservationContent goalId={goalId} metricKey={metricKey} metricTitle={metricTitle} />
+ ),
+ footer: null,
+ maskClosable: true,
+ title: t('goalProcess.northStar.record.title', { ns: 'chat' }),
+ width: 'min(90%, 420px)',
+ });
diff --git a/src/features/AgentGoals/NorthStarMetrics/Sparkline.tsx b/src/features/AgentGoals/NorthStarMetrics/Sparkline.tsx
new file mode 100644
index 00000000000..394e130da54
--- /dev/null
+++ b/src/features/AgentGoals/NorthStarMetrics/Sparkline.tsx
@@ -0,0 +1,38 @@
+'use client';
+
+import { cssVar } from 'antd-style';
+import { memo } from 'react';
+
+/**
+ * Trend-only miniature: no axes, no labels — the card's number carries the
+ * value, this carries the shape of the climb.
+ */
+const Sparkline = memo<{ met?: boolean; values: number[] }>(({ met, values }) => {
+ const width = 84;
+ const height = 22;
+ if (values.length < 2) return null;
+
+ const min = Math.min(...values);
+ const max = Math.max(...values);
+ const span = Math.max(1e-9, max - min);
+ const sx = (index: number) => (index / (values.length - 1)) * (width - 2) + 1;
+ const sy = (value: number) => height - 2 - ((value - min) / span) * (height - 4);
+ const d = values
+ .map((value, index) => `${index === 0 ? 'M' : 'L'} ${sx(index)} ${sy(value)}`)
+ .join(' ');
+
+ return (
+ <svg aria-hidden height={height} width={width}>
+ <path
+ d={d}
+ fill={'none'}
+ stroke={met ? cssVar.colorSuccess : cssVar.colorInfo}
+ strokeWidth={1.5}
+ />
+ </svg>
+ );
+});
+
+Sparkline.displayName = 'NorthStarSparkline';
+
+export default Sparkline;
diff --git a/src/features/AgentGoals/NorthStarMetrics/index.tsx b/src/features/AgentGoals/NorthStarMetrics/index.tsx
new file mode 100644
index 00000000000..b9e1b341343
--- /dev/null
+++ b/src/features/AgentGoals/NorthStarMetrics/index.tsx
@@ -0,0 +1,206 @@
+'use client';
+
+import { Flexbox, Icon } from '@lobehub/ui';
+import { Button, Skeleton, Tag, Text, Tooltip } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import dayjs from 'dayjs';
+import { Check, Plus, Target } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import { goalSelectors, useGoalStore } from '@/store/goal';
+
+import { openDeclareMetricModal } from './DeclareMetricModal';
+import { buildNorthStarCards, formatMetricValue, type NorthStarCard } from './northStar';
+import { openRecordObservationModal } from './RecordObservationModal';
+import Sparkline from './Sparkline';
+
+/**
+ * The goal's north-star strip: how far the *world* is from the declared
+ * numbers, above the header's execution metrics (rounds / spend / duration),
+ * which only say what the run cost. Clauses come from
+ * `config.acceptance.metrics` — the same numbers the coordinator's measured
+ * gate reads — so the strip and the acceptance verdict can never disagree
+ * about what is being tracked.
+ */
+
+const styles = createStaticStyles(({ css }) => ({
+ card: css`
+ flex: 1;
+
+ min-width: 236px;
+ max-width: 340px;
+ padding-block: 10px;
+ padding-inline: 14px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: ${cssVar.colorBgContainer};
+ `,
+ metValue: css`
+ color: ${cssVar.colorSuccess};
+ `,
+ stale: css`
+ color: ${cssVar.colorWarning};
+ `,
+ track: css`
+ overflow: hidden;
+ height: 4px;
+ border-radius: 2px;
+ background: ${cssVar.colorFillSecondary};
+ `,
+}));
+
+const MetricCard = memo<{ canEdit: boolean; card: NorthStarCard; goalId: string }>(
+ ({ canEdit, card, goalId }) => {
+ const { t } = useTranslation('chat');
+
+ const freshness =
+ card.latestAt == null
+ ? t('goalProcess.northStar.unmeasured')
+ : t('goalProcess.northStar.lastObserved', { time: dayjs(card.latestAt).fromNow() });
+
+ return (
+ <Flexbox className={styles.card} gap={6}>
+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {card.label}
+ </Text>
+ <Flexbox horizontal align={'center'} gap={4}>
+ {card.met && (
+ <Tag color={'success'} size={'small'}>
+ <Icon icon={Check} size={11} /> {t('goalProcess.northStar.met')}
+ </Tag>
+ )}
+ {/* Recording stays available after the target is met: the world
+ can regress, and a card whose only refresh path disappeared
+ would stay falsely met forever. */}
+ {canEdit && (
+ <Tooltip title={t('goalProcess.northStar.record.title')}>
+ <Button
+ icon={<Icon icon={Plus} size={13} />}
+ size={'small'}
+ type={'text'}
+ onClick={() => openRecordObservationModal(goalId, card.key, card.label)}
+ />
+ </Tooltip>
+ )}
+ </Flexbox>
+ </Flexbox>
+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
+ <Flexbox horizontal align={'baseline'} gap={6}>
+ <Text className={card.met ? styles.metValue : ''} fontSize={20} weight={700}>
+ {formatMetricValue(card.current)}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t(`goalProcess.northStar.op.${card.op}` as const)} {formatMetricValue(card.target)}
+ {card.unit ? ` ${card.unit}` : ''}
+ </Text>
+ </Flexbox>
+ <Sparkline met={card.met} values={card.trend} />
+ </Flexbox>
+ <div className={styles.track}>
+ <div
+ style={{
+ background: card.met ? cssVar.colorSuccess : cssVar.colorInfo,
+ borderRadius: 2,
+ height: '100%',
+ width: `${card.percent}%`,
+ }}
+ />
+ </div>
+ <Text className={card.stale ? styles.stale : ''} fontSize={11} type={'secondary'}>
+ {freshness}
+ {card.stale ? ` · ${t('goalProcess.northStar.staleWarning')}` : ''}
+ </Text>
+ </Flexbox>
+ );
+ },
+);
+
+MetricCard.displayName = 'NorthStarMetricCard';
+
+interface NorthStarMetricsProps {
+ canEdit: boolean;
+ goalId: string;
+}
+
+const NorthStarMetrics = memo<NorthStarMetricsProps>(({ canEdit, goalId }) => {
+ const { t } = useTranslation('chat');
+
+ const snapshot = useGoalStore(goalSelectors.goalGraph(goalId));
+ const useFetchGoalMetricSeries = useGoalStore((s) => s.useFetchGoalMetricSeries);
+ const series = useGoalStore(goalSelectors.goalMetricSeries(goalId));
+
+ const criteria = snapshot?.goal.config?.acceptance?.metrics;
+ // Fetch only when there is something to join against — a goal without
+ // declared clauses renders the guidance row and costs no series read.
+ const { error, isLoading, mutate } = useFetchGoalMetricSeries(
+ criteria?.length ? goalId : undefined,
+ );
+
+ const cards = useMemo(
+ () => (criteria?.length ? buildNorthStarCards(criteria, series ?? []) : []),
+ [criteria, series],
+ );
+
+ if (!criteria?.length)
+ return (
+ <Flexbox horizontal align={'center'} gap={12} paddingBlock={4}>
+ <Icon color={cssVar.colorTextQuaternary} icon={Target} size={16} />
+ <Text fontSize={13} type={'secondary'}>
+ {t('goalProcess.northStar.emptyHint')}
+ </Text>
+ {canEdit && (
+ <Button size={'small'} onClick={() => openDeclareMetricModal(goalId)}>
+ {t('goalProcess.northStar.declare.title')}
+ </Button>
+ )}
+ </Flexbox>
+ );
+
+ if (error && !series)
+ return (
+ <AsyncError
+ error={error}
+ variant={'metric'}
+ onRetry={() => {
+ void mutate();
+ }}
+ />
+ );
+
+ // First fetch still in flight: say nothing rather than confidently claiming
+ // "never measured" against an empty join — a false state, not feedback.
+ if (!series && isLoading)
+ return (
+ <Flexbox horizontal gap={10}>
+ {criteria.map((criterion) => (
+ <Skeleton height={96} key={criterion.key} width={236} />
+ ))}
+ </Flexbox>
+ );
+
+ return (
+ <Flexbox horizontal gap={10} wrap={'wrap'}>
+ {cards.map((card) => (
+ <MetricCard canEdit={canEdit} card={card} goalId={goalId} key={card.key} />
+ ))}
+ {canEdit && (
+ <Tooltip title={t('goalProcess.northStar.declare.title')}>
+ <Button
+ icon={<Icon icon={Plus} size={14} />}
+ style={{ alignSelf: 'center' }}
+ type={'text'}
+ onClick={() => openDeclareMetricModal(goalId)}
+ />
+ </Tooltip>
+ )}
+ </Flexbox>
+ );
+});
+
+NorthStarMetrics.displayName = 'NorthStarMetrics';
+
+export default NorthStarMetrics;
diff --git a/src/features/AgentGoals/NorthStarMetrics/northStar.test.ts b/src/features/AgentGoals/NorthStarMetrics/northStar.test.ts
new file mode 100644
index 00000000000..84add94eeba
--- /dev/null
+++ b/src/features/AgentGoals/NorthStarMetrics/northStar.test.ts
@@ -0,0 +1,146 @@
+import { describe, expect, it } from 'vitest';
+
+import type { MetricSeriesWithPoints } from '@/services/metric';
+
+import { buildNorthStarCards, formatMetricValue, NORTH_STAR_STALE_AFTER_MS } from './northStar';
+
+const NOW = Date.parse('2026-09-06T12:00:00Z');
+
+const series = (
+ key: string,
+ values: number[],
+ overrides: Partial<MetricSeriesWithPoints> = {},
+): MetricSeriesWithPoints => ({
+ firstPoint:
+ values.length > 0
+ ? { observedAt: new Date(NOW - (values.length - 1) * 60_000), value: values[0] }
+ : null,
+ id: `mtr_${key}`,
+ key,
+ kind: 'gauge',
+ points: values.map((value, index) => ({
+ observedAt: new Date(NOW - (values.length - 1 - index) * 60_000),
+ value,
+ })),
+ ...overrides,
+});
+
+describe('buildNorthStarCards', () => {
+ it('normalizes a count-up clause from its first observation', () => {
+ // 粉丝 42,180 → 目标 72,180,当前 57,180:爬了三万的一半。
+ const [card] = buildNorthStarCards(
+ [{ key: 'followers', target: 72_180 }],
+ [series('followers', [42_180, 48_000, 57_180], { title: '粉丝总数' })],
+ NOW,
+ );
+
+ expect(card).toMatchObject({ current: 57_180, label: '粉丝总数', met: false, op: 'gte' });
+ expect(card.percent).toBeCloseTo(50);
+ });
+
+ it("prefers the clause's own display name over the series title and the key", () => {
+ // Review r1: the key is the address, not the label — a declared display
+ // name must win even when the series carries its own title.
+ const [named, fallback] = buildNorthStarCards(
+ [
+ { key: 'followers', target: 1000, title: '粉丝总数' },
+ { key: 'security.open_issues', op: 'lte', target: 0 },
+ ],
+ [series('followers', [500], { title: 'series title' })],
+ NOW,
+ );
+
+ expect(named.label).toBe('粉丝总数');
+ expect(fallback.label).toBe('security.open_issues');
+ });
+
+ it('reads a count-down clause in its own direction', () => {
+ // 安全 issue 112 → 0,当前 37:清掉 67%,而不是「37/0」的除零。
+ const [card] = buildNorthStarCards(
+ [{ key: 'security.open_issues', op: 'lte', target: 0 }],
+ [series('security.open_issues', [112, 80, 37])],
+ NOW,
+ );
+
+ expect(card.met).toBe(false);
+ expect(card.percent).toBeCloseTo(((112 - 37) / 112) * 100);
+ });
+
+ it('marks the clause met once the latest observation clears the target', () => {
+ const [down, up] = buildNorthStarCards(
+ [
+ { key: 'issues', op: 'lte', target: 0 },
+ { key: 'followers', target: 1000 },
+ ],
+ [series('issues', [112, 3, 0]), series('followers', [400, 1200])],
+ NOW,
+ );
+
+ expect(down).toMatchObject({ met: true, percent: 100 });
+ expect(up).toMatchObject({ met: true, percent: 100 });
+ });
+
+ it('treats a never-measured clause as unmeasured, not as zero progress toward done', () => {
+ const [card] = buildNorthStarCards([{ key: 'followers', target: 1000 }], [], NOW);
+
+ expect(card).toMatchObject({ current: null, label: 'followers', met: false, percent: 0 });
+ expect(card.latestAt).toBeUndefined();
+ expect(card.stale).toBe(false);
+ });
+
+ it('flags data older than the staleness window', () => {
+ const old = {
+ ...series('followers', [500]),
+ points: [{ observedAt: new Date(NOW - NORTH_STAR_STALE_AFTER_MS - 1000), value: 500 }],
+ };
+
+ const [card] = buildNorthStarCards([{ key: 'followers', target: 1000 }], [old], NOW);
+
+ expect(card.stale).toBe(true);
+ });
+
+ it('guards a baseline that already sits at the target', () => {
+ // 起点即达标(span 0):met 时 100,不达标时 0,永不除零。
+ const [met] = buildNorthStarCards(
+ [{ key: 'x', op: 'lte', target: 5 }],
+ [series('x', [5, 5])],
+ NOW,
+ );
+ expect(met).toMatchObject({ met: true, percent: 100 });
+ });
+});
+
+describe('scale and windowing', () => {
+ it('compares at the persisted numeric(20, 6) scale, matching the server gate', () => {
+ // Recorded 0.1234567 reads back as 0.123457; a raw-target comparison
+ // would keep this card unmet forever while the goal already advanced.
+ const [card] = buildNorthStarCards(
+ [{ key: 'precision', op: 'eq', target: 0.123_456_7 }],
+ [series('precision', [0.123_457])],
+ NOW,
+ );
+
+ expect(card.met).toBe(true);
+ });
+
+ it('takes the baseline from the true first observation, not the recent window', () => {
+ // A 0 → 95 / 100 trajectory whose window only retains [90, 95] must read
+ // 95%, not the 50% a window-rebased baseline would claim.
+ const windowed = {
+ ...series('long', [90, 95]),
+ firstPoint: { observedAt: new Date(NOW - 10 * 86_400_000), value: 0 },
+ };
+
+ const [card] = buildNorthStarCards([{ key: 'long', target: 100 }], [windowed], NOW);
+
+ expect(card.percent).toBeCloseTo(95);
+ });
+});
+
+describe('formatMetricValue', () => {
+ it('groups integers and passes fractions through', () => {
+ expect(formatMetricValue(72_180)).toBe('72,180');
+ expect(formatMetricValue(0.07)).toBe('0.07');
+ expect(formatMetricValue(null)).toBe('—');
+ });
+});
diff --git a/src/features/AgentGoals/NorthStarMetrics/northStar.ts b/src/features/AgentGoals/NorthStarMetrics/northStar.ts
new file mode 100644
index 00000000000..c566bb7df7c
--- /dev/null
+++ b/src/features/AgentGoals/NorthStarMetrics/northStar.ts
@@ -0,0 +1,143 @@
+import {
+ type GoalMetricComparison,
+ type GoalMetricCriterion,
+ toMetricScale,
+} from '@lobechat/types';
+
+import type { MetricSeriesWithPoints } from '@/services/metric';
+
+/**
+ * View model of one north-star card: a declared acceptance clause joined with
+ * its measured series. Pure derivation — the server's gate (#19133) stays the
+ * authority on pass/fail; this only renders the same arithmetic.
+ */
+export interface NorthStarCard {
+ /** Latest observation, null when the clause was never measured. */
+ current: number | null;
+ key: string;
+ label: string;
+ /** When the latest observation landed; undefined when never measured. */
+ latestAt?: Date;
+ met: boolean;
+ op: GoalMetricComparison;
+ /** 0-100, baseline → target. 0 when unmeasured. */
+ percent: number;
+ /**
+ * The latest observation is older than the staleness window. A tracking
+ * surface is only as trustworthy as its data is fresh, so this renders as a
+ * warning, not a detail.
+ */
+ stale: boolean;
+ target: number;
+ /** Ascending observation values for the sparkline, capped. */
+ trend: number[];
+ unit?: string | null;
+}
+
+/** Two days without a sample and the number on the card is a claim, not a fact. */
+export const NORTH_STAR_STALE_AFTER_MS = 48 * 60 * 60 * 1000;
+
+const SPARKLINE_POINT_CAP = 60;
+
+const compare = (rawValue: number, op: GoalMetricComparison, rawTarget: number): boolean => {
+ // Both operands at the persisted numeric(20, 6) scale — the server's gate
+ // compares this way, and a raw-target comparison here could disagree with
+ // it at rounding boundaries (`eq 0.1234567` never holding while the goal
+ // already advanced).
+ 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;
+ }
+ }
+};
+
+/**
+ * Progress from the first observation (the baseline) toward the target,
+ * normalized by the clause's own direction — a count-down clause ("112 issues
+ * → 0") reads 67% at 37 exactly like a count-up one reads at 67% of the climb.
+ * `eq` measures closing distance from where the series started.
+ */
+const progress = (
+ op: GoalMetricComparison,
+ baseline: number,
+ current: number,
+ target: number,
+): number => {
+ const span =
+ op === 'eq'
+ ? Math.abs(baseline - target)
+ : op === 'lte' || op === 'lt'
+ ? baseline - target
+ : target - baseline;
+ if (span <= 0) return compare(current, op, target) ? 100 : 0;
+ const walked =
+ op === 'eq'
+ ? span - Math.abs(current - target)
+ : op === 'lte' || op === 'lt'
+ ? baseline - current
+ : current - baseline;
+ return Math.max(0, Math.min(100, (walked / span) * 100));
+};
+
+export const buildNorthStarCards = (
+ criteria: GoalMetricCriterion[],
+ series: MetricSeriesWithPoints[],
+ now = Date.now(),
+): NorthStarCard[] => {
+ const byKey = new Map(series.map((item) => [item.key, item]));
+
+ return criteria.map((criterion) => {
+ const op = criterion.op ?? 'gte';
+ const matched = byKey.get(criterion.key);
+ const points = matched?.points ?? [];
+ const latest = points.at(-1);
+ // The true first observation, not the window's oldest: `points` is a
+ // recent window, and rebasing on it would silently inflate or deflate
+ // progress once history outgrows the window.
+ const baseline = matched?.firstPoint?.value ?? points[0]?.value;
+
+ const trendSource = points.map((point) => point.value);
+ const step = Math.max(1, Math.ceil(trendSource.length / SPARKLINE_POINT_CAP));
+ const trend = trendSource.filter(
+ (_, index) => index % step === 0 || index === trendSource.length - 1,
+ );
+
+ return {
+ current: latest?.value ?? null,
+ key: criterion.key,
+ label: criterion.title || matched?.title || criterion.key,
+ latestAt: latest?.observedAt,
+ met: latest != null && compare(latest.value, op, criterion.target),
+ op,
+ percent:
+ latest == null || baseline == null
+ ? 0
+ : progress(op, baseline, latest.value, criterion.target),
+ stale: latest != null && now - latest.observedAt.getTime() > NORTH_STAR_STALE_AFTER_MS,
+ target: criterion.target,
+ trend,
+ unit: matched?.unit,
+ };
+ });
+};
+
+/** `6,234` — counts get grouping; fractional metrics keep their precision. */
+export const formatMetricValue = (value: number | null): string => {
+ if (value == null) return '—';
+ if (Number.isInteger(value)) return value.toLocaleString('en-US');
+ return String(value);
+};
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index c0f07f94827..f7e18d56def 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -347,6 +347,7 @@ export const isMyTaskListKey = (key: unknown): boolean =>
*/
export const goalKeys = {
graph: def('goal:graph', (goalId: string) => ['goal:graph', goalId]),
+ metricSeries: def('goal:metricSeries', (goalId: string) => ['goal:metricSeries', goalId]),
};
export const taskKeys = {
diff --git a/src/services/goal.ts b/src/services/goal.ts
index e2053fcc666..398639ca17d 100644
--- a/src/services/goal.ts
+++ b/src/services/goal.ts
@@ -1,5 +1,11 @@
import type { GoalStatus } from '@lobechat/const/goal';
-import type { GoalConfig, GoalGraphSnapshot, GoalNodeKind, GoalTickResult } from '@lobechat/types';
+import type {
+ GoalConfig,
+ GoalGraphSnapshot,
+ GoalMetricCriterion,
+ GoalNodeKind,
+ GoalTickResult,
+} from '@lobechat/types';
import { lambdaClient } from '@/libs/trpc/client';
@@ -44,6 +50,17 @@ class GoalService {
setAcceptanceCriteria = async (id: string, criteriaIds: string[]) =>
lambdaClient.goal.setAcceptanceCriteria.mutate({ criteriaIds, id });
+ setMetricCriteria = async (
+ id: string,
+ metrics: GoalMetricCriterion[],
+ mode?: 'merge' | 'replace',
+ ) => lambdaClient.goal.setMetricCriteria.mutate({ id, metrics, mode });
+
+ recordObservation = async (
+ id: string,
+ observation: { key: string; observedAt?: Date; title?: string; unit?: string; value: number },
+ ) => lambdaClient.goal.recordObservation.mutate({ id, ...observation });
+
/** Delete a goal and its graph. The dispatched Work Tasks are left in place. */
delete = async (id: string) => lambdaClient.goal.delete.mutate({ id });
diff --git a/src/services/metric.ts b/src/services/metric.ts
new file mode 100644
index 00000000000..1b78c1c36c6
--- /dev/null
+++ b/src/services/metric.ts
@@ -0,0 +1,63 @@
+import type { MetricKind, MetricSubjectType } from '@lobechat/types';
+
+import { lambdaClient } from '@/libs/trpc/client';
+
+/**
+ * One chartable series of a subject — the shape the north-star strip consumes.
+ * `firstPoint` is the series' true first observation, carried separately
+ * because `points` is a recent window: a progress baseline read from
+ * `points[0]` would silently rebase once history outgrows the window.
+ */
+export interface MetricSeriesWithPoints {
+ config?: { direction?: 'higher_is_better' | 'lower_is_better'; target?: number } | null;
+ firstPoint: { observedAt: Date; value: number } | null;
+ id: string;
+ key: string;
+ kind: MetricKind;
+ points: { observedAt: Date; value: number }[];
+ title?: string | null;
+ unit?: string | null;
+}
+
+/** Sparkline + progress need the shape, not the volume — cap the window. */
+const SERIES_POINT_LIMIT = 200;
+
+class MetricService {
+ /**
+ * One RPC for the whole tracking surface: only the named series (a declared
+ * acceptance contract is capped), each with its recent window and true
+ * first observation.
+ */
+ listSeriesWithPoints = async (
+ subjectType: MetricSubjectType,
+ subjectId: string,
+ keys: string[],
+ ): Promise<MetricSeriesWithPoints[]> => {
+ if (keys.length === 0) return [];
+
+ const { data } = await lambdaClient.metric.listSeriesWithPoints.query({
+ keys,
+ limit: SERIES_POINT_LIMIT,
+ subjectId,
+ subjectType,
+ });
+
+ return data.map((item) => ({
+ config: item.config,
+ firstPoint: item.firstPoint
+ ? { observedAt: new Date(item.firstPoint.observedAt), value: Number(item.firstPoint.value) }
+ : null,
+ id: item.id,
+ key: item.key,
+ kind: item.kind,
+ points: item.points.map((point) => ({
+ observedAt: new Date(point.observedAt),
+ value: Number(point.value),
+ })),
+ title: item.title,
+ unit: item.unit,
+ }));
+ };
+}
+
+export const metricService = new MetricService();
diff --git a/src/store/goal/action.ts b/src/store/goal/action.ts
index c92bece33d1..8a3295a50e6 100644
--- a/src/store/goal/action.ts
+++ b/src/store/goal/action.ts
@@ -1,9 +1,10 @@
import { type GoalStatus, goalStatuses } from '@lobechat/const/goal';
-import type { GoalTickResult } from '@lobechat/types';
+import type { GoalMetricCriterion, GoalTickResult } from '@lobechat/types';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { goalKeys, taskKeys } from '@/libs/swr/keys';
import { goalService } from '@/services/goal';
+import { metricService } from '@/services/metric';
import type { StoreSetter } from '@/store/types';
import type { GoalListFilter, GoalState, GoalViewMode } from './initialState';
@@ -162,6 +163,75 @@ export class GoalActionImpl {
revalidateOnFocus: true,
});
+ /**
+ * North-star data of the goal detail header. Polls on the same cadence logic
+ * as the graph: while the server is advancing, a probe Work or an agent
+ * `recordObservation` can land a fresh point at any time.
+ */
+ useFetchGoalMetricSeries = (goalId?: string | null) =>
+ useClientDataSWR(
+ goalId ? goalKeys.metricSeries(goalId) : null,
+ // Only the declared keys are fetched — the same goal can accumulate any
+ // number of other sampled series, and none of them can affect this view.
+ // Keys are read at fetch time; the declare path revalidates this cache
+ // key right after refreshing the graph, so a newly declared clause is
+ // fetched against fresh criteria.
+ () =>
+ metricService.listSeriesWithPoints(
+ 'goal',
+ goalId!,
+ (this.#get().goalGraphById[goalId!]?.goal.config?.acceptance?.metrics ?? []).map(
+ (criterion) => criterion.key,
+ ),
+ ),
+ {
+ onSuccess: (series) => {
+ this.#set(
+ ({ goalMetricSeriesById }) => ({
+ goalMetricSeriesById: { ...goalMetricSeriesById, [goalId!]: series },
+ }),
+ false,
+ 'useFetchGoalMetricSeries/success',
+ );
+ },
+ refreshInterval: () => {
+ const graph = this.#get().goalGraphById[goalId!];
+ return graph && SERVER_ADVANCING_STATUSES.has(graph.goal.status)
+ ? GOAL_GRAPH_POLL_INTERVAL
+ : 0;
+ },
+ revalidateOnFocus: true,
+ },
+ );
+
+ refreshGoalMetricSeries = async (goalId: string): Promise<void> => {
+ await mutate(goalKeys.metricSeries(goalId));
+ };
+
+ /** Append one clause to the goal's measured acceptance and refresh both reads. */
+ declareGoalMetric = async (goalId: string, criterion: GoalMetricCriterion): Promise<void> => {
+ // Merged on the server against its current list — a replacement array
+ // built from this client's snapshot would silently drop whatever a
+ // concurrent editor or agent declared since the snapshot was read.
+ await goalService.setMetricCriteria(goalId, [criterion], 'merge');
+ await this.refreshGoalGraph(goalId);
+ await this.refreshGoalMetricSeries(goalId);
+ };
+
+ /**
+ * Record a measurement against the goal. The server schedules an advance
+ * when the observation clears the gate, so the graph refresh may come back
+ * already reopened.
+ */
+ recordGoalObservation = async (
+ goalId: string,
+ observation: { key: string; title?: string; value: number },
+ ): Promise<void> => {
+ await goalService.recordObservation(goalId, observation);
+ await this.refreshGoalMetricSeries(goalId);
+ await this.refreshGoalGraph(goalId);
+ };
+
loadMoreGoals = (): void => {
this.#set(
({ goalListVisibleLimit }) => ({ goalListVisibleLimit: goalListVisibleLimit + 10 }),
diff --git a/src/store/goal/initialState.ts b/src/store/goal/initialState.ts
index 9b377b97efa..8f5f20a3c48 100644
--- a/src/store/goal/initialState.ts
+++ b/src/store/goal/initialState.ts
@@ -1,6 +1,7 @@
import type { GoalGraphSnapshot } from '@lobechat/types';
import type { GoalListItem } from '@/services/goal';
+import type { MetricSeriesWithPoints } from '@/services/metric';
export type { GoalListItem };
export type GoalListFilter = 'active' | 'all';
@@ -13,6 +14,12 @@ export interface GoalState {
goalListFilter: GoalListFilter;
goalListInitializedAgentIds: string[];
goalListVisibleLimit: number;
+ /**
+ * North-star series of a goal (subjectType 'goal'), points included. Keyed
+ * by goal id like the graph snapshot — the strip and the graph describe the
+ * same row and refresh together.
+ */
+ goalMetricSeriesById: Record<string, MetricSeriesWithPoints[]>;
goalViewMode: GoalViewMode;
/**
* Every agent's goals, for the home rail's cross-agent roll-up — keyed by
@@ -25,6 +32,7 @@ export interface GoalState {
}
export const initialState: GoalState = {
+ goalMetricSeriesById: {},
goalGraphById: {},
goalListByAgentId: {},
goalListFilter: 'active',
diff --git a/src/store/goal/selectors.ts b/src/store/goal/selectors.ts
index f0d9030fc5b..3bbf746d585 100644
--- a/src/store/goal/selectors.ts
+++ b/src/store/goal/selectors.ts
@@ -5,6 +5,9 @@ const EMPTY_GOALS: GoalStore['goalListByAgentId'][string] = [];
const goalGraph = (goalId?: string | null) => (s: GoalStore) =>
goalId ? s.goalGraphById[goalId] : undefined;
+const goalMetricSeries = (goalId?: string | null) => (s: GoalStore) =>
+ goalId ? s.goalMetricSeriesById[goalId] : undefined;
+
const goalList = (agentId: string) => (s: GoalStore) => s.goalListByAgentId[agentId] ?? EMPTY_GOALS;
const isGoalListInitialized = (agentId: string) => (s: GoalStore) =>
@@ -16,6 +19,7 @@ const isHomeGoalsInitialized = (scope: string) => (s: GoalStore) =>
s.homeGoalsInitializedScopes.includes(scope);
export const goalSelectors = {
+ goalMetricSeries,
goalGraph,
goalList,
homeGoals,