Coverage for app / services / swarms / ledger.py: 100%

17 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1"""What a swarm's team has established, shared with every agent in it. 

2 

3Each structured step adds to the run's ledger (``SwarmRun.ledger``): the 

4plan what the request already establishes and what it assumes, each review 

5the facts the work established and what it leaves unanswered. Every task is 

6shown it in its ``<swarm_context>`` (``swarms.prompts``), so a worker 

7starting late works from what the team already knows instead of its subtask 

8alone — the shared context whose absence makes parallel agents contradict 

9each other. 

10 

11Bounded: a few dozen short entries per kind, repeats dropped, so it never 

12crowds out the work it describes. 

13""" 

14 

15from __future__ import annotations 

16 

17from typing import Any 

18 

19#: The kinds of entry, in the order they are shown. 

20KINDS = ("facts", "assumptions", "gaps") 

21#: Entries kept per kind, and characters per entry. 

22MAX_ENTRIES = 30 

23MAX_CHARS = 300 

24 

25 

26def merge(ledger: Any, update: dict[str, list[str]]) -> dict[str, list[str]]: 

27 """``ledger`` with ``update``'s entries added: each kind's newest 

28 ``MAX_ENTRIES``, each entry once.""" 

29 current = ledger if isinstance(ledger, dict) else {} 

30 out: dict[str, list[str]] = {} 

31 for kind in KINDS: 

32 entries = [str(e) for e in current.get(kind) or [] if str(e).strip()] 

33 for entry in update.get(kind) or []: 

34 text = " ".join(str(entry).split())[:MAX_CHARS] 

35 if text and text not in entries: 

36 entries.append(text) 

37 if entries: 

38 out[kind] = entries[-MAX_ENTRIES:] 

39 return out