import { afterEach, describe, expect, it, vi } from 'vitest' import { confirmReleaseChangeSet, createReleaseBatch, fetchLatestReleaseChangeSet, fetchReleaseAuditChain, generateReleaseChangeSet, fetchReleaseBatches, fetchReleaseCapabilities, fetchReleaseExecution, fetchReleaseExecutions, fetchReleasePlan, fetchReviewCandidates, parseReleaseBatchDetailResponse, parseReleaseBatchesResponse, parseReleaseCapabilitiesResponse, parseReleaseExecutionDetailResponse, parseReleaseExecutionsResponse, parseReleasePlanResponse, parseReviewCandidatesResponse, reviewPublication, sealReleaseBatch, } 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: '' }) 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', 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' }) 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 }) }) 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') }) })