agent-core-qa 0.8.2__tar.gz

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.
@@ -0,0 +1,245 @@
1
+ # Memory compiler runtime state
2
+ memory-compiler/daily/
3
+ memory-compiler/reports/
4
+ memory-compiler/scripts/state.json
5
+ memory-compiler/scripts/last-flush.json
6
+ memory-compiler/scripts/flush.log
7
+ memory-compiler/scripts/compile.log
8
+ memory-compiler/scripts/session-flush-*.md
9
+ memory-compiler/scripts/flush-context-*.md
10
+
11
+ # Handoff writer state (placed alongside handoff files)
12
+ **/handoff-state.json
13
+
14
+ # Git worktrees (superpowers / parallel feature work)
15
+ .worktrees/
16
+ # Native (harness) worktrees
17
+ .claude/worktrees/
18
+
19
+ # Superpowers brainstorm mockups / scratch
20
+ .superpowers/
21
+
22
+ # Agent-core runtime state (handoffs, bus.sqlite, transcripts, etc.)
23
+ .agent-core/
24
+
25
+ # Local scratch / smoke-test artifacts
26
+ .tmp/
27
+
28
+ # Claude Code per-machine local overrides
29
+ .claude/settings.local.json
30
+ .claude/*.lock
31
+
32
+ # Byte-compiled / optimized / DLL files
33
+ __pycache__/
34
+ *.py[codz]
35
+ *$py.class
36
+
37
+ # C extensions
38
+ *.so
39
+
40
+ # Distribution / packaging
41
+ .Python
42
+ build/
43
+ develop-eggs/
44
+ dist/
45
+ downloads/
46
+ eggs/
47
+ .eggs/
48
+ lib/
49
+ lib64/
50
+ parts/
51
+ sdist/
52
+ var/
53
+ wheels/
54
+ share/python-wheels/
55
+ *.egg-info/
56
+ .installed.cfg
57
+ *.egg
58
+ MANIFEST
59
+
60
+ # PyInstaller
61
+ # Usually these files are written by a python script from a template
62
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
63
+ *.manifest
64
+ *.spec
65
+
66
+ # Installer logs
67
+ pip-log.txt
68
+ pip-delete-this-directory.txt
69
+
70
+ # Unit test / coverage reports
71
+ htmlcov/
72
+ .tox/
73
+ .nox/
74
+ .coverage
75
+ .coverage.*
76
+ .cache
77
+ nosetests.xml
78
+ coverage.xml
79
+ *.cover
80
+ *.py.cover
81
+ .hypothesis/
82
+ .pytest_cache/
83
+ cover/
84
+
85
+ # Translations
86
+ *.mo
87
+ *.pot
88
+
89
+ # Django stuff:
90
+ *.log
91
+ local_settings.py
92
+ db.sqlite3
93
+ db.sqlite3-journal
94
+
95
+ # Flask stuff:
96
+ instance/
97
+ .webassets-cache
98
+
99
+ # Scrapy stuff:
100
+ .scrapy
101
+
102
+ # Sphinx documentation
103
+ docs/_build/
104
+
105
+ # PyBuilder
106
+ .pybuilder/
107
+ target/
108
+
109
+ # Jupyter Notebook
110
+ .ipynb_checkpoints
111
+
112
+ # IPython
113
+ profile_default/
114
+ ipython_config.py
115
+
116
+ # pyenv
117
+ # For a library or package, you might want to ignore these files since the code is
118
+ # intended to run in multiple environments; otherwise, check them in:
119
+ # .python-version
120
+
121
+ # pipenv
122
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
123
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
124
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
125
+ # install all needed dependencies.
126
+ #Pipfile.lock
127
+
128
+ # UV
129
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
130
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
131
+ # commonly ignored for libraries.
132
+ #uv.lock
133
+
134
+ # poetry
135
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
136
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
137
+ # commonly ignored for libraries.
138
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
139
+ #poetry.lock
140
+ #poetry.toml
141
+
142
+ # pdm
143
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
144
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
145
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
146
+ #pdm.lock
147
+ #pdm.toml
148
+ .pdm-python
149
+ .pdm-build/
150
+
151
+ # pixi
152
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
153
+ #pixi.lock
154
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
155
+ # in the .venv directory. It is recommended not to include this directory in version control.
156
+ .pixi
157
+
158
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
159
+ __pypackages__/
160
+
161
+ # Celery stuff
162
+ celerybeat-schedule
163
+ celerybeat.pid
164
+
165
+ # SageMath parsed files
166
+ *.sage.py
167
+
168
+ # Environments
169
+ .env
170
+ .envrc
171
+ .venv
172
+ env/
173
+ venv/
174
+ ENV/
175
+ env.bak/
176
+ venv.bak/
177
+
178
+ # Spyder project settings
179
+ .spyderproject
180
+ .spyproject
181
+
182
+ # Rope project settings
183
+ .ropeproject
184
+
185
+ # mkdocs documentation
186
+ /site
187
+
188
+ # mypy
189
+ .mypy_cache/
190
+ .dmypy.json
191
+ dmypy.json
192
+
193
+ # Pyre type checker
194
+ .pyre/
195
+
196
+ # pytype static type analyzer
197
+ .pytype/
198
+
199
+ # Cython debug symbols
200
+ cython_debug/
201
+
202
+ # PyCharm
203
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
204
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
205
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
206
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
207
+ #.idea/
208
+
209
+ # Abstra
210
+ # Abstra is an AI-powered process automation framework.
211
+ # Ignore directories containing user credentials, local state, and settings.
212
+ # Learn more at https://abstra.io/docs
213
+ .abstra/
214
+
215
+ # Visual Studio Code
216
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
217
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
218
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
219
+ # you could uncomment the following to ignore the entire vscode folder
220
+ # .vscode/
221
+
222
+ # Ruff stuff:
223
+ .ruff_cache/
224
+
225
+ # PyPI configuration file
226
+ .pypirc
227
+
228
+ # Cursor
229
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
230
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
231
+ # refer to https://docs.cursor.com/context/ignore-files
232
+ .cursorignore
233
+ .cursorindexingignore
234
+
235
+ # Marimo
236
+ marimo/_static/
237
+ marimo/_lsp/
238
+ __marimo__/
239
+ .gstack/
240
+
241
+ # macOS Finder metadata (occasionally sneaks in via vendored sources)
242
+ .DS_Store
243
+
244
+ # Operational docs that must not live in source control
245
+ pepper-vault-plan.txt
@@ -0,0 +1,21 @@
1
+ # Changelog
2
+
3
+ ## [0.8.1](https://github.com/jeffrichley/agent_core/compare/v0.8.0...agent-core-qa-v0.8.1) (2026-07-22)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * republish package family to complete rate-limited first publish ([#477](https://github.com/jeffrichley/agent_core/issues/477)) ([32977ac](https://github.com/jeffrichley/agent_core/commit/32977ac78da4a15553329bb4e1fdaa9e894834ad))
9
+
10
+ ## [0.8.0](https://github.com/jeffrichley/agent_core/compare/v0.7.0...agent-core-qa-v0.8.0) (2026-07-21)
11
+
12
+
13
+ ### Features
14
+
15
+ * **hatchery:** ungendered templates + .mcp.json generation ([#81](https://github.com/jeffrichley/agent_core/issues/81)/[#82](https://github.com/jeffrichley/agent_core/issues/82)) ([#357](https://github.com/jeffrichley/agent_core/issues/357)) ([f48762d](https://github.com/jeffrichley/agent_core/commit/f48762df78eb12cfa9524e9b5a277741534ea8a7)), closes [#311](https://github.com/jeffrichley/agent_core/issues/311)
16
+ * **release:** configure release-please for 12-package synchronized version train ([#428](https://github.com/jeffrichley/agent_core/issues/428)) ([c1b4097](https://github.com/jeffrichley/agent_core/commit/c1b409765c61d09a6657b0e8b5e43a27cb235b3e))
17
+
18
+
19
+ ### Bug Fixes
20
+
21
+ * log or justify bare except-pass swallows + test get_client factory (closes [#408](https://github.com/jeffrichley/agent_core/issues/408)) ([#471](https://github.com/jeffrichley/agent_core/issues/471)) ([e67783c](https://github.com/jeffrichley/agent_core/commit/e67783ccb4dfab6f1783d6a67223f475f81526ea))
@@ -0,0 +1,9 @@
1
+ Metadata-Version: 2.4
2
+ Name: agent-core-qa
3
+ Version: 0.8.2
4
+ Summary: Release-validation scenario runner for the agent_core daemon (pytest-based)
5
+ Requires-Python: >=3.12
6
+ Requires-Dist: fastmcp>=3.0
7
+ Requires-Dist: httpx>=0.27
8
+ Requires-Dist: pytest-asyncio>=0.23
9
+ Requires-Dist: pytest>=8.0
@@ -0,0 +1,49 @@
1
+ # agent-core-qa
2
+
3
+ Release-validation scenario runner for the agent_core daemon. **A tool, not a being.**
4
+
5
+ ## What it is
6
+
7
+ Seven pytest scenarios that exercise a running Phase 3.5 test daemon (`agent-core daemon --instance test`) end-to-end. Each scenario maps to a "v0.3.0 cannot ship if broken" surface: daemon liveness, envelope round-trip, install identity (dynamic keystone), brief framework, scheduler, discord_send, voice synthesis.
8
+
9
+ ## Tool-shaped, not being-shaped
10
+
11
+ This package is a test runner. It has:
12
+ - No `IDENTITY.md`, `SOUL.md`, `MEMORY.md`, `HEARTBEAT.md`, diary, breadcrumbs, or lessons.
13
+ - No continuity of self — each pytest invocation is fresh.
14
+ - No ethical weight — `rm -rf packages/agent-core-qa/` is functionally identical to deleting any pytest suite.
15
+ - No registration on the bus as a peer; it's an HTTP client that exits when done.
16
+
17
+ Same shape as `pytest` or `playwright`. Procedural capability through playbooks (scenario functions); nothing for the tool to know about itself.
18
+
19
+ ## Architectural inheritance: standing dynamic surface
20
+
21
+ From Phase 2.6's PR description, the bug-cadence observation: static artifact analysis caught Bugs 1-2; dynamic real install caught Bug 3. The next failure class — "does the daemon actually start after install" — was named as Phase 2.7 territory.
22
+
23
+ This package is the standing dynamic surface that catches that failure class (Scenario 1 as autouse fixture precondition) and every subsequent dynamic-only failure class on every release going forward. Phase 3.5 + Phase 2.6 + agent-core-qa is one continuous arc: build the sandbox, fix the install, prove the install still works release over release.
24
+
25
+ ## Runbook
26
+
27
+ ```bash
28
+ # v0.3.0 release-validation runbook
29
+ AGENT_CORE_HOME=~/.agent-core-test agent-core daemon install --instance test --release v0.3.0
30
+ agent-core daemon start --instance test
31
+ cd packages/agent-core-qa
32
+ uv run pytest tests/
33
+ # all 7 pass → safe to refresh prod
34
+ # any fail → fix the regression first
35
+ ```
36
+
37
+ For an already-running test daemon, `agent-core daemon refresh --instance test --release vX.Y.Z` does install + restart in one command.
38
+
39
+ **Runtime note:** `pytest tests/` triggers Scenario 3 (`test_install_identity_dynamic_keystone`), which performs a SECOND install into a sandbox at `/tmp/qa-<uuid>/` to prove the install path is idempotent against a clean home. On a cold cache the torch download alone can take 5–10 minutes; budget 10–15 minutes for a full validation run on first invocation, 2–3 minutes on subsequent runs once wheels are cached.
40
+
41
+ ## Scenarios
42
+
43
+ 1. `test_daemon_liveness` — precondition (autouse).
44
+ 2. `test_envelope_send_receives_ack` — bus round-trip.
45
+ 3. `test_install_identity_dynamic_keystone` — install code path identity at runtime (the load-bearing scenario for release validation).
46
+ 4. `test_brief_framework_compose_and_submit` — brief framework smoke.
47
+ 5. `test_scheduler_create_and_delete_roundtrip` — scheduler round-trip.
48
+ 6. `test_discord_send_tool_routes_through_stub` — discord_send tool dispatch with stubbed discord endpoint.
49
+ 7. `test_voice_synthesize_returns_audio_bytes` — voice synthesis smoke (no audio-quality validation).
@@ -0,0 +1 @@
1
+ 0.8.1
@@ -0,0 +1,31 @@
1
+ [project]
2
+ name = "agent-core-qa"
3
+ dynamic = ["version"]
4
+ description = "Release-validation scenario runner for the agent_core daemon (pytest-based)"
5
+ requires-python = ">=3.12"
6
+ dependencies = [
7
+ "pytest>=8.0",
8
+ "pytest-asyncio>=0.23",
9
+ "httpx>=0.27",
10
+ "fastmcp>=3.0",
11
+ ]
12
+
13
+ [build-system]
14
+ requires = ["hatchling", "uv-dynamic-versioning"]
15
+ build-backend = "hatchling.build"
16
+
17
+ [tool.hatch.build.targets.wheel]
18
+ packages = ["src/agent_core_qa"]
19
+
20
+ [tool.hatch.version]
21
+ source = "uv-dynamic-versioning"
22
+
23
+ [tool.uv-dynamic-versioning]
24
+ fallback-version = "0.0.0"
25
+
26
+ [tool.uv]
27
+ cache-keys = [{ file = "pyproject.toml" }, { git = { commit = true, tags = true } }]
28
+
29
+ [tool.pytest.ini_options]
30
+ asyncio_mode = "auto"
31
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ """agent-core-qa — release-validation scenario runner for the agent_core daemon.
2
+
3
+ Tool-shaped, not being-shaped. See README.md for the constraint set.
4
+ """
@@ -0,0 +1,294 @@
1
+ """DaemonClient — thin HTTP wrapper for the agent_core daemon.
2
+
3
+ Tool-shaped: stateless across calls, no connection pooling beyond what
4
+ httpx does internally, no retry, no session caching.
5
+
6
+ Transport discovery (Preflight Step 0, Task 3):
7
+ The daemon's HTTPHost (Starlette+Uvicorn) mounts only MCPHostable
8
+ endpoint paths — there is NO /bus/publish or /bus/inbox route.
9
+ Endpoints that implement MCPHostable (i.e. ClaudeCodeMCPEndpoint)
10
+ are mounted at /mcp/<name>/ and expose a FastMCP Streamable HTTP
11
+ server. StubEndpoint is NOT MCPHostable — it has no HTTP surface.
12
+
13
+ To publish an envelope from the QA runner, we call the `send` MCP
14
+ tool on a ClaudeCodeMCPEndpoint (e.g. the `qa` agent endpoint). The
15
+ tool stamps from_=<agent-name> and dispatches to `stub`. The stub's
16
+ auto_ack=True calls bus.ack() (marks it handled in persistence) but
17
+ does NOT publish an Acknowledgment envelope back to the sender.
18
+
19
+ Round-trip proof: the `send` tool call returns
20
+ {"status": "published", "id": <envelope_id>} synchronously after
21
+ the bus has dispatched and stub has delivered+acked. The bus is
22
+ single-threaded and dispatches in-process, so delivery is complete
23
+ before the tool returns. We then call `list_pending` on the same
24
+ agent endpoint to confirm the queue count=0 (nothing waiting).
25
+
26
+ Transport: fastmcp.Client connected to
27
+ http://<host>:<port>/mcp/<agent>/ (Streamable HTTP). Async methods
28
+ because fastmcp.Client is an async context manager.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import asyncio
34
+ import json
35
+ import socket
36
+ import time
37
+ import urllib.parse
38
+ from collections.abc import Callable
39
+ from typing import Any
40
+
41
+ try:
42
+ from fastmcp.client import Client as _FastMCPClient
43
+
44
+ _HAS_FASTMCP = True
45
+ except ImportError: # pragma: no cover
46
+ _HAS_FASTMCP = False
47
+
48
+
49
+ class _FakeTCPResponse:
50
+ """Mimics a minimal httpx.Response for callers of health_check().
51
+
52
+ Used when health_check() falls back to a TCP-connect check because
53
+ the daemon has no dedicated HTTP liveness route. status_code=200
54
+ means the port is accepting connections; status_code=503 means it
55
+ isn't (or the connect timed out).
56
+ """
57
+
58
+ def __init__(self, *, status_code: int, text: str = ""):
59
+ self.status_code = status_code
60
+ self.text = text
61
+
62
+
63
+ class _MCPToolResult:
64
+ """Thin wrapper around a fastmcp tool-call result.
65
+
66
+ Mimics the httpx.Response API used by callers so scenario code reads
67
+ the same regardless of whether the underlying transport is raw HTTP
68
+ or MCP-over-HTTP. status_code=200 means the tool call succeeded;
69
+ status_code=500 means the tool raised.
70
+ """
71
+
72
+ def __init__(self, *, status_code: int, data: Any = None, text: str = ""):
73
+ self.status_code = status_code
74
+ self._data = data
75
+ self.text = text
76
+
77
+ def json(self) -> Any:
78
+ return self._data
79
+
80
+
81
+ class DaemonClient:
82
+ """HTTP client for the agent_core daemon.
83
+
84
+ Targets the daemon's HTTP API (default http://127.0.0.1:8787 for the
85
+ Phase 3.5 test instance). One client per scenario; no shared state.
86
+
87
+ Transport: MCP tools over FastMCP Streamable HTTP at /mcp/<agent>/.
88
+ send_envelope() and poll_envelopes() are async — call them with
89
+ `await` from async test functions (pytest-asyncio asyncio_mode=auto).
90
+
91
+ Preflight finding: the daemon's HTTPHost (Starlette+Uvicorn) has no
92
+ dedicated liveness HTTP route — it only mounts MCP endpoint paths.
93
+ health_check() therefore uses a TCP-connect check on the bind port
94
+ rather than a GET to a specific path. A successful TCP connect means
95
+ the daemon process is up and its HTTP server is accepting connections.
96
+ """
97
+
98
+ def __init__(
99
+ self,
100
+ base_url: str,
101
+ *,
102
+ timeout: float = 10.0,
103
+ mcp_agent: str = "qa",
104
+ ):
105
+ self.base_url = base_url.rstrip("/")
106
+ self._timeout = timeout
107
+ self._mcp_agent = mcp_agent
108
+
109
+ @property
110
+ def _mcp_url(self) -> str:
111
+ """URL of the agent's MCP endpoint on the daemon."""
112
+ return f"{self.base_url}/mcp/{self._mcp_agent}/"
113
+
114
+ def health_check(self) -> _FakeTCPResponse:
115
+ """TCP-connect check on the daemon's bind port.
116
+
117
+ TCP-connect fallback: the daemon's HTTPHost (Starlette+Uvicorn)
118
+ exposes no dedicated liveness route — only MCP endpoint mounts.
119
+ A successful TCP connect on the bind port indicates the HTTP
120
+ server is accepting connections. Returns a response-like object
121
+ with status_code=200 on success or status_code=503 on failure.
122
+ """
123
+ parsed = urllib.parse.urlparse(self.base_url)
124
+ host = parsed.hostname or "127.0.0.1"
125
+ port = parsed.port or 80
126
+ try:
127
+ conn = socket.create_connection((host, port), timeout=self._timeout)
128
+ conn.close()
129
+ return _FakeTCPResponse(status_code=200, text="TCP connect OK")
130
+ except OSError as exc:
131
+ return _FakeTCPResponse(status_code=503, text=str(exc))
132
+
133
+ async def send_envelope(self, envelope: dict[str, Any]) -> _MCPToolResult:
134
+ """Call the `send` MCP tool on the agent's ClaudeCodeMCPEndpoint.
135
+
136
+ Transport: fastmcp.Client connected to /mcp/<agent>/ (Streamable
137
+ HTTP). The `send` tool accepts the envelope fields as kwargs and
138
+ publishes to the bus. The bus stamps from_=<agent-name>.
139
+
140
+ The tool returns {"status": "published", "id": <envelope_id>}
141
+ synchronously after the bus dispatches and the recipient endpoint
142
+ delivers+acks. This is the round-trip signal for the stub endpoint
143
+ (stub auto-acks but does NOT publish an Acknowledgment reply).
144
+
145
+ envelope fields consumed:
146
+ to, kind, payload, correlation_id, in_reply_to, metadata,
147
+ urgency, expires_at. The id field is advisory (daemon
148
+ generates a fresh uuid4 hex for each send call).
149
+ """
150
+ if not _HAS_FASTMCP: # pragma: no cover
151
+ return _MCPToolResult(
152
+ status_code=500,
153
+ text="fastmcp not installed; add fastmcp>=3.0 to agent-core-qa deps",
154
+ )
155
+
156
+ try:
157
+ async with _FastMCPClient(self._mcp_url, timeout=self._timeout) as mcp:
158
+ result = await mcp.call_tool(
159
+ "send",
160
+ arguments={
161
+ "to": envelope["to"],
162
+ "kind": envelope["kind"],
163
+ "payload": envelope.get("payload", {}),
164
+ "correlation_id": envelope.get("correlation_id"),
165
+ "in_reply_to": envelope.get("in_reply_to"),
166
+ "metadata": envelope.get("metadata", {}),
167
+ "urgency": envelope.get("urgency", "green"),
168
+ "expires_at": envelope.get("expires_at"),
169
+ },
170
+ )
171
+ # fastmcp returns a list of content items; unwrap the first text block.
172
+ data: Any = None
173
+ if result and hasattr(result[0], "text"):
174
+ try:
175
+ data = json.loads(result[0].text)
176
+ except (json.JSONDecodeError, AttributeError):
177
+ data = result[0].text if hasattr(result[0], "text") else str(result)
178
+ return _MCPToolResult(status_code=200, data=data, text=str(data))
179
+ except Exception as exc:
180
+ return _MCPToolResult(status_code=500, text=str(exc))
181
+
182
+ async def poll_envelopes(
183
+ self,
184
+ predicate: Callable[[dict[str, Any]], bool],
185
+ *,
186
+ timeout: float = 5.0,
187
+ interval: float = 0.2,
188
+ ) -> dict[str, Any] | None:
189
+ """Poll the agent's pickup queue for an envelope matching predicate.
190
+
191
+ Calls the `list_pending` MCP tool on the agent's
192
+ ClaudeCodeMCPEndpoint in a loop until predicate matches or
193
+ timeout expires. Returns the first matching envelope dict,
194
+ or None if nothing matched within timeout.
195
+
196
+ Note: for the builtin.stub round-trip, stub does NOT publish an
197
+ Acknowledgment envelope back to the sender — it only calls
198
+ bus.ack() (marks the envelope handled in persistence). Therefore
199
+ list_pending on the sender's queue should return count=0 after a
200
+ successful send. Use poll_envelopes only when a true reply
201
+ envelope is expected (e.g. scheduler, discord).
202
+ """
203
+ if not _HAS_FASTMCP: # pragma: no cover
204
+ return None
205
+
206
+ deadline = time.monotonic() + timeout
207
+ while time.monotonic() < deadline:
208
+ try:
209
+ async with _FastMCPClient(self._mcp_url, timeout=self._timeout) as mcp:
210
+ result = await mcp.call_tool("list_pending", arguments={})
211
+
212
+ data: Any = None
213
+ if result and hasattr(result[0], "text"):
214
+ try:
215
+ data = json.loads(result[0].text)
216
+ except (json.JSONDecodeError, AttributeError):
217
+ # Justified: a malformed tool payload is treated as "no
218
+ # data" and the poll loop retries on the next tick.
219
+ data = None
220
+ if isinstance(data, dict):
221
+ for item in data.get("items", []):
222
+ if predicate(item):
223
+ return item
224
+ except Exception:
225
+ # Justified: this is a best-effort poll loop over a flaky MCP
226
+ # connection; transient errors are swallowed so it keeps retrying
227
+ # until the deadline, then returns None below.
228
+ pass
229
+ await asyncio.sleep(interval)
230
+ return None
231
+
232
+ async def list_pending(self) -> dict[str, Any]:
233
+ """Return the agent's current pending queue snapshot.
234
+
235
+ Calls the `list_pending` MCP tool. Returns the raw result dict
236
+ {"meta": {...}, "items": [...]} or {"meta": {}, "items": []} on
237
+ failure.
238
+ """
239
+ if not _HAS_FASTMCP: # pragma: no cover
240
+ return {"meta": {}, "items": []}
241
+
242
+ try:
243
+ async with _FastMCPClient(self._mcp_url, timeout=self._timeout) as mcp:
244
+ result = await mcp.call_tool("list_pending", arguments={})
245
+
246
+ if result and hasattr(result[0], "text"):
247
+ try:
248
+ return json.loads(result[0].text)
249
+ except (json.JSONDecodeError, AttributeError):
250
+ # Justified: a malformed payload falls through to the empty
251
+ # snapshot returned below.
252
+ pass
253
+ except Exception:
254
+ # Justified: list_pending is best-effort; any MCP/transport failure
255
+ # degrades to the documented empty snapshot returned below.
256
+ pass
257
+ return {"meta": {}, "items": []}
258
+
259
+ async def call_tool(
260
+ self,
261
+ tool_name: str,
262
+ arguments: dict[str, Any] | None = None,
263
+ ) -> _MCPToolResult:
264
+ """Call any MCP tool on the agent's ClaudeCodeMCPEndpoint.
265
+
266
+ Generic escape hatch for tools beyond `send` and `list_pending`.
267
+ Used by Scenario 4 to call `compose_brief` and `submit_brief`
268
+ on the `qa` endpoint (which has the briefs tools mounted via
269
+ ``briefs_orchestrator`` wiring in the test daemon's config).
270
+
271
+ Returns an _MCPToolResult with status_code=200 on success (the
272
+ tool returned without raising) and status_code=500 on transport
273
+ error or tool exception. The parsed result is available via
274
+ ``.json()``; the raw text via ``.text``.
275
+ """
276
+ if not _HAS_FASTMCP: # pragma: no cover
277
+ return _MCPToolResult(
278
+ status_code=500,
279
+ text="fastmcp not installed; add fastmcp>=3.0 to agent-core-qa deps",
280
+ )
281
+
282
+ try:
283
+ async with _FastMCPClient(self._mcp_url, timeout=self._timeout) as mcp:
284
+ result = await mcp.call_tool(tool_name, arguments=arguments or {})
285
+
286
+ data: Any = None
287
+ if result and hasattr(result[0], "text"):
288
+ try:
289
+ data = json.loads(result[0].text)
290
+ except (json.JSONDecodeError, AttributeError):
291
+ data = result[0].text if hasattr(result[0], "text") else str(result)
292
+ return _MCPToolResult(status_code=200, data=data, text=str(data))
293
+ except Exception as exc:
294
+ return _MCPToolResult(status_code=500, text=str(exc))
File without changes