feat(rectification): 生时纠正 marked 「随缘版」, every step recorded (adopted or not) in chart_choice_steps for later checking, the stale 「开头会说明是你选的」 line removed, privacy policy says so (BUG-2256)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXp2U3BH1SxwAGyhhbe1
This commit is contained in:
2026-11-23 15:36:44 +08:00
co-authored by Claude Opus 5.5
parent 309e57496f
commit 39e0ef8af2
19 changed files with 369 additions and 72 deletions
+12
View File
@@ -30347,3 +30347,15 @@
- 防复发:标题栏里的新按钮一律用 `.title-bar-button`(需要手机只留图标时加 `.title-bar-icon-on-phone` 并给 `aria-label`);回归测试钉住三个入口不能回到 outline / secondary。
- 关联记录:BUG-2081(页面级提问入口)、BUG-2082(标题栏随版本换语言、窄栏让位)、BUG-2093、BUG-2138(导出读取全文)、2026-11-02 顶栏控件 34px 规则。
- 修复版本:分支 `claude/header-buttons-2258`(待父会话推送)。
## BUG-2256 | 生时纠正没有标出实验性质,中途离开的过程也没有记录,无法检验
- 状态:fixed-pending-verify。
- 现象:产品负责人 2026-11-23:生时纠正对没有出生记录的用户能不能量准,目前没有数据可以回答(#329 因此暂停);后台只在用户点「采用」时写 `chart_choice_records`,中途离开的过程什么都不留。首页还写着「按你自己的选择:报告和问答都按这个时间写,开头会说明是你选的」,而报告与问答自 BUG-2146/2184 起已不在开头说明。
- 修复(设计稿 2026-11-23 负责人同意):
- 页头标题后、侧栏入口右上角加灰色小标签「随缘版」;删掉首页那句话。
- 新表 `chart_choice_steps`:生时纠正的五个接口(packet、adopt、supplement、reuse、astrologer)每次请求记一行,包括当时的出生资料与时间来源(由数据库按当时状态读取)、请求内容(经历、换盘选择、范围)、结果(状态、代码、放得下的 decision)、代码版本,不论成功失败、采用与否。随账号(auth.users)或人物档案(chart_profiles)级联删除;表对所有运行角色关闭,只能通过 `chart_choice_log_step_v1`(service_role)写入。写不进去时跳过,不影响用户这一步。没有任何算法读取它。
- 对照依据不另外问:填资料时时间来源为出生证明或证件的用户,其填写时间即标准答案(负责人 2026-11-23 批注)。
- 隐私政策「如何使用」与「保存期限」各补一条;原「生时纠正的问题数量与收敛情况,不含出生资料」一句改写(法律文件在内测期间仍隐藏)。
- 验证与防复发:`rect-casual-edition-2256`(标签、删句、五个接口都记录、表的级联与权限、隐私政策)、`rect-step-log-2256`(结果裁剪、一次调用、写失败不外抛)、`database-local-business`(表清单)。
- 关联记录:#329、BUG-2146、BUG-2184、BUG-1654。
- 修复版本:`claude/rect-casual-2256`。
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
import { isRectQuestionnaireRequest, RECT_QUESTIONNAIRE_ENABLED, RECT_QUESTIONNAIRE_PAUSED } from "@/components/chart-choice/questionnaire-switch";
import { z } from "zod";
import { recordChartChoiceStep } from "@/lib/chart-choice/step-log";
import { chartAnswersSchema, chartChoiceCaller, chartChoiceErrorResponse, evidenceInput, resolvedSchema, windowSchema } from "@/lib/chart-choice/route-support";
import { adoptCertainTime, adoptChartChoice, adoptDefaultChartChoice, adoptSelfChoice, previewAdaptiveChartChoice, previewChartChoice, previewSelfChoice, readDefaultChartChoice, restoreChartChoiceDefault } from "@/lib/chart-choice/server";
import { createAdminSupabaseClient } from "@/lib/supabase/admin";
@@ -67,42 +68,47 @@ export async function POST(request: Request) {
}
const parsed = bodySchema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "请求格式不对", code: "bad_request" }, { status: 400 });
try {
if ("selfChoice" in parsed.data) {
const admin = createAdminSupabaseClient();
return NextResponse.json(parsed.data.mode === "preview"
? await previewSelfChoice(caller.supabase, admin, caller.userId, parsed.data)
: await adoptSelfChoice(caller.supabase, admin, caller.userId, parsed.data));
}
if (!RECT_QUESTIONNAIRE_ENABLED && (parsed.data.mode === "preview" || parsed.data.mode === "choice")) {
const { subjectId, window, rangeChosen } = parsed.data;
// BUG-2256: every 生时纠正 step is recorded, adopted or not (lib/chart-choice/step-log.ts).
const response = await (async () => {
try {
if ("selfChoice" in parsed.data) {
const admin = createAdminSupabaseClient();
return NextResponse.json(parsed.data.mode === "preview"
? await previewSelfChoice(caller.supabase, admin, caller.userId, parsed.data)
: await adoptSelfChoice(caller.supabase, admin, caller.userId, parsed.data));
}
if (!RECT_QUESTIONNAIRE_ENABLED && (parsed.data.mode === "preview" || parsed.data.mode === "choice")) {
const { subjectId, window, rangeChosen } = parsed.data;
if (parsed.data.mode === "preview") {
const { decision } = await readDefaultChartChoice(caller.supabase, caller.userId, { subjectId, window });
return NextResponse.json({ decision });
}
return NextResponse.json(await adoptDefaultChartChoice(
caller.supabase, createAdminSupabaseClient(), caller.userId, { subjectId, window, rangeChosen },
));
}
if (parsed.data.mode === "restore_default") {
return NextResponse.json(await restoreChartChoiceDefault(
caller.supabase, createAdminSupabaseClient(), caller.userId, parsed.data,
));
}
if (parsed.data.mode === "preview") {
const { decision } = await readDefaultChartChoice(caller.supabase, caller.userId, { subjectId, window });
return NextResponse.json({ decision });
if (parsed.data.adaptive) {
return NextResponse.json(await previewAdaptiveChartChoice(caller.supabase, caller.userId, parsed.data));
}
return NextResponse.json(await previewChartChoice(caller.supabase, caller.userId, parsed.data, undefined,
parsed.data.resumeRecordId ? createAdminSupabaseClient() : undefined));
}
return NextResponse.json(await adoptDefaultChartChoice(
caller.supabase, createAdminSupabaseClient(), caller.userId, { subjectId, window, rangeChosen },
));
}
if (parsed.data.mode === "restore_default") {
return NextResponse.json(await restoreChartChoiceDefault(
caller.supabase, createAdminSupabaseClient(), caller.userId, parsed.data,
));
}
if (parsed.data.mode === "preview") {
if (parsed.data.adaptive) {
return NextResponse.json(await previewAdaptiveChartChoice(caller.supabase, caller.userId, parsed.data));
const admin = createAdminSupabaseClient();
if (parsed.data.mode === "certain") {
return NextResponse.json(await adoptCertainTime(caller.supabase, admin, caller.userId, parsed.data));
}
return NextResponse.json(await previewChartChoice(caller.supabase, caller.userId, parsed.data, undefined,
parsed.data.resumeRecordId ? createAdminSupabaseClient() : undefined));
const { decision, answers } = await adoptChartChoice(caller.supabase, admin, caller.userId, parsed.data);
return NextResponse.json({ decision, answers });
} catch (error) {
return chartChoiceErrorResponse(error, "POST /api/chart-choice/adopt");
}
const admin = createAdminSupabaseClient();
if (parsed.data.mode === "certain") {
return NextResponse.json(await adoptCertainTime(caller.supabase, admin, caller.userId, parsed.data));
}
const { decision, answers } = await adoptChartChoice(caller.supabase, admin, caller.userId, parsed.data);
return NextResponse.json({ decision, answers });
} catch (error) {
return chartChoiceErrorResponse(error, "POST /api/chart-choice/adopt");
}
})();
await recordChartChoiceStep({ userId: caller.userId, subjectId: parsed.data.subjectId, step: `adopt:${"selfChoice" in parsed.data ? "self_" : ""}${"mode" in parsed.data ? String(parsed.data.mode) : "choice"}`, request: parsed.data, response });
return response;
}
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
import { RECT_QUESTIONNAIRE_ENABLED, RECT_QUESTIONNAIRE_PAUSED } from "@/components/chart-choice/questionnaire-switch";
import { z } from "zod";
import { recordChartChoiceStep } from "@/lib/chart-choice/step-log";
import { chartChoiceCaller, chartChoiceErrorResponse, windowSchema } from "@/lib/chart-choice/route-support";
import { runAstrologerMethod } from "@/lib/chart-choice/server";
@@ -34,9 +35,14 @@ export async function POST(request: Request) {
}
const parsed = bodySchema.safeParse(await request.json().catch(() => null));
if (!parsed.success) return NextResponse.json({ error: "请求格式不对", code: "bad_request" }, { status: 400 });
try {
return NextResponse.json(await runAstrologerMethod(caller.supabase, caller.userId, parsed.data));
} catch (error) {
return chartChoiceErrorResponse(error, "POST /api/chart-choice/astrologer");
}
// BUG-2256: every 生时纠正 step is recorded, adopted or not (lib/chart-choice/step-log.ts).
const response = await (async () => {
try {
return NextResponse.json(await runAstrologerMethod(caller.supabase, caller.userId, parsed.data));
} catch (error) {
return chartChoiceErrorResponse(error, "POST /api/chart-choice/astrologer");
}
})();
await recordChartChoiceStep({ userId: caller.userId, subjectId: parsed.data.subjectId, step: "astrologer", request: parsed.data, response });
return response;
}
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
import { isRectQuestionnaireRequest, RECT_QUESTIONNAIRE_ENABLED, RECT_QUESTIONNAIRE_PAUSED } from "@/components/chart-choice/questionnaire-switch";
import { z } from "zod";
import { recordChartChoiceStep } from "@/lib/chart-choice/step-log";
import { chartChoiceCaller, chartChoiceErrorResponse, resolvedSchema, windowSchema } from "@/lib/chart-choice/route-support";
import { createAdminSupabaseClient } from "@/lib/supabase/admin";
import { buildChartChoicePacket, readDefaultChartChoice } from "@/lib/chart-choice/server";
@@ -27,13 +28,18 @@ export async function POST(request: Request) {
}
const parsed = bodySchema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "请求格式不对", code: "bad_request" }, { status: 400 });
try {
if (!RECT_QUESTIONNAIRE_ENABLED) {
return NextResponse.json(await readDefaultChartChoice(caller.supabase, caller.userId, parsed.data));
// BUG-2256: every 生时纠正 step is recorded, adopted or not (lib/chart-choice/step-log.ts).
const response = await (async () => {
try {
if (!RECT_QUESTIONNAIRE_ENABLED) {
return NextResponse.json(await readDefaultChartChoice(caller.supabase, caller.userId, parsed.data));
}
return NextResponse.json(await buildChartChoicePacket(caller.supabase, caller.userId, parsed.data, undefined,
parsed.data.resumeRecordId ? createAdminSupabaseClient() : undefined));
} catch (error) {
return chartChoiceErrorResponse(error, "POST /api/chart-choice/packet");
}
return NextResponse.json(await buildChartChoicePacket(caller.supabase, caller.userId, parsed.data, undefined,
parsed.data.resumeRecordId ? createAdminSupabaseClient() : undefined));
} catch (error) {
return chartChoiceErrorResponse(error, "POST /api/chart-choice/packet");
}
})();
await recordChartChoiceStep({ userId: caller.userId, subjectId: parsed.data.subjectId, step: "packet", request: parsed.data, response });
return response;
}
@@ -1,6 +1,7 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { recordChartChoiceStep } from "@/lib/chart-choice/step-log";
import { chartChoiceCaller, chartChoiceErrorResponse } from "@/lib/chart-choice/route-support";
import { reuseChartChoiceRecord } from "@/lib/chart-choice/server";
import { createAdminSupabaseClient } from "@/lib/supabase/admin";
@@ -15,9 +16,14 @@ export async function POST(request: Request) {
if (!caller.ok) return caller.response;
const parsed = bodySchema.safeParse(await request.json().catch(() => null));
if (!parsed.success) return NextResponse.json({ error: "请求格式不对", code: "bad_request" }, { status: 400 });
try {
return NextResponse.json(await reuseChartChoiceRecord(createAdminSupabaseClient(), caller.userId, parsed.data.recordId, parsed.data.subjectId));
} catch (error) {
return chartChoiceErrorResponse(error, "POST /api/chart-choice/reuse");
}
// BUG-2256: every 生时纠正 step is recorded, adopted or not (lib/chart-choice/step-log.ts).
const response = await (async () => {
try {
return NextResponse.json(await reuseChartChoiceRecord(createAdminSupabaseClient(), caller.userId, parsed.data.recordId, parsed.data.subjectId));
} catch (error) {
return chartChoiceErrorResponse(error, "POST /api/chart-choice/reuse");
}
})();
await recordChartChoiceStep({ userId: caller.userId, subjectId: parsed.data.subjectId, step: "reuse", request: parsed.data, response });
return response;
}
@@ -1,6 +1,7 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { recordChartChoiceStep } from "@/lib/chart-choice/step-log";
import { chartChoiceCaller, chartChoiceErrorResponse } from "@/lib/chart-choice/route-support";
import { readSupplement, supplementPatch } from "@/lib/chart-choice/supplement";
import { isChartSubjectId, SELF_SUBJECT_ID } from "@/lib/subject-birth";
@@ -64,20 +65,25 @@ export async function POST(request: Request) {
if (!caller.ok) return caller.response;
const parsed = bodySchema.safeParse(await request.json().catch(() => null));
if (!parsed.success) return NextResponse.json({ error: "请求格式不对", code: "bad_request" }, { status: 400 });
try {
const subject = target(createAdminSupabaseClient(), caller.userId, parsed.data.subjectId);
if (!subject) return NextResponse.json({ error: "星盘不存在", code: "subject_not_found" }, { status: 404 });
const { data, error } = await subject.read();
if (error) throw error;
if (!data) return NextResponse.json({ error: "星盘不存在", code: "subject_not_found" }, { status: 404 });
const answer = parsed.data.field === "timeSource"
? { field: "timeSource" as const, value: parsed.data.value }
: { field: "date" as const, value: parsed.data.value };
const patch = supplementPatch(data, answer);
const written = await subject.write(patch);
if (written.error) throw written.error;
return NextResponse.json({ supplement: readSupplement({ ...data, ...patch }) });
} catch (error) {
return chartChoiceErrorResponse(error, "POST /api/chart-choice/supplement");
}
// BUG-2256: every 生时纠正 step is recorded, adopted or not (lib/chart-choice/step-log.ts).
const response = await (async () => {
try {
const subject = target(createAdminSupabaseClient(), caller.userId, parsed.data.subjectId);
if (!subject) return NextResponse.json({ error: "星盘不存在", code: "subject_not_found" }, { status: 404 });
const { data, error } = await subject.read();
if (error) throw error;
if (!data) return NextResponse.json({ error: "星盘不存在", code: "subject_not_found" }, { status: 404 });
const answer = parsed.data.field === "timeSource"
? { field: "timeSource" as const, value: parsed.data.value }
: { field: "date" as const, value: parsed.data.value };
const patch = supplementPatch(data, answer);
const written = await subject.write(patch);
if (written.error) throw written.error;
return NextResponse.json({ supplement: readSupplement({ ...data, ...patch }) });
} catch (error) {
return chartChoiceErrorResponse(error, "POST /api/chart-choice/supplement");
}
})();
await recordChartChoiceStep({ userId: caller.userId, subjectId: parsed.data.subjectId, step: `supplement:${parsed.data.field}`, request: parsed.data, response });
return response;
}
+5
View File
@@ -8733,3 +8733,8 @@ button.report-ask-clear:hover { color: var(--color-ink); }
text-align: center;
}
}
/* BUG-2256 (产品负责人 2026-11-23): 生时纠正「随缘版」. A small grey tag after the page title, and in the
top-right corner of the sidebar tile. */
.secondary-header-tag { flex: none; padding: 3px 7px; border-radius: 999px; background: var(--color-canvas-muted); color: var(--color-ink-secondary); font-size: 12px; font-weight: 400; line-height: 1.2; white-space: nowrap; }
.sidebar-nav-link:has(.sidebar-nav-tag) { position: relative; }
.sidebar-nav-tag { position: absolute; top: 4px; right: 4px; padding: 2px 5px; border-radius: 999px; background: var(--sidebar-solid, var(--color-canvas)); color: var(--color-ink-secondary); font-size: 10px; line-height: 1.2; white-space: nowrap; pointer-events: none; }
+2
View File
@@ -61,6 +61,7 @@ import type { BeamAvatar } from "@/lib/beam-avatar";
import { groupSessionsByRecency } from "@/lib/session-groups";
import { markNewChatClick } from "@/lib/new-chat-timing";
import { homeWarmStartReady, waitForHomeWarmStart } from "@/lib/home-warm-prefetch";
import { RECTIFICATION_EDITION_TAG } from "@/lib/chart-choice/edition";
import { navigateInApp } from "@/lib/app-navigation";
export type SidebarAccount = {
@@ -418,6 +419,7 @@ export function AppSidebar({
{active ? <SidebarCurrentHighlight /> : null}
<Icon size={18} strokeWidth={1.75} aria-hidden="true" />
{showExpandedContent ? <span>{label}</span> : null}
{href === "/rectification" && showExpandedContent ? <span className="sidebar-nav-tag">{RECTIFICATION_EDITION_TAG}</span> : null}
{href === "/chart" && showChartDot ? <OnboardingDot playKey="sidebar-chart" /> : null}
</SidebarMenuLink>
</SidebarMenuItem>
@@ -1,5 +1,6 @@
"use client";
import { RECTIFICATION_EDITION_TAG } from "@/lib/chart-choice/edition";
import { Fragment, useCallback, useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
@@ -132,7 +133,7 @@ export function ChartChoicePage() {
const subjectId = useCurrentSubject();
const subjectReady = useCurrentSubjectReady();
return (
<SecondaryPageShell title={COPY.title} waiting={subjectReady ? undefined : "正在打开…"}>
<SecondaryPageShell title={COPY.title} titleTag={RECTIFICATION_EDITION_TAG} waiting={subjectReady ? undefined : "正在打开…"}>
<div className="chart-choice-page">
{/* A new person starts a new flow: keyed, so no state carries over. */}
{subjectReady ? <ChartChoiceFlow key={subjectId} subjectId={subjectId} /> : null}
@@ -1351,7 +1352,8 @@ export function HomeView({ history, onStartOver, onRestore, reportedAt, pending,
{decision?.segment ? <>
<p className="chart-choice-fine">范围 {segmentLabel(decision.segment)}</p>
{ownChoice ? <>
<p className="chart-choice-note">按你自己的选择:报告和问答都按这个时间写,开头会说明是你选的。</p>
{/* BUG-2256 (产品负责人 2026-11-23): 原值「按你自己的选择:报告和问答都按这个时间写,开头会说明是你选的。」;
删除,且报告与问答自 BUG-2146/2184 起不再在开头说明. */}
<SelfChoiceBothVersions domains={decision.both_versions_domains} />
</> : null}
<SelectedBand window={current.detail.window} segment={decision.segment} reportedAt={current.detail.reported_at} />
+4 -1
View File
@@ -25,6 +25,8 @@ import { SidebarTrigger } from "@/components/ui/sidebar";
export type SecondaryHeaderProps = {
/** Shown in the header. Pass a falsy value for pages that carry their own. */
readonly title: string;
/** A small grey tag after the title, e.g. 生时纠正「随缘版」 (BUG-2256). */
readonly titleTag?: string;
/** Right-aligned header controls: the one primary action, at most two. */
readonly actions?: ReactNode;
/** A quiet chip beside the title — birth line, report date. */
@@ -47,7 +49,7 @@ export type SecondaryHeaderProps = {
readonly titleYields?: boolean;
};
export function SecondaryHeader({ title, actions, note, besideTitle, reserveNote = false, back, titleYields = false }: SecondaryHeaderProps) {
export function SecondaryHeader({ title, titleTag, actions, note, besideTitle, reserveNote = false, back, titleYields = false }: SecondaryHeaderProps) {
const showNote = Boolean(note) || reserveNote;
return (
<header className={titleYields ? "chat-header has-title is-title-yielding" : "chat-header has-title"}>
@@ -65,6 +67,7 @@ export function SecondaryHeader({ title, actions, note, besideTitle, reserveNote
</>
) : null}
<strong>{title}</strong>
{titleTag ? <span className="secondary-header-tag">{titleTag}</span> : null}
{besideTitle}
{showNote ? (
<span className="chat-header-chart" aria-hidden={note ? undefined : true}>
@@ -8,6 +8,8 @@ import { usePageCurtain } from "@/hooks/use-page-curtain";
export type SecondaryPageShellProps = {
readonly title: string;
/** A small grey tag after the title (BUG-2256). */
readonly titleTag?: string;
readonly note?: ReactNode;
readonly besideTitle?: ReactNode;
readonly actions?: ReactNode;
@@ -33,6 +35,7 @@ export type SecondaryPageShellProps = {
*/
export function SecondaryPageShell({
title,
titleTag,
note,
besideTitle,
actions,
@@ -46,6 +49,7 @@ export function SecondaryPageShell({
<>
<SecondaryHeader
title={title}
titleTag={titleTag}
note={note}
besideTitle={besideTitle ?? <CurrentSubjectSwitcher variant="chip" />}
reserveNote
+5
View File
@@ -0,0 +1,5 @@
/**
* BUG-2256 (产品负责人 2026-11-23): 生时纠正 is shown as an experimental edition, 「随缘版」, beside its title in the
* page header and on its sidebar tile. Its steps are recorded for later checking (lib/chart-choice/step-log.ts).
*/
export const RECTIFICATION_EDITION_TAG = "随缘版";
@@ -0,0 +1,55 @@
import { isChartSubjectId } from "../subject-birth.ts";
/**
* BUG-2256 (产品负责人 2026-11-23,生时纠正「随缘版」): each 生时纠正 request is recorded with what it was
* computed from and how it ended, adopted or not, in `chart_choice_steps`. No algorithm reads it; it is for
* checking the feature later against users whose stated time comes from a certificate or an ID document.
* Recording never changes the response and never fails the request.
*/
const RESULT_LIMIT = 12_000;
export type Rpc = { rpc: (name: string, args: Record<string, unknown>) => PromiseLike<{ error: unknown }> };
export function chartChoiceCodeVersion(): string | null {
return process.env.GITHUB_SHA ?? process.env.VERCEL_GIT_COMMIT_SHA ?? process.env.NEXT_PUBLIC_GIT_COMMIT ?? null;
}
/** What the response said, small enough to keep: its status and code, and the decision when it fits. */
export function chartChoiceStepResult(httpStatus: number, json: unknown): Record<string, unknown> {
const result: Record<string, unknown> = { http: httpStatus };
if (!json || typeof json !== "object" || Array.isArray(json)) return result;
const body = json as Record<string, unknown>;
for (const key of ["status", "code"] as const) if (typeof body[key] === "string") result[key] = body[key];
if (body.decision !== undefined) {
const decision = JSON.stringify(body.decision);
if (decision.length <= RESULT_LIMIT) result.decision = body.decision;
else result.decision_omitted = decision.length;
}
return result;
}
export async function recordChartChoiceStepWith(input: {
userId: string;
subjectId: string | null | undefined;
step: string;
request: unknown;
response: Response;
}, client: Rpc | (() => Rpc)): Promise<void> {
try {
const subject = input.subjectId && isChartSubjectId(input.subjectId) ? input.subjectId : null;
const json = await input.response.clone().json().catch(() => null);
const request = input.request && typeof input.request === "object" && !Array.isArray(input.request) ? input.request : {};
const admin = typeof client === "function" ? client() : client;
await admin.rpc("chart_choice_log_step_v1", {
p_user_id: input.userId,
p_chart_profile_id: subject,
p_step: input.step.slice(0, 40),
p_outcome: input.response.ok ? "ok" : "error",
p_code_version: chartChoiceCodeVersion(),
p_request: request,
p_result: chartChoiceStepResult(input.response.status, json),
});
} catch {
// A record that cannot be written is skipped; the user's step is not affected.
}
}
@@ -0,0 +1,9 @@
import "server-only";
import { createAdminSupabaseClient } from "../supabase/admin.ts";
import { recordChartChoiceStepWith, type Rpc } from "./step-log-core.ts";
/** BUG-2256: the routes' entry; the recording itself is in step-log-core.ts. */
export function recordChartChoiceStep(input: Parameters<typeof recordChartChoiceStepWith>[0]): Promise<void> {
return recordChartChoiceStepWith(input, () => createAdminSupabaseClient() as unknown as Rpc);
}
+4 -1
View File
@@ -152,7 +152,9 @@ const PRIVACY: LegalDocument = {
"· 点数扣除与退回、订单处理与客户服务;",
"· 内容安全检查:对提问与模型回答进行检查,命中规则时拦截或替换,并记录去除身份信息的命中日志以便改进规则;",
"· 排查回答质量问题:由经授权的工作人员查看你点「踩」时保存的那一轮对话,找出答非所问、内容不准等问题的原因并改进服务;每次查看都会记入内部审计日志;",
"· 以去除个人身份信息的汇总统计改进服务(例如生时纠正的问题数量与收敛情况,不含出生资料与对话原文)。",
// BUG-2256 (产品负责人 2026-11-23,生时纠正随缘版): 原值「· 以去除个人身份信息的汇总统计改进服务(例如生时纠正的问题数量与收敛情况,不含出生资料与对话原文)。」
"· 改进生时纠正:你在生时纠正里填写的出生时间及其来源、经历、每一步的回答与选择,会逐步记录下来,在去掉姓名、邮箱与账号编号后,用于检验和改进生时纠正的准确度;这些记录只用于生时纠正,不用于其他解读;",
"· 以去除个人身份信息的汇总统计改进服务(不含出生资料与对话原文)。",
"我们不会用你的出生资料或对话内容做与上述目的无关的用途,也不会出售你的个人信息。",
],
},
@@ -177,6 +179,7 @@ const PRIVACY: LegalDocument = {
"· 注销账号:冷静期 7 天满后,上述数据与账号一并删除;法律法规要求保留的订单与点数流水去除个人身份信息后保存,期限依法确定【待确认:保存年限】;反馈与投诉保留处理记录并删除其中的联系方式【待确认:保存年限】。",
"· 内容安全命中日志:去除身份信息后保存【待确认:保存期限】。",
"· 生时纠正的匿名统计:保存 180 天。",
"· 生时纠正的逐步记录:在账号存续期间保存;删除对应的人物档案或注销账号时一并删除。",
"· 点「踩」时保存的对话记录:保存 90 天,期满后清空对话内容,只保留评价与不满意原因用于统计;你删除该条对话或注销账号时一并删除。",
"· 服务器日志:【待确认:保存期限】。",
],
@@ -0,0 +1,76 @@
-- BUG-2256 (产品负责人 2026-11-23,生时纠正「随缘版」): every step of 生时纠正 is recorded, whether or not
-- the user adopts a result, so the feature can later be checked against users whose time source is a
-- birth certificate or an ID document. chart_choice_records keeps only adopted results; this table keeps
-- each request (the stated time and source as they stood, the answers, the picks) and its outcome.
-- No algorithm reads it. Rows go with the account (auth.users) or the person's profile (chart_profiles).
create table if not exists public.chart_choice_steps (
id uuid primary key default gen_random_uuid(),
user_id uuid not null references auth.users(id) on delete cascade,
chart_profile_id uuid references public.chart_profiles(id) on delete cascade,
created_at timestamptz not null default clock_timestamp(),
step text not null check (char_length(step) between 1 and 40),
outcome text not null check (outcome in ('ok', 'error')),
code_version text check (code_version is null or char_length(code_version) <= 64),
declaration jsonb check (declaration is null or jsonb_typeof(declaration) = 'object'),
time_source text check (time_source is null or char_length(time_source) <= 40),
request jsonb not null check (jsonb_typeof(request) = 'object' and pg_catalog.octet_length(request::text) <= 65536),
result jsonb check (result is null or (jsonb_typeof(result) = 'object' and pg_catalog.octet_length(result::text) <= 16384))
);
create index if not exists chart_choice_steps_subject_idx
on public.chart_choice_steps (user_id, chart_profile_id, created_at);
alter table public.chart_choice_steps enable row level security;
revoke all on table public.chart_choice_steps from public, anon, authenticated, service_role;
do $$
begin
if exists (select 1 from pg_roles where rolname = 'app_runtime') then
revoke all on table public.chart_choice_steps from app_runtime;
end if;
if exists (select 1 from pg_roles where rolname = 'admin_runtime') then
revoke all on table public.chart_choice_steps from admin_runtime;
end if;
end;
$$;
-- One step. The stated birth facts and the time source are read here, as they stand at that moment,
-- so a later edit of the profile does not rewrite what the step was computed from.
create or replace function public.chart_choice_log_step_v1(
p_user_id uuid,
p_chart_profile_id uuid,
p_step text,
p_outcome text,
p_code_version text,
p_request jsonb,
p_result jsonb
)
returns void
language plpgsql
security definer
set search_path = ''
as $$
declare
v_declaration jsonb := public.chart_choice_declaration(p_user_id, p_chart_profile_id);
v_source text;
begin
if v_declaration is null then
return;
end if;
if p_chart_profile_id is null then
select p.birth_time_source into v_source from public.profiles p where p.id = p_user_id;
else
select c.birth_time_source into v_source from public.chart_profiles c
where c.id = p_chart_profile_id and c.user_id = p_user_id and c.role = 'other';
end if;
insert into public.chart_choice_steps
(user_id, chart_profile_id, step, outcome, code_version, declaration, time_source, request, result)
values
(p_user_id, p_chart_profile_id, p_step, p_outcome, left(p_code_version, 64), v_declaration, left(v_source, 40),
coalesce(p_request, '{}'::jsonb), p_result);
end;
$$;
revoke all on function public.chart_choice_log_step_v1(uuid, uuid, text, text, text, jsonb, jsonb) from public, anon, authenticated;
grant execute on function public.chart_choice_log_step_v1(uuid, uuid, text, text, text, jsonb, jsonb) to service_role;
@@ -398,6 +398,9 @@ test("local PostgreSQL applies the reviewed business schema and serves authentic
// 新值(2): 加入 chart_choice_records
// 原因(2): BUG-1654 生时纠正历史记录表(20261106030000_chart_choice_records.sql)
"chart_choice_records",
// 新值(3): 加入 chart_choice_steps
// 原因(3): BUG-2256 生时纠正随缘版逐步记录(20261123090000_chart_choice_steps.sql)
"chart_choice_steps",
"chart_profiles",
"chat_sessions",
// 新值: 加入 consult_preset_libraries
@@ -0,0 +1,53 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { RECTIFICATION_EDITION_TAG } from "../src/lib/chart-choice/edition.ts";
import { PRIVACY } from "../src/lib/legal-documents.ts";
// BUG-2256(产品负责人 2026-11-23):生时纠正标「随缘版」,每一步都记录下来(采用与否),供以后检验。
const read = (path: string) => readFileSync(new URL(path, import.meta.url), "utf8");
test("生时纠正 says 随缘版 beside its title and on its sidebar tile", () => {
assert.equal(RECTIFICATION_EDITION_TAG, "随缘版");
assert.match(read("../src/components/chart-choice/chart-choice-page.tsx"), /<SecondaryPageShell title=\{COPY\.title\} titleTag=\{RECTIFICATION_EDITION_TAG\}/);
assert.match(read("../src/components/secondary-header.tsx"), /\{titleTag \? <span className="secondary-header-tag">\{titleTag\}<\/span> : null\}/);
assert.match(read("../src/components/app-sidebar.tsx"), /href === "\/rectification" && showExpandedContent \? <span className="sidebar-nav-tag">\{RECTIFICATION_EDITION_TAG\}<\/span>/);
const css = read("../src/app/globals.css");
assert.match(css, /\.secondary-header-tag \{/);
assert.match(css, /\.sidebar-nav-tag \{/);
});
test("the home no longer says the report opens by naming your own choice", () => {
const page = read("../src/components/chart-choice/chart-choice-page.tsx");
assert.doesNotMatch(page, /<p className="chart-choice-note">按你自己的选择/);
});
test("every 生时纠正 POST records its step, whatever the outcome", () => {
for (const route of ["packet", "adopt", "supplement", "reuse", "astrologer"]) {
const source = read(`../src/app/api/chart-choice/${route}/route.ts`);
assert.match(source, /import \{ recordChartChoiceStep \} from "@\/lib\/chart-choice\/step-log";/, route);
assert.match(source, /const response = await \(async \(\) => \{/, route);
assert.match(source, /await recordChartChoiceStep\(\{ userId: caller\.userId, subjectId: parsed\.data\.subjectId, step: [^,]+, request: parsed\.data, response \}\);\n return response;/, route);
}
});
test("the step table goes with the account and the profile, and only the server writes it", () => {
const sql = read("../supabase/migrations/20261123090000_chart_choice_steps.sql");
assert.match(sql, /user_id uuid not null references auth\.users\(id\) on delete cascade/);
assert.match(sql, /chart_profile_id uuid references public\.chart_profiles\(id\) on delete cascade/);
assert.match(sql, /enable row level security/);
assert.match(sql, /revoke all on table public\.chart_choice_steps from public, anon, authenticated, service_role;/);
assert.match(sql, /grant execute on function public\.chart_choice_log_step_v1\(uuid, uuid, text, text, text, jsonb, jsonb\) to service_role;/);
// The stated facts and the time source are read as they stand when the step runs.
assert.match(sql, /v_declaration jsonb := public\.chart_choice_declaration\(p_user_id, p_chart_profile_id\);/);
assert.match(sql, /birth_time_source into v_source/);
});
test("the privacy policy says what is recorded and for what", () => {
const text = PRIVACY.sections.flatMap((section) => section.paragraphs).join("\n");
assert.match(text, /改进生时纠正:你在生时纠正里填写的出生时间及其来源、经历、每一步的回答与选择,会逐步记录下来/);
assert.match(text, /生时纠正的逐步记录:在账号存续期间保存;删除对应的人物档案或注销账号时一并删除。/);
assert.doesNotMatch(text, /生时纠正的问题数量与收敛情况,不含出生资料/);
});
+35
View File
@@ -0,0 +1,35 @@
import assert from "node:assert/strict";
import test from "node:test";
import { chartChoiceStepResult, recordChartChoiceStepWith as recordChartChoiceStep } from "../src/lib/chart-choice/step-log-core.ts";
// BUG-2256:记录只留状态、代码和放得下的 decision;写不进去时不影响用户这一步。
test("the kept result is the status, the code and the decision when it fits", () => {
assert.deepEqual(chartChoiceStepResult(200, { status: "choose", decision: { segment: "a" }, packet: { big: true } }),
{ http: 200, status: "choose", decision: { segment: "a" } });
assert.deepEqual(chartChoiceStepResult(400, { error: "请求格式不对", code: "bad_request" }), { http: 400, code: "bad_request" });
const big = chartChoiceStepResult(200, { decision: { text: "x".repeat(20_000) } });
assert.equal(big.decision, undefined);
assert.ok(Number(big.decision_omitted) > 12_000);
assert.deepEqual(chartChoiceStepResult(500, null), { http: 500 });
});
test("one step is one call with the subject, the request and the outcome", async () => {
const calls: { name: string; args: Record<string, unknown> }[] = [];
const client = { rpc: async (name: string, args: Record<string, unknown>) => { calls.push({ name, args }); return { error: null }; } };
const response = new Response(JSON.stringify({ decision: { saved_at: "04:58" } }), { status: 200 });
await recordChartChoiceStep({ userId: "u1", subjectId: "self", step: "adopt:choice", request: { window: { a: 1 } }, response }, client);
assert.equal(calls.length, 1);
assert.equal(calls[0]!.name, "chart_choice_log_step_v1");
assert.equal(calls[0]!.args.p_chart_profile_id, null, "self is the account's own profile");
assert.equal(calls[0]!.args.p_outcome, "ok");
assert.deepEqual(calls[0]!.args.p_request, { window: { a: 1 } });
assert.deepEqual(calls[0]!.args.p_result, { http: 200, decision: { saved_at: "04:58" } });
assert.deepEqual(await response.json(), { decision: { saved_at: "04:58" } }, "the response body is still readable");
});
test("a failed write never reaches the user", async () => {
const client = { rpc: async () => { throw new Error("database down"); } };
await recordChartChoiceStep({ userId: "u1", subjectId: "c9a3f0f2-1111-4222-8333-944455556666", step: "packet", request: {}, response: new Response("{}", { status: 500 }) }, client);
});