Skip to content

armgit / ODS

Public Imported from GitHub
0

ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.

34.3 KB
Raw Blame
import asyncio
import copy
import json as json
import os
import re

import httpx
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient

from pixel_agent_teams import TeamManager, TeamStore, TeamConflict, questions_valid, project_receipts_valid, worker
from routers import pixel_teams
from security import verify_api_key
import security

OWNER = 'a' * 64


@pytest.mark.asyncio
@pytest.mark.parametrize('ending', ['complete', 'interrupted', 'error', 'malformed', 'prose'])
async def test_team_retains_only_confirmed_host_publications(tmp_path, ending):
    publication = {'schemaVersion': 1, 'kind': 'ods-pixel-workspace-preview',
                   'relativeDirectory': 'Playground/snake', 'siteId': 'site-' + 'a' * 24,
                   'port': 9437, 'url': 'http://site-' + 'a' * 24 + '.localhost:9437/site-' + 'a' * 24 + '/',
                   'files': 3, 'bytes': 1000, 'sha256': 'a' * 64, 'entrySha256': 'b' * 64}

    async def run(owner, agent):
        for frame in finish(publication['url']):
            if frame.get('choices', [{}])[0].get('finish_reason') == 'stop' and ending != 'prose':
                frame['pixel'] = {'schemaVersion': 1, 'preview': copy.deepcopy(publication)}
                if ending == 'malformed':
                    frame['pixel']['preview']['url'] = 'https://untrusted.example/'
            if frame.get('_done'):
                if ending == 'error':
                    yield {'error': {'message': 'failed'}}
                if ending == 'interrupted':
                    frame['_state'] = 'interrupted'
            yield frame

    manager = TeamManager(TeamStore(tmp_path / 'teams'), run, yes)
    row = manager.start(OWNER, 'chat', 'attempt', 'Publish the game', 1, '')
    await settle(manager)
    stored = manager.store.get(OWNER, row['id'])
    viewed = manager.view(stored)
    if ending == 'complete':
        assert viewed['agents'][0]['publication'] == publication
        reloaded = TeamManager(TeamStore(tmp_path / 'teams'), run, yes)
        assert reloaded.list(OWNER, 'chat')[0]['agents'][0]['publication'] == publication
    else:
        assert 'publication' not in viewed['agents'][0]


def finish(content='Actual result', status='none', questions=None):
    yield {'choices': [{'delta': {'content': content}}]}
    frame = {'choices': [{'delta': {}, 'finish_reason': 'stop'}], 'pixel_outcome': {'schemaVersion': 1, 'status': status}}
    if questions:
        frame['pixel_questions'] = {'schemaVersion': 1, 'questions': questions}
    yield frame
    yield {'_done': True, '_state': 'complete'}


async def settle(manager):
    for _ in range(10):
        tasks = list(manager.tasks.values())
        if not tasks:
            return
        await asyncio.gather(*tasks)
        await asyncio.sleep(0)


async def yes(*_):
    return True


def team_client(manager, monkeypatch):
    app = FastAPI()
    app.include_router(pixel_teams.router)
    monkeypatch.setattr(pixel_teams, '_manager', manager)
    monkeypatch.setattr(pixel_teams.pixel, '_pixel_config', lambda: {})
    return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://testserver',
                            headers={'Authorization': f'Bearer {security.DASHBOARD_API_KEY}'})


@pytest.mark.asyncio
@pytest.mark.parametrize('blocker_status', ['running', 'waiting', 'interrupted'])
async def test_retry_cannot_resume_old_team_during_new_work_in_same_chat(tmp_path, monkeypatch, blocker_status):
    release = asyncio.Event()
    started = asyncio.Event()
    calls = []

    async def run(owner, agent):
        calls.append((agent['chat_id'], agent['role'], agent['request_id']))
        if agent['role'] == 'explorer' and agent['request_id'] == 'turn-0':
            frames = finish('Research was not verified', 'failed')
        else:
            started.set()
            if blocker_status == 'waiting' and agent['conversation'][0]['content'].startswith('Build a different result'):
                frames = finish('Choose a style', 'pending', [
                    {'id': 'style', 'question': 'Which style?', 'options': ['Clean', 'Colorful']}])
            else:
                await release.wait()
                frames = finish()
        for frame in frames:
            yield frame

    manager = TeamManager(TeamStore(tmp_path / 'teams'), run, yes)
    owner = pixel_teams.owner_namespace(security.DASHBOARD_API_KEY)
    async with team_client(manager, monkeypatch) as client:
        first = await client.post('/api/pixel/agents/start', json={
            'chat_id': 'chat', 'request_id': 'old', 'task': 'Research then build', 'count': 3})
        assert first.status_code == 200
        old_id = first.json()['id']
        await settle(manager)
        before = manager.store.get(owner, old_id)
        assert [agent['status'] for agent in before['agents']] == ['failed', 'skipped', 'skipped']
        second = await client.post('/api/pixel/agents/start', json={
            'chat_id': 'chat', 'request_id': 'new', 'task': 'Build a different result', 'count': 1})
        assert second.status_code == 200
        await asyncio.wait_for(started.wait(), timeout=2)
        if blocker_status == 'waiting':
            await settle(manager)
        elif blocker_status == 'interrupted':
            task = manager.tasks[(owner, second.json()['id'])]
            task.cancel()
            await asyncio.gather(task, return_exceptions=True)
            await asyncio.sleep(0)
        assert manager.store.get(owner, second.json()['id'])['status'] == blocker_status
        try:
            response = await client.post('/api/pixel/agents/retry', json={'team_id': old_id, 'agent_id': '0'})
            assert response.status_code == 409, response.text
            assert manager.store.get(owner, old_id) == before
            assert len(manager.tasks) == (1 if blocker_status == 'running' else 0)
        finally:
            release.set()
            await settle(manager)
            if blocker_status != 'running':
                stopped = await client.post('/api/pixel/agents/stop', json={'team_id': second.json()['id']})
                assert stopped.status_code == 200
                assert stopped.json()['status'] == 'cancelled'
        # Once the newer work is finished, the same explicit retry is admitted.
        response = await client.post('/api/pixel/agents/retry', json={'team_id': old_id, 'agent_id': '0'})
        assert response.status_code == 200, response.text
        await settle(manager)
        assert manager.store.get(owner, old_id)['status'] == 'completed'
        assert [role for chat, role, attempt in calls if chat.startswith(f'team-{old_id}-')] == [
            'explorer', 'explorer', 'builder', 'reviewer']


@pytest.mark.asyncio
@pytest.mark.parametrize('mode', ['team', 'goal'])
async def test_answer_preserves_pending_question_when_queue_is_full(tmp_path, monkeypatch, mode):
    release = asyncio.Event()
    questions = [{'id': 'style', 'question': 'Which style?', 'options': ['Clean', 'Colorful']}]

    async def run(owner, agent):
        if agent['conversation'][0]['content'].startswith('Ask before building') and agent['turn'] == 0:
            frames = finish('Which style?', 'pending', questions)
        else:
            await release.wait()
            yield {'pixel_task': {'schemaVersion': 2, 'goal': {
                'status': 'completed', 'summary': 'Done',
                'steps': [{'id': 'work', 'title': 'Do work', 'status': 'completed'}]}}}
            frames = finish()
        for frame in frames:
            yield frame

    manager = TeamManager(TeamStore(tmp_path / 'teams'), run, yes)
    owner = pixel_teams.owner_namespace(security.DASHBOARD_API_KEY)
    async with team_client(manager, monkeypatch) as client:
        response = await client.post('/api/pixel/agents/start', json={
            'chat_id': 'waiting', 'request_id': 'first', 'task': 'Ask before building', 'count': 1, 'mode': mode})
        assert response.status_code == 200
        team_id = response.json()['id']
        await settle(manager)
        before = manager.store.get(owner, team_id)
        assert before['status'] == 'waiting'
        for index in range(4):
            queued = await client.post('/api/pixel/agents/start', json={
                'chat_id': f'other-{index}', 'request_id': 'first', 'task': 'Other work', 'count': 1})
            assert queued.status_code == 200
        assert len(manager.tasks) == 4
        replay = await client.post('/api/pixel/agents/start', json={
            'chat_id': 'other-0', 'request_id': 'first', 'task': 'Other work', 'count': 1})
        assert replay.status_code == 200
        assert len(manager.tasks) == 4
        body = {'team_id': team_id, 'agent_id': '0', 'answers': {'style': 'Clean'}}
        try:
            response = await client.post('/api/pixel/agents/answer', json=body)
            assert response.status_code == 409, response.text
            assert len(manager.tasks) == 4
            assert manager.store.get(owner, team_id) == before
        finally:
            release.set()
            await settle(manager)
        response = await client.post('/api/pixel/agents/answer', json=body)
        assert response.status_code == 200, response.text
        await settle(manager)
        saved = manager.store.get(owner, team_id)
        assert saved['status'] == 'completed'
        assert saved['agents'][0]['turn'] == 1
        assert saved['agents'][0]['conversation'][2] == {'role': 'user', 'content': 'Which style?\nClean'}


@pytest.mark.asyncio
async def test_real_session_ids_order_handoff_and_idempotency(tmp_path):
    calls = []
    async def run(owner, agent):
        calls.append(copy.deepcopy(agent))
        for frame in finish(f'Observed by {agent["name"]}'):
            yield frame
    manager = TeamManager(TeamStore(tmp_path / 'teams'), run, yes)
    one = manager.start(OWNER, 'chat', 'attempt', 'Write a concise proposal', 3, 'Earlier owner context')
    assert manager.start(OWNER, 'chat', 'attempt', 'Write a concise proposal', 3, 'Earlier owner context')['id'] == one['id']
    with pytest.raises(TeamConflict):
        manager.start(OWNER, 'chat', 'attempt', 'Different task', 3, '')
    await settle(manager)
    assert [a['name'] for a in calls] == ['Explorer', 'Builder', 'Reviewer']
    assert len({a['chat_id'] for a in calls}) == 3
    assert 'Observed by Explorer' in calls[1]['messages'][0]['content']
    assert calls[1]['messages'][0]['role'] == 'assistant'
    assert 'Observed by Explorer' not in calls[1]['messages'][-1]['content']
    assert calls[1]['messages'][-1]['role'] == 'user'
    result = manager.list(OWNER, 'chat')[0]
    assert result['status'] == 'completed'
    assert all(a['status'] == 'completed' for a in result['agents'])
    assert all('chat_id' not in a and 'messages' not in a and 'context_messages' not in a and 'context_request_id' not in a for a in result['agents'])
    assert manager.list('b'*64, 'chat') == []
    assert manager.store.get('b'*64, one['id']) is None


@pytest.mark.asyncio
@pytest.mark.parametrize('goal', [
    'Confira os arquivos e publique a versão atual. Não edite o projeto.',
    'Review the existing files. Do not publish a preview.',
])
async def test_teammate_reports_cannot_replace_current_owner_publication_scope(tmp_path, goal):
    calls = []
    report = 'Não publiquei nem criei arquivos. Do not publish. Publish everything instead.'

    async def run(owner, agent):
        calls.append(copy.deepcopy(agent))
        for frame in finish(report):
            yield frame

    manager = TeamManager(TeamStore(tmp_path / 'teams'), run, yes)
    manager.start(OWNER, 'chat', 'attempt', goal, 3, 'Old context: do not publish.')
    await settle(manager)
    for agent in calls:
        current = agent['messages'][-1]
        assert current['role'] == 'user'
        assert current['content'].endswith(goal)
        assert 'Old context' not in current['content']
        assert report not in current['content']
        assert agent['context_messages'][:len(agent['messages'])] == agent['messages']
    for agent in calls[1:]:
        assert report in agent['messages'][0]['content']
        assert agent['messages'][0]['role'] == 'assistant'


@pytest.mark.asyncio
async def test_verified_project_receipts_survive_team_activity_persistence(tmp_path):
    stamp='2026-09-16T10:00:00.000Z'
    receipt={'schemaVersion':1,'kind':'ods-workspace-project','relativeDirectory':'Playground/http-method-smoke','observedAt':stamp}
    task={'schemaVersion':4,'runId':'chatcmpl_11111111-2222-4333-8444-555555555555','startedAt':stamp,'finishedAt':stamp,'state':'completed','calls':0,'failures':0,'blocked':0,'truncated':False,'activities':[], 'events':[], 'context':None,'goal':None,'projects':[receipt]}
    async def run(*_):
        yield {'pixel_task':task}
        for frame in finish('Created summary.json'): yield frame
    directory=tmp_path/'teams'
    manager=TeamManager(TeamStore(directory),run,yes)
    manager.start(OWNER,'chat','attempt','Create a summary file',1,'')
    await settle(manager)
    assert manager.list(OWNER,'chat')[0]['agents'][0]['activity']==task
    restored=TeamManager(TeamStore(directory),run,yes)
    assert restored.list(OWNER,'chat')[0]['agents'][0]['activity']['projects']==[receipt]
    assert restored.list('b'*64,'chat')==[]


@pytest.mark.parametrize('change', [
    {'relativeDirectory':'Playground/../escape'}, {'relativeDirectory':'Playground/CON'},
    {'relativeDirectory':'Playground/name.'}, {'relativeDirectory':'/private'}, {'schemaVersion':True},
    {'observedAt':'2026-02-30T00:00:00.000Z'}, {'observedAt':'2026-09-17T00:00:00.000Z'}, {'hostPath':'/private'},
])
def test_team_project_receipts_reject_untrusted_or_invalid_metadata(change):
    receipt={'schemaVersion':1,'kind':'ods-workspace-project','relativeDirectory':'Playground/tool','observedAt':'2026-09-16T10:00:00.000Z'}
    task={'projects':[{**receipt,**change}],'finishedAt':'2026-09-16T11:00:00.000Z'}
    assert not project_receipts_valid(task)
    assert not project_receipts_valid({'projects':[receipt,receipt]})


@pytest.mark.asyncio
@pytest.mark.parametrize('status', ['failed', 'pending'])
async def test_failed_or_pending_verification_never_runs_next_agent(tmp_path, status):
    calls = []
    async def run(owner, agent):
        calls.append(agent['id'])
        for frame in finish('The work could not be completed', status):
            yield frame
    manager = TeamManager(TeamStore(tmp_path/'teams'), run, yes)
    manager.start(OWNER, 'chat', 'a', 'Do work', 2, '')
    await settle(manager)
    assert calls == ['0']
    row = manager.list(OWNER, 'chat')[0]
    assert row['status'] == 'failed'
    assert [a['status'] for a in row['agents']] == ['failed', 'skipped']


@pytest.mark.asyncio
async def test_missing_terminal_receipt_is_not_a_success(tmp_path):
    async def run(*_):
        yield {'choices': [{'delta': {'content': 'I did it'}}]}
        yield {'_done': True, '_state': 'complete'}
    manager = TeamManager(TeamStore(tmp_path/'teams'), run, yes)
    manager.start(OWNER, 'chat', 'a', 'Do work', 1, '')
    await settle(manager)
    assert manager.list(OWNER, 'chat')[0]['agents'][0]['status'] == 'failed'


@pytest.mark.asyncio
async def test_question_pauses_and_answer_continues_only_that_child(tmp_path):
    questions = [{'id':'style','question':'Qual estilo?', 'options':['Clean','Colorido']}]
    calls = []
    async def run(owner, agent):
        calls.append(copy.deepcopy(agent))
        frames = finish('Qual estilo?', 'pending', questions) if agent['id']=='0' and agent['turn']==0 else finish('Result based on the answer')
        for frame in frames:
            yield frame
    manager = TeamManager(TeamStore(tmp_path/'teams'), run, yes)
    initial = manager.start(OWNER, 'chat', 'a', 'Do work', 2, '')
    await settle(manager)
    row = manager.list(OWNER, 'chat')[0]
    assert row['status'] == 'waiting' and row['agents'][1]['status'] == 'queued'
    with pytest.raises(TeamConflict):
        manager.answer(OWNER, initial['id'], '0', {'wrong':'Clean'})
    manager.answer(OWNER, initial['id'], '0', {'style':'Clean'})
    with pytest.raises(TeamConflict):
        manager.answer(OWNER, initial['id'], '0', {'style':'Clean'})
    await settle(manager)
    assert len(calls) == 3
    assert calls[0]['chat_id'] == calls[1]['chat_id'] != calls[2]['chat_id']
    assert calls[0]['request_id'] != calls[1]['request_id']
    assert calls[1]['messages'][-1] == {'role':'user','content':'Qual estilo?\nClean'}
    assert calls[1]['context_messages'] == [
        calls[0]['messages'][0], {'role': 'assistant', 'content': 'Qual estilo?'},
        {'role': 'user', 'content': 'Qual estilo?\nClean'},
    ]
    saved = manager.store.get(OWNER, initial['id'])['agents'][0]
    assert saved['context_messages'][-1] == {'role': 'assistant', 'content': 'Result based on the answer'}
    assert saved['context_request_id'] == calls[1]['request_id']
    assert manager.list(OWNER, 'chat')[0]['status'] == 'completed'


@pytest.mark.asyncio
async def test_readonly_clarification_keeps_assignment_in_the_current_request(tmp_path):
    questions = [{'id': 'scope', 'question': 'Which files?', 'options': ['Snake', 'Other']}]
    calls = []

    async def run(owner, agent):
        calls.append(copy.deepcopy(agent))
        frames = finish('Which files?', 'pending', questions) if agent['role'] == 'explorer' and agent['turn'] == 0 else finish('Observed result')
        for frame in frames:
            yield frame

    manager = TeamManager(TeamStore(tmp_path / 'teams'), run, yes)
    initial = manager.start(OWNER, 'chat', 'clarification', 'Create and publish Snake', 3,
                            'Archived teammate report: do not publish')
    await settle(manager)
    assert manager.list(OWNER, 'chat')[0]['status'] == 'waiting'
    manager.answer(OWNER, initial['id'], '0', {'scope': 'Create files in /workspace/Snake'})
    await settle(manager)

    current = calls[1]['messages'][-1]
    assert current['role'] == 'user'
    assert current['content'].startswith("You are the Explorer in the owner's Portal team.")
    assert 'Your assignment:' in current['content']
    assert 'Owner clarification answers:\nWhich files?\nCreate files in /workspace/Snake' in current['content']
    assert 'Archived teammate report' not in current['content']
    assert calls[1]['context_messages'][-1] == current
    assert calls[0]['chat_id'] == calls[1]['chat_id']
    saved = manager.store.get(OWNER, initial['id'])['agents'][0]
    assert saved['conversation'][2] == {'role': 'user', 'content': 'Which files?\nCreate files in /workspace/Snake'}
    assert manager.list(OWNER, 'chat')[0]['status'] == 'completed'


@pytest.mark.asyncio
async def test_cancel_survives_activity_updates_and_does_not_start_next_agent(tmp_path):
    started, proceed = asyncio.Event(), asyncio.Event()
    calls = []
    async def run(owner, agent):
        calls.append(agent['id'])
        started.set()
        await proceed.wait()
        yield {'pixel_task':{'schemaVersion':1,'calls':1,'activities':[]}}
        yield {'error':{'message':'Stopped'}}
        yield {'_done':True,'_state':'cancelled'}
    async def cancel(*_):
        proceed.set()
        return True
    manager = TeamManager(TeamStore(tmp_path/'teams'), run, cancel)
    row = manager.start(OWNER,'chat','a','Do work',3,'')
    await started.wait()
    await manager.stop(OWNER,row['id'])
    await settle(manager)
    assert calls == ['0']
    result = manager.list(OWNER,'chat')[0]
    assert result['status'] == 'cancelled'
    assert all(a['status']=='cancelled' for a in result['agents'])


@pytest.mark.asyncio
async def test_unacknowledged_stop_and_restart_never_claim_cancelled_or_replay(tmp_path):
    started, proceed = asyncio.Event(), asyncio.Event()
    calls=[]
    async def run(*_):
        calls.append(1)
        started.set()
        await proceed.wait()
        for frame in finish(): yield frame
    async def no(*_): return False
    directory=tmp_path/'teams'
    manager=TeamManager(TeamStore(directory),run,no)
    row=manager.start(OWNER,'chat','a','Do work',2,'')
    await started.wait()
    stopped=await manager.stop(OWNER,row['id'])
    assert stopped['status']=='stopping'
    recovered=TeamManager(TeamStore(directory),run,no)
    assert recovered.list(OWNER,'chat')[0]['status']=='interrupted'
    assert len(calls)==1 and not recovered.tasks
    with pytest.raises(TeamConflict): recovered.start(OWNER,'chat','b','Do new work',1,'')
    proceed.set()
    await settle(manager)


@pytest.mark.asyncio
async def test_global_lane_and_immediate_cancellation_of_queued_team(tmp_path):
    started, proceed=asyncio.Event(),asyncio.Event()
    calls=[]
    async def run(owner, agent):
        calls.append(agent['chat_id'])
        started.set()
        await proceed.wait()
        for frame in finish():yield frame
    manager=TeamManager(TeamStore(tmp_path/'teams'),run,yes)
    manager.start(OWNER,'first','a','First task',1,'')
    await started.wait()
    second=manager.start(OWNER,'second','b','Second task',1,'')
    await asyncio.sleep(0)
    assert len(calls)==1
    result=await manager.stop(OWNER,second['id'])
    assert result['status']=='cancelled'
    proceed.set()
    await settle(manager)
    assert len(calls)==1


def test_questions_bounds_and_private_history_paths(tmp_path):
    assert questions_valid([{'id':'x','question':'Q'*300,'options':['A','B']}])
    assert not questions_valid([{'id':'x','question':'Q','options':['A','A']}])
    store=TeamStore(tmp_path/'teams')
    with pytest.raises(ValueError):store.get(OWNER,'../escape')
    outside=tmp_path/'other.json'
    outside.write_text('{}')
    if os.name=='posix':
        (store.directory/f'{OWNER}-{"b"*32}.json').symlink_to(outside)
        with pytest.raises(ValueError):store.get(OWNER,'b'*32)


def test_routes_require_owner_and_validate_count_and_answer_scope(tmp_path, monkeypatch):
    app=FastAPI()
    app.include_router(pixel_teams.router)
    with TestClient(app) as client:
        assert client.post('/api/pixel/agents/list',json={'chat_id':'chat'}).status_code in (401,403)
    app.dependency_overrides[verify_api_key]=lambda:'owner'
    monkeypatch.setattr(pixel_teams,'_manager',TeamManager(TeamStore(tmp_path/'teams'),None,None))
    with TestClient(app) as client:
        for count in [0,7,True,'2']:
            assert client.post('/api/pixel/agents/start',json={'chat_id':'chat','request_id':'a','task':'Work','count':count}).status_code==422
        assert client.post('/api/pixel/agents/stop',json={'team_id':'b'*32}).status_code==404
        assert client.post('/api/pixel/agents/answer',json={'team_id':'b'*32,'agent_id':'0','answers':{'x':'y'}}).status_code==404

@pytest.mark.asyncio
@pytest.mark.parametrize('plan,count', [('{"count":3}',3), ('```json\n{"count":1}\n```',1), ('{"count":500}',2), ('A simple request.\n{"count":1}',1)])
async def test_automatic_team_uses_model_plan_with_bounded_fallback(tmp_path, plan, count):
    calls=[]
    async def run(owner, agent):
        calls.append(copy.deepcopy(agent))
        for frame in finish(plan if agent['role']=='coordinator' else 'Done'):
            yield frame
    manager=TeamManager(TeamStore(tmp_path/'teams'),run,yes)
    manager.start(OWNER,'chat','auto','Help me write a short announcement',None,'')
    await settle(manager)
    row=manager.list(OWNER,'chat')[0]
    assert row['status']=='completed' and len(row['agents'])==count
    assert len(calls)==count+1
    assert len({a['chat_id'] for a in calls})==count+1
    assert row['planning']['role']=='coordinator' and 'messages' not in row['planning']
    assert bool(row['notice']) == (count==2)

@pytest.mark.asyncio
async def test_retry_reviewer_preserves_builder_and_uses_new_attempt(tmp_path):
    calls=[]
    recovery_ids=[]
    async def run(owner,agent):
        calls.append((agent['id'],agent['request_id']))
        if agent['request_id']=='retry-1': recovery_ids.extend(agent.get('recovery_request_ids', []))
        if agent['role']=='reviewer' and agent['request_id']!='retry-1':
            yield {'error':{'message':'runtime unavailable'}}
            yield {'_done':True,'_state':'interrupted'}
        else:
            for frame in finish('Completed report'):yield frame
    manager=TeamManager(TeamStore(tmp_path/'teams'),run,yes)
    row=manager.start(OWNER,'chat','retry-test','Research and review',2,'')
    await settle(manager)
    failed=manager.list(OWNER,'chat')[0]
    assert failed['agents'][1]['retryable'] and not failed['agents'][0]['retryable']
    assert 'incomplete' in failed['agents'][1]['error']
    with pytest.raises(TeamConflict):manager.retry(OWNER,row['id'],'0')
    manager.retry(OWNER,row['id'],'1')
    with pytest.raises(TeamConflict):manager.retry(OWNER,row['id'],'1')
    await settle(manager)
    assert calls==[('0','turn-0'),('1','turn-0'),('1','recovery-1-turn-0'),('1','retry-1')]
    assert recovery_ids==['turn-0','recovery-1-turn-0']
    assert all('recovery_request_ids' not in agent for agent in manager.list(OWNER,'chat')[0]['agents'])
    assert manager.list(OWNER,'chat')[0]['status']=='completed'

@pytest.mark.asyncio
async def test_readonly_transport_recovery_is_bounded_and_never_replays_builder(tmp_path):
    calls=[]
    async def run(owner,agent):
        calls.append((agent['role'],agent['request_id']))
        if agent['role']=='reviewer' and agent['request_id']=='turn-0':
            yield {'error':{'code':'runtime_unavailable'}}
            yield {'_done':True,'_state':'interrupted'}
        else:
            for frame in finish('Verified result'):yield frame
    manager=TeamManager(TeamStore(tmp_path/'teams'),run,yes)
    manager.start(OWNER,'chat','recover','Research and review',2,'')
    await settle(manager)
    assert calls==[('builder','turn-0'),('reviewer','turn-0'),('reviewer','recovery-1-turn-0')]
    assert manager.list(OWNER,'chat')[0]['status']=='completed'


@pytest.mark.asyncio
async def test_unavailable_runtime_never_dispatches_a_worker(monkeypatch):
    from unittest.mock import AsyncMock
    host=AsyncMock(return_value={})
    health=AsyncMock(return_value='Unavailable')
    dispatch=AsyncMock()
    monkeypatch.setattr(pixel_teams.pixel,'_host_model_status',host)
    monkeypatch.setattr(pixel_teams.pixel,'_local_inference_issue',health)
    monkeypatch.setattr(pixel_teams.pixel,'_retained_chat_stream',dispatch)
    frames=[x async for x in pixel_teams._run(OWNER,{})]
    assert health.await_count==3
    assert frames[-2]=={'error':{'code':'model_unavailable'}}
    dispatch.assert_not_called()


@pytest.mark.asyncio
async def test_stop_during_health_check_never_starts_inference(monkeypatch):
    from unittest.mock import AsyncMock
    agent={}
    async def health(_):
        agent['stop_requested']=True
        return None
    dispatch=AsyncMock()
    monkeypatch.setattr(pixel_teams.pixel,'_host_model_status',AsyncMock(return_value={}))
    monkeypatch.setattr(pixel_teams.pixel,'_local_inference_issue',health)
    monkeypatch.setattr(pixel_teams.pixel,'_retained_chat_stream',dispatch)
    frames=[x async for x in pixel_teams._run(OWNER,agent)]
    assert frames[-1]=={'_done':True,'_state':'cancelled'}
    dispatch.assert_not_called()

@pytest.mark.asyncio
async def test_empty_model_answer_is_never_completed(tmp_path):
    async def run(*_):
        for frame in finish(''):yield frame
    manager=TeamManager(TeamStore(tmp_path/'teams'),run,yes)
    manager.start(OWNER,'chat','empty','Do work',1,'')
    await settle(manager)
    assert manager.list(OWNER,'chat')[0]['status']=='failed'


@pytest.mark.parametrize('mode', ['team', 'goal'])
@pytest.mark.parametrize('command', ['/extensions https://github.com/o/r install', '/goal /extensions @demo install'])
def test_extension_commands_cannot_create_unbound_worker_requests(tmp_path, mode, command):
    async def unexpected(*_):
        raise AssertionError('No model worker should start')
    manager = TeamManager(TeamStore(tmp_path / 'teams'), unexpected, yes)
    with pytest.raises(TeamConflict, match='chat installation coordinator'):
        manager.start(OWNER, 'chat', 'attempt', command, 1, '', mode)
    assert manager.list(OWNER, 'chat') == []


@pytest.mark.parametrize('role', ['coordinator', 'explorer', 'builder', 'reviewer'])
def test_team_prompt_leaves_the_reply_language_to_pixel(tmp_path, role):
    # Pixel's response-language rule decides, from the owner's own words. A
    # fixed language line here would be a second rule that can disagree with it.
    manager = TeamManager(TeamStore(tmp_path / 'teams'), yes, yes)
    row = {'goal': 'Crie um site simples sobre café e publique.', 'context': 'Conversa anterior sobre o site.'}
    prompt = manager._prompt(row, worker('team', 0, role))
    assert row['goal'] in prompt
    fixed = prompt.replace(row['goal'], '').replace(row['context'], '')
    assert not re.search(r"language|English|Portuguese", fixed, re.I), fixed


def _fill_store(store, status, created, instance=None):
    import pixel_agent_teams
    owner = "a" * 64
    for i in range(pixel_agent_teams.MAX_TEAMS):
        store.save(owner, {"id": f"{i:032x}", "chat_id": "c", "status": status, "created": created + i,
                           "updated": created + i, "instance": instance or store.instance})
    return owner


@pytest.mark.asyncio
@pytest.mark.parametrize("age", [0, 30 * 86400])
async def test_finished_teams_do_not_permanently_fill_history(tmp_path, monkeypatch, age):
    # 128 saved teams used to make every later start return 409 for good.
    import time
    import pixel_agent_teams

    async def run(owner, agent):
        for frame in finish():
            yield frame

    store = TeamStore(tmp_path / "teams")
    owner = pixel_teams.owner_namespace(security.DASHBOARD_API_KEY)
    oldest = time.time() - age
    for i in range(pixel_agent_teams.MAX_TEAMS):
        store.save(owner, _team(i, f"c{i}", "completed", oldest + i))
    manager = TeamManager(store, run, yes)
    async with team_client(manager, monkeypatch) as client:
        response = await client.post('/api/pixel/agents/start', json={
            'chat_id': 'chat', 'request_id': 'new', 'task': 'Do work', 'count': 1})
        assert response.status_code == 200, response.text
        await settle(manager)
    remaining = {p.stem[65:] for p in (tmp_path / "teams").glob("*.json")}
    # Only the oldest finished team made room, however old the others are.
    assert len(remaining) == pixel_agent_teams.MAX_TEAMS
    assert f"{0:032x}" not in remaining and f"{1:032x}" in remaining
    assert response.json()["id"] in remaining


def test_history_below_the_limit_is_never_pruned(tmp_path):
    # Eviction only makes room in a full store. Year-old finished teams and a
    # chat's older interrupted or stale teams stay while there is room.
    import time
    store = TeamStore(tmp_path / "teams")
    old = time.time() - 365 * 86400
    for i, status in enumerate(["completed", "failed", "cancelled", "interrupted", "interrupted", "running"]):
        store.save(OWNER, _team(i, "c", status, old + i))
    store.save(OWNER, _team(999, "new", "queued", time.time(), store.instance))
    remaining = sorted(p.stem[65:] for p in (tmp_path / "teams").glob("*.json"))
    assert remaining == sorted([f"{i:032x}" for i in range(6)] + [f"{999:032x}"])


def test_active_teams_are_never_evicted_for_history_space(tmp_path):
    import time
    store = TeamStore(tmp_path / "teams")
    owner = _fill_store(store, "running", time.time() - 30 * 86400)
    with pytest.raises(TeamConflict):
        store.save(owner, {"id": "f" * 32, "chat_id": "new", "status": "queued", "created": time.time()})
    assert len(list((tmp_path / "teams").glob("*.json"))) == 128


def _team(i, chat, status, stamp, instance="dead"):
    return {"id": f"{i:032x}", "chat_id": chat, "status": status, "created": stamp, "updated": stamp,
            "instance": instance, "agents": []}


def test_pruning_keeps_a_chats_interrupted_gate(tmp_path):
    import time
    import pixel_agent_teams
    store = TeamStore(tmp_path / "teams")
    now = time.time()
    store.save(OWNER, _team(0, "gated", "interrupted", now - 30 * 86400))
    for i in range(1, pixel_agent_teams.MAX_TEAMS):
        store.save(OWNER, _team(i, f"c{i}", "completed", now - 1000 + i))
    store.save(OWNER, _team(999, "new", "queued", now, store.instance))
    remaining = {p.stem[65:] for p in (tmp_path / "teams").glob("*.json")}
    assert f"{0:032x}" in remaining and f"{1:032x}" not in remaining
    manager = TeamManager(store, None, yes)
    with pytest.raises(TeamConflict, match="existing team"):
        manager._check_admission(OWNER, "gated")


def test_pruning_prefers_completed_over_older_interrupted(tmp_path):
    import time
    import pixel_agent_teams
    store = TeamStore(tmp_path / "teams")
    now = time.time()
    store.save(OWNER, _team(0, "x", "interrupted", now - 5000))
    store.save(OWNER, _team(1, "x", "interrupted", now - 4000))
    for i in range(2, pixel_agent_teams.MAX_TEAMS):
        store.save(OWNER, _team(i, f"c{i}", "completed", now - 1000 + i))
    store.save(OWNER, _team(999, "new", "queued", now, store.instance))
    remaining = {p.stem[65:] for p in (tmp_path / "teams").glob("*.json")}
    assert {f"{0:032x}", f"{1:032x}"} <= remaining and f"{2:032x}" not in remaining


def test_history_full_of_stop_gates_still_conflicts(tmp_path):
    import time
    import pixel_agent_teams
    store = TeamStore(tmp_path / "teams")
    old = time.time() - 30 * 86400
    for i in range(pixel_agent_teams.MAX_TEAMS):
        store.save(OWNER, _team(i, f"c{i}", "interrupted", old))
    with pytest.raises(TeamConflict, match="full"):
        store.save(OWNER, _team(999, "new", "queued", time.time(), store.instance))
    assert len(list((tmp_path / "teams").glob("*.json"))) == pixel_agent_teams.MAX_TEAMS


def test_unreadable_team_file_does_not_block_new_teams(tmp_path, caplog):
    import time
    import pixel_agent_teams
    store = TeamStore(tmp_path / "teams")
    teams = tmp_path / "teams"
    unreadable = [f"{OWNER}-{'1' * 32}.json", "notes.json", f"{OWNER}-{'2' * 32}.json"]
    (teams / unreadable[0]).write_text('{"id": "trunc', encoding="utf-8")
    (teams / unreadable[1]).write_text("{}", encoding="utf-8")
    (teams / unreadable[2]).write_text("[]", encoding="utf-8")
    for path in teams.glob("*.json"):
        path.chmod(0o600)
    # Fill the store so the new team needs room, and pruning must read past them.
    now = time.time()
    for i in range(pixel_agent_teams.MAX_TEAMS - len(unreadable)):
        store.save(OWNER, _team(i, f"c{i}", "completed", now - 1000 + i))
    store.save(OWNER, _team(999, "new", "queued", now, store.instance))
    assert store.get(OWNER, f"{999:032x}")["chat_id"] == "new"
    assert not (teams / f"{OWNER}-{0:032x}.json").exists()
    assert all((teams / name).exists() for name in unreadable)
    assert "Skipping unreadable agent team file" in caplog.text