From 1580ebd82665a4a57aaadab359e75b1560beb6e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?= Date: Tue, 20 Oct 2026 11:09:47 +0800 Subject: [PATCH] =?UTF-8?q?feat(qaops):=20=E5=A2=9E=E5=8A=A0=E7=AC=AC40?= =?UTF-8?q?=E8=87=B343=E5=91=A8=E5=AE=9E=E6=97=B6=E7=B4=AF=E8=AE=A1?= =?UTF-8?q?=E8=B6=8B=E5=8A=BF=E5=8F=8A=E5=8F=97=E6=8E=A7=E5=9B=9E=E5=A1=AB?= =?UTF-8?q?=E4=BE=9D=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 按北京时间各自然周截止对整张统计总表累计计数,字段取当前有效结论。 覆盖和正确各按周报是除以是加否,保留历史上报与冻结并优先展示动态累计。 新增30秒顺序刷新、本地规则和历史复用非模型依据,保护当前原问答与人工字段。 验证:完整make verify通过;隔离PostgreSQL全量mirror race通过; 恢复库与真实周报calc_metrics四点对拍、源点踩自然刷新、桌面/390px及PNG通过。 新增源同步成员变化、人工版本保护及跨策略标签间距回归已通过。 模型全量语义风险审核及正式业务回填尚未完成,未部署本版本。 --- CHANGELOG.md | 8 + api/openapi.yaml | 2 +- internal/qaopsmirror/dashboard.go | 35 ++-- internal/qaopsmirror/dashboard_cumulative.go | 126 ++++++++++++++ internal/qaopsmirror/dashboard_store.go | 8 + .../master_cumulative_integration_test.go | 159 ++++++++++++++++++ web/src/QAAI.tsx | 29 +++- web/src/QADashboard.tsx | 33 ++-- web/src/QADashboardDrawing.test.tsx | 61 +++++++ web/src/QADashboardDrawing.tsx | 43 +++-- web/src/qaAILocalDerivation.test.tsx | 48 ++++++ web/src/qaAITypes.ts | 40 ++++- web/src/qaCumulativeTrend.test.ts | 69 ++++++++ web/src/qaDashboardData.ts | 85 ++++++++++ web/src/qaDashboardLive.test.ts | 20 +++ web/src/qaHistoricalTrend.ts | 17 +- 16 files changed, 726 insertions(+), 57 deletions(-) create mode 100644 internal/qaopsmirror/dashboard_cumulative.go create mode 100644 internal/qaopsmirror/master_cumulative_integration_test.go create mode 100644 web/src/qaAILocalDerivation.test.tsx create mode 100644 web/src/qaCumulativeTrend.test.ts create mode 100644 web/src/qaDashboardLive.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index fbe4801..9e4a212 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -76,6 +76,14 @@ > `0.1.12`),由 `scripts/version.py` 从 git **算出来**;开发交付的独立说明写入本文件“开发快照”章节,并打 `snapshot/vX.Y.Z` 注释标签 ⇒ 每次开发交付均可追溯, > 但"发布版本"仍然只能由人定(CI 不会自动升版本、不会打 tag)。 +## 开发快照 snapshot/v0.1.43 - 2026-10-20 + +### Added + +- 知识覆盖率与回答正确率趋势新增第40–43周“总表累计”绿色曲线:按北京时间各自然周截止纳入整张总表的累计问题,使用当前有效字段及点踩结论动态计算;覆盖率和正确率分别使用“是÷(是+否)”,待确认等未明确结论不进入对应分母,零分母不伪造百分比。逐点展示实际截止、累计条数、分子分母及规则版本,保留原历史上报和冻结证据。 +- 字段依据区区分真实模型返回与本地规则/历史唯一标签复用:语言识别、中文原文保留及历史分类复用逐字段展示来源与回填状态,明确标注“非模型”,不把外部受控任务冒充平台服务模型配置。 +- 看板每30秒顺序读取最新总表,当前选周截止推进至当前时点,已闭周查询保持原范围;离开或换条件取消旧请求,读取失败明确提示,不展示过期图表或导出旧图。 + ## 开发快照 snapshot/v0.1.42 - 2026-10-20 ### Fixed diff --git a/api/openapi.yaml b/api/openapi.yaml index dc17065..e3b1822 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -125,7 +125,7 @@ "get": {"tags":["QA operations"],"operationId":"getQAOrganizationSync","summary":"管理员读取通讯录同步执行器状态及最近任务的安全汇总,不返回人员名单或运行配置","responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"状态存储不可用,不伪装为空记录"}}}, "post": {"tags":["QA operations"],"operationId":"startQAOrganizationSync","summary":"管理员同源发起持久化通讯录同步;重复请求重放同一任务,进行中任务合并;失败保留现有快照","parameters":[{"$ref":"#/components/parameters/IdempotencyKey"},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-organization"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false}}}},"responses":{"202":{"$ref":"#/components/responses/OperationEnvelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员同源操作"},"409":{"description":"操作标识与原请求冲突"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"同步未接线、执行器离线或入队失败;未创建新任务"}}} }, - "/api/v1/qa-ops/dashboard": {"post":{"operationId":"readQAOperationsDashboard","tags":["QA operations"],"summary":"管理员只读正式总表一致性看板:累计、所选周、新增/有效质量/类别及截止月区域统计;历史趋势区分用户提供百分比与真实冻结快照,缺失留空","description":"同一只读可重复读事务读取独立正式总表有效字段、质量及组织版本。不访问源端,不冻结或写入指标;区域分母为当前配置通讯录去重人数而非在职/绩效名单。冻结记录按保存的原始标量分子分母及问题文字支持字面关键词筛选,不用当前评估回填历史。reported_weeks 独立返回用户提供的历史百分比(QAReportedHistoricalRate),没有分子分母或冻结时间;只含所选截止前已结束周,关键词非空时为空,原冻结记录与当前指标保持不变。","parameters":[{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-dashboard"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["start","end"],"properties":{"start":{"type":"string","format":"date-time"},"end":{"type":"string","format":"date-time"},"keyword":{"type":"string","maxLength":200}}}}}},"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员同源读取"},"409":{"description":"质量输入指纹变化,拒绝混合数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"本地副本或一致性投影不可用,不返回伪零"}}}}, + "/api/v1/qa-ops/dashboard": {"post":{"operationId":"readQAOperationsDashboard","tags":["QA operations"],"summary":"管理员只读正式总表一致性看板:累计、所选周及区域统计;第40–43周动态累计、历史上报与真实冻结分别保留","description":"同一只读可重复读事务读取独立正式总表有效字段、质量及组织版本。不访问源端,不冻结或写入指标;区域分母为当前配置通讯录去重人数而非在职/绩效名单。冻结记录按保存的原始标量分子分母及问题文字支持字面关键词筛选,不用当前评估回填历史。reported_weeks 独立返回用户提供的历史百分比(QAReportedHistoricalRate),没有分子分母或冻结时间;只含所选截止前已结束周,关键词非空时为空,原冻结记录与当前指标保持不变。cumulative_weeks 独立返回2026WK40–WK43的master_live_cumulative_v1实时累计曲线,policy_version为weekly-strict-yes-over-yes-no-v1:各周成员为整张总表中提问时间早于北京时间下周一的记录,当前周截止min(查询end,事务当前时点),不被查询start截断;字段取当前有效结论,补值和后续点踩会追溯更新相关累计周。覆盖率与正确率分别按是÷(是+否),待确认/部分覆盖及其他值不入严格分母,零分母percent=null;各点保留成员数、两组分子分母、周边界、实际截止和计算时点。仅查询治理本地总表,不写历史上报/冻结证据;网页30秒顺序刷新,已闭查询周不推进到后周。","parameters":[{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-dashboard"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["start","end"],"properties":{"start":{"type":"string","format":"date-time"},"end":{"type":"string","format":"date-time"},"keyword":{"type":"string","maxLength":200}}}}}},"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员同源读取"},"409":{"description":"质量输入指纹变化,拒绝混合数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"本地副本或一致性投影不可用,不返回伪零"}}}}, "/api/v1/qa-ops/organization": { "get": { "tags": ["QA operations"], diff --git a/internal/qaopsmirror/dashboard.go b/internal/qaopsmirror/dashboard.go index 880df88..01d6173 100644 --- a/internal/qaopsmirror/dashboard.go +++ b/internal/qaopsmirror/dashboard.go @@ -42,23 +42,24 @@ type DashboardRegion struct { UsageCoverage qaopsquality.Rate `json:"usage_coverage"` } type Dashboard struct { - Start time.Time `json:"start"` - End time.Time `json:"end"` - Keyword string `json:"keyword"` - AsOf time.Time `json:"as_of"` - LocalRevision int64 `json:"local_revision"` - Organization dobotaiops.OrganizationVersion `json:"organization"` - TotalIssues int `json:"total_issues"` - NewThisWeek int `json:"new_this_week"` - WeekStart time.Time `json:"week_start"` - MonthStart time.Time `json:"month_start"` - Quality qaopsquality.Summary `json:"quality"` - IssueTypes []DashboardCount `json:"issue_types"` - Products []DashboardCount `json:"products"` - Daily []DashboardDaily `json:"daily"` - Regions []DashboardRegion `json:"regions"` - FrozenWeeks []DashboardFrozen `json:"frozen_weeks"` - ReportedWeeks []DashboardReported `json:"reported_weeks"` + Start time.Time `json:"start"` + End time.Time `json:"end"` + Keyword string `json:"keyword"` + AsOf time.Time `json:"as_of"` + LocalRevision int64 `json:"local_revision"` + Organization dobotaiops.OrganizationVersion `json:"organization"` + TotalIssues int `json:"total_issues"` + NewThisWeek int `json:"new_this_week"` + WeekStart time.Time `json:"week_start"` + MonthStart time.Time `json:"month_start"` + Quality qaopsquality.Summary `json:"quality"` + IssueTypes []DashboardCount `json:"issue_types"` + Products []DashboardCount `json:"products"` + Daily []DashboardDaily `json:"daily"` + Regions []DashboardRegion `json:"regions"` + FrozenWeeks []DashboardFrozen `json:"frozen_weeks"` + ReportedWeeks []DashboardReported `json:"reported_weeks"` + CumulativeWeeks []DashboardCumulative `json:"cumulative_weeks"` } var dashboardLocation = time.FixedZone("Asia/Shanghai", 8*60*60) diff --git a/internal/qaopsmirror/dashboard_cumulative.go b/internal/qaopsmirror/dashboard_cumulative.go new file mode 100644 index 0000000..2c969a2 --- /dev/null +++ b/internal/qaopsmirror/dashboard_cumulative.go @@ -0,0 +1,126 @@ +package qaopsmirror + +import ( + "context" + "encoding/json" + "fmt" + "github.com/jackc/pgx/v5" + "knowledge-governance/internal/dobotaiops" + "knowledge-governance/internal/qaopsquality" + "time" +) + +type DashboardCumulative struct { + Week string `json:"week"` + WeekStart time.Time `json:"week_start"` + WeekEnd time.Time `json:"week_end"` + CutoffAt time.Time `json:"cutoff_at"` + CalculatedAt time.Time `json:"calculated_at"` + Records int `json:"records"` + Coverage qaopsquality.Rate `json:"coverage"` + Correctness qaopsquality.Rate `json:"correctness"` + Source string `json:"source"` + PolicyVersion string `json:"policy_version"` +} + +// Membership closes at each week's cutoff; labels deliberately stay live. This is +// not a frozen snapshot and must never replace the older reported/frozen evidence. +func (s *Store) readMasterCumulativeDashboard(ctx context.Context, tx pgx.Tx, keyword string, end time.Time) ([]DashboardCumulative, error) { + out := []DashboardCumulative{} + var now time.Time + if e := tx.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&now); e != nil { + return nil, e + } + cutoff := end + if now.Before(cutoff) { + cutoff = now + } + first := time.Date(2026, time.September, 28, 0, 0, 0, 0, dashboardLocation) + if !first.Before(cutoff) { + return out, nil + } + rows, e := tx.Query(ctx, `SELECT id,asked_at,quality_hash,effective_fields,inline_fields,coverage_result,current_feedback FROM qa_ops_master_read_model WHERE tenant_key=$1 AND asked_at<$2 AND ($3='' OR position(lower($3) IN lower(question||E'\n'||chinese_question||E'\n'||COALESCE(ai_fields->>'question_chinese','')))>0) ORDER BY asked_at,id LIMIT 100001`, s.tenant, cutoff, keyword) + if e != nil { + return nil, dobotaiops.ErrUnavailable + } + records := []dashboardRecord{} + keys := []dobotaiops.QualityKey{} + for rows.Next() { + var r dashboardRecord + var f, ed, cov, fb []byte + if e = rows.Scan(&r.id, &r.at, &r.hash, &f, &ed, &cov, &fb); e != nil { + rows.Close() + return nil, e + } + if json.Unmarshal(f, &r.fields) != nil || json.Unmarshal(ed, &r.edits) != nil || json.Unmarshal(cov, &r.coverage) != nil || json.Unmarshal(fb, &r.feedback) != nil { + rows.Close() + return nil, dobotaiops.ErrUnavailable + } + records = append(records, r) + keys = append(keys, dobotaiops.QualityKey{ID: r.id, InputHash: r.hash}) + } + e = rows.Err() + rows.Close() + if e != nil { + return nil, e + } + if len(records) > dobotaiops.MaxMirrorRecords { + return nil, dobotaiops.ErrInvalidQuery + } + views := map[string]qaopsquality.View{} + store := qaopsquality.NewStore(s.pool, s.tenant+"::master") + for begin := 0; begin < len(keys); begin += 5000 { + limit := min(begin+5000, len(keys)) + part, e := store.ReadViewsInTx(ctx, tx, keys[begin:limit]) + if e != nil { + return nil, e + } + for id, v := range part { + views[id] = v + } + } + for i := 0; i < 4; i++ { + start := first.AddDate(0, 0, 7*i) + if !start.Before(cutoff) { + break + } + finish := start.AddDate(0, 0, 7) + until := finish + if cutoff.Before(until) { + until = cutoff + } + year, week := start.ISOWeek() + point := DashboardCumulative{Week: fmt.Sprintf("%dWK%02d", year, week), WeekStart: start, WeekEnd: finish, CutoffAt: until, CalculatedAt: now, Source: "master_live_cumulative_v1", PolicyVersion: "weekly-strict-yes-over-yes-no-v1"} + covered, uncovered, correct, incorrect := 0, 0, 0, 0 + for _, r := range records { + if !r.at.Before(until) { + continue + } + point.Records++ + v, ok := views[r.id] + if !ok { + return nil, qaopsquality.ErrUnavailable + } + v = qaopsquality.ProjectMasterWithEdits(v, r.fields, r.coverage, r.edits, r.feedback) + if v.State == "stale" { + continue + } + switch v.Effective.Coverage { + case "covered": + covered++ + case "uncovered": + uncovered++ + } + switch v.Effective.Correctness { + case "correct": + correct++ + case "incorrect": + incorrect++ + } + } + point.Coverage = dashboardRate(covered, covered+uncovered) + point.Correctness = dashboardRate(correct, correct+incorrect) + out = append(out, point) + } + return out, nil +} diff --git a/internal/qaopsmirror/dashboard_store.go b/internal/qaopsmirror/dashboard_store.go index ff8ffbc..fc8cd4e 100644 --- a/internal/qaopsmirror/dashboard_store.go +++ b/internal/qaopsmirror/dashboard_store.go @@ -264,6 +264,14 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas return out, dobotaiops.ErrInvalidQuery } } + if master { + out.CumulativeWeeks, e = s.readMasterCumulativeDashboard(ctx, tx, q.Keyword, q.Window.End) + if e != nil { + return out, e + } + } else { + out.CumulativeWeeks = []DashboardCumulative{} + } out.ReportedWeeks, e = s.readReportedDashboard(ctx, tx, q.Keyword, q.Window.End) if e != nil { return out, e diff --git a/internal/qaopsmirror/master_cumulative_integration_test.go b/internal/qaopsmirror/master_cumulative_integration_test.go new file mode 100644 index 0000000..ae6c5e5 --- /dev/null +++ b/internal/qaopsmirror/master_cumulative_integration_test.go @@ -0,0 +1,159 @@ +package qaopsmirror + +import ( + "context" + "encoding/json" + "knowledge-governance/internal/dobotaiops" + pg "knowledge-governance/internal/platform/postgres" + "testing" + "time" +) + +func TestMasterLiveCumulativeWeeksClampNowAndKeepZeroDenominatorsNull(t *testing.T) { + p := mirrorFixture(t) + ctx := context.Background() + s := NewStore(p, "fixture-cumulative-zero") + tx, err := p.Begin(ctx) + if err != nil { + t.Fatal(err) + } + defer tx.Rollback(ctx) + future := time.Now().AddDate(0, 0, 30) + points, err := s.readMasterCumulativeDashboard(ctx, tx, "", future) + if err != nil { + t.Fatal(err) + } + if len(points) != 4 { + t.Fatal("expected the four target weeks on current acceptance date") + } + for _, point := range points { + expected := point.WeekEnd + if point.CalculatedAt.Before(expected) { + expected = point.CalculatedAt + } + if future.Before(expected) { + expected = future + } + if !point.CutoffAt.Equal(expected) || point.Records != 0 || point.Coverage.Denominator != 0 || point.Correctness.Denominator != 0 || point.Coverage.Percent != nil || point.Correctness.Percent != nil { + t.Fatal("empty live cumulative point fabricated a rate or used a future cutoff") + } + } +} + +func TestMasterLiveCumulativeWeeksUseWholeLedgerAndWeeklyStrictRates(t *testing.T) { + p := mirrorFixture(t) + ctx := context.Background() + s := NewStore(p, "fixture-live-cumulative") + queue := pg.NewStore(p) + dates := []string{"2026-09-20T08:00:00+08:00", "2026-09-28T08:00:00+08:00", "2026-10-05T00:00:00+08:00", "2026-10-12T00:00:00+08:00", "2026-10-19T00:00:00+08:00"} + ids := []string{"older", "wk40", "boundary41", "wk42partial", "wk43pending"} + coverage := []string{"是", "是", "否", "部分覆盖", "是"} + correct := []string{"是", "否", "是", "否", "待确认"} + source := &fixtureSource{} + for i, at := range dates { + entry := fixtureEntry(ids[i], "已有正文") + var wire map[string]any + _ = json.Unmarshal(entry.Payload, &wire) + wire["asked_at"] = at + entry.Payload, _ = json.Marshal(wire) + source.rows = append(source.rows, entry) + } + job := claimMirrorJob(t, s, queue, "seed-live-cumulative") + if e := s.HandleSync(ctx, *job, func(context.Context) (Source, error) { return source, nil }); e != nil { + t.Fatal(e) + } + if e := queue.Complete(ctx, job.ID, job.LeaseOwner, time.Now()); e != nil { + t.Fatal(e) + } + for i, id := range ids { + fields, _ := json.Marshal(map[string]string{"coverage": coverage[i], "is_correct": correct[i]}) + if _, e := p.Exec(ctx, "UPDATE qa_ops_master_records SET local_fields=local_fields||$3::jsonb WHERE tenant_key=$1 AND id=$2", s.tenant, id, fields); e != nil { + t.Fatal(e) + } + } + start, _ := time.Parse(time.RFC3339, "2026-10-19T00:00:00+08:00") + end := start.AddDate(0, 0, 1) + data, e := s.ReadMasterDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: end}}) + if e != nil { + t.Fatal(e) + } + raw, _ := json.Marshal(data) + var wire map[string]any + _ = json.Unmarshal(raw, &wire) + points, ok := wire["cumulative_weeks"].([]any) + if !ok || len(points) != 4 { + t.Fatal("missing current master cumulative W40-W43; frozen snapshots are not a substitute") + } + expected := [][5]float64{{2, 2, 2, 1, 2}, {3, 2, 3, 2, 3}, {4, 2, 3, 2, 4}, {5, 3, 4, 2, 4}} + for i, item := range points { + point := item.(map[string]any) + cov := point["coverage"].(map[string]any) + acc := point["correctness"].(map[string]any) + want := expected[i] + if point["records"] != want[0] || cov["numerator"] != want[1] || cov["denominator"] != want[2] || acc["numerator"] != want[3] || acc["denominator"] != want[4] { + t.Fatalf("week %d is not whole-ledger strict weekly numerator/denominator: %v", i, point) + } + if point["source"] != "master_live_cumulative_v1" || point["policy_version"] != "weekly-strict-yes-over-yes-no-v1" { + t.Fatal("live cumulative provenance missing") + } + } + var before string + if e = p.QueryRow(ctx, `SELECT md5(string_agg(md5(payload::text||original_fields::text||local_fields::text),'' ORDER BY id)) FROM qa_ops_master_records WHERE tenant_key=$1`, s.tenant).Scan(&before); e != nil { + t.Fatal(e) + } + if _, e = p.Exec(ctx, `UPDATE qa_ops_mirror_records SET payload=jsonb_set(payload,'{feedback}','{"asker_value":"down","down":1,"up":0}')WHERE tenant_key=$1 AND id='older'`, s.tenant); e != nil { + t.Fatal(e) + } + fresh, e := s.ReadMasterDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: end}}) + if e != nil { + t.Fatal(e) + } + if len(fresh.CumulativeWeeks) != 4 || fresh.CumulativeWeeks[0].Correctness.Numerator != 0 || fresh.CumulativeWeeks[1].Correctness.Numerator != 1 || fresh.CumulativeWeeks[3].Correctness.Numerator != 1 { + t.Fatal("later source feedback did not update every affected cumulative week") + } + filtered, e := s.ReadMasterDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: end}, Keyword: "\n"}) + if e != nil { + t.Fatal(e) + } + if len(filtered.CumulativeWeeks) != 4 || filtered.CumulativeWeeks[3].Records != filtered.TotalIssues { + t.Fatal("cumulative keyword scope diverged from dashboard totals") + } + for _, point := range filtered.CumulativeWeeks { + if point.Records > filtered.TotalIssues { + t.Fatal("cumulative keyword scope exceeded dashboard totals") + } + } + var after string + if e = p.QueryRow(ctx, `SELECT md5(string_agg(md5(payload::text||original_fields::text||local_fields::text),'' ORDER BY id)) FROM qa_ops_master_records WHERE tenant_key=$1`, s.tenant).Scan(&after); e != nil || after != before { + t.Fatal("cumulative reads or feedback rewrote master business fields", e) + } + arrival := fixtureEntry("later-arrival", "新记录的成功非空答案") + var arrivalWire map[string]any + _ = json.Unmarshal(arrival.Payload, &arrivalWire) + arrivalWire["asked_at"] = start.Add(time.Hour).Format(time.RFC3339) + arrival.Payload, _ = json.Marshal(arrivalWire) + source.rows = append(source.rows, arrival) + nextJob := claimMirrorJob(t, s, queue, "append-live-cumulative-arrival") + if e = s.HandleSync(ctx, *nextJob, func(context.Context) (Source, error) { return source, nil }); e != nil { + t.Fatal(e) + } + appended, e := s.ReadMasterDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: end}}) + if e != nil { + t.Fatal(e) + } + for i, point := range appended.CumulativeWeeks { + previous := fresh.CumulativeWeeks[i] + if i < 3 { + if point.Records != previous.Records || point.Coverage.Denominator != previous.Coverage.Denominator { + t.Fatal("new current-week event changed an earlier cutoff membership") + } + continue + } + if point.Records != previous.Records+1 || point.Coverage.Numerator != previous.Coverage.Numerator+1 || point.Coverage.Denominator != previous.Coverage.Denominator+1 || point.Correctness.Numerator != previous.Correctness.Numerator || point.Correctness.Denominator != previous.Correctness.Denominator { + t.Fatal("new event failed to update live cumulative counts or manufactured correctness") + } + } + if e = p.QueryRow(ctx, `SELECT md5(string_agg(md5(payload::text||original_fields::text||local_fields::text),'' ORDER BY id))FROM qa_ops_master_records WHERE tenant_key=$1 AND id<>'later-arrival'`, s.tenant).Scan(&after); e != nil || after != before { + t.Fatal("source append overwrote existing master rows", e) + } +} diff --git a/web/src/QAAI.tsx b/web/src/QAAI.tsx index c60478f..5acdc35 100644 --- a/web/src/QAAI.tsx +++ b/web/src/QAAI.tsx @@ -430,6 +430,25 @@ export function QAAIEvidenceView({ evidence }: { evidence: AIEvidence[] }) { )) : null} + {work.result.local_derivations + ? Object.entries(work.result.local_derivations).map(([field, proof]) => ( +
+ + {field === 'language' + ? '语言' + : field === 'question_chinese' + ? '中文问题' + : (fieldLabels[field] ?? field)} + :{proof.value} + +

{proof.reason}

+ + 本地规则/历史复用(非模型); + {Object.hasOwn(work.applied_fields, field) ? '已回填' : '未回填,保留当前值'} + +
+ )) + : null} {work.result.question_chinese ? (
中文问题 @@ -442,10 +461,14 @@ export function QAAIEvidenceView({ evidence }: { evidence: AIEvidence[] }) {
模型、规则版本与输入指纹
-
实际返回模型
-
{work.actual_model || '尚未返回'}
+
{work.actual_model === 'local-rule-history-v1' ? '结论来源(非模型)' : '实际返回模型'}
+
+ {work.actual_model === 'local-rule-history-v1' + ? '本地规则/历史复用(非模型)' + : work.actual_model || '尚未返回'} +
配置修订
-
{work.config_revision}
+
{work.config_revision === 0 ? '外部受控回填,未使用服务模型配置' : work.config_revision}
提示词版本
{work.prompt_version}
正式字典版本
diff --git a/web/src/QADashboard.tsx b/web/src/QADashboard.tsx index 0cbf580..bc6c394 100644 --- a/web/src/QADashboard.tsx +++ b/web/src/QADashboard.tsx @@ -1,6 +1,6 @@ import { useEffect, useRef, useState } from 'react' import type { QAQuery } from './qaOps' -import { fetchQADashboard } from './qaDashboardData' +import { fetchQADashboard, liveDashboardQuery } from './qaDashboardData' import type { QADashboardData } from './qaDashboardData' import { QADashboardDrawing } from './QADashboardDrawing' import { createDashboardPNG } from './qaDashboardExport' @@ -100,18 +100,29 @@ export function QADashboard({ return } const abort = new AbortController() + let timer: ReturnType | undefined setLoading(true) - void fetchQADashboard(query, abort.signal) - .then((v) => { - if (!abort.signal.aborted) setData(v) - }) - .catch((e) => { + const refresh = async () => { + try { + const next = await fetchQADashboard(liveDashboardQuery(query, new Date()), abort.signal) + if (!abort.signal.aborted) { + setData(next) + setFailure('') + } + } catch (e) { if (!abort.signal.aborted) setFailure(e instanceof Error ? e.message : '统计看板读取失败') - }) - .finally(() => { - if (!abort.signal.aborted) setLoading(false) - }) - return () => abort.abort() + } finally { + if (!abort.signal.aborted) { + setLoading(false) + timer = setTimeout(() => void refresh(), 30000) + } + } + } + void refresh() + return () => { + abort.abort() + if (timer !== undefined) clearTimeout(timer) + } }, [query, revision]) return (
diff --git a/web/src/QADashboardDrawing.test.tsx b/web/src/QADashboardDrawing.test.tsx index 95a2c7d..c5348ae 100644 --- a/web/src/QADashboardDrawing.test.tsx +++ b/web/src/QADashboardDrawing.test.tsx @@ -49,6 +49,67 @@ it('renders reported history in both existing trend panels with exact values and expect((html.match(/data-panel=/g) || []).length).toBe(11) expect(html).toContain('data-frozen="available"') }) +it('renders dynamic cumulative points as a distinct green policy series in both charts', () => { + const data = parseQADashboard({ + ...dashboardFixture, + cumulative_weeks: [ + { + week: '2026WK40', + week_start: '2026-09-28T00:00:00+08:00', + week_end: '2026-10-05T00:00:00+08:00', + cutoff_at: '2026-10-05T00:00:00+08:00', + calculated_at: '2026-10-18T10:00:00Z', + records: 2, + coverage: { numerator: 1, denominator: 2, percent: 50 }, + correctness: { numerator: 1, denominator: 2, percent: 50 }, + source: 'master_live_cumulative_v1', + policy_version: 'weekly-strict-yes-over-yes-no-v1', + }, + ], + }) + const html = renderToStaticMarkup() + expect(html).toContain('绿:总表累计') + expect(html).toContain('stroke="#249c86"') + expect((html.match(/data-source="master_live_cumulative_v1"/g) || []).length).toBe(2) + expect(html).toContain('非历史冻结') +}) +it('keeps adjacent policy-boundary week and percentage labels from overlapping in long history', () => { + const data = parseQADashboard(dashboardFixture), + first = Date.parse('2026-04-06T00:00:00+08:00'), + week = 7 * 86400000 + data.end = '2026-10-20T01:00:00Z' + data.reported_weeks = Array.from({ length: 25 }, (_, i) => ({ + week: `2026WK${String(15 + i).padStart(2, '0')}`, + week_start: new Date(first + i * week).toISOString(), + week_end: new Date(first + (i + 1) * week).toISOString(), + coverage_percent: 70, + correctness_percent: 97, + source: 'user_provided_history', + })) + data.cumulative_weeks = Array.from({ length: 4 }, (_, i) => ({ + week: `2026WK${40 + i}`, + week_start: new Date(first + (25 + i) * week).toISOString(), + week_end: new Date(first + (26 + i) * week).toISOString(), + cutoff_at: new Date(Math.min(first + (26 + i) * week, Date.parse(data.end))).toISOString(), + calculated_at: data.end, + records: 1, + coverage: { numerator: 1, denominator: 1, percent: 100 }, + correctness: { numerator: 1, denominator: 1, percent: 100 }, + source: 'master_live_cumulative_v1', + policy_version: 'weekly-strict-yes-over-yes-no-v1', + })) + const html = renderToStaticMarkup(), + groups = [...html.matchAll(//g)] + const labels = groups + .slice(0, 29) + .map((g) => g[0].match(/]*>2026W[0-9]+<\/text>/)) + .filter((v): v is RegExpMatchArray => v !== null) + .map((m) => Number(m[1])) + .sort((a, b) => a - b) + expect(groups).toHaveLength(58) + for (let i = 1; i < labels.length; i++) expect(labels[i] - labels[i - 1]).toBeGreaterThanOrEqual(51.99) + expect(groups.find((g) => g[0].includes('data-week="2026WK40"'))?.[0]).toContain('2026W40') +}) it('reflows the same complete eleven panels at mobile width rather than clipping the canvas', () => { const html = renderToStaticMarkup() expect((html.match(/data-panel=/g) || []).length).toBe(11) diff --git a/web/src/QADashboardDrawing.tsx b/web/src/QADashboardDrawing.tsx index ee5ff59..4d338cf 100644 --- a/web/src/QADashboardDrawing.tsx +++ b/web/src/QADashboardDrawing.tsx @@ -3,6 +3,7 @@ import type { QADashboardData, DashboardCount, DashboardRegion } from './qaDashb import type { QualityRate } from './qaQuality' import { currentQAWeek } from './qaWeeks' import { historicalTrend } from './qaHistoricalTrend' +import type { HistoricalPlotPoint } from './qaHistoricalTrend' interface Box { x: number y: number @@ -267,14 +268,7 @@ function Products({ box, points }: { box: Box; points: DashboardCount[] }) { ) } -interface PlotPoint { - label: string - value: number | null - hint: string - frozen?: boolean - source?: 'user_provided_history' | 'system_frozen' - week?: string -} +type PlotPoint = HistoricalPlotPoint function Plot({ box, title, @@ -298,7 +292,8 @@ function Plot({ x = (i: number) => points.length === 1 ? (left + right) / 2 : left + (i * (right - left)) / Math.max(1, points.length - 1), y = (n: number) => bottom - (n / max) * (bottom - top) - const color = (source: PlotPoint['source']) => (source === 'system_frozen' ? '#8b68c7' : blue) + const color = (source: PlotPoint['source']) => + source === 'master_live_cumulative_v1' ? '#249c86' : source === 'system_frozen' ? '#8b68c7' : blue const paths = [...new Set(points.map((p) => p.source))].map((source) => { let path = '', open = false @@ -315,19 +310,21 @@ function Plot({ }) const every = Math.max(1, Math.ceil(points.length / (box.w < 420 ? 5 : 8))) const labelled = new Set() - points.forEach((point, i) => { - if ( - point.value !== null && - (i === 0 || - points[i - 1]?.source !== point.source || - i === points.length - 1 || - points[i + 1]?.source !== point.source) - ) + const label = (i: number) => { + if (points[i]?.value !== null && points[i] && [...labelled].every((k) => Math.abs(x(k) - x(i)) >= 52)) labelled.add(i) + } + label(0) + label(points.length - 1) + // Keep the first point of a new policy readable instead of forcing two adjacent labels at a boundary. + points.forEach((point, i) => { + if (i && points[i - 1]?.source !== point.source) label(i) + }) + points.forEach((point, i) => { + if (points[i + 1]?.source !== point.source) label(i) }) points.forEach((_, i) => { - if ((i % every === 0 || i === points.length - 1) && [...labelled].every((k) => Math.abs(x(k) - x(i)) >= 52)) - labelled.add(i) + if (i % every === 0) label(i) }) return ( @@ -387,9 +384,11 @@ function Plot({ ))} {percent ? ( - {points.some((p) => p.source === 'user_provided_history') - ? '蓝:用户提供(未提供分子/分母);紫:系统冻结' - : '缺失周留空;系统冻结与当前实时结果分开'} + {points.some((p) => p.source === 'master_live_cumulative_v1') + ? '蓝:历史上报;紫:系统冻结;绿:总表累计' + : points.some((p) => p.source === 'user_provided_history') + ? '蓝:用户提供(未提供分子/分母);紫:系统冻结' + : '缺失周留空;系统冻结与当前实时结果分开'} ) : null} {!points.some((p) => p.value !== null) ? ( diff --git a/web/src/qaAILocalDerivation.test.tsx b/web/src/qaAILocalDerivation.test.tsx new file mode 100644 index 0000000..855b776 --- /dev/null +++ b/web/src/qaAILocalDerivation.test.tsx @@ -0,0 +1,48 @@ +import { expect, it } from 'vitest' +import { renderToStaticMarkup } from 'react-dom/server' +import { parseAIEvidence } from './qaAITypes' +import { QAAIEvidenceView } from './QAAI' +const wire = { + id: 'fixture-local-proof', + record_id: 'fixture-record', + kind: 'evaluation', + state: 'succeeded', + stage: 'local_imported', + attempt: 1, + error_code: '', + skip_reason: '', + started_at: null, + updated_at: '2026-10-20T00:00:00Z', + input_hash: 'a'.repeat(64), + config_revision: 0, + prompt_version: 'qa-local-derivation-v1', + dictionary_version: 'qa-approved-labels-v1', + actual_model: 'local-rule-history-v1', + result: { + local_derivations: { + language: { value: '中文', kind: 'local_rule', reason: '原问题本地语言规则,不调用模型' }, + question_chinese: { value: 'MG400如何连接?', kind: 'original_chinese_copy', reason: '原始中文逐字保留' }, + product_category: { value: 'MG400', kind: 'unique_history_question_label', reason: '历史同问题标签唯一一致' }, + }, + }, + applied_fields: { language: '中文', question_chinese: 'MG400如何连接?', product_category: 'MG400' }, + skipped_fields: {}, +} +it('renders field-level local and history provenance without pretending it is model output', () => { + const result = parseAIEvidence(wire) + expect(result.result).toHaveProperty('local_derivations') + const html = renderToStaticMarkup() + for (const text of [ + '本地规则/历史复用(非模型)', + '原问题本地语言规则,不调用模型', + '原始中文逐字保留', + '历史同问题标签唯一一致', + '中文', + 'MG400', + ]) + expect(html).toContain(text) + expect(html).not.toContain('实际返回模型') +}) +it('rejects local provenance falsely attached to a GPT response', () => { + expect(() => parseAIEvidence({ ...wire, actual_model: 'gpt-6.1-sol' })).toThrow() +}) diff --git a/web/src/qaAITypes.ts b/web/src/qaAITypes.ts index bdb71c5..67dbe79 100644 --- a/web/src/qaAITypes.ts +++ b/web/src/qaAITypes.ts @@ -137,13 +137,22 @@ export interface AIFieldEvidence { reason: string quotes: AIQuote[] } +export interface AILocalDerivation { + value: string + kind: 'local_rule' | 'original_chinese_copy' | 'unique_history_question_label' + reason: string +} export interface AIEvidence extends AIWorkState { input_hash: string config_revision: number prompt_version: string dictionary_version: string actual_model: string - result: { fields?: Record; question_chinese?: string } + result: { + fields?: Record + question_chinese?: string + local_derivations?: Record + } applied_fields: Record skipped_fields: Record } @@ -231,6 +240,35 @@ export function parseAIEvidence(value: unknown): AIEvidence { }) ) } + if (r.local_derivations !== undefined) { + if (v.actual_model !== 'local-rule-history-v1') return bad() + const entries = Object.entries(aiObject(r.local_derivations)) + if (!entries.length || entries.length > 4) return bad() + result.local_derivations = Object.fromEntries( + entries.map(([field, raw]) => { + const proof = aiObject(raw), + value = text(proof.value), + reason = text(proof.reason) + const expected = + field === 'language' + ? 'local_rule' + : field === 'question_chinese' + ? 'original_chinese_copy' + : ['product_category', 'problem_type'].includes(field) + ? 'unique_history_question_label' + : null + if ( + !expected || + proof.kind !== expected || + !value.trim() || + !reason.trim() || + Object.keys(proof).some((k) => !['value', 'kind', 'reason'].includes(k)) + ) + return bad() + return [field, { value, kind: expected, reason } as AILocalDerivation] + }) + ) + } if (r.question_chinese !== undefined) result.question_chinese = text(r.question_chinese) const input_hash = text(v.input_hash) if (!/^[a-f0-9]{64}$/.test(input_hash)) return bad() diff --git a/web/src/qaCumulativeTrend.test.ts b/web/src/qaCumulativeTrend.test.ts new file mode 100644 index 0000000..41d48ce --- /dev/null +++ b/web/src/qaCumulativeTrend.test.ts @@ -0,0 +1,69 @@ +import { it, expect } from 'vitest' +import { parseQADashboard } from './qaDashboardData' +import { dashboardFixture } from './qaDashboard.fixture' +import { historicalTrend } from './qaHistoricalTrend' +it('rejects a closed-week cumulative point silently cut short before its required cutoff', () => { + const broken = structuredClone(live) + broken[1].cutoff_at = '2026-10-11T23:59:59+08:00' + expect(() => parseQADashboard({ ...dashboardFixture, cumulative_weeks: broken })).toThrow() +}) +const rates = (n: number, d: number) => ({ numerator: n, denominator: d, percent: d ? (100 * n) / d : null }) +const live = [ + { + week: '2026WK40', + week_start: '2026-09-28T00:00:00+08:00', + week_end: '2026-10-05T00:00:00+08:00', + cutoff_at: '2026-10-05T00:00:00+08:00', + calculated_at: '2026-10-18T10:00:00Z', + records: 2, + coverage: rates(1, 2), + correctness: rates(1, 2), + source: 'master_live_cumulative_v1', + policy_version: 'weekly-strict-yes-over-yes-no-v1', + }, + { + week: '2026WK41', + week_start: '2026-10-05T00:00:00+08:00', + week_end: '2026-10-12T00:00:00+08:00', + cutoff_at: '2026-10-12T00:00:00+08:00', + calculated_at: '2026-10-18T10:00:00Z', + records: 3, + coverage: rates(1, 3), + correctness: rates(2, 3), + source: 'master_live_cumulative_v1', + policy_version: 'weekly-strict-yes-over-yes-no-v1', + }, +] +it('prioritizes live cumulative weeks over an overlapping report without mutating historical evidence', () => { + const wire = { + ...dashboardFixture, + cumulative_weeks: live, + reported_weeks: [ + { + week: '2026WK40', + week_start: live[0].week_start, + week_end: live[0].week_end, + coverage_percent: 99, + correctness_percent: 99, + source: 'user_provided_history', + }, + ], + } + const before = JSON.stringify(wire), + parsed = parseQADashboard(wire) + expect(historicalTrend(parsed, false)[0].source).toBe('master_live_cumulative_v1') + expect(historicalTrend(parsed, false)[0].value).toBe(50) + expect(parsed.reported_weeks[0].coverage_percent).toBe(99) + expect(JSON.stringify(wire)).toBe(before) +}) +it('shows current cumulative counts instead of substituting old frozen-week values', () => { + const wire = { ...dashboardFixture, cumulative_weeks: live } + const before = JSON.stringify(wire) + const parsed = parseQADashboard(wire) + expect((parsed as unknown as { cumulative_weeks: unknown[] }).cumulative_weeks).toHaveLength(2) + expect(historicalTrend(parsed, false).map((p) => p.value)).toEqual([50, 100 / 3]) + expect(historicalTrend(parsed, true).map((p) => p.value)).toEqual([50, 200 / 3]) + expect(historicalTrend(parsed, true)[1].source).toBe('master_live_cumulative_v1') + expect(historicalTrend(parsed, true)[1].hint).toContain('2/3') + expect(JSON.stringify(wire)).toBe(before) +}) diff --git a/web/src/qaDashboardData.ts b/web/src/qaDashboardData.ts index 99361b8..94bfe6a 100644 --- a/web/src/qaDashboardData.ts +++ b/web/src/qaDashboardData.ts @@ -24,6 +24,18 @@ export interface DashboardFrozen { coverage: QualityRate correctness: QualityRate } +export interface DashboardCumulative { + week: string + week_start: string + week_end: string + cutoff_at: string + calculated_at: string + records: number + coverage: QualityRate + correctness: QualityRate + source: 'master_live_cumulative_v1' + policy_version: 'weekly-strict-yes-over-yes-no-v1' +} export interface DashboardRegion { id: string name: string @@ -51,6 +63,7 @@ export interface QADashboardData { regions: DashboardRegion[] frozen_weeks: DashboardFrozen[] reported_weeks: DashboardReported[] + cumulative_weeks?: DashboardCumulative[] } const bad = (): never => { throw new Error('统计看板响应无效,未展示可能失真的指标') @@ -233,6 +246,65 @@ export function parseQADashboard(value: unknown): QADashboardData { } }) if (reported_weeks.length > 5200) return bad() + const cumulative_weeks = list(v.cumulative_weeks === undefined ? [] : v.cumulative_weeks).map( + (raw, i): DashboardCumulative => { + const p = obj(raw), + begin = stamp(p.week_start), + finish = stamp(p.week_end), + cutoff = stamp(p.cutoff_at), + calculated = stamp(p.calculated_at), + records = count(p.records), + coverage = parseQualityRate(p.coverage), + correctness = parseQualityRate(p.correctness), + iso = currentQAWeek(new Date(begin)) + const previous = i ? obj(list(v.cumulative_weeks)[i - 1]) : null + if ( + i >= 4 || + Date.parse(begin) !== Date.parse('2026-09-28T00:00:00+08:00') + i * 7 * dayMS || + text(p.week) !== `${iso.year}WK${String(iso.week).padStart(2, '0')}` || + Date.parse(finish) - Date.parse(begin) !== 7 * dayMS || + Date.parse(cutoff) <= Date.parse(begin) || + Date.parse(cutoff) !== Math.min(Date.parse(finish), Date.parse(end), Date.parse(calculated)) || + p.source !== 'master_live_cumulative_v1' || + p.policy_version !== 'weekly-strict-yes-over-yes-no-v1' || + records > total_issues || + coverage.denominator > records || + correctness.denominator > records || + Object.keys(p).some( + (k) => + ![ + 'week', + 'week_start', + 'week_end', + 'cutoff_at', + 'calculated_at', + 'records', + 'coverage', + 'correctness', + 'source', + 'policy_version', + ].includes(k) + ) || + (previous && + (Date.parse(text(previous.cutoff_at)) !== Date.parse(text(previous.week_end)) || + records < count(previous.records) || + Date.parse(calculated) !== Date.parse(text(previous.calculated_at)))) + ) + return bad() + return { + week: text(p.week), + week_start: begin, + week_end: finish, + cutoff_at: cutoff, + calculated_at: calculated, + records, + coverage, + correctness, + source: 'master_live_cumulative_v1', + policy_version: 'weekly-strict-yes-over-yes-no-v1', + } + } + ) return { start, end, @@ -241,6 +313,7 @@ export function parseQADashboard(value: unknown): QADashboardData { week_start, month_start, reported_weeks, + cumulative_weeks, local_revision: count(v.local_revision), organization, total_issues, @@ -253,6 +326,18 @@ export function parseQADashboard(value: unknown): QADashboardData { frozen_weeks, } } +export function liveDashboardQuery(query: QAQuery, now: Date): QAQuery { + const last = currentQAWeek(new Date(Date.parse(query.end) - 1)), + current = currentQAWeek(now) + if ( + last.year !== current.year || + last.week !== current.week || + Date.parse(query.end) >= now.getTime() || + now.getTime() - Date.parse(query.start) > 90 * dayMS + ) + return query + return { ...query, end: now.toISOString() } +} export async function fetchQADashboard(query: QAQuery, signal?: AbortSignal): Promise { const response = await fetch('/api/v1/qa-ops/dashboard', { method: 'POST', diff --git a/web/src/qaDashboardLive.test.ts b/web/src/qaDashboardLive.test.ts new file mode 100644 index 0000000..8b5d3cd --- /dev/null +++ b/web/src/qaDashboardLive.test.ts @@ -0,0 +1,20 @@ +import { it, expect } from 'vitest' +import { liveDashboardQuery } from './qaDashboardData' +const query = { + start: '2026-10-19T00:00:00+08:00', + end: '2026-10-20T08:00:00+08:00', + keyword: 'needle', + cursor: '', + limit: 20, +} +it('advances current-week dashboard end on each refresh without mutating the executed filter', () => { + const next = liveDashboardQuery(query, new Date('2026-10-20T09:00:00+08:00')) + expect(next.end).toBe('2026-10-20T01:00:00.000Z') + expect(next.start).toBe(query.start) + expect(next.keyword).toBe(query.keyword) + expect(query.end).toBe('2026-10-20T08:00:00+08:00') +}) +it('never rolls an already closed selected week into a different week', () => { + const closed = { ...query, start: '2026-10-12T00:00:00+08:00', end: '2026-10-19T00:00:00+08:00' } + expect(liveDashboardQuery(closed, new Date('2026-10-20T09:00:00+08:00'))).toEqual(closed) +}) diff --git a/web/src/qaHistoricalTrend.ts b/web/src/qaHistoricalTrend.ts index 1c604cf..2b55305 100644 --- a/web/src/qaHistoricalTrend.ts +++ b/web/src/qaHistoricalTrend.ts @@ -5,14 +5,15 @@ export interface HistoricalPlotPoint { value: number | null hint: string frozen?: boolean - source?: 'user_provided_history' | 'system_frozen' + source?: 'user_provided_history' | 'system_frozen' | 'master_live_cumulative_v1' week?: string } // Never manufacture row counts or connect a line across missing weeks/policy changes. export function historicalTrend(data: QADashboardData, correctness: boolean): HistoricalPlotPoint[] { const frozen = new Map(data.frozen_weeks.map((p) => [Date.parse(p.week_start), p])) const reported = new Map(data.reported_weeks.map((p) => [Date.parse(p.week_start), p])) - const starts = [...frozen.keys(), ...reported.keys()] + const cumulative = new Map((data.cumulative_weeks ?? []).map((p) => [Date.parse(p.week_start), p])) + const starts = [...frozen.keys(), ...reported.keys(), ...cumulative.keys()] if (!starts.length) return [] const out: HistoricalPlotPoint[] = [] for (let at = Math.min(...starts); at < Date.parse(data.end) && out.length < 5200; at += 7 * 86400000) { @@ -20,6 +21,18 @@ export function historicalTrend(data: QADashboardData, correctness: boolean): Hi label = `${w.year}W${String(w.week).padStart(2, '0')}`, supplied = reported.get(at), point = frozen.get(at) + const live = cumulative.get(at) + if (live) { + const rate = correctness ? live.correctness : live.coverage + out.push({ + label, + week: live.week, + value: rate.percent, + source: 'master_live_cumulative_v1', + hint: `${live.week}:${rate.percent?.toFixed(2) ?? '—'}%;${rate.numerator}/${rate.denominator};总表累计 ${live.records} 条,截至 ${live.cutoff_at};当前有效字段动态重算,是÷(是+否),非历史冻结`, + }) + continue + } if (supplied) { const value = correctness ? supplied.correctness_percent : supplied.coverage_percent out.push({