Coverage for app / services / diff.py: 93%

67 statements  

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

1""" 

2Structured diff between two resource-version snapshots. 

3 

4Produces a git-style field-level diff: a shallow old/new comparison for 

5scalars and JSON values, plus a line-level diff (via ``difflib``) for long 

6free-form text fields so a system-prompt edit renders as +/- lines instead 

7of a single opaque "changed" blob. 

8""" 

9 

10import difflib 

11from typing import Any, Optional 

12 

13# Fields long/free-form enough to deserve line-level diffing. Declared here 

14# (not per-model) since this is a rendering concern, not a data-model one. 

15_TEXT_DIFF_FIELDS = {"system_prompt", "description", "prompt"} 

16_TEXT_DIFF_MIN_LENGTH = 80 

17 

18 

19def _text_diff_lines(old: str, new: str) -> list[dict[str, str]]: 

20 old_lines = old.splitlines() 

21 new_lines = new.splitlines() 

22 matcher = difflib.SequenceMatcher(None, old_lines, new_lines) 

23 lines: list[dict[str, str]] = [] 

24 for tag, i1, i2, j1, j2 in matcher.get_opcodes(): 

25 if tag == "equal": 

26 lines.extend({"op": "equal", "line": line} for line in old_lines[i1:i2]) 

27 else: 

28 lines.extend({"op": "delete", "line": line} for line in old_lines[i1:i2]) 

29 lines.extend({"op": "insert", "line": line} for line in new_lines[j1:j2]) 

30 return lines 

31 

32 

33def text_diff_hunks(old: str, new: str, context: int = 3) -> list[dict[str, str]]: 

34 """``_text_diff_lines`` with long unchanged runs folded away. 

35 

36 A web page is long and usually changes in a sentence; showing all of it 

37 buries the change. Keeps ``context`` equal lines either side of each 

38 change and replaces the rest of a run with one ``skip`` line saying how 

39 many were hidden. 

40 """ 

41 lines = _text_diff_lines(old, new) 

42 keep = [False] * len(lines) 

43 for i, line in enumerate(lines): 

44 if line["op"] != "equal": 

45 for j in range(max(0, i - context), min(len(lines), i + context + 1)): 

46 keep[j] = True 

47 folded: list[dict[str, str]] = [] 

48 hidden = 0 

49 for line, kept in zip(lines, keep): 

50 if kept: 

51 if hidden: 

52 folded.append({"op": "skip", "line": f"… {hidden} unchanged line(s)"}) 

53 hidden = 0 

54 folded.append(line) 

55 else: 

56 hidden += 1 

57 if hidden: 

58 folded.append({"op": "skip", "line": f"… {hidden} unchanged line(s)"}) 

59 return folded 

60 

61 

62def compute_field_diff(field: str, old_value: Any, new_value: Any) -> dict[str, Any]: 

63 """Classify one field's change and, for long text fields, attach a 

64 line-level diff.""" 

65 if old_value == new_value: 

66 change_type = "unchanged" 

67 elif old_value in (None, ""): 

68 change_type = "added" 

69 elif new_value in (None, ""): 

70 change_type = "removed" 

71 else: 

72 change_type = "changed" 

73 

74 text_diff = None 

75 if ( 

76 change_type == "changed" 

77 and field in _TEXT_DIFF_FIELDS 

78 and isinstance(old_value, str) 

79 and isinstance(new_value, str) 

80 and ( 

81 len(old_value) > _TEXT_DIFF_MIN_LENGTH 

82 or len(new_value) > _TEXT_DIFF_MIN_LENGTH 

83 ) 

84 ): 

85 text_diff = _text_diff_lines(old_value, new_value) 

86 

87 return { 

88 "field": field, 

89 "change_type": change_type, 

90 "old_value": old_value, 

91 "new_value": new_value, 

92 "text_diff": text_diff, 

93 } 

94 

95 

96def compute_diff( 

97 old_snapshot: Optional[dict[str, Any]], new_snapshot: dict[str, Any] 

98) -> list[dict[str, Any]]: 

99 """Field diffs for every field that changed between two snapshots. 

100 

101 ``old_snapshot=None`` diffs against a blank resource, i.e. every field 

102 in ``new_snapshot`` renders as "added" — used to view a resource's 

103 first version, or a not-yet-persisted generative proposal. 

104 """ 

105 old_snapshot = old_snapshot or {} 

106 fields = sorted(set(old_snapshot) | set(new_snapshot)) 

107 return [ 

108 compute_field_diff(field, old_snapshot.get(field), new_snapshot.get(field)) 

109 for field in fields 

110 if old_snapshot.get(field) != new_snapshot.get(field) 

111 ] 

112 

113 

114def _member_id(member: dict[str, Any]) -> Any: 

115 """A child-membership dict's own id, whichever key it's stored under 

116 (e.g. ``toolkit_id`` in an agent's ``children_snapshot["toolkits"]``).""" 

117 for key, value in member.items(): 

118 if key == "id" or key.endswith("_id"): 

119 return value 

120 return None 

121 

122 

123def compute_children_diff( 

124 old_children: Optional[dict[str, list[dict[str, Any]]]], 

125 new_children: Optional[dict[str, list[dict[str, Any]]]], 

126) -> dict[str, dict[str, list[str]]]: 

127 """Added/removed member ids per child collection (e.g. an agent's 

128 toolkit/skillset/repository grants) between two versions.""" 

129 old_children = old_children or {} 

130 new_children = new_children or {} 

131 result: dict[str, dict[str, list[str]]] = {} 

132 for key in sorted(set(old_children) | set(new_children)): 

133 old_ids = {str(_member_id(m)) for m in old_children.get(key, [])} 

134 new_ids = {str(_member_id(m)) for m in new_children.get(key, [])} 

135 added = sorted(new_ids - old_ids) 

136 removed = sorted(old_ids - new_ids) 

137 if added or removed: 

138 result[key] = {"added": added, "removed": removed} 

139 return result