gts-agency-python-sdk 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. agency_sdk/__init__.py +0 -0
  2. agency_sdk/auth_hooks.py +55 -0
  3. agency_sdk/client.py +212 -0
  4. agency_sdk/credentials.py +54 -0
  5. agency_sdk/delegates/__init__.py +0 -0
  6. agency_sdk/delegates/annotations_client.py +495 -0
  7. agency_sdk/delegates/annotations_dto.py +200 -0
  8. agency_sdk/delegates/base_client.py +126 -0
  9. agency_sdk/delegates/datasets_client.py +109 -0
  10. agency_sdk/delegates/datasets_dto.py +81 -0
  11. agency_sdk/delegates/datasource_client.py +44 -0
  12. agency_sdk/delegates/datasource_dto.py +107 -0
  13. agency_sdk/delegates/files_client.py +184 -0
  14. agency_sdk/delegates/files_dto.py +36 -0
  15. agency_sdk/delegates/gateway_client.py +81 -0
  16. agency_sdk/delegates/gateway_dto.py +37 -0
  17. agency_sdk/delegates/ontology_client.py +203 -0
  18. agency_sdk/delegates/ontology_dto.py +221 -0
  19. agency_sdk/delegates/prompts_client.py +56 -0
  20. agency_sdk/delegates/rules_client.py +33 -0
  21. agency_sdk/delegates/rules_dto.py +108 -0
  22. agency_sdk/delegates/session_client.py +95 -0
  23. agency_sdk/delegates/session_dto.py +94 -0
  24. agency_sdk/delegates/session_templates_client.py +23 -0
  25. agency_sdk/delegates/session_templates_dto.py +27 -0
  26. agency_sdk/delegates/session_vault_client.py +135 -0
  27. agency_sdk/delegates/session_vault_dto.py +75 -0
  28. agency_sdk/delegates/work_queue_client.py +230 -0
  29. agency_sdk/delegates/work_queue_dto.py +127 -0
  30. agency_sdk/domain.py +140 -0
  31. agency_sdk/observability/__init__.py +60 -0
  32. agency_sdk/observability/auth.py +15 -0
  33. agency_sdk/observability/bootstrap.py +344 -0
  34. agency_sdk/test/__init__.py +0 -0
  35. agency_sdk/test/conftest.py +106 -0
  36. agency_sdk/test/test_annotations_client.py +599 -0
  37. agency_sdk/test/test_annotations_dto.py +299 -0
  38. agency_sdk/test/test_base_client.py +153 -0
  39. agency_sdk/test/test_client_facade.py +105 -0
  40. agency_sdk/test/test_credentials.py +67 -0
  41. agency_sdk/test/test_files_client.py +264 -0
  42. agency_sdk/test/test_files_dto.py +93 -0
  43. agency_sdk/test/test_gateway_dto.py +70 -0
  44. agency_sdk/test/test_gateway_facade.py +229 -0
  45. agency_sdk/test/test_gateway_openai.py +76 -0
  46. agency_sdk/test/test_observability_auth.py +125 -0
  47. agency_sdk/test/test_observability_facade_threadsafety.py +50 -0
  48. agency_sdk/test/test_observability_langfuse.py +76 -0
  49. agency_sdk/test/test_observability_packaging.py +78 -0
  50. agency_sdk/test/test_observability_pipeline.py +246 -0
  51. agency_sdk/test/test_ontology_client.py +152 -0
  52. agency_sdk/test/test_ontology_dto.py +158 -0
  53. agency_sdk/test/test_session_client.py +128 -0
  54. agency_sdk/test/test_session_dto.py +75 -0
  55. agency_sdk/test/test_session_templates_client.py +36 -0
  56. agency_sdk/test/test_session_templates_dto.py +45 -0
  57. agency_sdk/test/test_session_vault_client.py +151 -0
  58. agency_sdk/test/test_session_vault_dto.py +27 -0
  59. agency_sdk/test/test_stub_requests.py +39 -0
  60. agency_sdk/test/test_work_queue_client.py +388 -0
  61. agency_sdk/test/test_work_queue_dto.py +233 -0
  62. gts_agency_python_sdk-0.0.1.dist-info/METADATA +221 -0
  63. gts_agency_python_sdk-0.0.1.dist-info/RECORD +66 -0
  64. gts_agency_python_sdk-0.0.1.dist-info/WHEEL +5 -0
  65. gts_agency_python_sdk-0.0.1.dist-info/licenses/LICENSE +201 -0
  66. gts_agency_python_sdk-0.0.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,151 @@
1
+ """Offline protocol tests for AgencySessionVaultClient.
2
+
3
+ Every test asserts the exact wire contract (URL, query params, headers, body)
4
+ verified against gts-agency-control/src/handler/sessions.rs and
5
+ src/service/sessions/session_vault_service.rs.
6
+ """
7
+
8
+ import pytest
9
+
10
+ from agency_sdk.delegates.session_vault_client import AgencySessionVaultClient
11
+ from agency_sdk.delegates.session_vault_dto import Classification
12
+
13
+ SESSION_ID = "11111111-2222-3333-4444-555555555555"
14
+
15
+ LIST_JSON = {
16
+ "entries": [
17
+ {"key": "checkpoint", "size": 128, "updated_at": "2026-06-17T12:00:00Z", "classification": "restricted"},
18
+ {"key": "notes", "size": 42, "updated_at": "2026-06-17T12:01:00Z", "classification": "public"},
19
+ ]
20
+ }
21
+
22
+ ENTRY_JSON = {
23
+ "key": "notes",
24
+ "value": {"items": ["a", "b", "c"]},
25
+ "classification": "public",
26
+ }
27
+
28
+
29
+ @pytest.fixture
30
+ def client(fake_credentials):
31
+ return AgencySessionVaultClient(token_supplier=fake_credentials, base_url="http://cp.test/")
32
+
33
+
34
+ class TestList:
35
+ def test_list_hits_vault_endpoint(self, client, stub_requests):
36
+ stub_requests.queue(json_data=LIST_JSON)
37
+
38
+ result = client.list(organisation_id=2, session_id=SESSION_ID)
39
+
40
+ call = stub_requests.calls[0]
41
+ assert call.method == "GET"
42
+ assert call.url == f"http://cp.test/api/sessions/{SESSION_ID}/vault"
43
+ assert call.kwargs["params"] == {"o": "2"}
44
+ assert call.kwargs["headers"]["Authorization"] == "Bearer test-token"
45
+ assert [e.key for e in result.entries] == ["checkpoint", "notes"]
46
+ assert result.entries[0].size == 128
47
+
48
+ def test_list_empty_vault(self, client, stub_requests):
49
+ stub_requests.queue(json_data={"entries": []})
50
+
51
+ result = client.list(organisation_id=2, session_id=SESSION_ID)
52
+
53
+ assert result.entries == []
54
+
55
+
56
+ class TestGet:
57
+ def test_get_without_reveal_omits_param(self, client, stub_requests):
58
+ stub_requests.queue(json_data=ENTRY_JSON)
59
+
60
+ result = client.get(organisation_id=2, session_id=SESSION_ID, key="notes")
61
+
62
+ call = stub_requests.calls[0]
63
+ assert call.method == "GET"
64
+ assert call.url == f"http://cp.test/api/sessions/{SESSION_ID}/vault/notes"
65
+ assert call.kwargs["params"] == {"o": "2"}
66
+ assert result.value == {"items": ["a", "b", "c"]}
67
+ assert result.classification == "public"
68
+
69
+ def test_get_with_reveal_adds_param(self, client, stub_requests):
70
+ stub_requests.queue(json_data={**ENTRY_JSON, "key": "draft", "classification": "confidential"})
71
+
72
+ client.get(organisation_id=2, session_id=SESSION_ID, key="draft", reveal=True)
73
+
74
+ call = stub_requests.calls[0]
75
+ assert call.url == f"http://cp.test/api/sessions/{SESSION_ID}/vault/draft"
76
+ assert call.kwargs["params"] == {"o": "2", "reveal": "true"}
77
+
78
+ def test_get_invalid_key_raises_before_network(self, client, stub_requests):
79
+ with pytest.raises(ValueError):
80
+ client.get(organisation_id=2, session_id=SESSION_ID, key="bad/key")
81
+
82
+ assert stub_requests.calls == []
83
+
84
+
85
+ class TestSet:
86
+ def test_set_default_classification_omits_param_and_sends_raw_value(self, client, stub_requests):
87
+ stub_requests.queue(json_data={"key": "checkpoint", "classification": "restricted"})
88
+ value = {"step": 3, "stage": "awaiting_human_review"}
89
+
90
+ result = client.set(organisation_id=2, session_id=SESSION_ID, key="checkpoint", value=value)
91
+
92
+ call = stub_requests.calls[0]
93
+ assert call.method == "PUT"
94
+ assert call.url == f"http://cp.test/api/sessions/{SESSION_ID}/vault/checkpoint"
95
+ assert call.kwargs["params"] == {"o": "2"}
96
+ # The body is the raw JSON value, not an envelope.
97
+ assert call.kwargs["json"] == value
98
+ assert result.key == "checkpoint"
99
+ assert result.classification == "restricted"
100
+
101
+ def test_set_explicit_classification_adds_param(self, client, stub_requests):
102
+ stub_requests.queue(json_data={"key": "notes", "classification": "public"})
103
+
104
+ client.set(
105
+ organisation_id=2,
106
+ session_id=SESSION_ID,
107
+ key="notes",
108
+ value=["a", "b", "c"],
109
+ classification=Classification.PUBLIC,
110
+ )
111
+
112
+ call = stub_requests.calls[0]
113
+ assert call.kwargs["params"] == {"o": "2", "classification": "public"}
114
+ # A list value is sent verbatim as the body.
115
+ assert call.kwargs["json"] == ["a", "b", "c"]
116
+
117
+ @pytest.mark.parametrize("value", ["a plain string", 42, 3.14, True, None])
118
+ def test_set_sends_scalar_values_verbatim(self, client, stub_requests, value):
119
+ stub_requests.queue(json_data={"key": "scalar", "classification": "restricted"})
120
+
121
+ client.set(organisation_id=2, session_id=SESSION_ID, key="scalar", value=value)
122
+
123
+ call = stub_requests.calls[0]
124
+ assert call.method == "PUT"
125
+ # Any JSON-serializable scalar is sent as the raw body, not wrapped.
126
+ assert call.kwargs["json"] == value
127
+
128
+ def test_set_invalid_key_raises_before_network(self, client, stub_requests):
129
+ with pytest.raises(ValueError):
130
+ client.set(organisation_id=2, session_id=SESSION_ID, key="", value={})
131
+
132
+ assert stub_requests.calls == []
133
+
134
+
135
+ class TestDelete:
136
+ def test_delete_issues_request_and_returns_none(self, client, stub_requests):
137
+ stub_requests.queue(json_data={"success": True})
138
+
139
+ result = client.delete(organisation_id=2, session_id=SESSION_ID, key="notes")
140
+
141
+ call = stub_requests.calls[0]
142
+ assert call.method == "DELETE"
143
+ assert call.url == f"http://cp.test/api/sessions/{SESSION_ID}/vault/notes"
144
+ assert call.kwargs["params"] == {"o": "2"}
145
+ assert result is None
146
+
147
+ def test_delete_invalid_key_raises_before_network(self, client, stub_requests):
148
+ with pytest.raises(ValueError):
149
+ client.delete(organisation_id=2, session_id=SESSION_ID, key="..")
150
+
151
+ assert stub_requests.calls == []
@@ -0,0 +1,27 @@
1
+ """Tests for session vault DTOs — Classification StrEnum semantics (PR #5 L1)."""
2
+
3
+ from enum import StrEnum
4
+
5
+ from agency_sdk.delegates.session_vault_dto import Classification
6
+
7
+
8
+ def test_classification_is_a_str_enum():
9
+ assert issubclass(Classification, StrEnum)
10
+
11
+
12
+ def test_members_equal_their_string_values():
13
+ assert Classification.PUBLIC == "public"
14
+ assert Classification.INTERNAL == "internal"
15
+ assert Classification.CONFIDENTIAL == "confidential"
16
+ assert Classification.RESTRICTED == "restricted"
17
+
18
+
19
+ def test_str_yields_bare_value():
20
+ # Query-param serialization relies on str() being "public", not "Classification.PUBLIC".
21
+ assert str(Classification.PUBLIC) == "public"
22
+ assert f"{Classification.INTERNAL}" == "internal"
23
+
24
+
25
+ def test_default_is_an_alias_of_restricted():
26
+ assert Classification.DEFAULT is Classification.RESTRICTED
27
+ assert Classification.DEFAULT == "restricted"
@@ -0,0 +1,39 @@
1
+ """Sanity tests for the shared offline requests stub used by all client tests."""
2
+
3
+ import pytest
4
+ import requests
5
+
6
+
7
+ def test_recorder_captures_call_and_replays_queued_response(stub_requests):
8
+ stub_requests.queue(json_data={"hello": "world"})
9
+
10
+ response = requests.request(method="GET", url="http://example.test/api/x", params={"o": "2"})
11
+
12
+ assert response.json() == {"hello": "world"}
13
+ assert len(stub_requests.calls) == 1
14
+ call = stub_requests.calls[0]
15
+ assert call.method == "GET"
16
+ assert call.url == "http://example.test/api/x"
17
+ assert call.kwargs["params"] == {"o": "2"}
18
+
19
+
20
+ def test_stub_response_raises_http_error_for_4xx(stub_requests):
21
+ stub_requests.queue(json_data={"error": "not found"}, status_code=404)
22
+
23
+ response = requests.request(method="GET", url="http://example.test/api/missing")
24
+ with pytest.raises(requests.HTTPError):
25
+ response.raise_for_status()
26
+
27
+
28
+ def test_recorder_intercepts_requests_get_for_downloads(stub_requests):
29
+ stub_requests.queue(content_bytes=b"abc123")
30
+
31
+ response = requests.get("http://signed.example.test/blob", timeout=300, stream=True)
32
+
33
+ assert b"".join(response.iter_content(chunk_size=2)) == b"abc123"
34
+ assert stub_requests.calls[0].method == "GET"
35
+ assert stub_requests.calls[0].kwargs["stream"] is True
36
+
37
+
38
+ def test_fake_credentials_supplies_static_token(fake_credentials):
39
+ assert fake_credentials.bearer_token() == "test-token"
@@ -0,0 +1,388 @@
1
+ """Offline protocol tests for AgencyWorkQueueClient.
2
+
3
+ Every test asserts the exact wire contract of the Track ① work-queue ingestion
4
+ surface: `?o={org}` on every call, the flat `{"command": ...}` envelope, and —
5
+ the load-bearing behaviour — 409 as control flow: `create_item` / `add_ref`
6
+ catch the HTTPError and return a typed result (`created=False` / `added=False`
7
+ + the owner fields), never re-raise. The 409 body is the standard error
8
+ envelope `{"error": {"message", "type", "details"}}`: `error.details` carries
9
+ the owner summary; `error.type == "CONFLICT_RETRY"` is the owner-less contended
10
+ fallback (→ `contended=True`).
11
+ """
12
+
13
+ import pytest
14
+ import requests
15
+
16
+ from agency_sdk.delegates.work_queue_client import AgencyWorkQueueClient
17
+ from agency_sdk.delegates.work_queue_dto import CreateItemResult, ItemCommandResponse, ItemResponse
18
+ from agency_sdk.test.test_work_queue_dto import CREATE_CONFLICT_JSON, ITEM_JSON, QUEUE_JSON
19
+
20
+ # Owner summary carried inside error.details (add_ref's is narrower — no `published`).
21
+ ADD_REF_CONFLICT_JSON = {"work_item_id": 4711, "status": "blocked"}
22
+
23
+ # The 409 wire bodies: standard error envelope. An owner conflict carries error.details;
24
+ # the owner-less fallback carries error.type == "CONFLICT_RETRY" and no details.
25
+ CREATE_CONFLICT_ENVELOPE = {
26
+ "error": {"message": "ref already claimed", "type": "CONFLICT", "details": CREATE_CONFLICT_JSON}
27
+ }
28
+ ADD_REF_CONFLICT_ENVELOPE = {
29
+ "error": {"message": "ref already claimed", "type": "CONFLICT", "details": ADD_REF_CONFLICT_JSON}
30
+ }
31
+ CONFLICT_RETRY_ENVELOPE = {"error": {"message": "claim contended, retry", "type": "CONFLICT_RETRY"}}
32
+
33
+ # The _command endpoint's real response shape (server ItemCommandResponse); session_id is
34
+ # omitted entirely for commands that dispatch no session.
35
+ PUBLISH_OK_JSON = {"success": True, "message": "Item published successfully", "session_id": "sess-0001"}
36
+
37
+
38
+ @pytest.fixture
39
+ def client(fake_credentials):
40
+ return AgencyWorkQueueClient(token_supplier=fake_credentials, base_url="http://cp.test/")
41
+
42
+
43
+ class TestCreateItem:
44
+ def test_create_item_posts_body_and_wraps_created_item(self, client, stub_requests):
45
+ stub_requests.queue(json_data=ITEM_JSON, status_code=201)
46
+
47
+ result = client.create_item(
48
+ queue_id=12,
49
+ organisation_id=2,
50
+ title="Ingest inbox/report.pdf",
51
+ session_template_id="guideline-extraction",
52
+ input_data={"file_id": "file_550e8400", "path": "inbox/report.pdf"},
53
+ external_refs=[
54
+ {"ref_type": "file_id", "ref_value": "file_550e8400"},
55
+ {"ref_type": "content_hash", "ref_value": "deadbeef"},
56
+ ],
57
+ metadata={"filename": "report.pdf"},
58
+ )
59
+
60
+ call = stub_requests.calls[0]
61
+ assert call.method == "POST"
62
+ assert call.url == "http://cp.test/api/work_queues/12/items"
63
+ assert call.kwargs["params"] == {"o": "2"}
64
+ assert call.kwargs["headers"]["Authorization"] == "Bearer test-token"
65
+ assert call.kwargs["json"] == {
66
+ "title": "Ingest inbox/report.pdf",
67
+ "session_template_id": "guideline-extraction",
68
+ "input_data": {"file_id": "file_550e8400", "path": "inbox/report.pdf"},
69
+ "external_refs": [
70
+ {"ref_type": "file_id", "ref_value": "file_550e8400"},
71
+ {"ref_type": "content_hash", "ref_value": "deadbeef"},
72
+ ],
73
+ "metadata": {"filename": "report.pdf"},
74
+ }
75
+ assert isinstance(result, CreateItemResult)
76
+ assert result.created is True
77
+ assert result.item is not None
78
+ assert result.item.id == ITEM_JSON["id"]
79
+ assert result.existing is None
80
+
81
+ def test_create_item_omits_optional_body_fields_when_absent(self, client, stub_requests):
82
+ stub_requests.queue(json_data=ITEM_JSON, status_code=201)
83
+
84
+ client.create_item(
85
+ queue_id=12,
86
+ organisation_id=2,
87
+ title="Ingest inbox/report.pdf",
88
+ session_template_id="guideline-extraction",
89
+ input_data={"file_id": "file_550e8400"},
90
+ )
91
+
92
+ body = stub_requests.calls[0].kwargs["json"]
93
+ assert "external_refs" not in body
94
+ assert "metadata" not in body
95
+
96
+ def test_create_item_conflict_returns_existing_summary_not_raise(self, client, stub_requests):
97
+ # Owner conflict: the owner summary comes from error.details.
98
+ stub_requests.queue(json_data=CREATE_CONFLICT_ENVELOPE, status_code=409)
99
+
100
+ result = client.create_item(
101
+ queue_id=12,
102
+ organisation_id=2,
103
+ title="Ingest inbox/report.pdf",
104
+ session_template_id="guideline-extraction",
105
+ input_data={"file_id": "file_550e8400"},
106
+ external_refs=[{"ref_type": "file_id", "ref_value": "file_550e8400"}],
107
+ )
108
+
109
+ assert result.created is False
110
+ assert result.item is None
111
+ assert result.contended is False
112
+ assert result.existing is not None
113
+ assert result.existing.work_item_id == 4711
114
+ assert result.existing.status == "doing"
115
+ assert result.existing.published is True
116
+
117
+ def test_create_item_conflict_retry_sets_contended_without_owner(self, client, stub_requests):
118
+ # Owner-less fallback: error.type == CONFLICT_RETRY, no details.
119
+ stub_requests.queue(json_data=CONFLICT_RETRY_ENVELOPE, status_code=409)
120
+
121
+ result = client.create_item(
122
+ queue_id=12,
123
+ organisation_id=2,
124
+ title="dup",
125
+ session_template_id="st",
126
+ input_data={},
127
+ external_refs=[{"ref_type": "file_id", "ref_value": "f1"}],
128
+ )
129
+
130
+ assert result.created is False
131
+ assert result.existing is None
132
+ assert result.contended is True
133
+
134
+ def test_create_item_envelope_409_without_owner_or_retry_reraises(self, client, stub_requests):
135
+ # An enveloped 409 that is neither an owner conflict nor CONFLICT_RETRY is unexpected —
136
+ # surface the original HTTPError rather than fabricate a claim-lost result.
137
+ stub_requests.queue(json_data={"error": {"message": "weird", "type": "SOMETHING_ELSE"}}, status_code=409)
138
+
139
+ with pytest.raises(requests.HTTPError):
140
+ client.create_item(queue_id=12, organisation_id=2, title="t", session_template_id="st", input_data={})
141
+
142
+ @pytest.mark.parametrize("body", [["not", "a", "dict"], {"error": "just a string"}, {"nope": 1}])
143
+ def test_create_item_non_envelope_409_reraises(self, client, stub_requests, body):
144
+ # A 409 that is not the standard {error:{...}} envelope (non-dict body, non-dict error,
145
+ # or a dict without `error`) is unexpected → re-raise the original HTTPError.
146
+ stub_requests.queue(json_data=body, status_code=409)
147
+
148
+ with pytest.raises(requests.HTTPError):
149
+ client.create_item(queue_id=12, organisation_id=2, title="t", session_template_id="st", input_data={})
150
+
151
+ def test_create_item_propagates_non_conflict_errors(self, client, stub_requests):
152
+ stub_requests.queue(json_data={"message": "Organisation not specified."}, status_code=400)
153
+
154
+ with pytest.raises(requests.HTTPError):
155
+ client.create_item(
156
+ queue_id=12,
157
+ organisation_id=2,
158
+ title="t",
159
+ session_template_id="st",
160
+ input_data={},
161
+ )
162
+
163
+ def test_create_item_malformed_409_body_reraises_original_httperror(self, client, stub_requests):
164
+ # A 409 whose body will not parse as JSON is unexpected — surface the original
165
+ # HTTPError, not a JSONDecodeError, and never fabricate a claim-lost result.
166
+ response = stub_requests.queue(status_code=409)
167
+
168
+ def _no_json():
169
+ raise ValueError("No JSON could be decoded")
170
+
171
+ response.json = _no_json # type: ignore[method-assign]
172
+
173
+ with pytest.raises(requests.HTTPError):
174
+ client.create_item(
175
+ queue_id=12,
176
+ organisation_id=2,
177
+ title="dup",
178
+ session_template_id="st",
179
+ input_data={},
180
+ external_refs=[{"ref_type": "file_id", "ref_value": "f1"}],
181
+ )
182
+
183
+
184
+ class TestAddRef:
185
+ def test_add_ref_posts_flat_command_envelope(self, client, stub_requests):
186
+ stub_requests.queue(json_data={"success": True}, status_code=201)
187
+
188
+ result = client.add_ref(
189
+ queue_id=12, item_id=4711, organisation_id=2, ref_type="content_hash", ref_value="deadbeef"
190
+ )
191
+
192
+ call = stub_requests.calls[0]
193
+ assert call.method == "POST"
194
+ assert call.url == "http://cp.test/api/work_queues/12/items/4711/_command"
195
+ assert call.kwargs["params"] == {"o": "2"}
196
+ assert call.kwargs["json"] == {"command": "add_ref", "ref_type": "content_hash", "ref_value": "deadbeef"}
197
+ assert result.added is True
198
+ assert result.owner_work_item_id is None
199
+ assert result.owner_status is None
200
+
201
+ def test_add_ref_conflict_returns_owner_not_raise(self, client, stub_requests):
202
+ # Owner conflict: owner from error.details.
203
+ stub_requests.queue(json_data=ADD_REF_CONFLICT_ENVELOPE, status_code=409)
204
+
205
+ result = client.add_ref(
206
+ queue_id=12, item_id=4712, organisation_id=2, ref_type="content_hash", ref_value="deadbeef"
207
+ )
208
+
209
+ assert result.added is False
210
+ assert result.owner_work_item_id == 4711
211
+ assert result.owner_status == "blocked"
212
+ assert result.contended is False
213
+
214
+ def test_add_ref_conflict_retry_sets_contended_without_owner(self, client, stub_requests):
215
+ # Owner-less fallback: error.type == CONFLICT_RETRY.
216
+ stub_requests.queue(json_data=CONFLICT_RETRY_ENVELOPE, status_code=409)
217
+
218
+ result = client.add_ref(
219
+ queue_id=12, item_id=4712, organisation_id=2, ref_type="content_hash", ref_value="deadbeef"
220
+ )
221
+
222
+ assert result.added is False
223
+ assert result.owner_work_item_id is None
224
+ assert result.owner_status is None
225
+ assert result.contended is True
226
+
227
+ def test_add_ref_propagates_non_conflict_errors(self, client, stub_requests):
228
+ stub_requests.queue(json_data={"message": "boom"}, status_code=500)
229
+
230
+ with pytest.raises(requests.HTTPError):
231
+ client.add_ref(queue_id=12, item_id=4711, organisation_id=2, ref_type="file_id", ref_value="x")
232
+
233
+
234
+ class TestPublishItem:
235
+ def test_publish_item_sends_publish_command_and_returns_command_response(self, client, stub_requests):
236
+ stub_requests.queue(json_data=PUBLISH_OK_JSON)
237
+
238
+ result = client.publish_item(queue_id=12, item_id=4711, organisation_id=2)
239
+
240
+ call = stub_requests.calls[0]
241
+ assert call.method == "POST"
242
+ assert call.url == "http://cp.test/api/work_queues/12/items/4711/_command"
243
+ assert call.kwargs["params"] == {"o": "2"}
244
+ assert call.kwargs["json"] == {"command": "publish"}
245
+ assert isinstance(result, ItemCommandResponse)
246
+ assert result.success is True
247
+ assert result.message == "Item published successfully"
248
+ assert result.session_id == "sess-0001"
249
+
250
+ def test_publish_item_propagates_precondition_errors(self, client, stub_requests):
251
+ # publish hard-rejects anything not backlog+unpublished — that is an error, not control flow
252
+ stub_requests.queue(json_data={"message": "not in backlog"}, status_code=400)
253
+
254
+ with pytest.raises(requests.HTTPError):
255
+ client.publish_item(queue_id=12, item_id=4711, organisation_id=2)
256
+
257
+
258
+ class TestItemCommand:
259
+ @pytest.mark.parametrize("command", ["unblock", "retry", "reprocess"])
260
+ def test_item_command_passes_command_through(self, client, stub_requests, command):
261
+ # non-dispatching command responses carry no session_id key at all
262
+ stub_requests.queue(json_data={"success": True, "message": f"Item {command} ok"})
263
+
264
+ result = client.item_command(queue_id=12, item_id=4711, organisation_id=2, command=command)
265
+
266
+ call = stub_requests.calls[0]
267
+ assert call.url == "http://cp.test/api/work_queues/12/items/4711/_command"
268
+ assert call.kwargs["json"] == {"command": command}
269
+ assert isinstance(result, ItemCommandResponse)
270
+ assert result.success is True
271
+ assert result.message == f"Item {command} ok"
272
+ assert result.session_id is None
273
+
274
+ def test_item_command_forwards_extra_fields(self, client, stub_requests):
275
+ stub_requests.queue(json_data={"success": True, "message": "Item unblocked"})
276
+
277
+ client.item_command(queue_id=12, item_id=4711, organisation_id=2, command="unblock", feedback="fixed creds")
278
+
279
+ assert stub_requests.calls[0].kwargs["json"] == {"command": "unblock", "feedback": "fixed creds"}
280
+
281
+ def test_item_command_propagates_conflicts(self, client, stub_requests):
282
+ # only create_item/add_ref treat 409 as control flow; commands do not
283
+ stub_requests.queue(json_data={"message": "conflict"}, status_code=409)
284
+
285
+ with pytest.raises(requests.HTTPError):
286
+ client.item_command(queue_id=12, item_id=4711, organisation_id=2, command="retry")
287
+
288
+
289
+ class TestGetItem:
290
+ def test_get_item_hits_item_endpoint(self, client, stub_requests):
291
+ stub_requests.queue(json_data=ITEM_JSON)
292
+
293
+ result = client.get_item(queue_id=12, item_id=4711, organisation_id=2)
294
+
295
+ call = stub_requests.calls[0]
296
+ assert call.method == "GET"
297
+ assert call.url == "http://cp.test/api/work_queues/12/items/4711"
298
+ assert call.kwargs["params"] == {"o": "2"}
299
+ assert result.id == 4711
300
+ assert result.status == "backlog"
301
+
302
+
303
+ class TestGetItemsByRef:
304
+ def test_org_scope_uses_underscore_path_and_returns_list(self, client, stub_requests):
305
+ # queue_id=None → the whole-org scope `_`; ref_type/ref_value turn the paged /items into an
306
+ # owner lookup. A ref may be held once per queue, so a list; owners come from the page's items.
307
+ stub_requests.queue(json_data={"page": {"page": 0, "size": 1, "total": 1}, "items": [ITEM_JSON]})
308
+
309
+ result = client.get_items_by_ref(organisation_id=2, ref_type="file_id", ref_value="file_550e8400")
310
+
311
+ call = stub_requests.calls[0]
312
+ assert call.method == "GET"
313
+ assert call.url == "http://cp.test/api/work_queues/_/items"
314
+ assert call.kwargs["params"] == {"o": "2", "ref_type": "file_id", "ref_value": "file_550e8400", "s": "1000"}
315
+ assert [item.id for item in result] == [4711]
316
+
317
+ def test_queue_scope_uses_queue_id_path(self, client, stub_requests):
318
+ stub_requests.queue(json_data={"page": {"page": 0, "size": 1, "total": 1}, "items": [ITEM_JSON]})
319
+
320
+ result = client.get_items_by_ref(organisation_id=2, queue_id=12, ref_type="file_id", ref_value="file_550e8400")
321
+
322
+ assert stub_requests.calls[0].url == "http://cp.test/api/work_queues/12/items"
323
+ assert len(result) == 1
324
+
325
+ def test_empty_items_means_no_owner(self, client, stub_requests):
326
+ stub_requests.queue(json_data={"page": {"page": 0, "size": 0, "total": 0}, "items": []})
327
+
328
+ result = client.get_items_by_ref(organisation_id=2, ref_type="content_hash", ref_value="missing")
329
+
330
+ assert result == []
331
+
332
+ def test_404_propagates(self, client, stub_requests):
333
+ # A miss is 200 + empty items (above); a genuine 404 is still a real error and propagates.
334
+ stub_requests.queue(json_data={"message": "not found"}, status_code=404)
335
+
336
+ with pytest.raises(requests.HTTPError):
337
+ client.get_items_by_ref(organisation_id=2, ref_type="file_id", ref_value="x")
338
+
339
+ def test_propagates_other_errors(self, client, stub_requests):
340
+ stub_requests.queue(json_data={"message": "boom"}, status_code=500)
341
+
342
+ with pytest.raises(requests.HTTPError):
343
+ client.get_items_by_ref(organisation_id=2, ref_type="file_id", ref_value="x")
344
+
345
+ def test_old_singular_get_item_by_ref_is_removed(self, client):
346
+ # Clean rename, no alias — an alias would perpetuate the wrong "single owner" model.
347
+ assert not hasattr(client, "get_item_by_ref")
348
+
349
+
350
+ class TestDeleteItem:
351
+ def test_delete_item_hits_item_endpoint_and_returns_none(self, client, stub_requests):
352
+ stub_requests.queue(json_data={"success": True})
353
+
354
+ result = client.delete_item(queue_id=12, item_id=4711, organisation_id=2)
355
+
356
+ call = stub_requests.calls[0]
357
+ assert call.method == "DELETE"
358
+ assert call.url == "http://cp.test/api/work_queues/12/items/4711"
359
+ assert call.kwargs["params"] == {"o": "2"}
360
+ assert result is None
361
+
362
+ def test_delete_item_propagates_404(self, client, stub_requests):
363
+ stub_requests.queue(json_data={"message": "not found"}, status_code=404)
364
+
365
+ with pytest.raises(requests.HTTPError):
366
+ client.delete_item(queue_id=12, item_id=9999, organisation_id=2)
367
+
368
+
369
+ class TestListQueues:
370
+ def test_list_hits_work_queues_endpoint_paged(self, client, stub_requests):
371
+ stub_requests.queue(json_data={"page": {"page": 0, "size": 1, "total": 1}, "items": [QUEUE_JSON]})
372
+
373
+ result = client.list(organisation_id=2)
374
+
375
+ call = stub_requests.calls[0]
376
+ assert call.method == "GET"
377
+ assert call.url == "http://cp.test/api/work_queues"
378
+ assert call.kwargs["params"] == {"o": "2", "p": "0", "s": "50"}
379
+ assert result.page.total == 1
380
+ assert [q.id for q in result.items] == [8]
381
+ assert result.items[0].name == "Guideline Ingestion"
382
+
383
+ def test_list_forwards_pagination(self, client, stub_requests):
384
+ stub_requests.queue(json_data={"page": {"page": 2, "size": 10, "total": 0}, "items": []})
385
+
386
+ client.list(organisation_id=9, page=2, size=10)
387
+
388
+ assert stub_requests.calls[0].kwargs["params"] == {"o": "9", "p": "2", "s": "10"}