fix(report): synastry and annual reports salvage named sentences instead of failing whole; annual start keeps a busy refusal in the card; English failure reason in the report read (BUG-2183, BUG-2184, BUG-2185)

Synastry: sections that passed the first check get their draft back when the
rewrite breaks them, then only the sentences/reasons the gate named are removed
(same patterns as the Python gate); structural failures still reject.
Annual: text-rule failures left after the rewrite become month-level dates or a
removed sentence; 409 (another report still writing) stays in the start card;
a time chosen in rectification gets no opening sentence (BUG-2146 rule).
English: the stored englishUnavailable reason is returned (not rendered).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
This commit is contained in:
2026-11-22 18:47:56 +08:00
co-authored by Claude Opus 5.5
parent 5fb7d8fa2b
commit d0328b083a
12 changed files with 332 additions and 13 deletions
+41
View File
@@ -29589,3 +29589,44 @@
- 验证:公开名人盘、deepseek-flash 抽测 4 条「接下来两年我的事业会怎样?用一两句话说」:只加一句「按用户说的长度」时正文 281 / 363 字,仍带 2–3 条「能做的几件事」;写明「不写「能做的几件事」、不分段」后正文 217 / 126 字,没有清单,「判断依据」照常。VISIBLE VOICE 长度上限 4420 → 4500,三个测试按原值/新值/原因更新。报告内提问的三处说明没有单独抽测。
- 关联记录:BUG-2140、BUG-2149。
- 修复版本:`claude/acceptance-fixes-a`。
## BUG-2183 | 合盘报告改写一次后仍有一节没过核对,整份失败(report_guard_rejected),没有逐节兜底
- 状态:fixed-pending-verify。
- 首次发现 / 最近更新:2026-11-22 / 2026-11-22。
- 现象:负责人验收 T-04:乔布斯 × 奥巴马合盘约 6 分钟后显示「本次生成没有产出可用报告」,失败码 `report_guard_rejected`,退回 100 点。生成期间测试员恢复过填报时间。
- 触发条件:任意一节在一次改写和程序修依据之后仍有硬性核对失败(断语词、分数、带年份的事件、私有术语、未解释缩写、分析式开头等)。
- 根因:`frontend/src/lib/synastry-full-generate.ts` 在改写、程序修依据之后,只要还剩一条非可读性失败就 `throw new SynastryGateRejected`,整份不出;没有像个人报告那样逐节挽救。核对失败行写在 `personal_report_sections` 的 `gate-*` 行里,用户读取和后台写作记录都看不到(后台写作记录只收个人报告),所以这次具体是哪一节、哪个码,客户端取不到;生成期间改出生资料只在开头核对一次(`assertSynastryBirthInputs`),不会造成核对失败。
- 修复:新增 `frontend/src/lib/synastry-salvage.ts`,在拒稿前多两步:(1) 第一次核对时已经通过、改写后反而不过的节,换回第一次的稿;(2) 仍不过的节只删核对点名的句子或理由——带原词的失败(private_term、supplementary_method、unexplained_term、banned_judgement、analytic_opening)删含该词的句子和理由,分数和带年份事件用与 Python 核对相同的正则找句子;每段最多删一半,理由至少留一条;删完再核对一次,并在日志记下剩余失败码。结构性失败(缺节、太短、形状不对)不处理,仍然拒稿。
- 验证:`frontend/tests/acceptance-salvage-2183.test.ts`(7 项全过,含合盘 3 项与调用顺序)。真实生成待 staging 复测。
- 防复发:同上测试;剩余失败码写进 `[synastry-report] salvage codes=` 日志。
- 尚未处理:合盘 `gate-*` 失败行仍不在后台写作记录里,诊断要读数据库;结构性失败仍会整份失败。
- 关联记录:BUG-1908、BUG-1910、BUG-1913、BUG-2008、BUG-2117(个人报告挽救)。
- 修复版本:`claude/acceptance-fixes-b`。
## BUG-2184 | 年运一节改写后仍写了具体日期或断语词,整份在第 8/10 节卡住后失败;本人档案点「开始写年运」回到表单
- 状态:fixed-pending-verify。
- 首次发现 / 最近更新:2026-11-22 / 2026-11-22。
- 现象:负责人验收 T-05:(1) 档案 B 的年运逐节写到 8/10「这一年怎么走」后 7 分钟以上没有进展,之后报告状态为 `failed / report_guard_rejected`;(2) 在生时纠正里保存过自选时间的本人档案,点「开始写年运」显示「正在开始…」后回到原表单,没有入队。
- 触发条件:(1) 任意一节改写后仍命中 `certainty_word / forbidden_topic / explicit_date / asserted_past / repeated_heading`;(2) 本人档案的出生时间来源是生时纠正里的自选情景。
- 根因:(1) `frontend/src/lib/annual-report-generate.ts` 逐节写,改写一次后仍有硬性失败就 `throw new AnnualGateError`,整份失败;这些都是文字规则,程序本可以自己改。(2) 同一时间段账户里还有个人报告、合盘在写(验收时 16:12–16:22 先后有两份),`POST /api/reports` 返回 409,`startErrorFor` 只给一闪而过的浮出提示「已经有一份报告正在写…」,看起来像点了没反应(生时纠正窗口同时查到个人报告一侧同样的 409,见其修复)。(3) 开始卡片在生时纠正里选过情景时写「出生时间按你在生时纠正里选的情况来算。」,改回填报时间后仍显示;按 BUG-2146 的规则自选时间不该有开头说明。
- 修复:`frontend/src/lib/annual-report-sections.ts` 新增 `salvageAnnualTexts`:具体日期改成月份级(「3 月 14 日」→「3 月中」,「2027-03-14」→「2027 年 3 月」),删除含断语词、禁写话题、断言读者过去的句子,去掉重复成标签的标题;每个字段至少保留一半,否则保持原样。`annual-report-generate.ts` 在抛出 `AnnualGateError` 之前对命中这些码的节做一次挽救并重新核对,日志记下剩余失败码。形状和编号不符仍会失败。`components/annual/annual-report-page.tsx`:409 留在开始卡片里(和点数不够一样是持续状态);选过情景时开始卡片不再写开头说明(`birthNotice` 返回 null)。
- 验证:`frontend/tests/acceptance-salvage-2183.test.ts` 的年运 2 项通过;`annual-report.test.tsx`(改写后仍写日期的节现在完成、日期为「2027 年 3 月上旬」)、`annual-user-layer-2037.test.tsx`、`results-as-toasts-2056.test.ts` 按原值/新值/原因更新后通过。
- 防复发:同上测试;`[annual-report] salvage section=… left=…` 日志。
- 尚未处理:`annualBirthTime` 的「chosen」判断依赖共享的 `resolveReportBirthClock`,改回填报时间后是否仍算 chosen 由生时纠正窗口一侧确认;年运逐节串行写作本身较慢。
- 关联记录:BUG-1911、BUG-1640、BUG-2037、验收 T-03。
- 修复版本:`claude/acceptance-fixes-b`。
## BUG-2185 | 个人报告英文版没生成成功,读取接口只说 unavailable,看不到原因
- 状态:investigating。
- 首次发现 / 最近更新:2026-11-22 / 2026-11-22。
- 现象:负责人验收 T-11:档案 B 的个人报告导出只能选中文,提示「这份报告的英文版没有生成成功,只能导出中文版。」。
- 触发条件:生成时英文版被判不合格(引擎 `english_unavailable`,或前端 `han_leak / public_leak / fact_tables_invalid / fact_tables_han`)。
- 根因:未定。用同一份公开出生资料、同一版本引擎(`1b2af85ba`)在本机按报告的请求重算,英文版通过全部检查(无汉字、无公开泄漏、资料表无汉字)。失败原因码存在快照的 `englishUnavailable` 里,但读取接口只返回 `unavailable`,无法诊断。英文版目前也没有单独重试的入口(只有合盘有)。
- 修复:读取接口在英文版不可用时多返回 `englishUnavailableReason`(只返回原因码,页面不显示),上线后据此定位。
- 验证:`frontend/tests/acceptance-salvage-2183.test.ts` 的读取接口 1 项。
- 尚未处理:拿到原因码后修具体泄漏;个人报告英文版单独重试入口。
- 关联记录:BUG-2109、BUG-2115。
- 修复版本:`claude/acceptance-fixes-b`。
@@ -120,7 +120,7 @@ async function resolvePersistenceForUser() {
if (snapshot.version === 1) return { status: "legacy" };
return snapshot.english
? { status: "ready", markdown: snapshot.english.markdown, factTables: snapshot.english.factTables }
: { status: "unavailable" };
: { status: "unavailable", ...(snapshot.englishUnavailable ? { reason: snapshot.englishUnavailable } : {}) };
};
/**
* BUG-2175: the version of the stored text a chapter is cut from, read without the text: the
@@ -291,7 +291,9 @@ function AnnualTimeline({ snapshot, failed }: Readonly<{ snapshot: AnnualSnapsho
export function birthNotice(subject: AnnualOverview["subject"]): { text: string } | null {
const who = subject.isSelf ? "你" : subject.name;
// BUG-2037: a range chosen in 生时纠正 is not "the error you filled in", and it is not the 30-minute trial.
if (subject.birthTime.range === "chosen") return { text: `出生时间按${who}在生时纠正里选的情况来算。` };
// BUG-2184 (产品负责人 2026-11-22,BUG-2146 同一规则): a time chosen in 生时纠正 counts as rectified and
// gets no opening sentence. 原值:「出生时间按你在生时纠正里选的情况来算。」;改回填报时间后仍显示(验收 T-05)。
if (subject.birthTime.range === "chosen") return null;
const range = birthRangeText(subject.birthTime);
if (range === null) return { text: `${who}没有填出生时间的误差范围,按前后各 30 分钟试算。这只是试算,不能确认稳定。` };
if (range === "准确到分钟") return null;
@@ -1081,7 +1083,9 @@ export function AnnualReportPage({ initialReportId = null }: Readonly<{ initialR
// BUG-2056: a failed start is a toast. Only "not enough credits" stays in the card,
// because it is a standing state with its own way out (去补点数).
const failure = startErrorFor(response.status, json);
if (failure.billing) setStartError(failure);
// BUG-2184: another report still being written (409) is a standing state, not a passing result —
// it stays in the card (验收 T-05: the toast went by and the page looked like it just went back).
if (failure.billing || response.status === 409) setStartError(failure);
else notifyError(failure.message);
} catch {
notifyError("网络不太稳,再点一次试试。");
@@ -32,6 +32,8 @@ import {
repairAnnualInternalWording,
remainingRows,
SOFT_GATE_CODES,
ANNUAL_SALVAGEABLE,
salvageAnnualTexts,
sectionEvidence,
systemPrompt,
userPrompt,
@@ -1115,6 +1117,13 @@ export async function writeAnnualReport(input: Readonly<{
// BUG-1640: wording slips (a 顺/紧 verdict, a dasha word, talk about the material)
// no longer stop the whole report after the one rewrite; hard rules still do.
const repairable = ["grade_above_cap", "d_without_reason", "incorrect_variation"];
// BUG-2184: text-rule failures left after the rewrite are fixed by the program (dates to month,
// the offending sentence removed) instead of stopping the whole report; the section is gated again.
if (failures.some((code) => (ANNUAL_SALVAGEABLE as readonly string[]).some((prefix) => code.startsWith(`${prefix}:`)))) {
body = salvageAnnualTexts(entry, body);
failures = gateSection(entry, body, allowedWindowIds);
console.info(`[annual-report] salvage section=${entry.id} left=${[...new Set(failures.map((code) => code.split(":")[0]))].join(",") || "none"}`);
}
if (failures.some((code) => ![...SOFT_GATE_CODES, ...repairable].some((soft) => code.startsWith(`${soft}:`)))) {
throw new AnnualGateError(entry.id, failures);
}
@@ -1192,6 +1192,69 @@ export function annualReaderLayer(entry: AnnualPlanEntry, value: unknown): unkno
}
/** Program-side reader gate. Returns failure codes; an empty list passes. */
/**
* BUG-2184: the last pass before a section stops the whole annual report (acceptance T-05: a report
* stopped at 8/10 and then failed with report_guard_rejected). It touches only the text rules:
* exact dates become month-level (「3 月 14 日」→「3 月中」, 「2027-03-14」→「2027 年 3 月」); a sentence with a
* certainty word, a forbidden topic or a claim about the reader's past is removed; a heading repeated as
* a label is stripped. A text field keeps at least half its length, or it is left as it was.
* Shape and id mismatches are not touched here and still stop the report.
*/
export const ANNUAL_SALVAGEABLE = ["certainty_word", "forbidden_topic", "explicit_date", "asserted_past", "repeated_heading"] as const;
function monthLevel(text: string): string {
return text
.replace(/(\d{4})\s*[-/]\s*(\d{1,2})\s*[-/]\s*(\d{1,2})/g, (_m, y: string, mo: string) => `${y} 年 ${Number(mo)} 月`)
.replace(/(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*[日号]/g, (_m, y: string, mo: string, d: string) => `${y} 年 ${Number(mo)} 月${Number(d) <= 10 ? "上旬" : Number(d) <= 20 ? "中" : "下旬"}`)
.replace(/(\d{1,2})\s*月\s*(\d{1,2})\s*[日号]/g, (_m, mo: string, d: string) => `${Number(mo)} 月${Number(d) <= 10 ? "上旬" : Number(d) <= 20 ? "中" : "下旬"}`);
}
function salvageText(text: string, title: string): string {
let out = monthLevel(text);
const heading = new RegExp(`^\\s*${title.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*[::]\\s*`);
out = out.replace(heading, "");
const parts = out.match(/[^。!?!?;;\n]+[。!?!?;;]?\n?|\n/g) ?? [out];
const kept = parts.filter((part) => !CERTAINTY.test(part) && !FORBIDDEN_TOPICS.test(part) && !ALREADY.test(part));
const joined = kept.join("").trim();
return joined && joined.length >= text.trim().length * 0.5 ? joined : text;
}
export function salvageAnnualTexts(entry: AnnualPlanEntry, body: unknown): unknown {
const value = body && typeof body === "object" && !Array.isArray(body) ? { ...(body as Row) } : null;
if (!value) return body;
const fix = (text: unknown) => typeof text === "string" ? salvageText(text, entry.title) : text;
const fixFields = (item: unknown, fields: readonly string[]) => {
const row = item && typeof item === "object" && !Array.isArray(item) ? { ...(item as Row) } : item;
if (row && typeof row === "object") for (const field of fields) (row as Row)[field] = fix((row as Row)[field]);
return row;
};
switch (entry.kind) {
case "person":
case "overview":
value.paragraphs = rows(value.paragraphs).map((item) => fixFields(item, ["evidence", "text"]));
break;
case "area":
for (const key of ["evidence", "text", "timing", "remember"]) value[key] = fix(value[key]);
break;
case "domain":
value.base = fix(value.base);
value.segments = rows(value.segments).map((item) => fixFields(item, ["text"]));
break;
case "windows":
value.items = rows(value.items).map((item) => fixFields(item, ["theme", "action", "evidence", "support", "divergence", "conditions"]));
break;
case "remaining":
value.rows = rows(value.rows).map((item) => fixFields(item, ["matter", "arrange", "evidence"]));
break;
case "close":
value.line = fix(value.line);
break;
default:
return body;
}
return value;
}
export function gateSection(entry: AnnualPlanEntry, body: unknown, allowedWindowIds: readonly string[]): string[] {
const parsed = annualSectionSchemas[entry.kind].safeParse(body);
if (!parsed.success) return ["shape_invalid"];
@@ -745,7 +745,7 @@ export type ReportReadCoreDeps = Readonly<{
export type EnglishEditionRead =
| Readonly<{ status: "ready"; markdown: string; factTables: readonly ReportFactTable[] }>
| Readonly<{ status: Exclude<EnglishEditionStatus, "ready"> }>;
| Readonly<{ status: Exclude<EnglishEditionStatus, "ready">; reason?: string }>;
export async function resolveReportRead(deps: ReportReadCoreDeps): Promise<ReportRouteResponse> {
const originDecision = checkSameOrigin(deps.requestUrl, deps.origin, deps.allowedOrigins, deps.requestHeaders);
@@ -829,6 +829,9 @@ export async function resolveReportRead(deps: ReportReadCoreDeps): Promise<Repor
report: reportView(row, job),
...(publicReading ? { reading: publicReading } : {}),
englishEdition: english.status,
// BUG-2185: the stored reason code (han_leak, public_leak, render_error, …) so a failed
// English edition can be diagnosed from the report read; never rendered.
...(english.status === "unavailable" && english.reason ? { englishUnavailableReason: english.reason } : {}),
...(english.status === "ready" ? {
longformMarkdownEn: projectOrdinaryReportMarkdown(english.markdown, "en"),
factTablesEn: english.factTables,
@@ -3,6 +3,7 @@
* the failed sections, once. The timeline basis lines stay program-owned.
*/
import { SALVAGEABLE_CODES, salvageSynastryDraft } from "./synastry-salvage.ts";
import type { SynastryMatchingProfiles } from "./synastry-matching-profiles.ts";
import { buildTechnicalBasis, type TechnicalBlock } from "./synastry-full-technical.ts";
import {
@@ -502,6 +503,12 @@ export async function writeSynastryLanguage(input: Readonly<{
await input.onProgress?.("checking_report");
let parts = materialize();
let gated = await check(parts);
// BUG-2183: drafts that passed this first check are kept, so a section the rewrite breaks gets them back.
const firstPass = new Map<SynastrySectionId, unknown>();
{
const failingFirst = new Set(gated.failures.filter(({ code }) => !SOFT_GATE_CODES.has(code)).map(({ section }) => section));
if (!failingFirst.has("delivery")) for (const id of order) if (!failingFirst.has(id)) firstPass.set(id, drafts.get(id));
}
if (!gated.ok) {
const failed = new Set(gated.failures.map(({ section }) => section));
const targets = order.filter((id) => failed.has(id));
@@ -537,6 +544,30 @@ export async function writeSynastryLanguage(input: Readonly<{
parts = materialize();
gated = await check(parts);
}
// BUG-2183: last pass before failing the report — earlier passing drafts come back, then only the
// sentences or reasons the gate named are removed (lib/synastry-salvage.ts). Structural failures stay.
if (!gated.ok && hard().length > 0) {
let changed = false;
const failingNow = new Set(hard().map(({ section }) => section));
for (const id of order) {
if (failingNow.has(id) && firstPass.has(id)) { drafts.set(id, firstPass.get(id)); changed = true; }
}
if (changed) { parts = materialize(); gated = await check(parts); }
}
if (!gated.ok && hard().length > 0 && hard().every(({ code }) => SALVAGEABLE_CODES.has(code))) {
let changed = false;
for (const id of order) {
const fixes = hard().filter(({ section }) => section === id);
if (fixes.length === 0) continue;
const salvaged = salvageSynastryDraft(drafts.get(id), fixes);
if (salvaged) { drafts.set(id, salvaged); changed = true; }
}
if (changed) {
parts = materialize();
gated = await check(parts);
console.info(`[synastry-report] salvage codes=${[...new Set(gated.failures.map(({ code }) => code))].join(",") || "none"}`);
}
}
// Readability checks ask for one rewrite and never fail a report (owner rule 2026-11-13).
if (!gated.ok && hard().length === 0) gated = { ok: true, failures: [] };
if (!gated.ok) throw new SynastryGateRejected(gated.failures);
+94
View File
@@ -0,0 +1,94 @@
/**
* BUG-2183: after the one rewrite and the program's basis fixes, a synastry report used to fail as a
* whole when any section still had a hard gate failure (acceptance T-04: Jobs × Obama ended in
* report_guard_rejected after six minutes). Owner rule (2026-11-13): never withhold a report. This
* module is the last pass before that: it removes only what the gate named and leaves the rest.
*
* - A failure whose detail quotes the offending words (private term, supplementary method, unexplained
* abbreviation, banned judgement, analytic opening) drops the sentences that contain those words.
* - A score or dated-event failure carries no words, so the same patterns the gate uses find the
* sentences here.
* - A reason that still carries a named word is dropped as a whole, as long as one reason is left.
* - A section that passed an earlier check and only fails after the rewrite gets that earlier draft back.
*
* Nothing here writes new content; structural failures (missing section, too short, wrong shape) stay
* failures and still stop the report.
*/
type Row = Record<string, unknown>;
export type SalvageFailure = Readonly<{ section: string; code: string; detail?: string }>;
const QUOTED_CODES = new Set(["private_term", "supplementary_method", "unexplained_term", "banned_judgement", "analytic_opening"]);
// Same patterns as scripts/marriage_match_service/synastry_full_reader_gate.py (ZH_SCORE, ZH_EVENT, EN_SCORE, EN_EVENT).
const PATTERNS: Readonly<Record<string, readonly RegExp[]>> = {
score: [/\d+(?:\.\d+)?\s*分(?![钟之盘开别享工配析散量手歧布寸身清明秒])/, /\b\d+\s*(points|point|score)\b/i],
dated_event: [/(19|20)\d{2}\s*年.{0,12}(结婚|领证|分手|离婚)/, /\b(19|20)\d{2}\b.{0,24}\b(marry|married|marriage|divorce|break up)\b/i],
};
export const SALVAGEABLE_CODES: ReadonlySet<string> = new Set([...QUOTED_CODES, ...Object.keys(PATTERNS)]);
/** Never drop more than this share of a text; past it the failure stays. */
const MIN_KEEP = 0.5;
function asRecord(value: unknown): Row | null {
return value && typeof value === "object" && !Array.isArray(value) ? value as Row : null;
}
function sentences(text: string): string[] {
return text.match(/[^。!?!?;;\n]+[。!?!?;;]?\n?|\n/g) ?? [text];
}
function matcher(failure: SalvageFailure): ((sentence: string) => boolean) | null {
if (QUOTED_CODES.has(failure.code)) {
const words = (failure.detail ?? "").trim();
if (words.length < 2) return null;
return (sentence) => sentence.includes(words);
}
const patterns = PATTERNS[failure.code];
return patterns ? (sentence) => patterns.some((pattern) => pattern.test(sentence)) : null;
}
/** The text with the matching sentences removed, or null when nothing matched or too much would go. */
export function dropSentences(text: string, hit: (sentence: string) => boolean): string | null {
const parts = sentences(text);
const kept = parts.filter((part) => !hit(part));
if (kept.length === parts.length) return null;
const result = kept.join("").trim();
if (!result || result.length < text.trim().length * MIN_KEEP) return null;
return result;
}
/**
* Applies the failures of one section to its draft. Returns the new draft when anything changed,
* otherwise null. Handles prose sections (text + reasons), the timeline (segments) and practices (items).
*/
export function salvageSynastryDraft(draft: unknown, failures: readonly SalvageFailure[]): unknown {
const row = asRecord(draft);
if (!row) return null;
let changed = false;
const next: Row = { ...row };
for (const failure of failures) {
const hit = matcher(failure);
if (!hit) continue;
if (typeof next.text === "string") {
const text = dropSentences(next.text, hit);
if (text !== null) { next.text = text; changed = true; }
}
if (Array.isArray(next.reasons)) {
const reasons = (next.reasons as unknown[]).map((item) => ({ ...(asRecord(item) ?? {}) }));
const keep = reasons.filter((reason) => !hit(String(reason.plain ?? "")) && !hit(String(reason.basis ?? "")));
if (keep.length < reasons.length && keep.length > 0) { next.reasons = keep; changed = true; }
}
for (const key of ["segments", "items"] as const) {
if (!Array.isArray(next[key])) continue;
const list = (next[key] as unknown[]).map((item) => {
const entry = { ...(asRecord(item) ?? {}) };
if (typeof entry.text === "string" && hit(entry.text)) {
const text = dropSentences(entry.text, hit);
if (text !== null) { entry.text = text; changed = true; }
}
return entry;
});
next[key] = list;
}
}
return changed ? next : null;
}
@@ -0,0 +1,71 @@
// BUG-2183 / BUG-2184 / BUG-2185: the last-pass salvage for synastry and annual sections, and the
// English edition's stored failure reason in the report read.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { dropSentences, salvageSynastryDraft, SALVAGEABLE_CODES } from "../src/lib/synastry-salvage.ts";
import { ANNUAL_SALVAGEABLE, salvageAnnualTexts } from "../src/lib/annual-report-sections.ts";
test("synastry salvage drops only the sentence the gate quoted", () => {
const draft = {
text: "你们的相处有很多默契。这段关系注定失败。日常节奏也合得来,彼此愿意让步。",
reasons: [
{ plain: "沟通顺", basis: "水星与水星三分", evidence: "e1", label: "" },
{ plain: "注定失败的一面", basis: "土星对冲", evidence: "e2", label: "" },
],
};
const out = salvageSynastryDraft(draft, [{ section: "core", code: "banned_judgement", detail: "注定失败" }]) as { text: string; reasons: unknown[] };
assert.equal(out.text, "你们的相处有很多默契。日常节奏也合得来,彼此愿意让步。");
assert.equal(out.reasons.length, 1);
});
test("synastry salvage finds score and dated-event sentences with the gate's own patterns", () => {
const draft = { text: "整体匹配度很高,有 28 分。你们在一起很自在,也愿意一起规划生活。2019 年领证之后关系更稳。两个人都看重家庭,彼此照应。" };
const score = salvageSynastryDraft(draft, [{ section: "core", code: "score", detail: "数字分" }]) as { text: string };
assert.ok(!/28 分/.test(score.text));
const dated = salvageSynastryDraft(score, [{ section: "core", code: "dated_event", detail: "年份事件" }]) as { text: string };
assert.ok(!/2019 年领证/.test(dated.text));
assert.ok(dated.text.includes("两个人都看重家庭"));
// 「30 分钟」 is a birth-time window, not a score.
assert.equal(dropSentences("出生时间前后 30 分钟。其余不变,照旧。", (s) => /\d+(?:\.\d+)?\s*分(?![钟之盘开别享工配析散量手歧布寸身清明秒])/.test(s)), null);
});
test("synastry salvage never removes more than half a text and leaves structural failures alone", () => {
assert.equal(salvageSynastryDraft({ text: "这段关系注定失败。" }, [{ section: "core", code: "banned_judgement", detail: "注定失败" }]), null);
assert.equal(SALVAGEABLE_CODES.has("missing_section"), false);
assert.equal(SALVAGEABLE_CODES.has("too_short"), false);
});
test("the synastry writer restores first-pass drafts and salvages before rejecting the report", () => {
const source = readFileSync(new URL("../src/lib/synastry-full-generate.ts", import.meta.url), "utf8");
const salvage = source.indexOf("salvageSynastryDraft(drafts.get(id), fixes)");
const restore = source.indexOf("firstPass.get(id)");
const reject = source.indexOf("throw new SynastryGateRejected(gated.failures)");
assert.ok(restore > 0 && salvage > restore && reject > salvage);
});
test("annual salvage turns exact dates into month level and drops certainty sentences", () => {
const entry = { id: "overview", kind: "overview", title: "这一年", disposition: "write" } as never;
const body = { paragraphs: [{ evidence: "10 月 20 日前后木星离开。", text: "这一年:你必定会升职。工作在 2027-03-14 有变化,9 月 9 日前后注意休息。整体节奏稳中有进,适合把计划写下来逐步推进。" }] };
const out = salvageAnnualTexts(entry, body) as { paragraphs: { evidence: string; text: string }[] };
assert.equal(out.paragraphs[0].evidence, "10 月中前后木星离开。");
assert.ok(!out.paragraphs[0].text.includes("必定"));
assert.ok(out.paragraphs[0].text.includes("2027 年 3 月"));
assert.ok(out.paragraphs[0].text.includes("9 月上旬"));
assert.ok(!out.paragraphs[0].text.startsWith("这一年:"));
assert.deepEqual([...ANNUAL_SALVAGEABLE], ["certainty_word", "forbidden_topic", "explicit_date", "asserted_past", "repeated_heading"]);
});
test("the annual writer salvages text rules before a section stops the report", () => {
const source = readFileSync(new URL("../src/lib/annual-report-generate.ts", import.meta.url), "utf8");
const salvage = source.indexOf("salvageAnnualTexts(entry, body)");
const reject = source.indexOf("throw new AnnualGateError(entry.id, failures)");
assert.ok(salvage > 0 && reject > salvage);
});
test("the report read carries the stored English failure reason", () => {
const route = readFileSync(new URL("../src/app/api/reports/[reportId]/route.ts", import.meta.url), "utf8");
assert.match(route, /status: "unavailable", \.\.\.\(snapshot\.englishUnavailable \? \{ reason: snapshot\.englishUnavailable \}/);
const core = readFileSync(new URL("../src/lib/personal-report-route-core.ts", import.meta.url), "utf8");
assert.match(core, /englishUnavailableReason: english\.reason/);
});
+8 -7
View File
@@ -150,13 +150,14 @@ test("a section that fails the gate is rewritten once with the reasons, then the
// 原值节级 evidence / confidence。新值逐段依据与等级,日期检查继续约束正文。
const always = writerFor(plan, (entry) => (entry.id === "overview"
? prose(entry, "2027年3月5日你会搬家。", "年主落第 9 宫。") : undefined));
await assert.rejects(
writeAnnualReport({
facts, situation: EMPTY_ANNUAL_SITUATION, subject: { name: "阿宁", isSelf: false }, rangeKind: "birthday_year",
rangeKey: "annual:birthday_year:2026", birthTime: BIRTH, write: always.write, signal: new AbortController().signal,
}),
(error: unknown) => error instanceof AnnualGateError && error.sectionId === "overview" && error.failures.some((code) => code.startsWith("explicit_date")),
);
// BUG-2184 原值:改写后仍写具体日期 → AnnualGateError,整份年运失败(验收 T-05);
// 新值:程序把日期改成月份级后再核对,报告照常完成;原因:文字规则不该让整份报告失败(产品 2026-11-13)。
const written = await writeAnnualReport({
facts, situation: EMPTY_ANNUAL_SITUATION, subject: { name: "阿宁", isSelf: false }, rangeKind: "birthday_year",
rangeKey: "annual:birthday_year:2026", birthTime: BIRTH, write: always.write, signal: new AbortController().signal,
});
assert.match(JSON.stringify(written), /2027 年 3 月上旬/);
assert.doesNotMatch(JSON.stringify(written), /2027年3月5日/);
});
test("the gate keeps the writing rules", () => {
@@ -51,7 +51,8 @@ test("a range chosen in rectification is the range the annual report reads, roun
test("the start page and the parameters block name a chosen range as chosen, not as a filled-in error or a 30-minute trial", () => {
const birth: AnnualBirthTime = { known: true, beforeMinutes: 6, afterMinutes: 1, source: "family_exact", rectification: "adopted", range: "chosen" };
assert.deepEqual(birthNotice({ id: "self", name: "小林", isSelf: true, birthTime: birth }), { text: "出生时间按你在生时纠正里选的情况来算。" });
// BUG-2184 原值 { text: "出生时间按你在生时纠正里选的情况来算。" };新值 null;原因:产品 2026-11-22(BUG-2146 同一规则)自选的时间按已纠正处理,不写开头说明。
assert.equal(birthNotice({ id: "self", name: "小林", isSelf: true, birthTime: birth }), null);
const lines = birthTimeLines(facts, birth);
assert.equal(lines[1], "出生时间记录:家人记得的时间;误差:生时纠正里选定的区间(早 6 分钟到晚 1 分钟)");
assert.doesNotMatch(lines.join("\n"), /30 分钟试算|没有填/);
@@ -65,7 +65,8 @@ test("ephemeris look-back answers are saved or refused through toasts", () => {
test("annual: a failed start is a toast; only 'not enough credits' stays in the card", () => {
const source = read("src/components/annual/annual-report-page.tsx");
assert.match(source, /if \(failure\.billing\) setStartError\(failure\);\s*else notifyError\(failure\.message\);/);
// BUG-2184 原值:只有点数不够留在卡片里;新值:另一份报告还在写(409)也留在卡片里;原因:这是持续状态,浮出提示一闪而过,验收 T-05 以为点了没反应。
assert.match(source, /if \(failure\.billing \|\| response\.status === 409\) setStartError\(failure\);\s*else notifyError\(failure\.message\);/);
assert.match(source, /notifyError\("网络不太稳,再点一次试试。"\)/);
assert.doesNotMatch(source, /setStartError\(\{ message:/);
});