import { afterEach, describe, expect, it, vi } from 'vitest' import { confirmReleaseChangeSet, createReleaseBatch, fetchLatestReleaseChangeSet, fetchReleaseAuditChain, generateReleaseChangeSet, fetchReleaseBatches, fetchReleaseCapabilities, fetchReleaseExecution, fetchReleaseExecutions, productionConfirmationPhrases, runProductionAction, fetchReleasePlan, fetchReviewCandidates, parseReleaseBatchDetailResponse, parseReleaseBatchesResponse, parseReleaseCapabilitiesResponse, parseReleaseExecutionDetailResponse, parseReleaseExecutionsResponse, parseReleasePlanResponse, parseReviewCandidatesResponse, reviewPublication, sealReleaseBatch, reviewPublicationsBatch, runPublishNow, } from './reviewRelease' afterEach(() => vi.unstubAllGlobals()) const candidate = { publication_id: 'tp-safe', title: 'Synthetic', source_type: 'manual', current_visibility: 'internal', knowledge_exists: 'passed', chunks_present: 'passed', retrieval_hit: 'manual_required', gate_status: 'ready', gate_code: 'ready', review_state: 'pending', decided_visibility: '', decision_code: '', reviewer_ref: '', reviewed_at: null, updated_at: '2026-09-06T10:00:00Z', acceptance_run_id: 'must-drop', knowledge_id: 'must-drop', } const batch = { id: 'rb-safe', name: 'Batch', state: 'draft', policy_version: 'release-gate-v1', created_by: 'engineer-1', sealed_by: '', item_count: 1, created_at: '2026-09-06T10:00:00Z', sealed_at: null, acceptance_run_id: 'must-drop', } describe('review and batch response parsing', () => { it('strictly rebuilds the source-truth release plan', () => { const plan = parseReleasePlanResponse({ data: { items: [ { publication_id: 'tp-safe', title: 'B.pdf', target_scope: 'external', action: 'add', test_state: 'ready', production_state: 'absent', can_release: true, blocker: '', production_revision: 'must-drop', }, ], summary: { add: 1, update: 0, delete: 0, blocked: 0, unchanged: 10 }, }, }) expect(plan.summary).toEqual({ add: 1, update: 0, delete: 0, blocked: 0, unchanged: 10 }) expect(plan.items[0]).toEqual({ publication_id: 'tp-safe', title: 'B.pdf', target_scope: 'external', action: 'add', test_state: 'ready', production_state: 'absent', can_release: true, blocker: '', }) expect(plan.items[0]).not.toHaveProperty('production_revision') }) it('strictly rebuilds safe review candidates', () => { const page = parseReviewCandidatesResponse({ data: [candidate], total: 1, limit: 20, offset: 0 }) expect(page).toEqual({ items: [ { publication_id: 'tp-safe', title: 'Synthetic', source_type: 'manual', current_visibility: 'internal', knowledge_exists: 'passed', chunks_present: 'passed', retrieval_hit: 'manual_required', gate_status: 'ready', gate_code: 'ready', review_state: 'pending', decided_visibility: '', decision_code: '', reviewer_ref: '', reviewed_at: null, updated_at: '2026-09-06T10:00:00Z', }, ], total: 1, limit: 20, offset: 0, }) expect(page.items[0]).not.toHaveProperty('acceptance_run_id') expect(page.items[0]).not.toHaveProperty('knowledge_id') }) it('strictly rebuilds safe batch list and detail', () => { expect(parseReleaseBatchesResponse({ data: [batch], total: 1, limit: 20, offset: 0 }).items[0]).toEqual({ id: 'rb-safe', name: 'Batch', state: 'draft', policy_version: 'release-gate-v1', created_by: 'engineer-1', sealed_by: '', item_count: 1, created_at: '2026-09-06T10:00:00Z', sealed_at: null, }) expect( parseReleaseBatchDetailResponse({ data: { ...batch, items: [ { publication_id: 'tp-safe', title: 'Synthetic', decided_visibility: 'internal', action: 'delete', publication_updated_at: 'must-drop', }, ], }, }).items ).toEqual([{ publication_id: 'tp-safe', title: 'Synthetic', decided_visibility: 'internal', action: 'delete' }]) }) }) describe('review and batch requests', () => { it('uses fixed scoped endpoints and explicit JSON fields', async () => { const fetchMock = vi .fn() .mockResolvedValueOnce( new Response(JSON.stringify({ data: [candidate], total: 1, limit: 20, offset: 0 }), { status: 200 }) ) .mockResolvedValueOnce( new Response( JSON.stringify({ data: { id: 'rv-safe', publication_id: 'tp-safe', decision: 'approved', decided_visibility: 'internal', reviewer_ref: 'engineer-1', decision_code: 'approved_for_release', created_at: '2026-09-06T10:01:00Z', }, }), { status: 201 } ) ) .mockResolvedValueOnce(new Response(JSON.stringify({ data: batch }), { status: 201 })) .mockResolvedValueOnce( new Response( JSON.stringify({ data: { ...batch, state: 'sealed', sealed_by: 'engineer-2', sealed_at: '2026-09-06T10:02:00Z' }, }), { status: 200 } ) ) .mockResolvedValueOnce( new Response(JSON.stringify({ data: [batch], total: 1, limit: 20, offset: 0 }), { status: 200 }) ) vi.stubGlobal('fetch', fetchMock) await fetchReviewCandidates('pending') await reviewPublication('tp-safe', 'approved', 'internal', 'approved_for_release') await createReleaseBatch('Batch', ['tp-safe'], ['tp-delete']) await sealReleaseBatch('rb-safe') await fetchReleaseBatches('draft') expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/review-candidates?review_state=pending&limit=20&offset=0') expect(fetchMock.mock.calls[1][0]).toBe('/api/v1/review-candidates/tp-safe/decision') // actor fields are server-stamped from the session; bodies must not carry them // P0: the browser must never name the actor again; the server stamps it. expect(JSON.parse((fetchMock.mock.calls[1][1] as RequestInit).body as string)).toEqual({ decision: 'approved', decided_visibility: 'internal', decision_code: 'approved_for_release', }) expect(fetchMock.mock.calls[2][0]).toBe('/api/v1/release-batches') expect(JSON.parse((fetchMock.mock.calls[2][1] as RequestInit).body as string)).toEqual({ name: 'Batch', publication_ids: ['tp-safe'], delete_publication_ids: ['tp-delete'], release_change_set_id: '', seal: false, }) expect(fetchMock.mock.calls[3][0]).toBe('/api/v1/release-batches/rb-safe/seal') expect(fetchMock.mock.calls[4][0]).toBe('/api/v1/release-batches?state=draft&limit=20&offset=0') }) }) describe('release execution audit parsing', () => { const execution = { id: 'rx-safe', release_batch_id: 'rb-safe', operation: 'publish', prior_execution_id: '', state: 'completed', target_environment: 'production', authorized_by: 'owner', job_id: 'job-safe', item_count: 105, batch_size: 50, current_batch: 2, total_batches: 3, completed_item_count: 1, failed_item_count: 0, error_code: '', created_at: '2026-09-06T10:00:00Z', started_at: '2026-09-06T10:01:00Z', completed_at: '2026-09-06T10:02:00Z', authorization_code: 'must-drop', manifest_sha256: 'must-drop', knowledge_id: 'must-drop', } it('strictly rebuilds execution and capability responses', () => { const page = parseReleaseExecutionsResponse({ data: [execution], total: 1, limit: 20, offset: 0 }) expect(page.items[0]).toMatchObject({ batch_size: 50, current_batch: 2, total_batches: 3 }) expect(page.items[0]).not.toHaveProperty('authorization_code') expect(page.items[0]).not.toHaveProperty('manifest_sha256') const detail = parseReleaseExecutionDetailResponse({ data: { ...execution, items: [ { publication_id: 'tp-safe', title: 'Synthetic', action: 'delete', state: 'verified', previous_production_revision: 'prod-v0', production_revision: 'absent', error_code: '', created_at: '2026-09-06T10:00:00Z', completed_at: '2026-09-06T10:02:00Z', target_knowledge_base_id: 'kb-target-1', knowledge_id: 'must-drop', }, ], }, }) expect(detail.items[0]).toEqual({ publication_id: 'tp-safe', title: 'Synthetic', action: 'delete', state: 'verified', previous_production_revision: 'prod-v0', production_revision: 'absent', error_code: '', created_at: '2026-09-06T10:00:00Z', completed_at: '2026-09-06T10:02:00Z', target_knowledge_base_id: 'kb-target-1', }) expect( parseReleaseCapabilitiesResponse({ data: { production_release_requests_enabled: true, production_backup_restore_verified: false, secret: 'drop' }, }) ).toEqual({ production_release_requests_enabled: true, production_backup_restore_verified: false, test_auto_review_policy: '', }) }) it('rejects a release item execution the API forgot to describe', () => { // 线上 DTO 曾漏 action:一条明细不合法就让整个明细区报 invalid release item execution。 const missingAction = { publication_id: 'tp-safe', title: 'Synthetic', state: 'verified', previous_production_revision: 'prod-v0', production_revision: 'absent', error_code: '', created_at: '2026-09-06T10:00:00Z', completed_at: null, } expect(() => parseReleaseExecutionDetailResponse({ data: { ...execution, items: [missingAction] } })).toThrow( 'invalid release item execution' ) }) it('fetches only read-only execution audit endpoints', async () => { const fetchMock = vi .fn() .mockResolvedValueOnce( new Response(JSON.stringify({ data: [execution], total: 1, limit: 20, offset: 0 }), { status: 200 }) ) .mockResolvedValueOnce(new Response(JSON.stringify({ data: { ...execution, items: [] } }), { status: 200 })) .mockResolvedValueOnce( new Response( JSON.stringify({ data: { production_release_requests_enabled: false, production_backup_restore_verified: false }, }), { status: 200 } ) ) vi.stubGlobal('fetch', fetchMock) await fetchReleaseExecutions('publish', 'completed') await fetchReleaseExecution('rx-safe') await fetchReleaseCapabilities() expect(fetchMock.mock.calls.map((call) => call[0])).toEqual([ '/api/v1/release-executions?operation=publish&state=completed&limit=20&offset=0', '/api/v1/release-executions/rx-safe', '/api/v1/release-capabilities', ]) expect(fetchMock.mock.calls.every((call) => !call[1] || (call[1] as RequestInit).method === undefined)).toBe(true) }) it('fetches the source-truth release plan from its fixed endpoint', async () => { const fetchMock = vi .fn() .mockResolvedValue( new Response( JSON.stringify({ data: { items: [], summary: { add: 0, update: 0, delete: 0, blocked: 0, unchanged: 0 } } }), { status: 200 } ) ) vi.stubGlobal('fetch', fetchMock) await fetchReleasePlan() expect(fetchMock).toHaveBeenCalledWith( '/api/v1/release-plan', expect.objectContaining({ headers: { Accept: 'application/json' } }) ) }) }) describe('release change set (R1)', () => { const changeSetPayload = { id: 'rcs-1', number: 1, name: '9月发布', state: 'planned', source_snapshot_ids: ['snap-a'], source_change_set_ids: [], acceptance_cutoff: '2026-09-11T21:00:00Z', production_baseline_ref: '', item_count: 1, add_count: 1, update_count: 0, delete_count: 0, blocked_count: 0, manifest_sha256: 'a'.repeat(64), created_by: 'engineer-1', created_at: '2026-09-12T07:00:00Z', confirmed_by: '', confirmed_at: null, } it('generates with idempotency and rejects a manifest-less envelope', async () => { const fetchMock = vi .fn() .mockResolvedValue( new Response(JSON.stringify({ data: changeSetPayload, operation: 'created' }), { status: 201 }) ) vi.stubGlobal('fetch', fetchMock) const set = await generateReleaseChangeSet('9月发布') expect(set.id).toBe('rcs-1') expect(set.manifest_sha256).toBe('a'.repeat(64)) const [, init] = fetchMock.mock.calls[0] as [string, RequestInit] expect(init.headers).toMatchObject({ 'Idempotency-Key': expect.any(String) }) expect(init.body as string).toContain('"name":"9月发布"') const bad = vi .fn() .mockResolvedValue( new Response(JSON.stringify({ data: { ...changeSetPayload, manifest_sha256: '' } }), { status: 201 }) ) vi.stubGlobal('fetch', bad) await expect(generateReleaseChangeSet('x')).rejects.toThrow('发布计划集响应缺少标识或清单摘要') }) it('confirms via scoped endpoint and loads latest detail tolerating 404', async () => { const confirmMock = vi .fn() .mockResolvedValue( new Response( JSON.stringify({ data: { ...changeSetPayload, state: 'confirmed', confirmed_by: 'boss', confirmed_at: '2026-09-12T08:00:00Z', }, operation: 'created', }), { status: 200 } ) ) vi.stubGlobal('fetch', confirmMock) const confirmed = await confirmReleaseChangeSet('rcs-1') expect(confirmed.state).toBe('confirmed') expect(confirmMock.mock.calls[0][0]).toBe('/api/v1/release-change-sets/rcs-1/confirm') const latest404 = vi.fn().mockResolvedValue(new Response('{}', { status: 404 })) vi.stubGlobal('fetch', latest404) expect(await fetchLatestReleaseChangeSet()).toBeNull() const detailMock = vi.fn().mockResolvedValue( new Response( JSON.stringify({ data: { ...changeSetPayload, items: [ { seq: 1, publication_id: 'tp-keep', title: '手册', target_scope: 'internal', action: 'add', test_state: 'ready', production_state: 'absent', can_release: true, blocker: '', }, { seq: 2, publication_id: 'x', title: '', target_scope: 'bogus', action: 'nope', test_state: '', production_state: '', can_release: false, blocker: '', }, ], }, }), { status: 200 } ) ) vi.stubGlobal('fetch', detailMock) const detail = await fetchLatestReleaseChangeSet() expect(detail?.items.length).toBe(1) expect(detail?.items[0].publication_id).toBe('tp-keep') }) }) describe('release audit chain (R6)', () => { const chain = { execution_id: 'rx-1', operation: 'publish', state: 'completed', failure_level: '', release_batch_id: 'rb-1', release_batch_name: '9月批次', created_by: 'e1', sealed_by: 'e2', authorized_by: 'own', release_change_set_id: 'rcs-1', release_change_set_name: '9月发布', release_change_set_state: 'confirmed', release_change_set_created_by: 'e1', release_change_set_confirmed_by: 'boss', release_change_set_confirmed_at: '2026-09-12T08:00:00Z', manifest_sha256: 'a'.repeat(64), snapshots: [ { id: 'snap-1', source_name: 'PP', node_count: 66, file_count: 621, observed_at: '2026-09-11T00:00:00Z' }, ], catalog_change_sets: [ { id: 'cs-1', state: 'applied', add_count: 2, update_count: 1, move_count: 0, delete_count: 0 }, ], prior_execution_id: '', rollback_execution_id: '', items: [ { publication_id: 'tp-1', title: '手册.pdf', action: 'upsert', item_state: 'verified', review_id: 'rev-1', acceptance_run_id: 'run-1', source_item_id: 'si-1', source_item_version_id: 'siv-1', production_revision: 'v1', error_code: '', }, ], } it('loads the chain and returns null on 404', async () => { const ok = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: chain }), { status: 200 })) vi.stubGlobal('fetch', ok) const result = await fetchReleaseAuditChain('rx-1') expect(result?.release_batch_name).toBe('9月批次') expect(result?.snapshots[0].file_count).toBe(621) expect(result?.items[0].publication_id).toBe('tp-1') expect(ok.mock.calls[0][0]).toBe('/api/v1/release-executions/rx-1/audit-chain') const missing = vi.fn().mockResolvedValue(new Response('{}', { status: 404 })) vi.stubGlobal('fetch', missing) expect(await fetchReleaseAuditChain('rx-x')).toBeNull() const bad = vi.fn().mockResolvedValue(new Response('{}', { status: 500 })) vi.stubGlobal('fetch', bad) await expect(fetchReleaseAuditChain('rx-1')).rejects.toThrow('HTTP 500') }) }) // 生产动作:三条路径 + 服务端原因回传(页面通道 = 管理员会话 + 固定确认语句)。 describe('production actions', () => { it('routes each action to its endpoint with the fixed phrase and an idempotency key', async () => { const fetchMock = vi .fn() .mockImplementation(() => Promise.resolve( new Response( JSON.stringify({ data: { id: 'rx-1', state: 'pending', operation: 'publish', item_count: 1 } }), { status: 202 } ) ) ) vi.stubGlobal('fetch', fetchMock) await expect(runProductionAction('authorize', 'rb-1', 'publish-to-production')).resolves.toEqual({ id: 'rx-1', state: 'pending', operation: 'publish', item_count: 1, }) await runProductionAction('retry', 'rx-1', 'retry-production-release') await runProductionAction('rollback', 'rx-1', 'rollback-production-release') const urls = fetchMock.mock.calls.map((call) => call[0]) expect(urls).toEqual([ '/api/v1/release-batches/rb-1/authorize-production', '/api/v1/release-executions/rx-1/retry', '/api/v1/release-executions/rx-1/authorize-rollback', ]) expect(fetchMock.mock.calls[0][1].headers['Idempotency-Key']).toBeTruthy() vi.unstubAllGlobals() }) it('surfaces the server reason and keeps the phrases fixed', async () => { vi.stubGlobal( 'fetch', vi .fn() .mockResolvedValue( new Response(JSON.stringify({ error: 'production release authorization required' }), { status: 401 }) ) ) await expect(runProductionAction('authorize', 'rb-1', 'publish-to-production')).rejects.toThrow( 'production release authorization required' ) expect(productionConfirmationPhrases).toEqual({ authorize: 'publish-to-production', retry: 'retry-production-release', rollback: 'rollback-production-release', publish_now: 'publish-to-production', }) vi.unstubAllGlobals() }) }) describe('建批失败时把服务端原因带出来', () => { it('覆盖清单不足时给出下一步(生成新版本 + 确认冻结)', async () => { const fetchMock = vi.fn().mockResolvedValue({ ok: false, status: 422, json: async () => ({ error: 'release change set must be confirmed and cover every requested publication' }), }) vi.stubGlobal('fetch', fetchMock) await expect(createReleaseBatch('验收12', ['tp-x'], [], 'rcs-x')).rejects.toThrow( '请先点「生成新版本」再「确认冻结(此后不可更改)」' ) }) it('未知原因原样带出,不再只给状态码', async () => { const fetchMock = vi .fn() .mockResolvedValue({ ok: false, status: 500, json: async () => ({ error: 'could not create release batch' }) }) vi.stubGlobal('fetch', fetchMock) await expect(createReleaseBatch('验收12', ['tp-x'], [], '')).rejects.toThrow('could not create release batch') }) }) describe('审核策略的只读展示', () => { it('服务端返回策略时解析出来', () => { const parsed = parseReleaseCapabilitiesResponse({ data: { production_release_requests_enabled: true, production_backup_restore_verified: true, test_auto_review_policy: 'internal', }, }) expect(parsed.test_auto_review_policy).toBe('internal') }) it('旧服务端不返回策略时不报错', () => { const parsed = parseReleaseCapabilitiesResponse({ data: { production_release_requests_enabled: false, production_backup_restore_verified: false }, }) expect(parsed.test_auto_review_policy).toBe('') }) }) describe('批量审核与建批即锁定', () => { it('批量审核发送选中的条目与同一决定', async () => { const fetchMock = vi .fn() .mockResolvedValue({ ok: true, json: async () => ({ data: { selected: 2, decided: 2, skipped: 0, skipped_ids: [], reviews: [] } }), }) vi.stubGlobal('fetch', fetchMock) const result = await reviewPublicationsBatch(['tp-a', 'tp-b'], 'approved', 'internal', 'approved_for_release') expect(result).toEqual({ selected: 2, decided: 2, skipped: 0, skipped_ids: [] }) const [url, init] = fetchMock.mock.calls[0] expect(url).toBe('/api/v1/review-candidates/batch-decision') expect(JSON.parse(String(init.body))).toEqual({ publication_ids: ['tp-a', 'tp-b'], decision: 'approved', decided_visibility: 'internal', decision_code: 'approved_for_release', }) }) it('如实回报被跳过的条目', async () => { const fetchMock = vi .fn() .mockResolvedValue({ ok: true, json: async () => ({ data: { selected: 3, decided: 2, skipped: 1, skipped_ids: ['tp-c'], reviews: [] } }), }) vi.stubGlobal('fetch', fetchMock) const result = await reviewPublicationsBatch( ['tp-a', 'tp-b', 'tp-c'], 'approved', 'internal', 'approved_for_release' ) expect(result.skipped).toBe(1) expect(result.skipped_ids).toEqual(['tp-c']) }) it('建批要求服务端立即冻结并锁定', async () => { // 只断言请求体:响应形状由 parseBatchEnvelope 自己的用例覆盖。 const fetchMock = vi.fn().mockResolvedValue({ ok: false, status: 500, json: async () => ({ error: 'boom' }) }) vi.stubGlobal('fetch', fetchMock) await expect(createReleaseBatch('批次', ['tp-a'], [], '', true)).rejects.toThrow() const [, init] = fetchMock.mock.calls[0] expect(JSON.parse(String(init.body)).seal).toBe(true) expect(JSON.parse(String(init.body)).release_change_set_id).toBe('') }) }) describe('发布到生产(建批+锁定+授权合成一个动作)', () => { it('提交条目与固定确认语句,回传批次与执行', async () => { const fetchMock = vi .fn() .mockResolvedValue({ ok: true, json: async () => ({ data: { batch: { id: 'rb-now', name: '立即发布 · 2026/10/10' }, execution: { id: 'rx-now' } }, }), }) vi.stubGlobal('fetch', fetchMock) const result = await runPublishNow(['tp-a', 'tp-b'], [], '立即发布 · 2026/10/10', 'publish-to-production') expect(result).toEqual({ batch_id: 'rb-now', batch_name: '立即发布 · 2026/10/10', execution_id: 'rx-now' }) const [url, init] = fetchMock.mock.calls[0] expect(url).toBe('/api/v1/release-batches/publish-now') expect(JSON.parse(String(init.body))).toEqual({ publication_ids: ['tp-a', 'tp-b'], delete_publication_ids: [], name: '立即发布 · 2026/10/10', confirmation: 'publish-to-production', }) }) it('服务端拒绝时把原因带出来', async () => { const fetchMock = vi .fn() .mockResolvedValue({ ok: false, status: 412, json: async () => ({ error: 'production backup restore verification is required' }), }) vi.stubGlobal('fetch', fetchMock) await expect(runPublishNow(['tp-a'], [], 'x', 'publish-to-production')).rejects.toThrow( 'production backup restore verification is required' ) }) })