feat: M3 — 伏笔账本 + 节奏引擎 + 大纲(含并发记账 bugfix)

- 伏笔账本:纯函数状态机(OPEN/PARTIAL/CLOSED/OVERDUE) + ForeshadowLedger repo;验收后到期扫描(BackgroundTask 自建 session 置 OVERDUE);登记/状态变更端点
- 节奏 + 三审齐:foreshadow-analyst + pace-checker 并入 LangGraph 并行审(REVIEW_SPECS),collect 分列落 chapter_reviews(conflicts/foreshadow_sug/pace),review SSE 加 foreshadow/pace 事件
- 大纲:outliner Agent 产 OutlineResult(含 foreshadow_windows),POST /outline 逐章 upsert outline 表;GET /foreshadow?status= 看板
- 前端:伏笔四泳道看板(OVERDUE 琥珀) + 大纲编辑器(窗口徽标) + 节奏节拍图(▁▃▅) + 审稿页消费 foreshadow/pace SSE
- bugfix(T3.8):并行三审共用请求 session 记账触发 'Session is already flushing' → foreshadow/pace 静默丢失;SqlAlchemyLedgerSink.record 改 add-only(靠端点/事务 commit),加并发回归测试
- M3 E2E:真实 DB + mock 网关零 token 走通 埋设→进展→验收后扫描 OVERDUE→看板 + 大纲含窗口 + 三审齐 SSE/留痕;E2E 暴露并钉住上述 bug
- 门禁绿:mypy 111 / pytest 228(0 xfailed) / alembic 无漂移;前端 gen:api/lint/tsc/vitest 69/build
This commit is contained in:
Yaojia Wang
2026-06-18 14:21:17 +02:00
parent 68f194a043
commit 5fb7bfb1de
74 changed files with 6529 additions and 126 deletions

View File

@@ -0,0 +1,134 @@
import { describe, expect, it } from "vitest";
import type { ForeshadowView } from "@/lib/api/types";
import {
buildRegisterRequest,
buildTransitionRequest,
extractReason,
groupByStatus,
isWindowApproaching,
validationReasonMessage,
} from "./board";
const view = (over: Partial<ForeshadowView>): ForeshadowView => ({
code: "F-001",
title: "线索",
status: "OPEN",
...over,
});
describe("groupByStatus", () => {
it("splits items into four lanes preserving order", () => {
const lanes = groupByStatus([
view({ code: "F-001", status: "OPEN" }),
view({ code: "F-002", status: "OVERDUE" }),
view({ code: "F-003", status: "OPEN" }),
view({ code: "F-004", status: "CLOSED" }),
view({ code: "F-005", status: "PARTIAL" }),
]);
expect(lanes.OPEN.map((v) => v.code)).toEqual(["F-001", "F-003"]);
expect(lanes.OVERDUE.map((v) => v.code)).toEqual(["F-002"]);
expect(lanes.CLOSED.map((v) => v.code)).toEqual(["F-004"]);
expect(lanes.PARTIAL.map((v) => v.code)).toEqual(["F-005"]);
});
it("falls back unknown status to OPEN and handles undefined", () => {
const lanes = groupByStatus([view({ status: "WEIRD" })]);
expect(lanes.OPEN).toHaveLength(1);
expect(groupByStatus(undefined).OPEN).toEqual([]);
});
});
describe("isWindowApproaching", () => {
it("is true when current chapter is inside [from,to] for OPEN/PARTIAL", () => {
const f = view({
status: "PARTIAL",
expected_close_from: 40,
expected_close_to: 60,
});
expect(isWindowApproaching(f, 50)).toBe(true);
expect(isWindowApproaching(f, 39)).toBe(false);
expect(isWindowApproaching(f, 61)).toBe(false);
});
it("never flags CLOSED/OVERDUE or items without a window", () => {
expect(
isWindowApproaching(
view({ status: "CLOSED", expected_close_to: 60 }),
50,
),
).toBe(false);
expect(isWindowApproaching(view({ status: "OPEN" }), 50)).toBe(false);
});
});
describe("buildRegisterRequest", () => {
it("trims and omits empty optionals", () => {
expect(
buildRegisterRequest({
projectId: "p1",
code: " F-007 ",
title: " 旧誓约 ",
content: " ",
expectedCloseTo: 110,
}),
).toEqual({ code: "F-007", title: "旧誓约", expected_close_to: 110 });
});
it("keeps numeric and non-empty string optionals", () => {
expect(
buildRegisterRequest({
projectId: "p1",
code: "F-1",
title: "t",
plantedAt: 8,
content: "线索",
expectedCloseFrom: 40,
importance: "主线",
}),
).toEqual({
code: "F-1",
title: "t",
planted_at: 8,
content: "线索",
expected_close_from: 40,
importance: "主线",
});
});
});
describe("buildTransitionRequest", () => {
it("includes only provided fields", () => {
expect(buildTransitionRequest({ projectId: "p1", toStatus: "PARTIAL" })).toEqual({
to_status: "PARTIAL",
});
expect(
buildTransitionRequest({
projectId: "p1",
progressEntry: { chapter: 23, note: "发光" },
}),
).toEqual({ progress_entry: { chapter: 23, note: "发光" } });
expect(buildTransitionRequest({ projectId: "p1" })).toEqual({});
expect(
buildTransitionRequest({ projectId: "p1", progressEntry: {} }),
).toEqual({});
});
});
describe("validationReasonMessage / extractReason", () => {
it("maps known reasons to friendly text", () => {
expect(validationReasonMessage("duplicate")).toContain("已存在");
expect(validationReasonMessage("invalid_transition")).toContain("终态");
expect(validationReasonMessage("empty_update")).toContain("进展");
expect(validationReasonMessage("invalid_status")).toContain("筛选");
expect(validationReasonMessage(undefined)).toContain("校验");
});
it("extracts details.reason from envelope", () => {
expect(
extractReason({ error: { details: { reason: "duplicate" } } }),
).toBe("duplicate");
expect(extractReason({ error: { details: null } })).toBeUndefined();
expect(extractReason("oops")).toBeUndefined();
});
});

View File

@@ -0,0 +1,141 @@
// 伏笔看板纯逻辑:四泳道分组、登记/转移请求体组装、422 reason 映射。
// 对齐 C3 扩GET/POST/PATCH .../foreshadow。纯逻辑便于 node 环境单测。
import type {
ForeshadowRegisterRequest,
ForeshadowTransitionRequest,
ForeshadowView,
} from "@/lib/api/types";
// 四状态泳道UX §6.8OVERDUE 用琥珀强调(渲染层处理)。
export type ForeshadowStatus = "OPEN" | "PARTIAL" | "CLOSED" | "OVERDUE";
export const LANES: readonly ForeshadowStatus[] = [
"OPEN",
"PARTIAL",
"CLOSED",
"OVERDUE",
] as const;
export const LANE_LABELS: Record<ForeshadowStatus, string> = {
OPEN: "OPEN",
PARTIAL: "PARTIAL",
CLOSED: "CLOSED",
OVERDUE: "OVERDUE",
};
export type ForeshadowLanes = Record<ForeshadowStatus, ForeshadowView[]>;
function emptyLanes(): ForeshadowLanes {
return { OPEN: [], PARTIAL: [], CLOSED: [], OVERDUE: [] };
}
function isStatus(v: string): v is ForeshadowStatus {
return v === "OPEN" || v === "PARTIAL" || v === "CLOSED" || v === "OVERDUE";
}
// 按 status 分四泳道(未知 status 落 OPEN 兜底);保持 repo 已排序的 code 顺序。
export function groupByStatus(
items: readonly ForeshadowView[] | undefined,
): ForeshadowLanes {
const lanes = emptyLanes();
for (const item of items ?? []) {
const status = isStatus(item.status) ? item.status : "OPEN";
lanes[status] = [...lanes[status], item];
}
return lanes;
}
// 接近回收窗口判定current 在 [from, to] 内,或已超 from 但尚未 CLOSED提示安排回收
// 仅对 OPEN/PARTIAL 提示CLOSED 已回收、OVERDUE 已逾期另有强调。
export function isWindowApproaching(
item: ForeshadowView,
currentChapter: number,
): boolean {
if (item.status === "CLOSED" || item.status === "OVERDUE") return false;
const to = item.expected_close_to;
if (typeof to !== "number") return false;
const from = item.expected_close_from ?? to;
return currentChapter >= from && currentChapter <= to;
}
export interface RegisterInput {
projectId: string;
code: string;
title: string;
plantedAt?: number | null;
content?: string | null;
expectedCloseFrom?: number | null;
expectedCloseTo?: number | null;
importance?: string | null;
}
// 组装登记请求体(去空白;空可选字段省略)。
export function buildRegisterRequest(
input: RegisterInput,
): ForeshadowRegisterRequest {
const body: ForeshadowRegisterRequest = {
code: input.code.trim(),
title: input.title.trim(),
};
if (typeof input.plantedAt === "number") body.planted_at = input.plantedAt;
const content = input.content?.trim();
if (content) body.content = content;
if (typeof input.expectedCloseFrom === "number")
body.expected_close_from = input.expectedCloseFrom;
if (typeof input.expectedCloseTo === "number")
body.expected_close_to = input.expectedCloseTo;
const importance = input.importance?.trim();
if (importance) body.importance = importance;
return body;
}
export interface TransitionInput {
projectId: string;
toStatus?: ForeshadowStatus | null;
// 一条进展记录(自由 dict如 {chapter, note})。
progressEntry?: Record<string, unknown> | null;
}
// 组装转移/进展请求体(两字段皆可选;至少给一项由调用方校验)。
export function buildTransitionRequest(
input: TransitionInput,
): ForeshadowTransitionRequest {
const body: ForeshadowTransitionRequest = {};
if (input.toStatus) body.to_status = input.toStatus;
if (input.progressEntry && Object.keys(input.progressEntry).length > 0)
body.progress_entry = input.progressEntry;
return body;
}
// 422 VALIDATION 信封 details.reasonC3 扩)→ 用户文案。
export type ValidationReason =
| "duplicate"
| "invalid_transition"
| "empty_update"
| "invalid_status";
export function validationReasonMessage(reason: string | undefined): string {
switch (reason) {
case "duplicate":
return "该伏笔代号已存在,请换一个。";
case "invalid_transition":
return "非法状态转移CLOSED 为终态,不可再改)。";
case "empty_update":
return "请填写目标状态或一条进展。";
case "invalid_status":
return "无效的筛选状态。";
default:
return "操作未通过校验,请检查输入。";
}
}
// 从错误信封安全提取 details.reason。
export function extractReason(error: unknown): string | undefined {
if (typeof error !== "object" || error === null) return undefined;
const env = error as {
error?: { details?: { reason?: unknown } | null };
};
const reason = env.error?.details?.reason;
return typeof reason === "string" ? reason : undefined;
}

View File

@@ -0,0 +1,96 @@
"use client";
import { useCallback, useState } from "react";
import { api } from "@/lib/api/client";
import { useToast } from "@/components/Toast";
import type { ForeshadowView } from "@/lib/api/types";
import {
buildRegisterRequest,
buildTransitionRequest,
extractReason,
validationReasonMessage,
type ForeshadowStatus,
type RegisterInput,
type TransitionInput,
} from "./board";
export interface UseForeshadow {
items: ForeshadowView[];
busy: boolean;
register: (input: RegisterInput) => Promise<boolean>;
transition: (code: string, input: TransitionInput) => Promise<boolean>;
}
// 伏笔登记/状态变更(乐观更新 + 回滚 + Toast
// register成功后把返回行追加进 items422 duplicate → 友好提示,不改 items。
// transition先乐观替换该行 status失败回滚到旧 items 并 toast读 details.reason
export function useForeshadow(initial: ForeshadowView[]): UseForeshadow {
const [items, setItems] = useState<ForeshadowView[]>(initial);
const [busy, setBusy] = useState(false);
const toast = useToast();
const register = useCallback<UseForeshadow["register"]>(
async (input) => {
setBusy(true);
try {
const { data, error } = await api.POST(
"/projects/{project_id}/foreshadow",
{
params: { path: { project_id: input.projectId } },
body: buildRegisterRequest(input),
},
);
if (error || !data) {
toast(validationReasonMessage(extractReason(error)), "error");
return false;
}
setItems((prev) => [...prev, data]);
toast(`已登记伏笔 ${data.code}`, "success");
return true;
} finally {
setBusy(false);
}
},
[toast],
);
const transition = useCallback<UseForeshadow["transition"]>(
async (code, input) => {
const snapshot = items;
// 乐观:本地先改 status若给了 toStatus
if (input.toStatus) {
const next = input.toStatus as ForeshadowStatus;
setItems((prev) =>
prev.map((it) => (it.code === code ? { ...it, status: next } : it)),
);
}
setBusy(true);
try {
const { data, error } = await api.PATCH(
"/projects/{project_id}/foreshadow/{code}",
{
params: {
path: { project_id: input.projectId, code },
},
body: buildTransitionRequest(input),
},
);
if (error || !data) {
setItems(snapshot); // 回滚
toast(validationReasonMessage(extractReason(error)), "error");
return false;
}
// 用服务端权威行替换status + progress 都对齐)。
setItems((prev) => prev.map((it) => (it.code === code ? data : it)));
toast(`已更新 ${data.code}`, "success");
return true;
} finally {
setBusy(false);
}
},
[items, toast],
);
return { items, busy, register, transition };
}