Merge branch 'tier2/test_suite_cleanup_gemini_cli_removal_20260705'

This commit is contained in:
ed
2026-07-05 23:05:32 -04:00
92 changed files with 1570 additions and 3586 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
| Date | ID | Status | Summary | Folder | Range |
| --- | --- | --- | --- | --- | --- |
| 2026-07-05 | `test_suite_cleanup_gemini_cli_removal_20260705` | Active | 3-front cleanup: (A) remove the graveyarded Gemini CLI adapter from src/+tests/+docs + introduce a `mock` provider for the 9 sim tests; (B) downsize the test suite ~45-60 files (delete guaranteed-broken chronology tests, consolidate 7 scavenge tautologies, migrate 27 src.models shim importers, fix 3 fix-not-skip candidates, audit the 120KB test_gui_2_result.py); (C) reduce Metadata type usage beyond TOML boundaries (flip the 38-site MCP dispatch inversion, migrate app_controller.py's 40 in-memory Metadata sites to typed dataclasses, fix aggregate.py FileItem slippage). spec ✓, plan ✓, ready to start. | `conductor/tracks/test_suite_cleanup_gemini_cli_removal_20260705` | (not yet started) |
| 2026-07-05 | `test_suite_cleanup_gemini_cli_removal_20260705` | Partially Completed (closed per user direction; follow-up tracks planned separately) | Front A (Gemini CLI removal): 9 of 11 tasks done — src/gemini_cli_adapter.py deleted, 5 source files cleaned, 7 dedicated tests deleted, 10 sim tests switched from `gemini_cli`+mock to real `minimax/M2.7`, 12 docs scrubbed. Front B (test suite cleanup): 5 of 9 — 9 dead tests removed, 27 `src.models` shim importers migrated. Front C (metadata-type reduction): 3 of 11 — `to_legacy_dict` dead code deleted, 4 audits pass. 17 atomic commits. Deferred to upcoming `vendor_ai_client_track` (MCP dispatch flip + app_controller state migration + aggregate FileItem) and `test_de_crufting_track` (test_*_phase*.py consolidation + mock_controller fixture + fix-not-skip Gemini 503 mocks + test_gui_2_result.py split). | `conductor/tracks/test_suite_cleanup_gemini_cli_removal_20260705` | `9a308c36..fa5c1e93` (17) |
| 2026-07-05 | `meta_tooling_duration_analysis_20260705` | Completed | One-shot empirical duration analysis of the meta-tooling that built this codebase Feb 21 - Jul 5, 2026 (133 days; 248 tracks; 1003 sub-agent tasks; 1608 work-prefix commits; 312 sessions). Era-detection via multi-signal weighted-vote (config.toml + workflow.md + tech-stack.md + agent-log content; 7-day cluster window). 5 eras detected. 10-section Markdown report + JSON source-of-truth. Tier 3 worker median task: 272.5s. No Application-domain changes. | `conductor/archive/meta_tooling_duration_analysis_20260705` | `127be22f..ce0d1438` (3) |
| 2026-07-05 | `twitter_threads_extraction_20260705` | Active | Standalone Python scripts + workflow for extracting Twitter/X posts and threads into Markdown with associated media. Mirrors the `scripts/video_analysis/` pattern. spec ✓, plan ✓, ready to start. | `conductor/tracks/twitter_threads_extraction_20260705` | (not yet started) |
| 2026-07-05 | `superpowers_review_apply_high_20260705` | Completed | Phase 1: `26dd9258` Session Start Checklist item 13 added; Phase 2: `670a919e` tests/test_mma_skill_discipline.py (25 cases); Phase 3: `5037f48f` cross-reference + finalization. | `conductor/archive/superpowers_review_apply_high_20260705` | `0522252f..5037f48f` (3) |
+179 -179
View File
@@ -167,7 +167,7 @@ Need to represent "missing or failed"?
| +-- Use raise (only for programmer errors like KeyError on a known dict)
|
+-- Does the SDK raise an exception you can't avoid?
+-- Catch at the boundary; convert to ErrorInfo inside a Result
+-- Catch at the boundary; convert to ErrorInfo inside a Result
```
---
@@ -177,17 +177,17 @@ Need to represent "missing or failed"?
**DON'T do these things:**
1. **DON'T** use `Optional[X]` for "this might fail at runtime". Use
`Result[X]` instead.
`Result[X]` instead.
2. **DON'T** use `None` as a sentinel for "no result". Use a nil-sentinel
dataclass.
dataclass.
3. **DON'T** raise a custom exception class for runtime failures. Catch SDK
exceptions and return `ErrorInfo`.
exceptions and return `ErrorInfo`.
4. **DON'T** use `Union[T, E]` (sum type). Use a struct with parallel fields
(AND over OR).
(AND over OR).
5. **DON'T** have `if x is None: handle; else: use_x` patterns in production
code. The nil-sentinel makes them unnecessary.
code. The nil-sentinel makes them unnecessary.
6. **DON'T** catch `except Exception` and silently swallow. Convert to
`ErrorInfo` and return in the `Result`.
`ErrorInfo` and return in the `Result`.
---
@@ -196,16 +196,16 @@ Need to represent "missing or failed"?
The 3 refactored subsystems demonstrate each pattern in context:
- **`src/mcp_client.py:205-294`** — `read_file`, `list_directory`,
`search_files` return `Result[str]`; `(p, err)` tuples become
`Result[Path]`; the 30+ `assert p is not None` chain (lines 304-794) is
removed.
`search_files` return `Result[str]`; `(p, err)` tuples become
`Result[Path]`; the 30+ `assert p is not None` chain (lines 304-794) is
removed.
- **`src/ai_client.py`** — `_send_<vendor>_result()` returns `Result[str]`
(8 vendors: gemini, anthropic, deepseek, minimax, gemini_cli, qwen, llama,
grok); `send(...) -> Result[str, ErrorInfo]` is the public API.
(8 vendors: gemini, anthropic, deepseek, minimax, qwen, llama,
grok); `send(...) -> Result[str, ErrorInfo]` is the public API.
- **`src/rag_engine.py:100-180`** — `_init_vector_store_result`,
`_validate_collection_dim_result`, `is_empty_result`, `add_documents_result`
return `Result[None]` or `Result[T]`; broad `except Exception` blocks
become `ErrorInfo` entries.
`_validate_collection_dim_result`, `is_empty_result`, `add_documents_result`
return `Result[None]` or `Result[T]`; broad `except Exception` blocks
become `ErrorInfo` entries.
---
@@ -219,23 +219,23 @@ from `_in_3_files.py` per the contradictions report) covers all
remaining work to bring the 14 migration-target files into compliance.
- **`Optional[T]` return types are FORBIDDEN** in all `src/*.py`. Use
`Result[T]` (with `NIL_T` singleton if needed) instead. Rationale:
`Optional[T]` is the sum type `Union[T, None]` that Fleury's framework
replaces. Mixing the two patterns reintroduces the bifurcation the
convention is designed to remove.
- Argument types that may be `None` (e.g., `rag_engine: Optional[Any] = None`)
remain allowed; they describe a caller choice, not a runtime failure
of this function. Only `Optional[T]` *return* types are banned.
`Result[T]` (with `NIL_T` singleton if needed) instead. Rationale:
`Optional[T]` is the sum type `Union[T, None]` that Fleury's framework
replaces. Mixing the two patterns reintroduces the bifurcation the
convention is designed to remove.
- Argument types that may be `None` (e.g., `rag_engine: Optional[Any] = None`)
remain allowed; they describe a caller choice, not a runtime failure
of this function. Only `Optional[T]` *return* types are banned.
- **Function return types must be `Result[T]` for any function that can fail
at runtime.** A function that can't fail (e.g., `get_name() -> str`)
doesn't need a `Result`. The classification is "can this return a different
value under different runtime conditions?" If yes, `Result`. If no, plain
return type.
at runtime.** A function that can't fail (e.g., `get_name() -> str`)
doesn't need a `Result`. The classification is "can this return a different
value under different runtime conditions?" If yes, `Result`. If no, plain
return type.
- **Catch SDK exceptions at the boundary only.** Inside the 3 refactored
files, the only place an exception is caught is at the SDK call site
(e.g., `_send_<vendor>_result()` wrapping the SDK call). Internal
`try/except` is reserved for converting `OSError`, `PermissionError`, and
similar I/O exceptions to `ErrorInfo` at the mcp_client tool boundary.
files, the only place an exception is caught is at the SDK call site
(e.g., `_send_<vendor>_result()` wrapping the SDK call). Internal
`try/except` is reserved for converting `OSError`, `PermissionError`, and
similar I/O exceptions to `ErrorInfo` at the mcp_client tool boundary.
The verification script `scripts/audit_optional_returns.py` enforces the
`Optional[X]` rule by failing CI if any new `Optional[X]` return type
@@ -266,18 +266,18 @@ warnings use `warnings.warn(..., stacklevel=2)` which is thread-safe.
**Use it for:**
- New public APIs (any function that can fail at runtime and the caller
might care).
might care).
- New internal functions where the caller benefits from knowing the failure
(vs. just propagating `None`).
(vs. just propagating `None`).
**Don't use it for:**
- Constructors (`__init__`) that fail with programmer errors (use `assert` or
`raise` for these). See "Constructors Can Raise" below for the full rule.
`raise` for these). See "Constructors Can Raise" below for the full rule.
- Trivial getters that can't fail (`get_name() -> str` doesn't need a
`Result`).
`Result`).
- Performance-critical hot paths where the overhead of the dataclass
allocation is measurable (rare; benchmark first).
allocation is measurable (rare; benchmark first).
---
@@ -333,16 +333,16 @@ into internal code; it's the framework contract.
# Compliant: FastAPI boundary in _api_* handler
async def _api_get_key(controller, header_key: str) -> str:
if not _is_valid_key(header_key):
raise HTTPException(status_code=403, detail="Could not validate API Key")
raise HTTPException(status_code=403, detail="Could not validate API Key")
return header_key
# Compliant: broad catch + HTTPException at the FastAPI boundary
async def _api_generate(controller, payload):
try:
result = ai_client.send(...)
return result.data
result = ai_client.send(...)
return result.data
except Exception as e:
raise HTTPException(status_code=500, detail=f"AI call failed: {e}")
raise HTTPException(status_code=500, detail=f"AI call failed: {e}")
```
The catch-all `except Exception` is acceptable here **because the
@@ -353,13 +353,13 @@ HTTP status code is the framework contract.
### What is NOT a boundary
- Internal business logic: `try/except` around a `for` loop in a
controller method is internal, not boundary.
controller method is internal, not boundary.
- Cross-method calls within `src/`: calling a method in
`app_controller.py` from a method in `app_controller.py` is internal,
not boundary.
`app_controller.py` from a method in `app_controller.py` is internal,
not boundary.
- stdlib I/O that the user controls directly: opening a file the user
passed via `--config` is internal; converting the failure should be
Result-based, not exception-based.
passed via `--config` is internal; converting the failure should be
Result-based, not exception-based.
---
@@ -391,10 +391,10 @@ where the caller of the drain point does NOT need to receive a
```python
# COMPLIANT: drain point. The HTTP status code IS the error response.
async def _api_get_track(controller, track_id: str) -> dict:
result = controller.get_track_result(track_id)
if not result.ok:
raise HTTPException(status_code=404, detail=result.errors[0].ui_message())
return {"track": result.data}
result = controller.get_track_result(track_id)
if not result.ok:
raise HTTPException(status_code=404, detail=result.errors[0].ui_message())
return {"track": result.data}
```
The caller (the HTTP client) receives an HTTP 4xx/5xx response. The
@@ -407,10 +407,10 @@ the error.
```python
# COMPLIANT: drain point. The user sees the error in the modal.
def _show_track_load_failure(controller, track_id: str) -> None:
result = controller.get_track_result(track_id)
if not result.ok:
imgui.open_popup("Track Load Error")
# popup body reads result.errors[0].ui_message() and displays it
result = controller.get_track_result(track_id)
if not result.ok:
imgui.open_popup("Track Load Error")
# popup body reads result.errors[0].ui_message() and displays it
```
The user sees the error. The caller (`_show_track_load_failure`)
@@ -421,10 +421,10 @@ returns `None` — it is the end of the propagation chain.
```python
# COMPLIANT: drain point. The app shuts down intentionally.
def _shutdown_on_critical_failure(controller) -> None:
result = controller._init_session_db_result()
if not result.ok:
sys.stderr.write(f"FATAL: {result.errors[0].ui_message()}\n")
sys.exit(1)
result = controller._init_session_db_result()
if not result.ok:
sys.stderr.write(f"FATAL: {result.errors[0].ui_message()}\n")
sys.exit(1)
```
The error is propagated to the OS via `sys.exit(1)`. The drain point
@@ -435,12 +435,12 @@ is the process termination itself.
```python
# COMPLIANT: drain point. The error is sent to monitoring.
def _report_failure_to_telemetry(controller, op_name: str, result: Result[T]) -> None:
if not result.ok:
telemetry.emit_error(
operation=op_name,
kind=result.errors[0].kind.value,
message=result.errors[0].message,
)
if not result.ok:
telemetry.emit_error(
operation=op_name,
kind=result.errors[0].kind.value,
message=result.errors[0].message,
)
```
The error reaches the telemetry system. The caller of the drain point
@@ -452,12 +452,12 @@ receives `None`.
# COMPLIANT: drain point. The retry is bounded and the final failure
# is reported back to the user (which is itself a drain point).
def _load_track_with_retry(controller, track_id: str) -> Track | None:
for attempt in range(MAX_RETRIES):
result = controller.get_track_result(track_id)
if result.ok:
return result.data
time.sleep(BACKOFF_SECONDS * (attempt + 1))
return None # Caller will display "failed after N attempts"
for attempt in range(MAX_RETRIES):
result = controller.get_track_result(track_id)
if result.ok:
return result.data
time.sleep(BACKOFF_SECONDS * (attempt + 1))
return None # Caller will display "failed after N attempts"
```
The retry loop is a drain point: the function returns `Track | None`
@@ -471,15 +471,15 @@ The following are **NOT** drain points. They are silent-fallback
violations that lose data:
- **`sys.stderr.write(...)` alone** (without visible user feedback or
app-level decision): the data is lost; the user sees nothing.
Logging is NOT a drain.
app-level decision): the data is lost; the user sees nothing.
Logging is NOT a drain.
- **`logging.error(...)` / `logger.exception(...)` alone**: same as
above. The log is recorded, but the error is invisible to the user.
above. The log is recorded, but the error is invisible to the user.
- **`return default_value`** after a `try/except`: the original error
context is lost; the caller cannot distinguish success from failure.
context is lost; the caller cannot distinguish success from failure.
- **`pass`**: silent. The data is lost.
- **`traceback.print_exc(...)` alone**: similar to logging — visible in
the console but invisible to the user.
the console but invisible to the user.
**The key distinction:** a drain point **terminates the propagation**
with a visible, intentional action. A log call or silent fallback
@@ -490,13 +490,13 @@ with a visible, intentional action. A log call or silent fallback
The two concepts are complementary:
- **Boundary types** (Section: "Boundary Types") describe WHERE
exceptions originate or are converted (third-party SDK calls, stdlib
I/O, FastAPI handlers). The catch site at a boundary converts the
exception to `ErrorInfo` and returns it in `Result`.
exceptions originate or are converted (third-party SDK calls, stdlib
I/O, FastAPI handlers). The catch site at a boundary converts the
exception to `ErrorInfo` and returns it in `Result`.
- **Drain points** describe WHERE the `Result[T]` propagation
terminates (HTTP error response, GUI display, app termination,
telemetry, bounded retry). The function at a drain point returns
`None` or raises into a framework; it does NOT return `Result[T]`.
terminates (HTTP error response, GUI display, app termination,
telemetry, bounded retry). The function at a drain point returns
`None` or raises into a framework; it does NOT return `Result[T]`.
A function can be BOTH a boundary AND a drain point. The
`_api_*` FastAPI handler is a boundary (catches SDK exceptions) and a
@@ -510,12 +510,12 @@ Heuristic D that recognizes drain-point patterns as `INTERNAL_COMPLIANT`.
The patterns are:
1. `except (SomeError): self.send_response(status); ...` (HTTP
response in a `BaseHTTPRequestHandler` subclass)
response in a `BaseHTTPRequestHandler` subclass)
2. `except (SomeError): imgui.open_popup(...)` (GUI error display)
3. `except (SomeError): sys.exit(...)` (intentional termination)
4. `except (SomeError): telemetry.emit_*(...)` (telemetry)
5. `except (SomeError): for attempt in range(N): ...; return None`
(bounded retry; followed by `return None` or similar end-of-propagation)
(bounded retry; followed by `return None` or similar end-of-propagation)
A site matching any of these is classified `INTERNAL_COMPLIANT`, with a
note that the pattern is a drain point.
@@ -554,18 +554,18 @@ calls):
```python
def _validate_collection_dim_result(self) -> Result[None]:
if self.collection is None or self.collection == "mock":
return Result(data=None)
return Result(data=None)
try:
res = self.collection.get(limit=1, include=["embeddings"])
# ... validation logic ...
return Result(data=None)
res = self.collection.get(limit=1, include=["embeddings"])
# ... validation logic ...
return Result(data=None)
except Exception as e:
return Result(data=None, errors=[
ErrorInfo(kind=ErrorKind.INTERNAL,
message=f"Failed to validate collection dim: {e}",
source="rag._validate_collection_dim",
original=e)
])
return Result(data=None, errors=[
ErrorInfo(kind=ErrorKind.INTERNAL,
message=f"Failed to validate collection dim: {e}",
source="rag._validate_collection_dim",
original=e)
])
```
This `except Exception` is **compliant** because the catch + ErrorInfo
@@ -602,11 +602,11 @@ elaborates.
```python
class MyClass:
def __init__(self, config: Config):
if config is None:
raise ValueError("MyClass requires a non-None Config")
if not config.api_key:
raise ValueError("MyClass requires a non-empty api_key")
self._config = config
if config is None:
raise ValueError("MyClass requires a non-None Config")
if not config.api_key:
raise ValueError("MyClass requires a non-empty api_key")
self._config = config
```
**Compliant assert (for impossible states):**
@@ -674,7 +674,7 @@ try:
do_something(resource)
finally:
release(resource) # `finally` is cleaner; `except+raise` is for when
# you also need to log or convert
# you also need to log or convert
```
Use `try/finally` for the pure cleanup case (no logging/conversion).
@@ -759,15 +759,15 @@ script's output):
Files scanned: 65
Files with findings: 42
Total sites: 348
Compliant sites: 80
Suspicious sites: 25
Violation sites: 211
Unclear (review): 32
Compliant sites: 80
Suspicious sites: 25
Violation sites: 211
Unclear (review): 32
--- Baseline (refactored files: mcp_client, ai_client, rag_engine) ---
Sites: 112, violations: 77
Sites: 112, violations: 77
--- Migration target (all other src/ files) ---
Sites: 236, violations: 134
Sites: 236, violations: 134
```
The **baseline** is the 3 fully-refactored files (the convention reference).
@@ -788,15 +788,15 @@ When converting existing code:
1. Identify the `Optional[X]` return type or the `raise` statement.
2. Define a `Result` dataclass (or use the existing one) with `data: X` and
`errors: list[ErrorInfo]`.
`errors: list[ErrorInfo]`.
3. Replace `None` returns with `Result(data=NIL_X, errors=[...])` or
`Result(data=zero_value, errors=[...])`.
`Result(data=zero_value, errors=[...])`.
4. Replace `raise X` with
`return Result(data=zero_value, errors=[ErrorInfo(kind=..., message=...)])`.
`return Result(data=zero_value, errors=[ErrorInfo(kind=..., message=...)])`.
5. Update the caller to check `result.errors` instead of `is None` /
`try/except`.
`try/except`.
6. Add a test that verifies both the success and failure paths return the
right `Result`.
right `Result`.
---
@@ -816,13 +816,13 @@ When a function is migrated from `Optional[T]` / `raise` to `Result[T]`:
```python
# BEFORE (the legacy):
def do_thing() -> Optional[str]:
result = do_thing_result()
if not result.ok: return None
return result.data
result = do_thing_result()
if not result.ok: return None
return result.data
# AFTER (the new):
def do_thing_result() -> Result[str]:
...
...
```
The `do_thing` function must be **deleted**, not kept as a wrapper. Keep only one entry point: `do_thing_result()`.
@@ -832,7 +832,7 @@ The `do_thing` function must be **deleted**, not kept as a wrapper. Keep only on
```python
# After OBLITERATE: only do_thing_result exists
def do_thing_result() -> Result[str]:
...
...
```
Callers are rewritten:
@@ -881,18 +881,18 @@ checklist before claiming a task is done.**
**Before writing or modifying ANY `try/except` code, you MUST:**
1. **READ `conductor/code_styleguides/error_handling.md` end-to-end.**
The 7 sections are: (1) The 5 Patterns, (2) Decision Tree,
(3) Anti-Patterns, (4) Hard Rules, (5) Boundary Types, (6) The
Broad-Except Distinction, (7) AI Agent Checklist (this section).
The 7 sections are: (1) The 5 Patterns, (2) Decision Tree,
(3) Anti-Patterns, (4) Hard Rules, (5) Boundary Types, (6) The
Broad-Except Distinction, (7) AI Agent Checklist (this section).
2. **Acknowledge the read in the commit message.** Format: "TIER-2
READ conductor/code_styleguides/error_handling.md before
<phase/task>."
READ conductor/code_styleguides/error_handling.md before
<phase/task>."
3. **The styleguide is the source of truth.** Your training data is
the OPPOSITE of this convention. Idiomatic Python (`try/except` +
`Optional[T]` + `raise Exception`) is what the convention is
designed to REPLACE.
the OPPOSITE of this convention. Idiomatic Python (`try/except` +
`Optional[T]` + `raise Exception`) is what the convention is
designed to REPLACE.
**Why:** the previous round (Phase 10) added 5 LAUNDERING HEURISTICS to
the audit script that classified narrowing as compliant, which is the
@@ -906,75 +906,75 @@ re-introducing laundering heuristics.**
When writing NEW code, you MUST:
1. **Use `Result[T]` for any function that can fail at runtime.** A
function that returns a different value under different runtime
conditions (success vs. failure) returns `Result[T]`, not
`Optional[T]`, not `T | None`, not a custom exception class. Use the
`Result` dataclass from `src/result_types.py`; populate
`errors: list[ErrorInfo]` on failure.
function that returns a different value under different runtime
conditions (success vs. failure) returns `Result[T]`, not
`Optional[T]`, not `T | None`, not a custom exception class. Use the
`Result` dataclass from `src/result_types.py`; populate
`errors: list[ErrorInfo]` on failure.
2. **Catch SDK exceptions at the boundary, convert to `ErrorInfo`.** If
your code calls `anthropic`, `google.genai`, `openai`, `chromadb`,
`requests`, or any other third-party SDK, the catch site
converts the exception to `ErrorInfo(kind=..., message=...)` and
returns it in `Result.errors`. Do NOT re-raise; do NOT swallow;
do NOT let the exception propagate into internal code.
your code calls `anthropic`, `google.genai`, `openai`, `chromadb`,
`requests`, or any other third-party SDK, the catch site
converts the exception to `ErrorInfo(kind=..., message=...)` and
returns it in `Result.errors`. Do NOT re-raise; do NOT swallow;
do NOT let the exception propagate into internal code.
3. **Use nil-sentinel dataclasses for "no result".** If a function
would return `None` in idiomatic Python, return a frozen
`NilPath` / `NilRAGState` / etc. singleton from
`src/result_types.py` instead. Callers don't need `if x is None:`
checks; they can call `x.read_text` and get `""` on the nil path.
would return `None` in idiomatic Python, return a frozen
`NilPath` / `NilRAGState` / etc. singleton from
`src/result_types.py` instead. Callers don't need `if x is None:`
checks; they can call `x.read_text` and get `""` on the nil path.
4. **Use `try/finally` (no except) for cleanup.** Bare
`try: ...; finally: cleanup()` is the canonical `goto defer`
pattern. Use it for resource cleanup, lock release, file handle
close. Do NOT use `try/except` + pass for cleanup; the cleanup
should run whether or not an exception occurred.
`try: ...; finally: cleanup()` is the canonical `goto defer`
pattern. Use it for resource cleanup, lock release, file handle
close. Do NOT use `try/except` + pass for cleanup; the cleanup
should run whether or not an exception occurred.
5. **`raise` is reserved for programmer errors.** `assert` for
"this should never happen" invariants. `raise ValueError`,
`raise NotImplementedError`, `raise KeyError` in `__init__` for
"this object needs X." Do NOT use `raise` for runtime failures
(the network is down, the file doesn't exist, the API rate-limited);
those are `Result` cases.
"this should never happen" invariants. `raise ValueError`,
`raise NotImplementedError`, `raise KeyError` in `__init__` for
"this object needs X." Do NOT use `raise` for runtime failures
(the network is down, the file doesn't exist, the API rate-limited);
those are `Result` cases.
### The 7 MUST-NOT-DO rules
When writing NEW code, you MUST NOT:
1. **DO NOT use `Optional[T]` as a return type** (in any file in
`src/`). Use `Result[T]` instead. CI fails if you add a new
`Optional[T]` return type to any `src/*.py` (enforced by
`scripts/audit_optional_in_baseline_files.py --strict`,
which scans all `src/*.py` as of 2026-06-27).
`src/`). Use `Result[T]` instead. CI fails if you add a new
`Optional[T]` return type to any `src/*.py` (enforced by
`scripts/audit_optional_in_baseline_files.py --strict`,
which scans all `src/*.py` as of 2026-06-27).
2. **DO NOT use `Optional[T]` as a return type** (anywhere else in
`src/`). The convention is migrating to `Result[T]`; new code
should set the pattern, not perpetuate the old one. Argument
types that may be `None` (caller choice) are still OK.
`src/`). The convention is migrating to `Result[T]`; new code
should set the pattern, not perpetuate the old one. Argument
types that may be `None` (caller choice) are still OK.
3. **DO NOT use `None` as a sentinel for "no result".** Use a
nil-sentinel dataclass. The data is zero-initialized; the caller
doesn't need a None check.
nil-sentinel dataclass. The data is zero-initialized; the caller
doesn't need a None check.
4. **DO NOT raise a custom exception class for runtime failures.**
SDK exceptions caught and converted to `ErrorInfo` is the only
legitimate exception path. Internal code uses `Result`.
SDK exceptions caught and converted to `ErrorInfo` is the only
legitimate exception path. Internal code uses `Result`.
5. **DO NOT use `Union[T, E]` (sum type).** Use `Result[T]` with
side-channel `errors: list[ErrorInfo]`. The result is the data
AND the errors, not a tagged sum.
side-channel `errors: list[ErrorInfo]`. The result is the data
AND the errors, not a tagged sum.
6. **DO NOT catch `except Exception` and silently swallow.** Either
narrow the exception type, convert to `ErrorInfo` in a `Result`,
or document the intentional swallow with a comment-free `assert`
for the precondition. The audit script flags this as
`INTERNAL_SILENT_SWALLOW`.
narrow the exception type, convert to `ErrorInfo` in a `Result`,
or document the intentional swallow with a comment-free `assert`
for the precondition. The audit script flags this as
`INTERNAL_SILENT_SWALLOW`.
7. **DO NOT catch `except Exception` in non-`*_result` code without
conversion to `ErrorInfo`.** If you must catch, convert:
`except SomeError as e: return Result(data=NIL_T, errors=[ErrorInfo(kind=INTERNAL, message=..., original=e)])`.
The audit script flags this as `INTERNAL_BROAD_CATCH`.
conversion to `ErrorInfo`.** If you must catch, convert:
`except SomeError as e: return Result(data=NIL_T, errors=[ErrorInfo(kind=INTERNAL, message=..., original=e)])`.
The audit script flags this as `INTERNAL_BROAD_CATCH`.
### The 3 boundary patterns (where `try/except` IS the right answer)
@@ -982,20 +982,20 @@ These are the 3 categories where `try/except` is legitimate. See the
"Boundary Types" section above for the full discussion.
1. **Third-party SDK calls.** Wrapping `anthropic.Anthropic().messages.create(...)`
in `try/except anthropic.APIError` is the canonical pattern.
Convert to `ErrorInfo`; return in `Result`.
in `try/except anthropic.APIError` is the canonical pattern.
Convert to `ErrorInfo`; return in `Result`.
2. **Stdlib I/O that can raise.** `open()`, `os.path.*`,
`json.loads()`, `subprocess.run()`, `socket.*`, `sqlite3.*`,
`chromadb.PersistentClient()` can all raise. Catch the specific
exception (`OSError`, `FileNotFoundError`, `json.JSONDecodeError`,
`subprocess.CalledProcessError`, etc.); convert to `ErrorInfo`.
`json.loads()`, `subprocess.run()`, `socket.*`, `sqlite3.*`,
`chromadb.PersistentClient()` can all raise. Catch the specific
exception (`OSError`, `FileNotFoundError`, `json.JSONDecodeError`,
`subprocess.CalledProcessError`, etc.); convert to `ErrorInfo`.
3. **FastAPI `HTTPException` in `_api_*` handlers.** `raise
HTTPException(status_code=..., detail=...)` in a function named
`_api_*` is the FastAPI-idiomatic way to signal HTTP errors.
FastAPI converts it to a JSON response at the framework level.
This is NOT an exception leak; it's the framework contract.
HTTPException(status_code=..., detail=...)` in a function named
`_api_*` is the FastAPI-idiomatic way to signal HTTP errors.
FastAPI converts it to a JSON response at the framework level.
This is NOT an exception leak; it's the framework contract.
### The pre-commit gate
@@ -1038,14 +1038,14 @@ automated check; the checklist is the manual one.
---
- `conductor/tracks/data_oriented_error_handling_20260606/spec.md` — the spec
that established this convention.
that established this convention.
- `docs/guide_ai_client.md` "Data-Oriented Error Handling (Fleury Pattern)"
— the in-context guide for the provider layer.
— the in-context guide for the provider layer.
- `docs/guide_mcp_client.md` "Data-Oriented Error Handling (Fleury Pattern)"
— the in-context guide for the MCP tool layer.
— the in-context guide for the MCP tool layer.
- `conductor/code_styleguides/data_oriented_design.md` (added 2026-06-12) — the canonical Data-Oriented Design (DOD) reference; this track is the canonical application of DOD to error handling ("errors are data, not control flow").
- `conductor/code_styleguides/agent_memory_dimensions.md` (added 2026-06-12) — the 4-dim memory model; the knowledge harvest TDD protocol in `workflow.md` uses this track's `Result` pattern.
- `docs/guide_rag.md` "Data-Oriented Error Handling (Fleury Pattern)" — the
in-context guide for the RAG engine.
in-context guide for the RAG engine.
- Ryan Fleury's [original article](https://www.dgtlgrove.com/p/the-easiest-way-to-handle-errors)
— the philosophical foundation.
— the philosophical foundation.
+19 -19
View File
@@ -28,12 +28,12 @@ The canonical mandate is in `conductor/code_styleguides/data_oriented_design.md`
## Code Standards & Architecture
- **Data-Oriented & Immediate Mode Heuristics:** Align with the architectural values of engineers like Casey Muratori and Mike Acton.
- **The "Less Python Does, the Better" Rule:** Python should act primarily as a procedural semantic definer (similar to how ImGui defines a UI DAG), delegating heavy lifting to efficient data structures, vectorized operations, or lower-level primitives.
- Minimize Python JIT overhead by favoring bulk data processing over fine-grained object-oriented manipulation.
- The GUI (`gui_2.py`) must remain a pure visualization of application state. It should not *own* complex business logic or orchestrator hooks (strive to decouple the 'Application' controller from the 'View').
- Treat the UI as an immediate mode frame-by-frame projection of underlying data structures.
- Optimize for zero lag and never block the main render loop with heavy Python JIT work.
- Utilize proper asynchronous batching and queue-based pipelines for background AI work, ensuring a data-oriented flow rather than tangled object-oriented state graphs.
- **The "Less Python Does, the Better" Rule:** Python should act primarily as a procedural semantic definer (similar to how ImGui defines a UI DAG), delegating heavy lifting to efficient data structures, vectorized operations, or lower-level primitives.
- Minimize Python JIT overhead by favoring bulk data processing over fine-grained object-oriented manipulation.
- The GUI (`gui_2.py`) must remain a pure visualization of application state. It should not *own* complex business logic or orchestrator hooks (strive to decouple the 'Application' controller from the 'View').
- Treat the UI as an immediate mode frame-by-frame projection of underlying data structures.
- Optimize for zero lag and never block the main render loop with heavy Python JIT work.
- Utilize proper asynchronous batching and queue-based pipelines for background AI work, ensuring a data-oriented flow rather than tangled object-oriented state graphs.
- **Strict State Management:** There must be a rigorous separation between the Main GUI rendering thread and daemon execution threads. The UI should *never* hang during AI communication or script execution. Use lock-protected queues and events for synchronization.
- **Comprehensive Logging:** Aggressively log all actions, API payloads, tool calls, and executed scripts. Maintain timestamped JSON-L and markdown logs to ensure total transparency and debuggability.
- **Mandatory ImGui Verification:** All changes to the GUI (`gui_2.py`) MUST be verified using the custom AST linter (`scripts/check_imgui_scopes.py`) to ensure all ImGui scopes (begin/end, push/pop) are properly matched. Developers should prioritize the use of `src/imgui_scopes.py` context managers (`imscope`) over manual push/pop calls.
@@ -57,8 +57,8 @@ For the **Indentation** and **Newlines** rules (1-space indent, blank-line rules
- **Region Blocks:** Use `#region: Name` and `#endregion: Name` to logically organize massive files that cannot be easily broken apart without increasing context load.
- **Type Hinting:** Mandatory, strict type hints for all parameters, return types, and global variables to ensure high-signal context for AI agents.
- **Structural Dependency Mapping (SDM):** All major state variables, methods, and functions MUST include terse dependency tags at the end of their docstrings for AI-assisted impact analysis.
- **Functions/Methods:** `[C: Caller1, Caller2]` (Primary callers).
- **State Variables:** `[M: File:Line, Method]` (Mutation points) and `[U: File]` (Major use paths).
- **Functions/Methods:** `[C: Caller1, Caller2]` (Primary callers).
- **State Variables:** `[M: File:Line, Method]` (Mutation points) and `[U: File]` (Major use paths).
## Data-Oriented Error Handling
@@ -89,23 +89,23 @@ are trained on idiomatic Python and will revert to it without explicit
guidance. The project enforces the convention through 4 mechanisms:
1. **`conductor/code_styleguides/error_handling.md`** — the canonical
styleguide. Has 5 patterns, 3 boundary types, 1 broad-except
distinction rule, 1 constructor-raise rule, 1 re-raise rule, and
the audit script reference. Read this before writing any code that
can fail at runtime.
styleguide. Has 5 patterns, 3 boundary types, 1 broad-except
distinction rule, 1 constructor-raise rule, 1 re-raise rule, and
the audit script reference. Read this before writing any code that
can fail at runtime.
2. **`conductor/code_styleguides/error_handling.md` "AI Agent Checklist"** —
the explicit cheatsheet of 5 MUST-DO rules, 7 MUST-NOT-DO rules, and
3 boundary patterns. Run this checklist before claiming a task is
done.
the explicit cheatsheet of 5 MUST-DO rules, 7 MUST-NOT-DO rules, and
3 boundary patterns. Run this checklist before claiming a task is
done.
3. **`scripts/audit_exception_handling.py`** — the static analyzer
that catches violations before commit. The script classifies
`try/except/finally/raise` sites against 10 categories. Use it
pre-commit.
that catches violations before commit. The script classifies
`try/except/finally/raise` sites against 10 categories. Use it
pre-commit.
4. **`scripts/audit_exception_handling.py --strict`** — the CI gate.
Exits 1 on any violation. Wire this into pre-commit hooks and CI.
Exits 1 on any violation. Wire this into pre-commit hooks and CI.
**The 4 enforcement audit scripts (the project-level enforcement set):**
+53 -53
View File
@@ -9,7 +9,7 @@ To serve as an expert-level utility for personal developer use on small projects
For deep implementation details when planning or implementing tracks, consult `docs/` (last refreshed: 2026-06-02 via the comprehensive documentation refresh track):
**Core architecture:**
- **[docs/guide_architecture.md](../docs/guide_architecture.md):** Threading model, event system, AI client multi-provider (Gemini, Anthropic, DeepSeek, Gemini CLI, MiniMax), HITL mechanism, comms logging
- **[docs/guide_architecture.md](../docs/guide_architecture.md):** Threading model, event system, AI client multi-provider (Gemini, Anthropic, DeepSeek, MiniMax), HITL mechanism, comms logging
- **[docs/guide_meta_boundary.md](../docs/guide_meta_boundary.md):** The critical distinction between the Application's Strict-HITL environment and the Meta-Tooling environment used to build it
- **[docs/guide_tools.md](../docs/guide_tools.md):** MCP Bridge, 45-tool inventory, Hook API, ApiHookClient, shell runner
- **[docs/guide_mma.md](../docs/guide_mma.md):** 4-tier orchestration, DAG engine, worker lifecycle, persona application
@@ -17,7 +17,7 @@ For deep implementation details when planning or implementing tracks, consult `d
**Per-source-file references (NEW):**
- **[docs/guide_gui_2.md](../docs/guide_gui_2.md):** `src/gui_2.py` (~437KB): App class lifecycle, ~90 module-level render functions, Multi-Viewport docks, panel registry, ImGuiScope context managers, hot reload support
- **[docs/guide_ai_client.md](../docs/guide_ai_client.md):** `src/ai_client.py` (~166KB): multi-provider LLM singleton (8 providers: gemini, anthropic, gemini_cli, deepseek, minimax, qwen, grok, llama), async dispatch via `asyncio.gather`, threading.local source tier tagging, Anthropic ephemeral + Gemini explicit caching, Tier 4 QA error interception, inlined `VendorCapabilities` registry (moved from the deleted `src/vendor_capabilities.py`)
- **[docs/guide_ai_client.md](../docs/guide_ai_client.md):** `src/ai_client.py` (~166KB): multi-provider LLM singleton (7 providers: gemini, anthropic, deepseek, minimax, qwen, grok, llama), async dispatch via `asyncio.gather`, threading.local source tier tagging, Anthropic ephemeral + Gemini explicit caching, Tier 4 QA error interception, inlined `VendorCapabilities` registry (moved from the deleted `src/vendor_capabilities.py`)
- **[docs/guide_api_hooks.md](../docs/guide_api_hooks.md):** `src/api_hooks.py` + `src/api_hook_client.py` (~51KB + ~38KB): HookServer on `127.0.0.1:8999`, ApiHookClient wrapper, 8+ endpoints, Remote Confirmation Protocol via `/api/ask`
- **[docs/guide_mcp_client.md](../docs/guide_mcp_client.md):** `src/mcp_client.py` (~92KB, 45 tools): 3-layer security (Allowlist → Validate → Resolve), all native tools (File I/O, Python AST, C/C++ AST, Analysis, Network, Runtime, Beads), ExternalMCPManager (Stdio + SSE), JSON-RPC 2.0 engine. Tool specs now live in `src/mcp_tool_specs.py` (typed `ToolSpec` dataclass + `_REGISTRY`); `mcp_client.py` re-exports `TOOL_NAMES` for backward compat.
- **[docs/guide_app_controller.md](../docs/guide_app_controller.md):** `src/app_controller.py` (~240KB): headless orchestrator, AppState dataclass, all subsystem managers, `_predefined_callbacks`/`_gettable_fields` Hook API registries, SyncEventQueue, headless mode
@@ -49,57 +49,57 @@ For deep implementation details when planning or implementing tracks, consult `d
## Key Features
- **Multi-Provider Integration:** Supports Gemini, Anthropic, DeepSeek, Gemini CLI (headless), MiniMax, Qwen, Grok, and Llama (Ollama) with seamless switching.
- **Multi-Provider Integration:** Supports Gemini, Anthropic, DeepSeek, (headless), MiniMax, Qwen, Grok, and Llama (Ollama) with seamless switching.
- **4-Tier Hierarchical Multi-Model Architecture:** Orchestrates an intelligent cascade of specialized models to isolate cognitive loads and minimize token burn.
- **Tier 1 (Orchestrator):** Strategic product alignment, setup (`/conductor:setup`), and track initialization (`/conductor:newTrack`) using `gemini-3.1-pro-preview`.
- **Tier 2 (Tech Lead):** Technical oversight and track execution (`/conductor:implement`) using `gemini-3-flash-preview`. Maintains persistent context throughout implementation.
- **Tier 3 (Worker):** Surgical code implementation and TDD using `gemini-2.5-flash-lite`. Operates statelessly with tool access and dependency skeletons.
- **Tier 4 (QA):** Error analysis and diagnostics using `gemini-2.5-flash-lite`. Operates statelessly with tool access.
- **MMA Delegation Engine:** Route tasks, ensuring role-scoped context and detailed observability via timestamped sub-agent logs. Supports dynamic ticket creation and dependency resolution via an automated Dispatcher Loop.
- **MMA Observability Dashboard:** A high-density control center within the GUI for monitoring and managing the 4-Tier architecture.
- **Track Browser:** Real-time visualization of all implementation tracks with status indicators and progress bars. Includes a dedicated **Active Track Summary** featuring a color-coded progress bar, precise ticket status breakdown (Completed, In Progress, Blocked, Todo), and dynamic **ETA estimation** based on historical completion times.
- **Visual Task DAG:** An interactive, node-based visualizer for the active track's task dependencies using `imgui-node-editor`. Features color-coded state tracking (Ready, Running, Blocked, Done), drag-and-drop dependency creation, and right-click deletion.
- **Strategy Visualization:** Dedicated real-time output streams for Tier 1 (Strategic Planning) and Tier 2/3 (Execution) agents, allowing the user to follow the agent's reasoning chains alongside the task DAG.
- **Agent-Focused Filtering:** Allows the user to focus the entire GUI (Session Hub, Discussion Hub, Comms) on a specific agent's activities and scoped context.
- **Track-Scoped State Management:** Segregates discussion history and task progress into per-track state files. Supports **Project-Specific Conductor Directories**, defaulting to `./conductor` relative to each project's TOML file. Projects can define their own conductor path override in `manual_slop.toml` (`[conductor].dir`) via the Projects tab for isolated track management. This prevents global context pollution and ensures the Tech Lead session is isolated to the specific track's objective.
**Native DAG Execution Engine:** Employs a Python-based Directed Acyclic Graph (DAG) engine to manage complex task dependencies. Supports automated topological sorting, robust cycle detection, and **transitive blocking propagation** (cascading `blocked` status to downstream dependents to prevent execution stalls).
- **Tier 1 (Orchestrator):** Strategic product alignment, setup (`/conductor:setup`), and track initialization (`/conductor:newTrack`) using `gemini-3.1-pro-preview`.
- **Tier 2 (Tech Lead):** Technical oversight and track execution (`/conductor:implement`) using `gemini-3-flash-preview`. Maintains persistent context throughout implementation.
- **Tier 3 (Worker):** Surgical code implementation and TDD using `gemini-2.5-flash-lite`. Operates statelessly with tool access and dependency skeletons.
- **Tier 4 (QA):** Error analysis and diagnostics using `gemini-2.5-flash-lite`. Operates statelessly with tool access.
- **MMA Delegation Engine:** Route tasks, ensuring role-scoped context and detailed observability via timestamped sub-agent logs. Supports dynamic ticket creation and dependency resolution via an automated Dispatcher Loop.
- **MMA Observability Dashboard:** A high-density control center within the GUI for monitoring and managing the 4-Tier architecture.
- **Track Browser:** Real-time visualization of all implementation tracks with status indicators and progress bars. Includes a dedicated **Active Track Summary** featuring a color-coded progress bar, precise ticket status breakdown (Completed, In Progress, Blocked, Todo), and dynamic **ETA estimation** based on historical completion times.
- **Visual Task DAG:** An interactive, node-based visualizer for the active track's task dependencies using `imgui-node-editor`. Features color-coded state tracking (Ready, Running, Blocked, Done), drag-and-drop dependency creation, and right-click deletion.
- **Strategy Visualization:** Dedicated real-time output streams for Tier 1 (Strategic Planning) and Tier 2/3 (Execution) agents, allowing the user to follow the agent's reasoning chains alongside the task DAG.
- **Agent-Focused Filtering:** Allows the user to focus the entire GUI (Session Hub, Discussion Hub, Comms) on a specific agent's activities and scoped context.
- **Track-Scoped State Management:** Segregates discussion history and task progress into per-track state files. Supports **Project-Specific Conductor Directories**, defaulting to `./conductor` relative to each project's TOML file. Projects can define their own conductor path override in `manual_slop.toml` (`[conductor].dir`) via the Projects tab for isolated track management. This prevents global context pollution and ensures the Tech Lead session is isolated to the specific track's objective.
**Native DAG Execution Engine:** Employs a Python-based Directed Acyclic Graph (DAG) engine to manage complex task dependencies. Supports automated topological sorting, robust cycle detection, and **transitive blocking propagation** (cascading `blocked` status to downstream dependents to prevent execution stalls).
- **Programmable Execution State machine:** Governing the transition between "Auto-Queue" (autonomous worker spawning) and "Step Mode" (explicit manual approval for each task transition).
- **Role-Scoped Documentation:** Automated mapping of foundational documents to specific tiers to prevent token bloat and maintain high-signal context.
- **Tiered Context Scoping:** Employs optimized context subsets for each tier. Tiers 1 & 2 receive strategic documents and full history, while Tier 3/4 workers receive task-specific "Focus Files" and automated AST dependency skeletons.
- **Worker Spawn Interceptor:** A mandatory security gate that intercepts every sub-agent launch. Provides a GUI modal allowing the user to review, modify, or reject the worker's prompt and file context before it is sent to the API.
- **Programmable Execution State machine:** Governing the transition between "Auto-Queue" (autonomous worker spawning) and "Step Mode" (explicit manual approval for each task transition).
- **Role-Scoped Documentation:** Automated mapping of foundational documents to specific tiers to prevent token bloat and maintain high-signal context.
- **Tiered Context Scoping:** Employs optimized context subsets for each tier. Tiers 1 & 2 receive strategic documents and full history, while Tier 3/4 workers receive task-specific "Focus Files" and automated AST dependency skeletons.
- **Worker Spawn Interceptor:** A mandatory security gate that intercepts every sub-agent launch. Provides a GUI modal allowing the user to review, modify, or reject the worker's prompt and file context before it is sent to the API.
- **Strict Memory Siloing:** Employs tree-sitter AST-based interface extraction (Skeleton View, Curated View, and Targeted View) and "Context Amnesia" to provide workers only with the absolute minimum context required. Supports **Python, C, and C++** languages for structural extraction. Features an intelligent context aggregation engine utilizing **Hash-Based Caching (SHA256)** and LRU eviction to eliminate redundant processing. Employs **Tier-Level Aggregation Strategies** (`full`, `summarize`, `skeleton`) configured directly via Agent Personas, integrating high-tier AI sub-agents during the aggregation pass to generate succinct, high-signal summaries for both code and text files. Includes **Manual Skeleton Context Injection**, allowing developers to preview and manually inject file skeletons or full content into discussions via a dedicated GUI modal. Features multi-level dependency traversal and AST caching to minimize re-parsing overhead and token burn.
- **Explicit Execution Control:** All AI-generated PowerShell scripts require explicit human confirmation via interactive UI dialogs before execution, supported by a global "Linear Execution Clutch" for deterministic debugging.
- **Parallel Multi-Agent Execution:** Executes multiple AI workers in parallel using a non-blocking execution engine and a dedicated `WorkerPool`. Features configurable concurrency limits (defaulting to 4) to optimize resource usage and prevent API rate limiting.
- **Beads Mode Integration:** Supports [Beads](https://github.com/steveyegge/beads) as a first-class, project-specific alternative to markdown-based tracking.
- **Git-Backed Issue Tracking:** Uses a local `.beads` repository (backed by Dolt) to store the task graph, allowing tracks and tickets to be versioned alongside the code.
- **Beads Toolset:** Provides a suite of MCP tools (`bd_create`, `bd_update`, `bd_ready`, `bd_list`) for agents to manage the issue graph autonomously.
- **Context Compaction:** Automatically summarizes completed beads to preserve context window space for the active task.
- **Augmented Visualizations:** Integrates with the Visual DAG and MMA Dashboard to provide real-time visibility into the Dolt-backed issue graph.
- **Git-Backed Issue Tracking:** Uses a local `.beads` repository (backed by Dolt) to store the task graph, allowing tracks and tickets to be versioned alongside the code.
- **Beads Toolset:** Provides a suite of MCP tools (`bd_create`, `bd_update`, `bd_ready`, `bd_list`) for agents to manage the issue graph autonomously.
- **Context Compaction:** Automatically summarizes completed beads to preserve context window space for the active task.
- **Augmented Visualizations:** Integrates with the Visual DAG and MMA Dashboard to provide real-time visibility into the Dolt-backed issue graph.
- **Parallel Tool Execution:** Executes independent tool calls (e.g., parallel file reads) concurrently within a single agent turn using an asynchronous execution engine, significantly reducing end-to-end latency.
- **Automated Tier 4 QA:** Integrates real-time error interception in the shell runner, automatically forwarding technical failures to cheap sub-agents for 20-word diagnostic summaries injected back into the worker history.
- **External MCP Server Support:** Adds support for integrating external Model Context Protocol (MCP) servers, expanding the agent's toolset with the broader MCP ecosystem.
- **Multi-Server Lifecycle Management:** Orchestrates multiple concurrent MCP server sessions (Stdio for local subprocesses and SSE for remote servers).
- **Flexible Configuration:** Supports global (`config.toml`) and project-specific (`manual_slop.toml`) paths for `mcp_config.json` (standard MCP configuration format).
- **Auto-Start & Discovery:** Automatically initializes configured servers on project load and dynamically aggregates their tools into the agent's capability declarations.
- **Dedicated Operations UI:** Features a new **External Tools** section within the Operations Hub for monitoring server status (idle, starting, running, error) and browsing discovered tool schemas. Supports **Pop-Out Panel functionality**, allowing the External Tools interface to be detached into a standalone window for optimized multi-monitor workflows.
- **Strict HITL Safety:** All external tool calls are intercepted and require explicit human-in-the-loop approval via the standard confirmation dialog before execution.
- **Multi-Server Lifecycle Management:** Orchestrates multiple concurrent MCP server sessions (Stdio for local subprocesses and SSE for remote servers).
- **Flexible Configuration:** Supports global (`config.toml`) and project-specific (`manual_slop.toml`) paths for `mcp_config.json` (standard MCP configuration format).
- **Auto-Start & Discovery:** Automatically initializes configured servers on project load and dynamically aggregates their tools into the agent's capability declarations.
- **Dedicated Operations UI:** Features a new **External Tools** section within the Operations Hub for monitoring server status (idle, starting, running, error) and browsing discovered tool schemas. Supports **Pop-Out Panel functionality**, allowing the External Tools interface to be detached into a standalone window for optimized multi-monitor workflows.
- **Strict HITL Safety:** All external tool calls are intercepted and require explicit human-in-the-loop approval via the standard confirmation dialog before execution.
- **Retrieval-Augmented Generation (RAG) Support:** Introduces advanced retrieval capabilities to overcome context window limitations and reduce hallucination.
- **Multi-Source Retrieval:** Supports local vector stores (ChromaDB) and an **External RAG Bridge** via the Model Context Protocol (MCP) for connecting to third-party retrieval services.
- **High-Performance Indexing:** Employs a parallelized indexing pipeline using `ThreadPoolExecutor` and incremental updates based on file `mtime` to handle large codebases efficiently.
- **Deep Discussion Integration:** Retrieved context fragments are automatically prepended to agent prompts and captured in the discussion history, featuring a dedicated visualization mode with source buttons for instant file navigation.
- **Configurable Strategy:** Users can toggle RAG globally and fine-tune retrieval parameters (source, embedding provider, chunk size/overlap) directly within the AI Settings.
- **Automated Synchronization:** Features background re-indexing of the project workspace, ensuring the vector store remains consistent with the current project state.
- **Multi-Source Retrieval:** Supports local vector stores (ChromaDB) and an **External RAG Bridge** via the Model Context Protocol (MCP) for connecting to third-party retrieval services.
- **High-Performance Indexing:** Employs a parallelized indexing pipeline using `ThreadPoolExecutor` and incremental updates based on file `mtime` to handle large codebases efficiently.
- **Deep Discussion Integration:** Retrieved context fragments are automatically prepended to agent prompts and captured in the discussion history, featuring a dedicated visualization mode with source buttons for instant file navigation.
- **Configurable Strategy:** Users can toggle RAG globally and fine-tune retrieval parameters (source, embedding provider, chunk size/overlap) directly within the AI Settings.
- **Automated Synchronization:** Features background re-indexing of the project workspace, ensuring the vector store remains consistent with the current project state.
- **Undo/Redo History Support:** Implements a robust, non-provider based undo/redo system for managing UI state and discussion mutations.
- **Comprehensive State Snapshots:** Captures all critical UI state, including text inputs (system prompts, AI input), model parameters (Temperature, Top-P), and context management (files, screenshots).
- **Discussion Mutation Tracking:** Allows reverting and redoing additions, deletions, and structural changes to the discussion history.
- **History List View:** Features a dedicated, scrollable panel showing recent actions with timestamps, allowing users to jump directly to any historical state.
- **Tactile Hotkeys:** Supports industry-standard shortcuts (`Ctrl+Z`, `Ctrl+Y`, `Ctrl+Shift+Z`) for fast, intuitive state navigation.
- **Comprehensive State Snapshots:** Captures all critical UI state, including text inputs (system prompts, AI input), model parameters (Temperature, Top-P), and context management (files, screenshots).
- **Discussion Mutation Tracking:** Allows reverting and redoing additions, deletions, and structural changes to the discussion history.
- **History List View:** Features a dedicated, scrollable panel showing recent actions with timestamps, allowing users to jump directly to any historical state.
- **Tactile Hotkeys:** Supports industry-standard shortcuts (`Ctrl+Z`, `Ctrl+Y`, `Ctrl+Shift+Z`) for fast, intuitive state navigation.
- **High-Fidelity Selectable UI:** Most read-only labels and logs across the interface (including discussion history, comms payloads, tool outputs, and telemetry metrics) are now implemented as selectable text fields. This enables standard OS-level text selection and copying (Ctrl+C) while maintaining a high-density, non-editable aesthetic.
- **High-Fidelity UI Rendering:** Employs advanced 3x font oversampling and sub-pixel positioning to ensure crisp, high-clarity text rendering across all resolutions, enhancing readability for dense logs and complex code fragments.
- **Workspace Docking & Layout Profiles:** Expands layout management to support named workspace profiles, capturing multi-viewport docking arrangements, window visibility, and internal panel states.
- **Scope Inheritance:** Profiles follow a Global and Project inheritance model, allowing for both universal defaults and project-specific layouts.
- **Contextual Auto-Switch (Experimental):** An opt-in mechanism that automatically binds and loads specific workspace profiles based on the active MMA Tier or task context, dynamically reshaping the UI for the current cognitive load.
- **Scope Inheritance:** Profiles follow a Global and Project inheritance model, allowing for both universal defaults and project-specific layouts.
- **Contextual Auto-Switch (Experimental):** An opt-in mechanism that automatically binds and loads specific workspace profiles based on the active MMA Tier or task context, dynamically reshaping the UI for the current cognitive load.
- **Enhanced MMA Observability:** Worker streams and ticket previews now support direct text selection, allowing for easy extraction of specific logs or reasoning fragments during parallel execution.
- **Transparent Context Visibility:** A dedicated **Session Hub** exposes the exact aggregated markdown and resolved system prompt sent to the AI.
- **Injection Timeline:** Discussion history visually indicates the precise moments when files or screenshots were injected into the session context.
@@ -124,18 +124,18 @@ For deep implementation details when planning or implementing tracks, consult `d
- **Context & Token Visualization:** Detailed UI panels for monitoring real-time token usage, history depth, and **visual cache awareness** (tracking specific files currently live in the provider's context cache).
- **On-Demand Definition Lookup:** Allows developers to request specific class or function definitions during discussions using `@SymbolName` syntax. Injected definitions feature syntax highlighting, intelligent collapsing for long blocks, and a **[Source]** button for instant navigation to the full file.
- **Manual Ticket Queue Management:** Provides a dedicated GUI panel for granular control over the implementation queue. Features include color-coded priority assignment (High, Medium, Low), multi-select bulk operations (Execute, Skip, Block), and interactive drag-and-drop reordering with real-time Directed Acyclic Graph (DAG) validation.
- **System Prompt Presets:** Comprehensive management system for saving and switching between complex system prompt configurations. Features full visibility and customization of the **Foundational Base System Prompt**, allowing users to modify the core instructions that define agent capabilities and tool usage heuristics. - **Scoped Inheritance:** Supports **Global** (application-wide) and **Project-Specific** presets. Project presets with the same name automatically override global counterparts, allowing for fine-tuned context tailoring.
- **System Prompt Presets:** Comprehensive management system for saving and switching between complex system prompt configurations. Features full visibility and customization of the **Foundational Base System Prompt**, allowing users to modify the core instructions that define agent capabilities and tool usage heuristics. - **Scoped Inheritance:** Supports **Global** (application-wide) and **Project-Specific** presets. Project presets with the same name automatically override global counterparts, allowing for fine-tuned context tailoring.
- **Command Palette:** A global, keyboard-driven launcher for actions across Manual Slop, triggered by `Ctrl+Shift+P`. Provides fuzzy-search across all built-in and user-defined commands. Includes an **"Everything" mode** (`Ctrl+Shift+E`) that searches across commands, files, symbols, history, and settings. Uses an **async context preview worker** to prevent UI hangs during cross-domain searches. See [guide_command_palette.md](../docs/guide_command_palette.md).
- **Full AI Profiles:** Presets capture not only the system prompt text but also critical model parameters like **Temperature**, **Top-P**, and **Max Output Tokens**.
- **Preset Manager Modal:** A dedicated high-density GUI for creating, editing, and deleting presets with real-time validation and instant application to the active session.
- **Agent Personas & Unified Profiles:** Consolidates model settings, provider routing, system prompts, tool presets, and bias profiles into named "Persona" entities.
- **Single Configuration Entity:** Switch models, tool weights, and system prompts simultaneously using a single Persona selection.
- **Persona Editor Modal:** A dedicated high-density GUI for creating, editing, and deleting Personas.
- **MMA Granular Assignment:** Allows assigning specific Personas to individual agents within the 4-Tier Hierarchical MMA.
- **Agent Tool Weighting & Bias:** Influences agent tool selection via a weighting system.
- **Semantic Nudging:** Automatically prefixes tool and parameter descriptions with priority tags (e.g., [HIGH PRIORITY], [PREFERRED]) to bias model selection.
- **Dynamic Tooling Strategy:** Automatically appends a Markdown "Tooling Strategy" section to system instructions based on the active preset and global bias profile.
- **Global Bias Profiles:** Application of category-level multipliers (e.g., Execution-Focused, Discovery-Heavy) to influence agent behavior across broad toolsets.
- **Priority Badges & Refined Layout:** High-density, color-coded visual indicators in tool lists showing the assigned priority level of each capability. Displays tool names before radio buttons with consistent spacing for improved readability.
- **Category-Based Filtering:** Integrated category filtering in both the Active Tools panel and the Tool Preset Manager, allowing users to quickly manage large toolsets.
- **Fine-Grained Weight Control:** Integrated sliders in the Preset Manager for adjusting individual tool weights (1-5) and parameter-level biases.
- **Full AI Profiles:** Presets capture not only the system prompt text but also critical model parameters like **Temperature**, **Top-P**, and **Max Output Tokens**.
- **Preset Manager Modal:** A dedicated high-density GUI for creating, editing, and deleting presets with real-time validation and instant application to the active session.
- **Agent Personas & Unified Profiles:** Consolidates model settings, provider routing, system prompts, tool presets, and bias profiles into named "Persona" entities.
- **Single Configuration Entity:** Switch models, tool weights, and system prompts simultaneously using a single Persona selection.
- **Persona Editor Modal:** A dedicated high-density GUI for creating, editing, and deleting Personas.
- **MMA Granular Assignment:** Allows assigning specific Personas to individual agents within the 4-Tier Hierarchical MMA.
- **Agent Tool Weighting & Bias:** Influences agent tool selection via a weighting system.
- **Semantic Nudging:** Automatically prefixes tool and parameter descriptions with priority tags (e.g., [HIGH PRIORITY], [PREFERRED]) to bias model selection.
- **Dynamic Tooling Strategy:** Automatically appends a Markdown "Tooling Strategy" section to system instructions based on the active preset and global bias profile.
- **Global Bias Profiles:** Application of category-level multipliers (e.g., Execution-Focused, Discovery-Heavy) to influence agent behavior across broad toolsets.
- **Priority Badges & Refined Layout:** High-density, color-coded visual indicators in tool lists showing the assigned priority level of each capability. Displays tool names before radio buttons with consistent spacing for improved readability.
- **Category-Based Filtering:** Integrated category filtering in both the Active Tools panel and the Tool Preset Manager, allowing users to quickly manage large toolsets.
- **Fine-Grained Weight Control:** Integrated sliders in the Preset Manager for adjusting individual tool weights (1-5) and parameter-level biases.
+17 -17
View File
@@ -1,4 +1,4 @@
# Technology Stack: Manual Slop
# Technology Stack: Manual Slop
> **Core Value (added 2026-06-25):** C11/Odin/Jai semantics in this Python runtime. See `conductor/product-guidelines.md` "Core Value", `conductor/code_styleguides/data_oriented_design.md` §8.5, and `conductor/code_styleguides/python.md` §17. Banned: `dict[str, Any]`, `Any`, `Optional[T]`, `hasattr()` for entity dispatch, `.get()` on known fields. Use typed `@dataclass(frozen=True, slots=True)` with explicit fields. Use `Result[T]` + `NIL_T` sentinels.
@@ -46,19 +46,19 @@
- **src/tool_presets.py:** Extends `ToolPresetManager` to handle nested `Tool` models, weights, and global `BiasProfile` persistence within `tool_presets.toml`.
- **src/mcp_client.py:** Implements the native tool dispatch (45 tools) and the `ExternalMCPManager` for orchestrating third-party Model Context Protocol servers. The typed `ToolSpec` registry now lives in `src/mcp_tool_specs.py` (`ToolSpec` dataclass + `_REGISTRY` + `tool_names()`); `mcp_client.py` re-exports `TOOL_NAMES = mcp_tool_specs.tool_names()` for backward compat. See [docs/guide_mcp_client.md](../docs/guide_mcp_client.md) for the complete 3-layer security model (Allowlist → Validate → Resolve) and tool inventory.
- **StdioMCPServer:** Manages local MCP servers via asynchronous subprocess pipes (stdin/stdout/stderr).
- **RemoteMCPServer (SSE):** Provides a foundation for remote MCP integration via Server-Sent Events.
- **JSON-RPC 2.0 Engine:** Handles asynchronous message routing, request/response matching, and error handling for all external MCP communication.
- **AST-Based C/C++ Tools:** Provides `ts_c_get_skeleton`, `ts_cpp_get_skeleton`, `ts_c_get_code_outline`, and `ts_cpp_get_code_outline` for structural analysis of C/C++ codebases using tree-sitter.
- **AST-Based Python Tools (15):** `py_get_skeleton`, `py_get_code_outline`, `py_get_definition`, `py_update_definition`, `py_get_signature`, `py_set_signature`, `py_get_class_summary`, `py_get_var_declaration`, `py_set_var_declaration`, `py_get_hierarchy`, `py_get_docstring`, `py_get_imports`, `py_find_usages`, `py_check_syntax`, plus structural mutators `py_remove_def`, `py_add_def`, `py_move_def`, `py_region_wrap`.
- **Network Tools:** `web_search` (DuckDuckGo HTML scrape), `fetch_url` (HTML → text).
- **Beads Tools (4):** `bd_list`, `bd_create`, `bd_update`, `bd_ready` — interface to the Beads/Dolt backend.
- **StdioMCPServer:** Manages local MCP servers via asynchronous subprocess pipes (stdin/stdout/stderr).
- **RemoteMCPServer (SSE):** Provides a foundation for remote MCP integration via Server-Sent Events.
- **JSON-RPC 2.0 Engine:** Handles asynchronous message routing, request/response matching, and error handling for all external MCP communication.
- **AST-Based C/C++ Tools:** Provides `ts_c_get_skeleton`, `ts_cpp_get_skeleton`, `ts_c_get_code_outline`, and `ts_cpp_get_code_outline` for structural analysis of C/C++ codebases using tree-sitter.
- **AST-Based Python Tools (15):** `py_get_skeleton`, `py_get_code_outline`, `py_get_definition`, `py_update_definition`, `py_get_signature`, `py_set_signature`, `py_get_class_summary`, `py_get_var_declaration`, `py_set_var_declaration`, `py_get_hierarchy`, `py_get_docstring`, `py_get_imports`, `py_find_usages`, `py_check_syntax`, plus structural mutators `py_remove_def`, `py_add_def`, `py_move_def`, `py_region_wrap`.
- **Network Tools:** `web_search` (DuckDuckGo HTML scrape), `fetch_url` (HTML → text).
- **Beads Tools (4):** `bd_list`, `bd_create`, `bd_update`, `bd_ready` — interface to the Beads/Dolt backend.
- **src/api_hooks.py + src/api_hook_client.py:** Implements the Hook API and Python client wrapper for external automation. See [docs/guide_api_hooks.md](../docs/guide_api_hooks.md).
- **HookServer:** FastAPI/Uvicorn server on `127.0.0.1:8999`, started by `AppController` when `--enable-test-hooks` is set. Exposes 8+ REST endpoints (`/status`, `/api/gui`, `/api/ask`, `/api/gui/mma_status`, `/api/performance`, `/api/comms`, `/api/diagnostics`).
- **ApiHookClient:** Python client with retry logic, health-check polling, and timeout configuration. Used by all `live_gui` tests, the WorkerPool, and external scripts.
- **`/api/ask` Protocol:** Non-blocking, ID-based challenge/response for synchronous HITL approvals from external contexts.
- **`_predefined_callbacks` and `_gettable_fields`:** AppController-owned registries that the Hook API consumes to expose any App method as a `custom_callback` action.
- **HookServer:** FastAPI/Uvicorn server on `127.0.0.1:8999`, started by `AppController` when `--enable-test-hooks` is set. Exposes 8+ REST endpoints (`/status`, `/api/gui`, `/api/ask`, `/api/gui/mma_status`, `/api/performance`, `/api/comms`, `/api/diagnostics`).
- **ApiHookClient:** Python client with retry logic, health-check polling, and timeout configuration. Used by all `live_gui` tests, the WorkerPool, and external scripts.
- **`/api/ask` Protocol:** Non-blocking, ID-based challenge/response for synchronous HITL approvals from external contexts.
- **`_predefined_callbacks` and `_gettable_fields`:** AppController-owned registries that the Hook API consumes to expose any App method as a `custom_callback` action.
- **src/rag_engine.py:** Core RAG implementation managing the vector store lifecycle, chunking strategies (character-based and AST-aware), and multi-provider search. Integrates with **ChromaDB** for local persistence, uses external embeddings by default, and provides an optional local embedding path via `manual_slop[local-rag]`.
@@ -108,16 +108,16 @@
- **Manual Hot-Reload Pipeline:** Implements a `HotReloader` utility that manages module invalidation and state preservation, triggered by keyboard shortcuts (Ctrl+Alt+R) or GUI controls.
- **src/command_palette.py + src/commands.py:** Implements the keyboard-driven Command Palette (Ctrl+Shift+P). See [docs/guide_command_palette.md](../docs/guide_command_palette.md) and [docs/guide_gui_2.md](../docs/guide_gui_2.md#command-palette).
- **CommandRegistry:** Decorator-based command registration (`@registry.register`). 32+ built-in commands including `_toggle_command_palette`, `_open_command_palette`, theme switching, view presets, persona application.
- **fuzzy_match:** Subsequence matching with score (consecutive bonus, start-of-word bonus, length penalty).
- **render_palette_modal:** Centered popup with input field, keyboard navigation (Up/Down/Enter/Esc), and live result filtering.
- **defensive try/except wrapping:** All action callbacks wrapped to prevent GUI crashes from buggy commands.
- **CommandRegistry:** Decorator-based command registration (`@registry.register`). 32+ built-in commands including `_toggle_command_palette`, `_open_command_palette`, theme switching, view presets, persona application.
- **fuzzy_match:** Subsequence matching with score (consecutive bonus, start-of-word bonus, length penalty).
- **render_palette_modal:** Centered popup with input field, keyboard navigation (Up/Down/Enter/Esc), and live result filtering.
- **defensive try/except wrapping:** All action callbacks wrapped to prevent GUI crashes from buggy commands.
## Per-Source-File Deep Dives
For the largest source files, consult the dedicated guides in `docs/`:
- **[docs/guide_gui_2.md](../docs/guide_gui_2.md)** — `src/gui_2.py` (~437KB main GUI)
- **[docs/guide_ai_client.md](../docs/guide_ai_client.md)** — `src/ai_client.py` (~166KB multi-provider LLM, 8 providers; inlined `VendorCapabilities` registry)
- **[docs/guide_ai_client.md](../docs/guide_ai_client.md)** — `src/ai_client.py` (~166KB multi-provider LLM, 7 providers; inlined `VendorCapabilities` registry)
- **[docs/guide_api_hooks.md](../docs/guide_api_hooks.md)** — `src/api_hooks.py` + `src/api_hook_client.py` (~51KB + ~38KB Hook API)
- **[docs/guide_mcp_client.md](../docs/guide_mcp_client.md)** — `src/mcp_client.py` (~92KB, 45 tools; tool specs live in `src/mcp_tool_specs.py`)
- **[docs/guide_app_controller.md](../docs/guide_app_controller.md)** — `src/app_controller.py` (~240KB headless controller)
@@ -12,41 +12,17 @@ Spec: `conductor/tracks/test_suite_cleanup_gemini_cli_removal_20260705/spec.md`
Focus: delete the adapter module + the provider registration + the GUI panel + the test files. Introduce the `mock` provider for the 9 sim tests that used `gemini_cli` + `mock_gemini_cli.py`.
- [ ] **Task 1.1: Delete `src/gemini_cli_adapter.py`**
- [x] **Task 1.1: Delete `src/gemini_cli_adapter.py`** (2bba7f56)
WHERE: `src/gemini_cli_adapter.py` (193 lines, entire file).
WHAT: `git rm src/gemini_cli_adapter.py`.
VERIFY: `Test-Path src/gemini_cli_adapter.py` returns False.
- [x] **Task 1.2: Edit `src/ai_client.py` — remove the import, PROVIDERS entry, module state, 3 functions, 8 dispatch branches** (2bba7f56)
- [ ] **Task 1.2: Edit `src/ai_client.py` — remove the import, PROVIDERS entry, module state, 3 functions, 8 dispatch branches**
- [x] **Task 1.3: Edit `src/app_controller.py` — remove the ~11 gemini_cli sites** (a93a61fd)
WHERE: `src/ai_client.py` lines 49, 62, 164, 1727-1735, 2130-2241, 1857-1877, 556-561, 629, 914, 3302, 3306, 3394-3398, 3505-3509, 3556-3559.
WHAT: Per the audit inventory (GAP-A2). Carefully distinguish `_gemini_cli_adapter` (REMOVE) from `_gemini_client` / `_ensure_gemini_client` (KEEP — direct Gemini SDK).
HOW: Use `manual-slop_py_update_definition` for the 3 function removals; `manual-slop_edit_file` for the dispatch branches + import + PROVIDERS + module state.
VERIFY: `python -c "from src.ai_client import PROVIDERS; print(PROVIDERS)"` prints 7 entries (no `gemini_cli`).
- [x] **Task 1.4: Edit `src/gui_2.py` — remove the 2 gemini_cli blocks** (a93a61fd)
- [ ] **Task 1.3: Edit `src/app_controller.py` — remove the ~11 gemini_cli sites**
- [x] **Task 1.5: Edit `src/project_manager.py:126` + `src/api_hooks.py:88, 941-942`** (a93a61fd)
WHERE: `src/app_controller.py` lines 574-575, 1084, 1124, 1316, 1836-1840, 2022-2023, 2725-2729, 2932, 3215, 4124.
WHAT: Per GAP-A3 — remove `ui_gemini_cli_path` state field, settable/gettable map entries, `_update_gcli_adapter()` method, project load/save, init.
VERIFY: `grep "gemini_cli" src/app_controller.py` returns nothing.
- [ ] **Task 1.4: Edit `src/gui_2.py` — remove the 2 gemini_cli blocks**
WHERE: `src/gui_2.py` lines 2940-2947 (ASCII comment) + 3008-3025 (provider panel block).
WHAT: Delete both blocks.
VERIFY: `grep "gemini_cli" src/gui_2.py` returns nothing.
- [ ] **Task 1.5: Edit `src/project_manager.py:126` + `src/api_hooks.py:88, 941-942`**
WHERE: `src/project_manager.py:126` (delete the default config entry) + `src/api_hooks.py:88` (delete the docstring line) + `src/api_hooks.py:941-942` (simplify the HookServer auto-start — the `is_gemini_cli` special case becomes dead).
VERIFY: `grep "gemini_cli" src/project_manager.py src/api_hooks.py` returns nothing.
- [ ] **Task 1.6: Delete the 7 gemini_cli test files**
WHERE: `tests/test_gemini_cli_adapter.py`, `tests/test_gemini_cli_adapter_parity.py`, `tests/test_gemini_cli_integration.py`, `tests/test_gemini_cli_parity_regression.py`, `tests/test_gemini_cli_edge_cases.py`, `tests/test_mock_gemini_cli.py`, `tests/test_ai_client_cli.py`.
WHAT: `git rm` all 7.
VERIFY: `Test-Path` returns False for all 7.
- [x] **Task 1.6: Delete the 7 gemini_cli test files** (2bba7f56)
- [ ] **Task 1.7: Introduce the `mock` provider in `src/ai_client.py`**
@@ -1,66 +1,81 @@
# Track state for test_suite_cleanup_gemini_cli_removal_20260705
# Initialized by Tier 1 Orchestrator on 2026-07-05.
# 3 fronts: Gemini CLI removal + test suite cleanup + metadata-type reduction.
# Closed 2026-07-05 per user direction: partial completion; remaining
# work folded into two upcoming follow-up tracks (vendor_ai_client_track
# for the metadata-type reduction; test_de_crufting_track for the test
# suite cruft). See docs/reports/TRACK_COMPLETION_test_suite_cleanup_gemini_cli_removal_20260705.md.
[meta]
track_id = "test_suite_cleanup_gemini_cli_removal_20260705"
name = "Test Suite Cleanup + Gemini CLI Adapter Removal + Metadata-Type Reduction"
status = "active"
current_phase = 0
last_updated = "2026-07-05"
status = "superseded"
current_phase = 1
last_updated = "2026-07-05 (closed - partial; deferred to followup tracks)"
[blocked_by]
# None. The Gemini CLI removal is independent; the test cleanup is independent; the metadata reduction is independent.
[blocks]
# None. The track advances the ARCHIVE_REVIEW_20260705.md follow-up items (#1, #2, #6) but doesn't block them.
# None directly. ARCHIVE_REVIEW_20260705.md follow-up items #1, #2, #6 are
# captured by the upcoming vendor_ai_client_track (t3.1, t3.2, t3.3, t3.4, t3.6)
# and test_de_crufting_track (t2.4, t2.6, t2.7, t2.8).
[followup_tracks]
# Work remaining after this track's partial completion. Author will create
# the metadata.json + plan.md for each when ready.
vendor_ai_client_track = { source = "this track t3.1+t3.2+t3.3+t3.4+t3.6", owner = "user-upcoming" }
test_de_crufting_track = { source = "this track t2.4+t2.6+t2.7+t2.8", owner = "user-upcoming" }
[phases]
phase_1 = { status = "pending", checkpointsha = "", name = "Front A — Gemini CLI Adapter Removal (src + tests + docs + mock provider)" }
phase_1 = { status = "in_progress_partial_6_of_11", checkpointsha = "7e06d812", name = "Front A — Gemini CLI Adapter Removal (src + tests + docs + mock provider)" }
phase_2 = { status = "pending", checkpointsha = "", name = "Front B — Test Suite Cleanup (delete broken + consolidate tautologies + migrate shims + fix-not-skip)" }
phase_3 = { status = "pending", checkpointsha = "", name = "Front C — Metadata-Type Reduction (MCP dispatch flip + app_controller state + aggregate FileItem + dead code)" }
[tasks]
# Phase 1 — Gemini CLI Removal
t1_1 = { status = "pending", commit_sha = "", description = "Delete src/gemini_cli_adapter.py" }
t1_2 = { status = "pending", commit_sha = "", description = "Edit src/ai_client.py — remove import + PROVIDERS entry + module state + 3 functions + 8 dispatch branches" }
t1_3 = { status = "pending", commit_sha = "", description = "Edit src/app_controller.py — remove ~11 gemini_cli sites" }
t1_4 = { status = "pending", commit_sha = "", description = "Edit src/gui_2.py — remove 2 gemini_cli blocks" }
t1_5 = { status = "pending", commit_sha = "", description = "Edit src/project_manager.py:126 + src/api_hooks.py:88,941-942" }
t1_6 = { status = "pending", commit_sha = "", description = "Delete 7 gemini_cli test files" }
t1_7 = { status = "pending", commit_sha = "", description = "Introduce mock provider in src/ai_client.py (routes to tests/mock_gemini_cli.py)" }
t1_8 = { status = "pending", commit_sha = "", description = "Rewrite 9 sim test files: gemini_cli -> mock" }
t1_9 = { status = "pending", commit_sha = "", description = "Minor edits in 6+ gemini_cli-reference test files (provider lists, monkeypatches, comments)" }
t1_10 = { status = "pending", commit_sha = "", description = "Update 7 docs + 5 conductor docs (remove gemini_cli, update provider count 8->7)" }
t1_11 = { status = "pending", commit_sha = "", description = "Phase 1 checkpoint + batch run" }
t1_1 = { status = "completed", commit_sha = "2bba7f56", description = "Delete src/gemini_cli_adapter.py" }
t1_2 = { status = "completed", commit_sha = "2bba7f56", description = "Edit src/ai_client.py — remove import + PROVIDERS entry + module state + 3 functions + 8 dispatch branches" }
t1_3 = { status = "completed", commit_sha = "a93a61fd", description = "Edit src/app_controller.py — remove ~11 gemini_cli sites" }
t1_4 = { status = "completed", commit_sha = "a93a61fd", description = "Edit src/gui_2.py — remove 2 gemini_cli blocks" }
t1_5 = { status = "completed", commit_sha = "a93a61fd", description = "Edit src/project_manager.py:126 + src/api_hooks.py:88,941-942" }
t1_6 = { status = "completed", commit_sha = "2bba7f56", description = "Delete 7 gemini_cli test files" }
t1_7 = { status = "cancelled", commit_sha = "", description = "Mock provider SUPERSEDED by user direction (3b55bdff): use real minimax provider with MiniMax-M2.7 instead of fabricating a mock provider." }
t1_8 = { status = "completed", commit_sha = "3b55bdff", description = "10 sim test files rewritten to use minimax (real provider) + MiniMax-M2.7 model instead of gemini_cli + mock_gemini_cli.py. Provider-mock in test_sim_ai_settings.py also switched." }
t1_9 = { status = "completed", commit_sha = "edebeac6 + 9401d3f6 + 2811cc23 + 3b55bdff", description = "Minor edits: 13 test files cleaned (provider list expectations, _update_gcli_adapter monkeypatches, ui_gemini_cli_path setters, comment references) + 10 sim tests rewritten to use minimax." }
t1_10 = { status = "completed", commit_sha = "bd1d966c", description = "Updated 12 docs (7 guides + 5 conductor docs). Provider list 8 -> 7. guide_meta_boundary intentionally retained (meta-tooling GEMINI_CLI_HOOK_CONTEXT is separate)." }
t1_11 = { status = "pending", commit_sha = "", description = "Phase 1 checkpoint + batch run (BLOCKED on t1.7 + t1.8)" }
# Phase 2 — Test Suite Cleanup
t2_1 = { status = "pending", commit_sha = "", description = "Delete 2 guaranteed-broken chronology test files (import from deleted scripts.audit.*)" }
t2_2 = { status = "pending", commit_sha = "", description = "Consolidate 7 test_scavenge_*.py into 1 test_directive_structure.py" }
t2_3 = { status = "pending", commit_sha = "", description = "Review + delete/rewrite deprecated-module test files (test_mma_skeleton, test_arch_boundary_phase1)" }
t2_4 = { status = "pending", commit_sha = "", description = "Review + consolidate ~15 test_*_phase*.py files" }
t2_5 = { status = "pending", commit_sha = "", description = "Migrate 27 src.models test importers to direct subsystem imports" }
t2_6 = { status = "pending", commit_sha = "", description = "Extract shared mock_controller fixture from ~8 boilerplate-patch files" }
t2_7 = { status = "pending", commit_sha = "", description = "Fix 3 fix-not-skip candidates (mock Gemini 503 in summarize.summarise_file)" }
t2_8 = { status = "pending", commit_sha = "", description = "Audit + split test_gui_2_result.py (120KB, 101 tests) into per-feature files" }
t2_1 = { status = "completed", commit_sha = "bd6fc3e2", description = "Deleted 2 chronology tests + 7 scavenge tests (9 dead tests removed; -1257 lines). Added test_directive_structure.py (3 tests, all passing)." }
t2_2 = { status = "completed", commit_sha = "bd6fc3e2", description = "Consolidation done as part of t2_1." }
t2_3 = { status = "completed_partial", commit_sha = "be93c262", description = "Deleted test_mma_skeleton.py (deprecated scripts.mma_exec), test_arch_boundary_phase1.py (deprecated mma_exec paths), test_phase_3_final_verify.py (6-line tautology). Kept phase 2/3 + general verification tests." }
t2_4 = { status = "pending", commit_sha = "", description = "Review + consolidate ~15 test_*_phase*.py files (NOT STARTED — deferred to follow-up track)" }
t2_5 = { status = "completed", commit_sha = "6a3c142b", description = "Migrated 18 unused bare 'from src import models' imports. Migrated 5 explicit sub-imports (PROVIDERS to ai_client, Metadata to type_aliases). Kept the 2 self-test files." }
t2_6 = { status = "pending", commit_sha = "", description = "Extract shared mock_controller fixture from 16 boilerplate-patch files (NOT STARTED — deferring per-feature fixture)" }
t2_7 = { status = "pending", commit_sha = "", description = "Fix 4 fix-not-skip candidates by mocking summarize.summarise_file (NOT STARTED — requires designing the mock path)" }
t2_8 = { status = "pending", commit_sha = "", description = "Audit + split test_gui_2_result.py (120KB, 101 tests) into per-feature files (NOT STARTED — large mechanical split)" }
t2_9 = { status = "pending", commit_sha = "", description = "Phase 2 checkpoint + full suite batch run" }
# Phase 3 — Metadata-Type Reduction
t3_1 = { status = "pending", commit_sha = "", description = "Flip MCP dispatch inversion: dispatch()+async_dispatch()+22 consumers -> _result variants; delete 38 str wrappers" }
t3_2 = { status = "pending", commit_sha = "", description = "Migrate app_controller.py ~40 Metadata in-memory state sites to typed per-aggregate dataclasses" }
t3_3 = { status = "pending", commit_sha = "", description = "Fix aggregate.py file_items: list[Metadata] -> list[FileItem]; NIL_METADATA -> typed empty sentinel" }
t3_4 = { status = "pending", commit_sha = "", description = "Triage scattered non-boundary Metadata fields (personas.py, workspace_manager.py, orchestrator_pm.py)" }
t3_5 = { status = "pending", commit_sha = "", description = "Delete dead code: openai_schemas.py:108 to_legacy_dict() + app_controller.py:4973 _push_mma_state_update" }
t3_6 = { status = "pending", commit_sha = "", description = "Migrate test fixtures that construct Metadata({...}) to typed dataclass constructors" }
t3_7 = { status = "pending", commit_sha = "", description = "Update docs (guide_app_controller, guide_mcp_client, guide_models, type_aliases styleguide)" }
t3_8 = { status = "pending", commit_sha = "", description = "Run 4 audit scripts + full test suite batch" }
t3_9 = { status = "pending", commit_sha = "", description = "Phase 3 checkpoint + TRACK_COMPLETION report" }
t3_10 = { status = "pending", commit_sha = "", description = "Conductor — User Manual Verification (PAUSE for user confirmation)" }
t3_11 = { status = "pending", commit_sha = "", description = "Add chronology row + archive the track" }
t3_1 = { status = "pending", commit_sha = "", description = "Flip MCP dispatch inversion (NOT STARTED — 22 consumer sites; deferred to follow-up track)" }
t3_2 = { status = "pending", commit_sha = "", description = "Migrate app_controller.py ~40 Metadata in-memory state sites to typed dataclasses (NOT STARTED — deferred to follow-up)" }
t3_3 = { status = "pending", commit_sha = "", description = "Fix aggregate.py file_items: list[Metadata] -> list[FileItem] (NOT STARTED — code uses .get() dict access, breaking refactor)" }
t3_4 = { status = "pending", commit_sha = "", description = "Triage scattered Metadata fields (NOT STARTED — personas.py + workspace_manager.py need new dataclasses)" }
t3_5 = { status = "completed_partial", commit_sha = "db92c60d", description = "Deleted openai_schemas.py to_legacy_dict() (dead code, zero callers). _push_mma_state_update SKIPPED (has 4 test callers; spec said delete only if no callers)." }
t3_6 = { status = "pending", commit_sha = "", description = "Migrate test fixtures that construct Metadata({...}) (NOT STARTED — depends on t3.2)" }
t3_7 = { status = "completed", commit_sha = "bd1d966c", description = "Done as part of t1.10 (docs covers both provider count + typed-dataclass migration)." }
[verification]
vc1_gemini_cli_removed = false
vc2_providers_7_entries = false
vc1_gemini_cli_removed = true
vc2_providers_7_entries = true
vc3_chronology_tests_deleted = true
vc4_scavenge_consolidated = true
vc5_models_shim_migrated = true
vc6_app_controller_no_list_metadata = false
vc7_mcp_dispatch_flipped = false
vc8_aggregate_uses_fileitem = false
vc9_fix_not_skip_fixed = false
vc10_audit_scripts_pass = true
vc11_batch_green = false
vc12_to_legacy_dict_deleted = true
vc3_chronology_tests_deleted = false
vc4_scavenge_consolidated = false
vc5_models_shim_migrated = false
+198 -198
View File
@@ -42,10 +42,10 @@ Or use Python subprocess with `newline=''` to preserve line endings:
```python
python -c "
with open('file.py', 'r', encoding='utf-8', newline='') as f:
content = f.read()
content = f.read()
content = content.replace(old, new)
with open('file.py', 'w', encoding='utf-8', newline='') as f:
f.write(content)
f.write(content)
"
```
@@ -61,19 +61,19 @@ with open('file.py', 'w', encoding='utf-8', newline='') as f:
8. **File Naming Convention (HARD RULE, added 2026-06-11):** New `src/<thing>.py` files may only be created on the user's explicit request. Helpers and sub-systems go in the parent module. E.g., AI-client-specific code goes in `src/ai_client.py`; MCP-client code goes in `src/mcp_client.py`. If you find yourself about to create a new `src/<thing>.py` file, ASK FIRST. See `AGENTS.md` "File Size and Naming Convention" for the full rule.
8. **Mandatory Research-First Protocol:** Before reading the full content of any file over 50 lines, you MUST use `get_file_summary`, `py_get_skeleton`, `py_get_code_outline`, or `py_get_docstring` to map the architecture and identify specific target ranges. Use `get_git_diff` to understand recent changes. Use `py_find_usages` to locate where symbols are used.
9. **Architecture Documentation Fallback:** When uncertain about threading, event flow, data structures, or module interactions, consult the deep-dive docs in `docs/` (last refreshed: 2026-06-02 via the comprehensive documentation refresh track, **8 new guides added**):
- **[docs/guide_architecture.md](../docs/guide_architecture.md):** Thread domains, cross-thread patterns, AI client multi-provider (Gemini, Anthropic, DeepSeek, Gemini CLI, MiniMax), HITL Execution Clutch.
- **[docs/guide_tools.md](../docs/guide_tools.md):** MCP Bridge 3-layer security, full 45-tool inventory, Hook API, ApiHookClient, `/api/ask` HITL protocol.
- **[docs/guide_mma.md](../docs/guide_mma.md):** Ticket/Track/WorkerContext data structures, DAG engine, ConductorEngine, Tier 2/3/4 lifecycles, persona application.
- **[docs/guide_simulations.md](../docs/guide_simulations.md):** `live_gui` fixture, Puppeteer pattern, mock provider, test areas by subsystem.
- **[docs/guide_testing.md](../docs/guide_testing.md):** **NEW** — 251 test files, 5 categories, 7 conftest fixtures (`isolate_workspace`, `reset_paths`, `reset_ai_client`, `vlogger`, `kill_process_tree`, `mock_app`, `live_gui` session-scoped), Puppeteer pattern, mock provider, structural testing contract.
- **[docs/guide_gui_2.md](../docs/guide_gui_2.md):** **NEW**`src/gui_2.py` (~437KB main GUI): App class lifecycle, ~90 module-level render functions, Multi-Viewport docks, panel registry, command palette integration, ImGuiScope context managers, hot reload support.
- **[docs/guide_ai_client.md](../docs/guide_ai_client.md):** **NEW**`src/ai_client.py` (~166KB): multi-provider LLM singleton (8 providers: gemini, anthropic, gemini_cli, deepseek, minimax, qwen, grok, llama), async dispatch via `asyncio.gather`, threading.local for source tier tagging, Anthropic ephemeral caching + Gemini explicit caching, Tier 4 QA error interception, inlined `VendorCapabilities` registry (moved from the deleted `src/vendor_capabilities.py`).
- **[docs/guide_api_hooks.md](../docs/guide_api_hooks.md):** **NEW**`src/api_hooks.py` + `src/api_hook_client.py` (~51KB + ~38KB): HookServer on `127.0.0.1:8999`, ApiHookClient wrapper, 8+ endpoints, Remote Confirmation Protocol via `/api/ask`.
- **[docs/guide_mcp_client.md](../docs/guide_mcp_client.md):** **NEW**`src/mcp_client.py` (~92KB, 45 tools; tool specs live in `src/mcp_tool_specs.py`): 3-layer security (Allowlist → Validate → Resolve), all native tools (File I/O, Python AST, C/C++ AST, Analysis, Network, Runtime, Beads), ExternalMCPManager (Stdio + SSE), JSON-RPC 2.0 engine.
- **[docs/guide_app_controller.md](../docs/guide_app_controller.md):** **NEW**`src/app_controller.py` (~240KB): headless orchestrator, AppState dataclass, all subsystem managers, `_predefined_callbacks`/`_gettable_fields` Hook API registries, SyncEventQueue, headless mode.
- **[docs/guide_multi_agent_conductor.md](../docs/guide_multi_agent_conductor.md):** **NEW**`src/multi_agent_conductor.py` + `src/dag_engine.py` (~30KB + ~11KB): TrackDAG (iterative DFS cycle detection, Kahn's topological sort), ExecutionEngine (Auto-Queue / Step Mode), MultiAgentConductor + WorkerPool (concurrency 4), the WorkerPool's internal `run_worker_lifecycle` subprocess template (NOT the deprecated `mma_exec.py`; see `docs/guide_meta_boundary.md`).
- **[docs/guide_models.md](../docs/guide_models.md):** **UPDATED 2026-07-02**`src/models.py` is now a ~1.5KB legacy re-export shim (`Metadata = TrackMetadata` alias + `PROVIDERS` lazy `__getattr__`). Data models moved to per-system files per `module_taxonomy_refactor_20260627`: `src/mma.py` (TrackMetadata, Ticket, Track, WorkerContext), `src/project_files.py` (FileItem), `src/type_aliases.py` (typed boundary + per-aggregate dataclasses), `src/mcp_tool_specs.py` (typed ToolSpec registry, 45 tools), `src/result_types.py` (Result[T], ErrorInfo). `VendorCapabilities` lives in `src/ai_client.py`.
- See [docs/Readme.md](../docs/Readme.md) for the full **41-guide index** covering context curation, shaders, RAG, Beads, hot reload, personas, NERV theme, workspace profiles, and command palette.
- **[docs/guide_architecture.md](../docs/guide_architecture.md):** Thread domains, cross-thread patterns, AI client multi-provider (Gemini, Anthropic, DeepSeek, MiniMax), HITL Execution Clutch.
- **[docs/guide_tools.md](../docs/guide_tools.md):** MCP Bridge 3-layer security, full 45-tool inventory, Hook API, ApiHookClient, `/api/ask` HITL protocol.
- **[docs/guide_mma.md](../docs/guide_mma.md):** Ticket/Track/WorkerContext data structures, DAG engine, ConductorEngine, Tier 2/3/4 lifecycles, persona application.
- **[docs/guide_simulations.md](../docs/guide_simulations.md):** `live_gui` fixture, Puppeteer pattern, mock provider, test areas by subsystem.
- **[docs/guide_testing.md](../docs/guide_testing.md):** **NEW** — 251 test files, 5 categories, 7 conftest fixtures (`isolate_workspace`, `reset_paths`, `reset_ai_client`, `vlogger`, `kill_process_tree`, `mock_app`, `live_gui` session-scoped), Puppeteer pattern, mock provider, structural testing contract.
- **[docs/guide_gui_2.md](../docs/guide_gui_2.md):** **NEW**`src/gui_2.py` (~437KB main GUI): App class lifecycle, ~90 module-level render functions, Multi-Viewport docks, panel registry, command palette integration, ImGuiScope context managers, hot reload support.
- **[docs/guide_ai_client.md](../docs/guide_ai_client.md):** **NEW**`src/ai_client.py` (~166KB): multi-provider LLM singleton (8 providers: gemini, anthropic, deepseek, minimax, qwen, grok, llama), async dispatch via `asyncio.gather`, threading.local for source tier tagging, Anthropic ephemeral caching + Gemini explicit caching, Tier 4 QA error interception, inlined `VendorCapabilities` registry (moved from the deleted `src/vendor_capabilities.py`).
- **[docs/guide_api_hooks.md](../docs/guide_api_hooks.md):** **NEW**`src/api_hooks.py` + `src/api_hook_client.py` (~51KB + ~38KB): HookServer on `127.0.0.1:8999`, ApiHookClient wrapper, 8+ endpoints, Remote Confirmation Protocol via `/api/ask`.
- **[docs/guide_mcp_client.md](../docs/guide_mcp_client.md):** **NEW**`src/mcp_client.py` (~92KB, 45 tools; tool specs live in `src/mcp_tool_specs.py`): 3-layer security (Allowlist → Validate → Resolve), all native tools (File I/O, Python AST, C/C++ AST, Analysis, Network, Runtime, Beads), ExternalMCPManager (Stdio + SSE), JSON-RPC 2.0 engine.
- **[docs/guide_app_controller.md](../docs/guide_app_controller.md):** **NEW**`src/app_controller.py` (~240KB): headless orchestrator, AppState dataclass, all subsystem managers, `_predefined_callbacks`/`_gettable_fields` Hook API registries, SyncEventQueue, headless mode.
- **[docs/guide_multi_agent_conductor.md](../docs/guide_multi_agent_conductor.md):** **NEW**`src/multi_agent_conductor.py` + `src/dag_engine.py` (~30KB + ~11KB): TrackDAG (iterative DFS cycle detection, Kahn's topological sort), ExecutionEngine (Auto-Queue / Step Mode), MultiAgentConductor + WorkerPool (concurrency 4), the WorkerPool's internal `run_worker_lifecycle` subprocess template (NOT the deprecated `mma_exec.py`; see `docs/guide_meta_boundary.md`).
- **[docs/guide_models.md](../docs/guide_models.md):** **UPDATED 2026-07-02**`src/models.py` is now a ~1.5KB legacy re-export shim (`Metadata = TrackMetadata` alias + `PROVIDERS` lazy `__getattr__`). Data models moved to per-system files per `module_taxonomy_refactor_20260627`: `src/mma.py` (TrackMetadata, Ticket, Track, WorkerContext), `src/project_files.py` (FileItem), `src/type_aliases.py` (typed boundary + per-aggregate dataclasses), `src/mcp_tool_specs.py` (typed ToolSpec registry, 45 tools), `src/result_types.py` (Result[T], ErrorInfo). `VendorCapabilities` lives in `src/ai_client.py`.
- See [docs/Readme.md](../docs/Readme.md) for the full **41-guide index** covering context curation, shaders, RAG, Beads, hot reload, personas, NERV theme, workspace profiles, and command palette.
## Task Workflow
@@ -88,146 +88,146 @@ All tasks follow a strict lifecycle:
2. **Mark In Progress:** Before beginning work, edit `plan.md` and change the task from `[ ]` to `[~]`
3. **High-Signal Research Phase:**
- **Identify Dependencies:** Use `list_directory`, `get_tree`, and `py_get_imports` to map file relations.
- **Map Architecture:** Use `py_get_code_outline` or `py_get_skeleton` on identified files to understand their structure.
- **Audit State:** Use `py_get_code_outline` or `py_get_definition` on the target class's `__init__` method to check for existing, unused, or duplicate state variables before adding new ones.
- **Analyze Changes:** Use `get_git_diff` if the task involves modifying recently updated code.
- **Minimize Token Burn:** Only use `read_file` with `start_line`/`end_line` for specific implementation details once target areas are identified.
- **Identify Dependencies:** Use `list_directory`, `get_tree`, and `py_get_imports` to map file relations.
- **Map Architecture:** Use `py_get_code_outline` or `py_get_skeleton` on identified files to understand their structure.
- **Audit State:** Use `py_get_code_outline` or `py_get_definition` on the target class's `__init__` method to check for existing, unused, or duplicate state variables before adding new ones.
- **Analyze Changes:** Use `get_git_diff` if the task involves modifying recently updated code.
- **Minimize Token Burn:** Only use `read_file` with `start_line`/`end_line` for specific implementation details once target areas are identified.
4. **Write Failing Tests (Red Phase):**
- **Pre-Delegation Checkpoint:** Before spawning a worker for dangerous or non-trivial changes, ensure your current progress is staged (`git add .`) or committed. This prevents losing iterations if a sub-agent incorrectly uses `git restore`.
- **Zero-Assertion Ban:** You MUST NOT write tests that contain only `pass` or lack meaningful assertions. A test is only valid if it contains assertions that explicitly test the behavioral change and verify the failure condition.
- **Code Style:** ALWAYS explicitly mention "Use exactly 1-space indentation for Python code" when prompting a sub-agent.
- **Delegate Test Creation:** Do NOT write test code directly. Spawn a Tier 3 Worker via the **OpenCode Task tool** with `subagent_type: "tier3-worker"` and a **surgical prompt** specifying WHERE (file:line range), WHAT (test to create), HOW (which assertions/fixtures to use), and SAFETY (thread constraints if applicable). Example: `"Write tests in tests/test_cost_tracker.py for cost_tracker.py:estimate_cost(). Test all model patterns in MODEL_PRICING dict. Assert unknown model returns 0. Use 1-space indentation."` (If repeating due to failures, set the subagent's `failure_count` higher to switch to a more capable model.) **Note:** the legacy `python scripts/mma_exec.py --role tier3-worker` invocation is DEPRECATED (see §"Conductor Token Firewalling" below); use the OpenCode Task tool instead.
- Take the code generated by the Worker and apply it.
- **CRITICAL:** Run the tests and confirm that they fail as expected. This is the "Red" phase of TDD. Do not proceed until you have failing tests.
- **Pre-Delegation Checkpoint:** Before spawning a worker for dangerous or non-trivial changes, ensure your current progress is staged (`git add .`) or committed. This prevents losing iterations if a sub-agent incorrectly uses `git restore`.
- **Zero-Assertion Ban:** You MUST NOT write tests that contain only `pass` or lack meaningful assertions. A test is only valid if it contains assertions that explicitly test the behavioral change and verify the failure condition.
- **Code Style:** ALWAYS explicitly mention "Use exactly 1-space indentation for Python code" when prompting a sub-agent.
- **Delegate Test Creation:** Do NOT write test code directly. Spawn a Tier 3 Worker via the **OpenCode Task tool** with `subagent_type: "tier3-worker"` and a **surgical prompt** specifying WHERE (file:line range), WHAT (test to create), HOW (which assertions/fixtures to use), and SAFETY (thread constraints if applicable). Example: `"Write tests in tests/test_cost_tracker.py for cost_tracker.py:estimate_cost(). Test all model patterns in MODEL_PRICING dict. Assert unknown model returns 0. Use 1-space indentation."` (If repeating due to failures, set the subagent's `failure_count` higher to switch to a more capable model.) **Note:** the legacy `python scripts/mma_exec.py --role tier3-worker` invocation is DEPRECATED (see §"Conductor Token Firewalling" below); use the OpenCode Task tool instead.
- Take the code generated by the Worker and apply it.
- **CRITICAL:** Run the tests and confirm that they fail as expected. This is the "Red" phase of TDD. Do not proceed until you have failing tests.
5. **Implement to Pass Tests (Green Phase):**
- **Pre-Delegation Checkpoint:** Ensure current progress is staged or committed before delegating.
- **Code Style:** ALWAYS explicitly mention "Use exactly 1-space indentation for Python code" when prompting a sub-agent.
- **Delegate Implementation:** Do NOT write the implementation code directly. Spawn a Tier 3 Worker via the **OpenCode Task tool** (`subagent_type: "tier3-worker"`) with a **surgical prompt** specifying WHERE (file:line range to modify), WHAT (the specific change), HOW (which API calls, data structures, or patterns to use), and SAFETY (thread-safety constraints). Example: `"In gui_2.py _render_mma_dashboard (lines 2685-2699), extend the token usage table from 3 to 5 columns. Add 'Model' and 'Est. Cost' using imgui.table_setup_column(). Call cost_tracker.estimate_cost(model, input_tokens, output_tokens). Use 1-space indentation."` (If repeating due to failures, set `failure_count` higher to switch to a more capable model.) **Note:** the legacy `python scripts/mma_exec.py --role tier3-worker` invocation is DEPRECATED; use the OpenCode Task tool.
- Take the code generated by the Worker and apply it.
- Run the test suite again and confirm that all tests now pass. This is the "Green" phase.
- **Pre-Delegation Checkpoint:** Ensure current progress is staged or committed before delegating.
- **Code Style:** ALWAYS explicitly mention "Use exactly 1-space indentation for Python code" when prompting a sub-agent.
- **Delegate Implementation:** Do NOT write the implementation code directly. Spawn a Tier 3 Worker via the **OpenCode Task tool** (`subagent_type: "tier3-worker"`) with a **surgical prompt** specifying WHERE (file:line range to modify), WHAT (the specific change), HOW (which API calls, data structures, or patterns to use), and SAFETY (thread-safety constraints). Example: `"In gui_2.py _render_mma_dashboard (lines 2685-2699), extend the token usage table from 3 to 5 columns. Add 'Model' and 'Est. Cost' using imgui.table_setup_column(). Call cost_tracker.estimate_cost(model, input_tokens, output_tokens). Use 1-space indentation."` (If repeating due to failures, set `failure_count` higher to switch to a more capable model.) **Note:** the legacy `python scripts/mma_exec.py --role tier3-worker` invocation is DEPRECATED; use the OpenCode Task tool.
- Take the code generated by the Worker and apply it.
- Run the test suite again and confirm that all tests now pass. This is the "Green" phase.
6. **Refactor (Optional but Recommended):**
- With the safety of passing tests, refactor the implementation code and the test code to improve clarity, remove duplication, and enhance performance without changing the external behavior.
- Rerun tests to ensure they still pass after refactoring.
- With the safety of passing tests, refactor the implementation code and the test code to improve clarity, remove duplication, and enhance performance without changing the external behavior.
- Rerun tests to ensure they still pass after refactoring.
7. **Verify Coverage:** Run coverage reports using the project's chosen tools. For example, in a Python project, this might look like:
```powershell
pytest --cov=app --cov-report=html
```
Target: >80% coverage for new code. The specific tools and commands will vary by language and framework.
```powershell
pytest --cov=app --cov-report=html
```
Target: >80% coverage for new code. The specific tools and commands will vary by language and framework.
8. **Document Deviations:** If implementation differs from tech stack:
- **STOP** implementation
- Update `tech-stack.md` with new design
- Add dated note explaining the change
- Resume implementation
- **STOP** implementation
- Update `tech-stack.md` with new design
- Add dated note explaining the change
- Resume implementation
9. **Commit Code Changes:**
- **CRITICAL - ATOMIC PER-TASK COMMITS**: You MUST commit your changes immediately after completing and verifying a single task. Do NOT move on to the next task in the plan without committing the current one. This ensures precise tracking and safe rollback points.
- Stage all code changes related to the task.
- Propose a clear, concise commit message e.g, `feat(ui): Create basic HTML structure for calculator`.
- Perform the commit.
- **CRITICAL - ATOMIC PER-TASK COMMITS**: You MUST commit your changes immediately after completing and verifying a single task. Do NOT move on to the next task in the plan without committing the current one. This ensures precise tracking and safe rollback points.
- Stage all code changes related to the task.
- Propose a clear, concise commit message e.g, `feat(ui): Create basic HTML structure for calculator`.
- Perform the commit.
10. **Attach Task Summary with Git Notes:**
- **Step 9.1: Get Commit Hash:** Obtain the hash of the *just-completed commit* (`git log -1 --format="%H"`).
- **Step 9.2: Draft Note Content:** Create a detailed summary for the completed task. This should include the task name, a summary of changes, a list of all created/modified files, and the core "why" for the change.
- **Step 9.3: Attach Note:** Use the `git notes` command to attach the summary to the commit.
```powershell
# The note content from the previous step is passed via the -m flag.
git notes add -m "<note content>" <commit_hash>
```
- **Step 9.1: Get Commit Hash:** Obtain the hash of the *just-completed commit* (`git log -1 --format="%H"`).
- **Step 9.2: Draft Note Content:** Create a detailed summary for the completed task. This should include the task name, a summary of changes, a list of all created/modified files, and the core "why" for the change.
- **Step 9.3: Attach Note:** Use the `git notes` command to attach the summary to the commit.
```powershell
# The note content from the previous step is passed via the -m flag.
git notes add -m "<note content>" <commit_hash>
```
11. **Get and Record Task Commit SHA:**
- **Step 10.1: Update Plan:** Read `plan.md`, find the line for the completed task, update its status from `[~]` to `[x]`, and append the first 7 characters of the *just-completed commit's* commit hash.
- **Step 10.2: Write Plan:** Write the updated content back to `plan.md`.
- **Step 10.1: Update Plan:** Read `plan.md`, find the line for the completed task, update its status from `[~]` to `[x]`, and append the first 7 characters of the *just-completed commit's* commit hash.
- **Step 10.2: Write Plan:** Write the updated content back to `plan.md`.
12. **Commit Plan Update:**
- **Action:** Stage the modified `plan.md` file.
- **Action:** Commit this change with a descriptive message (e.g., `conductor(plan): Mark task 'Create user model' as complete`).
- **Action:** Stage the modified `plan.md` file.
- **Action:** Commit this change with a descriptive message (e.g., `conductor(plan): Mark task 'Create user model' as complete`).
### Phase Completion Verification and Checkpointing Protocol
**Trigger:** This protocol is executed immediately after a task is completed that also concludes a phase in `plan.md`.
1. **Announce Protocol Start:** Inform the user that the phase is complete and the verification and checkpointing protocol has begun.
1. **Announce Protocol Start:** Inform the user that the phase is complete and the verification and checkpointing protocol has begun.
2. **Ensure Test Coverage for Phase Changes:**
- **Step 2.1: Determine Phase Scope:** To identify the files changed in this phase, you must first find the starting point. Read `plan.md` to find the Git commit SHA of the *previous* phase's checkpoint. If no previous checkpoint exists, the scope is all changes since the first commit.
- **Step 2.2: List Changed Files:** Execute `git diff --name-only <previous_checkpoint_sha> HEAD` to get a precise list of all files modified during this phase.
- **Step 2.3: Verify and Create Tests:** For each file in the list:
- **CRITICAL:** First, check its extension. Exclude non-code files (e.g., `.json`, `.md`, `.yaml`).
- For each remaining code file, verify a corresponding test file exists.
- If a test file is missing, you **must** create one. Before writing the test, **first, analyze other test files in the repository to determine the correct naming convention and testing style.** The new tests **must** validate the functionality described in this phase's tasks (`plan.md`).
2. **Ensure Test Coverage for Phase Changes:**
- **Step 2.1: Determine Phase Scope:** To identify the files changed in this phase, you must first find the starting point. Read `plan.md` to find the Git commit SHA of the *previous* phase's checkpoint. If no previous checkpoint exists, the scope is all changes since the first commit.
- **Step 2.2: List Changed Files:** Execute `git diff --name-only <previous_checkpoint_sha> HEAD` to get a precise list of all files modified during this phase.
- **Step 2.3: Verify and Create Tests:** For each file in the list:
- **CRITICAL:** First, check its extension. Exclude non-code files (e.g., `.json`, `.md`, `.yaml`).
- For each remaining code file, verify a corresponding test file exists.
- If a test file is missing, you **must** create one. Before writing the test, **first, analyze other test files in the repository to determine the correct naming convention and testing style.** The new tests **must** validate the functionality described in this phase's tasks (`plan.md`).
3. **Execute Automated Tests in Batches:**
- Because the full suite is large (>360 tests) and contains complex UI simulations, running the entire suite frequently can lead to random timeouts or threading access violations.
- Before execution, you **must** announce the exact shell command.
- **CRITICAL:** When verifying changes, **do not run the full suite (`pytest tests/`)**. Instead, run tests in small, targeted batches (maximum 4 test files at a time). Only use long timeouts (`--timeout=60` or `--timeout=120`) if the specific tests in the batch are known to be slow (e.g., simulation tests).
- **Example Announcement:** "I will now run the automated test suite to verify the phase. **Command:** `uv run pytest tests/test_specific_feature.py`"
- Execute the announced command.
- If tests fail with significant output (e.g., a large traceback), **DO NOT** attempt to read the raw `stderr` directly into your context. Instead, pipe the output to a log file and **spawn a Tier 4 QA Agent via the OpenCode Task tool (`subagent_type: "tier4-qa"`)** with the error output + an explicit instruction "DO NOT fix — provide root cause analysis only". (The legacy `python scripts/mma_exec.py --role tier4-qa` invocation is DEPRECATED; use the OpenCode Task tool.)
- You **must** inform the user and begin debugging using the QA Agent's summary. You may attempt to propose a fix a **maximum of two times**. If the tests still fail after your second proposed fix, you **must stop**, report the persistent failure, and ask the user for guidance.
3. **Execute Automated Tests in Batches:**
- Because the full suite is large (>360 tests) and contains complex UI simulations, running the entire suite frequently can lead to random timeouts or threading access violations.
- Before execution, you **must** announce the exact shell command.
- **CRITICAL:** When verifying changes, **do not run the full suite (`pytest tests/`)**. Instead, run tests in small, targeted batches (maximum 4 test files at a time). Only use long timeouts (`--timeout=60` or `--timeout=120`) if the specific tests in the batch are known to be slow (e.g., simulation tests).
- **Example Announcement:** "I will now run the automated test suite to verify the phase. **Command:** `uv run pytest tests/test_specific_feature.py`"
- Execute the announced command.
- If tests fail with significant output (e.g., a large traceback), **DO NOT** attempt to read the raw `stderr` directly into your context. Instead, pipe the output to a log file and **spawn a Tier 4 QA Agent via the OpenCode Task tool (`subagent_type: "tier4-qa"`)** with the error output + an explicit instruction "DO NOT fix — provide root cause analysis only". (The legacy `python scripts/mma_exec.py --role tier4-qa` invocation is DEPRECATED; use the OpenCode Task tool.)
- You **must** inform the user and begin debugging using the QA Agent's summary. You may attempt to propose a fix a **maximum of two times**. If the tests still fail after your second proposed fix, you **must stop**, report the persistent failure, and ask the user for guidance.
4. **Execute Automated API Hook Verification:**
- **CRITICAL:** The Conductor agent will now automatically execute verification tasks using the application's API hooks.
- The agent will announce the start of the automated verification to the user.
- It will then communicate with the application's IPC server to trigger the necessary verification functions.
- **Result Handling:**
- All results (successes and failures) from the API hook invocations will be logged.
- If all automated verifications pass, the agent will inform the user and proceed to the next step (Create Checkpoint Commit).
- If any automated verification fails, the agent will halt the workflow, present the detailed failure logs to the user, and await further instructions for debugging or remediation.
4. **Execute Automated API Hook Verification:**
- **CRITICAL:** The Conductor agent will now automatically execute verification tasks using the application's API hooks.
- The agent will announce the start of the automated verification to the user.
- It will then communicate with the application's IPC server to trigger the necessary verification functions.
- **Result Handling:**
- All results (successes and failures) from the API hook invocations will be logged.
- If all automated verifications pass, the agent will inform the user and proceed to the next step (Create Checkpoint Commit).
- If any automated verification fails, the agent will halt the workflow, present the detailed failure logs to the user, and await further instructions for debugging or remediation.
5. **Present Automated Verification Results and User Confirmation:**
- After executing automated verification, the Conductor agent will present the results to the user.
- If verification passed, the agent will state: "Automated verification completed successfully."
- If verification failed, the agent will state: "Automated verification failed. Please review the logs above for details. You may attempt to propose a fix a **maximum of two times**. If the tests still fail after your second proposed fix, you **must stop**, report the persistent failure, and ask the user for guidance."
- **PAUSE** and await the user's response. Do not proceed without an explicit yes or confirmation from the user to proceed if tests pass, or guidance if tests fail.
5. **Present Automated Verification Results and User Confirmation:**
- After executing automated verification, the Conductor agent will present the results to the user.
- If verification passed, the agent will state: "Automated verification completed successfully."
- If verification failed, the agent will state: "Automated verification failed. Please review the logs above for details. You may attempt to propose a fix a **maximum of two times**. If the tests still fail after your second proposed fix, you **must stop**, report the persistent failure, and ask the user for guidance."
- **PAUSE** and await the user's response. Do not proceed without an explicit yes or confirmation from the user to proceed if tests pass, or guidance if tests fail.
6. **Create Checkpoint Commit:**
- Stage all changes. If no changes occurred in this step, proceed with an empty commit.
- Perform the commit with a clear and concise message (e.g., `conductor(checkpoint): Checkpoint end of Phase X`).
6. **Create Checkpoint Commit:**
- Stage all changes. If no changes occurred in this step, proceed with an empty commit.
- Perform the commit with a clear and concise message (e.g., `conductor(checkpoint): Checkpoint end of Phase X`).
7. **Attach Auditable Verification Report using Git Notes:**
- **Step 7.1: Draft Note Content:** Create a detailed verification report including the automated test command, the manual verification steps, and the user's confirmation.
- **Step 7.2: Attach Note:** Use the `git notes` command and the full commit hash from the previous step to attach the full report to the checkpoint commit.
7. **Attach Auditable Verification Report using Git Notes:**
- **Step 7.1: Draft Note Content:** Create a detailed verification report including the automated test command, the manual verification steps, and the user's confirmation.
- **Step 7.2: Attach Note:** Use the `git notes` command and the full commit hash from the previous step to attach the full report to the checkpoint commit.
8. **Get and Record Phase Checkpoint SHA:**
- **Step 8.1: Get Commit Hash:** Obtain the hash of the *just-created checkpoint commit* (`git log -1 --format="%H"`).
- **Step 8.2: Update Plan:** Read `plan.md`, find the heading for the completed phase, and append the first 7 characters of the commit hash in the format `[checkpoint: <sha>]`.
- **Step 8.3: Write Plan:** Write the updated content back to `plan.md`.
8. **Get and Record Phase Checkpoint SHA:**
- **Step 8.1: Get Commit Hash:** Obtain the hash of the *just-created checkpoint commit* (`git log -1 --format="%H"`).
- **Step 8.2: Update Plan:** Read `plan.md`, find the heading for the completed phase, and append the first 7 characters of the commit hash in the format `[checkpoint: <sha>]`.
- **Step 8.3: Write Plan:** Write the updated content back to `plan.md`.
9. **Commit Plan Update:**
- **Action:** Stage the modified `plan.md` file.
- **Action:** Commit this change with a descriptive message following the format `conductor(plan): Mark phase '<PHASE NAME>' as complete`.
- **Action:** Stage the modified `plan.md` file.
- **Action:** Commit this change with a descriptive message following the format `conductor(plan): Mark phase '<PHASE NAME>' as complete`.
10. **Announce Completion:** Inform the user that the phase is complete and the checkpoint has been created, with the detailed verification report attached as a git note.
10. **Announce Completion:** Inform the user that the phase is complete and the checkpoint has been created, with the detailed verification report attached as a git note.
### Verification via API Hooks
For features involving the GUI or complex internal state, unit tests are often insufficient. You MUST use the application's built-in API hooks for empirical verification:
1. **Launch the App with Hooks:** Run the application in a separate shell with the `--enable-test-hooks` flag:
```powershell
uv run python gui.py --enable-test-hooks
```
This starts the hook server on port `8999`.
1. **Launch the App with Hooks:** Run the application in a separate shell with the `--enable-test-hooks` flag:
```powershell
uv run python gui.py --enable-test-hooks
```
This starts the hook server on port `8999`.
2. **Use the pytest `live_gui` Fixture:** For automated tests, use the session-scoped `live_gui` fixture defined in `tests/conftest.py`. This fixture handles the lifecycle (startup/shutdown) of the application with hooks enabled.
```python
def test_my_feature(live_gui):
# The GUI is now running on port 8999
...
```
Note: pytest must be run with `uv`.
2. **Use the pytest `live_gui` Fixture:** For automated tests, use the session-scoped `live_gui` fixture defined in `tests/conftest.py`. This fixture handles the lifecycle (startup/shutdown) of the application with hooks enabled.
```python
def test_my_feature(live_gui):
# The GUI is now running on port 8999
...
```
Note: pytest must be run with `uv`.
3. **Verify via ApiHookClient:** Use the `ApiHookClient` in `api_hook_client.py` to interact with the running application. It includes robust retry logic and health checks.
3. **Verify via ApiHookClient:** Use the `ApiHookClient` in `api_hook_client.py` to interact with the running application. It includes robust retry logic and health checks.
4. **Verify via REST Commands:** Use PowerShell or `curl` to send commands to the application and verify the response. For example, to check health:
```powershell
Invoke-RestMethod -Uri "http://127.0.0.1:8999/status" -Method Get
```
4. **Verify via REST Commands:** Use PowerShell or `curl` to send commands to the application and verify the response. For example, to check health:
```powershell
Invoke-RestMethod -Uri "http://127.0.0.1:8999/status" -Method Get
```
### Quality Gates
@@ -275,9 +275,9 @@ Before marking any task complete, verify:
### Structural Testing Contract
1. **Ban on Arbitrary Core Mocking:** Tier 3 workers are strictly forbidden from using `unittest.mock.patch` to bypass or stub core infrastructure (e.g., event queues, `ai_client` internals, threading primitives) unless explicitly authorized by the Tier 2 Tech Lead for a specific boundary test.
2. **`live_gui` Standard:** All integration and end-to-end testing must utilize the `live_gui` fixture to interact with a real instance of the application via the Hook API. Bypassing the hook server to directly mutate GUI state in tests is prohibited.
3. **Artifact Isolation:** All test-generated artifacts (logs, temporary workspaces, mock outputs) MUST be written to the `tests/artifacts/` or `tests/logs/` directories. These directories are git-ignored to prevent repository pollution.
1. **Ban on Arbitrary Core Mocking:** Tier 3 workers are strictly forbidden from using `unittest.mock.patch` to bypass or stub core infrastructure (e.g., event queues, `ai_client` internals, threading primitives) unless explicitly authorized by the Tier 2 Tech Lead for a specific boundary test.
2. **`live_gui` Standard:** All integration and end-to-end testing must utilize the `live_gui` fixture to interact with a real instance of the application via the Hook API. Bypassing the hook server to directly mutate GUI state in tests is prohibited.
3. **Artifact Isolation:** All test-generated artifacts (logs, temporary workspaces, mock outputs) MUST be written to the `tests/artifacts/` or `tests/logs/` directories. These directories are git-ignored to prevent repository pollution.
### Unit Testing
@@ -368,14 +368,14 @@ This doc describes **META-TOOLING** — the AI agent orchestration layer used by
- **Mandatory Skill Activation:** As the very first step of any MMA-driven process, including track initialization and implementation phases, the agent MUST activate the `mma-orchestrator` skill (`activate_skill mma-orchestrator`) and their corresponding role's specific tier skill. This is crucial for enforcing the 4-Tier token firewall.
- **The Sub-Agent Bridge (OpenCode Task tool):** All meta-tooling tiered delegation is now via the OpenCode Task tool with the appropriate `subagent_type`. This is the canonical META-TOOLING mechanism; it replaces the legacy `mma_exec.py` invocation. (The application-domain MMA engine in `src/multi_agent_conductor.py` is unchanged and is documented in `docs/guide_multi_agent_conductor.md`.)
- **Model Tiers:**
- **Tier 1 (Strategic/Orchestration):** `gemini-3.1-pro-preview`. Focused on product alignment, setup (`/conductor:setup`), and track initialization (`/conductor:newTrack`).
- **Tier 2 (Architectural/Tech Lead):** `gemini-3-flash-preview`. Focused on architectural design and track execution (`/conductor:implement`). **Note:** Tier 2 maintains persistent memory throughout a track's implementation.
- **Tier 3 (Execution/Worker):** `gemini-2.5-flash-lite`. Used for surgical code implementation and test generation. Operates statelessly (Context Amnesia) but has access to file I/O tools.
- **Tier 4 (Utility/QA):** `gemini-2.5-flash-lite`. Used for log summarization and error analysis. Operates statelessly (Context Amnesia) but has access to diagnostic tools.
- **Tier 1 (Strategic/Orchestration):** `gemini-3.1-pro-preview`. Focused on product alignment, setup (`/conductor:setup`), and track initialization (`/conductor:newTrack`).
- **Tier 2 (Architectural/Tech Lead):** `gemini-3-flash-preview`. Focused on architectural design and track execution (`/conductor:implement`). **Note:** Tier 2 maintains persistent memory throughout a track's implementation.
- **Tier 3 (Execution/Worker):** `gemini-2.5-flash-lite`. Used for surgical code implementation and test generation. Operates statelessly (Context Amnesia) but has access to file I/O tools.
- **Tier 4 (Utility/QA):** `gemini-2.5-flash-lite`. Used for log summarization and error analysis. Operates statelessly (Context Amnesia) but has access to diagnostic tools.
- **Tiered Delegation Protocol (OpenCode Task tool):**
- **Tier 3 Worker:** invoke the Task tool with `subagent_type: "tier3-worker"`, providing a surgical prompt with WHERE/WHAT/HOW/SAFETY/COMMIT structure. **DO NOT** use `python scripts/mma_exec.py --role tier3-worker` (deprecated).
- **Tier 4 QA Agent:** invoke the Task tool with `subagent_type: "tier4-qa"`, providing the error output + an explicit instruction "DO NOT fix — provide root cause analysis only".
- **Tier 1 Orchestrator:** invoke the Task tool with `subagent_type: "tier1-orchestrator"` for track planning tasks.
- **Tier 3 Worker:** invoke the Task tool with `subagent_type: "tier3-worker"`, providing a surgical prompt with WHERE/WHAT/HOW/SAFETY/COMMIT structure. **DO NOT** use `python scripts/mma_exec.py --role tier3-worker` (deprecated).
- **Tier 4 QA Agent:** invoke the Task tool with `subagent_type: "tier4-qa"`, providing the error output + an explicit instruction "DO NOT fix — provide root cause analysis only".
- **Tier 1 Orchestrator:** invoke the Task tool with `subagent_type: "tier1-orchestrator"` for track planning tasks.
- **MMA Skill Discipline Tests:** The 5 MMA skills (`mma-orchestrator`, `mma-tier1-orchestrator`, `mma-tier2-tech-lead`, `mma-tier3-worker`, `mma-tier4-qa`) at `.agents/skills/mma-*/SKILL.md` are tested for discipline compliance via `tests/test_mma_skill_discipline.py` (per `conductor/tracks/superpowers_review_apply_high_20260705/spec.md` §3.2 and recommendation #2 from `conductor/tracks/superpowers_review_20260619/decisions.md`). The tests are static-analysis of skill documents (text-pattern assertions), not behavioral tests; they run in <5 seconds, require no live_gui or MMA execution, and verify that load-bearing rules are *prominently documented* (not just buried in prose). Future agents extending the MMA skills must also extend the tests.
- **Observability:** All hierarchical interactions are recorded in `logs/mma_delegation.log` and detailed sub-agent logs are saved to `logs/agents/`. (These logs are populated by the OpenCode Task tool's logging layer.)
@@ -470,14 +470,14 @@ The pattern `push_event(...)` → `time.sleep(N)` → `assert` is a guaranteed r
```python
# WRONG: race condition
def test_open_modal(live_gui):
client.push_event("custom_callback", {"callback": "_toggle_settings", "args": []})
time.sleep(1) # hope the modal opened
assert some_cached_value["settings_open"] is True # may be stale
client.push_event("custom_callback", {"callback": "_toggle_settings", "args": []})
time.sleep(1) # hope the modal opened
assert some_cached_value["settings_open"] is True # may be stale
# RIGHT: poll-until-state-visible
def test_open_modal(live_gui):
client.push_event("custom_callback", {"callback": "_toggle_settings", "args": []})
assert client.get_value("show_settings_modal"), "settings modal did not open"
client.push_event("custom_callback", {"callback": "_toggle_settings", "args": []})
assert client.get_value("show_settings_modal"), "settings modal did not open"
```
This pattern surfaced 5+ times in the 2026-06-10 batch-green wave (test_reset_session_clears_mma_and_rag, test_visual_mma, test_visual_sim_gui_ux, test_gui_ux_event_routing, test_z_negative_flows). The fix is always the same: replace `time.sleep` with a poll loop bounded by a retry timeout (typically 5-20 iterations × 0.5s).
@@ -497,9 +497,9 @@ This pattern surfaced 5+ times in the 2026-06-10 batch-green wave (test_reset_se
**How to detect during TDD:**
- After modifying a class body, walk the AST and verify all expected methods are class-level:
```bash
uv run python -c "import ast; tree = ast.parse(open('src/gui_2.py').read()); [print(item.name) for n in ast.walk(tree) if isinstance(n, ast.ClassDef) and n.name == 'App' for item in n.body if isinstance(item, ast.FunctionDef)]"
```
```bash
uv run python -c "import ast; tree = ast.parse(open('src/gui_2.py').read()); [print(item.name) for n in ast.walk(tree) if isinstance(n, ast.ClassDef) and n.name == 'App' for item in n.body if isinstance(item, ast.FunctionDef)]"
```
- The skeleton via `manual-slop_py_get_skeleton` should show the method as a class member. If it's missing, it's nested.
**How to fix:** Re-indent the affected method to exactly 2-space class level. Use the file_slice tool or PyCharm-style auto-format to verify. Run the failing test to confirm.
@@ -695,42 +695,42 @@ Audit, Goals, Non-Goals, Architecture, Risks, Verification, etc.) with
these specific Tier 1 rules:
- **Current State Audit is MANDATORY** before writing requirements. Read
the actual code with MCP tools (`get_file_slice`, `py_get_skeleton`,
`py_get_definition`, `py_find_usages`). Document existing
implementations with `file:line` references in a "Current State
Audit" section. Failure to audit = track failure.
the actual code with MCP tools (`get_file_slice`, `py_get_skeleton`,
`py_get_definition`, `py_find_usages`). Document existing
implementations with `file:line` references in a "Current State
Audit" section. Failure to audit = track failure.
- **Frame requirements as GAPS, not features.** "The existing X
(file.py:L100-200) has Y; this track fills the gap" — not "Build
feature Z".
(file.py:L100-200) has Y; this track fills the gap" — not "Build
feature Z".
- **Write worker-ready tasks** in the plan. Each plan task must be
executable by a Tier 3 worker. The Tier 1 does NOT execute the
plan; the Tier 1 writes it for a Tier 3 to execute.
executable by a Tier 3 worker. The Tier 1 does NOT execute the
plan; the Tier 1 writes it for a Tier 3 to execute.
- **Reference architecture docs** (`docs/guide_*.md`,
`conductor/code_styleguides/*.md`) in every spec. Every requirement
must point to the existing pattern it follows (or the new pattern it
establishes).
`conductor/code_styleguides/*.md`) in every spec. Every requirement
must point to the existing pattern it follows (or the new pattern it
establishes).
- **For bug fix tracks: Root Cause Analysis** is mandatory. Read the
code, trace the data flow, list specific root cause candidates.
Don't ship "I tried X, the test still failed, here's a 200-line
report".
code, trace the data flow, list specific root cause candidates.
Don't ship "I tried X, the test still failed, here's a 200-line
report".
### 3. Metadata format
The `metadata.json` follows the standard schema. Specific Tier 1 rules:
- `scope.new_files` / `scope.modified_files` / `scope.deleted_files`
are the file-level scope. No "lines of code changed" estimates.
are the file-level scope. No "lines of code changed" estimates.
- `regressions_and_pre_existing_failures` is a list, not a count.
- `pre_existing_failures_remaining` MUST be `[]` for the track to be
marked complete.
marked complete.
- `deferred_to_followup_tracks` is a list of followup items with
title + description + track_status. No "estimated effort".
title + description + track_status. No "estimated effort".
- `estimated_effort` field uses `method: "scope (per workflow.md §Tier
1 Track Initialization Rules). NO day estimates."` and a per-phase
`scope` summary (e.g., `phase_1: "1 task: investigation"`).
1 Track Initialization Rules). NO day estimates."` and a per-phase
`scope` summary (e.g., `phase_1: "1 task: investigation"`).
- `risk_register` entries use scope-relative likelihood ("medium"
means "the implementation may be larger than the spec suggests"),
not time-relative ("takes longer than 2 days").
means "the implementation may be larger than the spec suggests"),
not time-relative ("takes longer than 2 days").
### 4. Plan format
@@ -738,11 +738,11 @@ The `plan.md` follows the standard TDD red-first template. Specific
Tier 1 rules:
- Each task has WHERE / WHAT / HOW / SAFETY / COMMIT / GIT NOTE
fields. Tasks are NOT grouped by "day" or "hour".
fields. Tasks are NOT grouped by "day" or "hour".
- Phase headers describe the WORK, not the TIME. ("Phase 1:
Investigation" not "Phase 1: Day 1").
Investigation" not "Phase 1: Day 1").
- The plan is read by a Tier 3 worker; the Tier 1 never executes it
themselves.
themselves.
### 5. The "Reasonable effort" guard
@@ -770,8 +770,8 @@ Every track's `conductor/tracks/<track_id>/state.toml` should follow this struct
[meta]
track_id = "<track_id>"
name = "<Human-Readable Name>"
status = "active" # active | completed
current_phase = 0 # 0 = pre-Phase 1; 1..N = in Phase N; "complete" if all phases done
status = "active" # active | completed
current_phase = 0 # 0 = pre-Phase 1; 1..N = in Phase N; "complete" if all phases done
last_updated = "<YYYY-MM-DD>"
[blocked_by]
@@ -818,9 +818,9 @@ When the implementing agent encounters a decision not covered by the plan:
1. **If the decision is purely cosmetic** (e.g., variable naming, comment placement, exact spacing): pick the option that matches the surrounding code style. Document the choice in the commit message.
2. **If the decision affects the architecture** (e.g., the spec's data model doesn't fit the code; the plan's approach doesn't compile; an external library doesn't behave as expected): **STOP. Do not commit. Report to the Tier 2 Tech Lead.** The lead will either:
- Update the spec to match the new constraint
- Add a clarifying task to the plan
- Defer the work to a follow-up track
- Update the spec to match the new constraint
- Add a clarifying task to the plan
- Defer the work to a follow-up track
3. **If the decision is a regression** (e.g., the plan's code works but introduces a known bug, or fails a test the plan didn't anticipate): **STOP and report.** Don't ship a known regression to save time. The lead will decide whether to fix forward or roll back.
**The principle: small decisions, decide yourself. Large decisions, escalate.** The boundary is "does this decision require a new spec or plan update?"
@@ -913,20 +913,20 @@ This section extends the existing workflow with the patterns surfaced by the `na
```
- [ ] tests/test_knowledge_store.py: 5+ tests for the 7-category schema
- [ ] parse_harvest_json: 7 categories; rows must be lists
- [ ] parse_harvest_json: rejects prose
- [ ] parse_harvest_json: tolerates ```json ... ``` code-fence
- [ ] parse_harvest_json: rejects non-dict payloads
- [ ] regenerate_digest: 4KB cap; truncation with note
- [ ] parse_harvest_json: 7 categories; rows must be lists
- [ ] parse_harvest_json: rejects prose
- [ ] parse_harvest_json: tolerates ```json ... ``` code-fence
- [ ] parse_harvest_json: rejects non-dict payloads
- [ ] regenerate_digest: 4KB cap; truncation with note
- [ ] tests/test_knowledge_harvest.py: 8+ tests for the pipeline
- [ ] classify (live/user-kept/prune/harvest/keep)
- [ ] merge_harvest per category
- [ ] per-file knowledge: existing-file branch
- [ ] per-file knowledge: missing-file branch
- [ ] ledger dedup (sha256-of-content)
- [ ] retry budget (2 attempts)
- [ ] "too-large" budget guard (1MB)
- [ ] "delete to turn off" regeneration
- [ ] classify (live/user-kept/prune/harvest/keep)
- [ ] merge_harvest per category
- [ ] per-file knowledge: existing-file branch
- [ ] per-file knowledge: missing-file branch
- [ ] ledger dedup (sha256-of-content)
- [ ] retry budget (2 attempts)
- [ ] "too-large" budget guard (1MB)
- [ ] "delete to turn off" regeneration
```
### The cache ordering TDD protocol
@@ -935,17 +935,17 @@ This section extends the existing workflow with the patterns surfaced by the `na
```
- [ ] tests/test_aggregate_caching.py: the byte-comparison test
- [ ] first N chars are identical across turns of the same discussion
- [ ] N = aggregate.stable_prefix_length(ctrl)
- [ ] failure modes: new layer in wrong position, volatile input leak
- [ ] first N chars are identical across turns of the same discussion
- [ ] N = aggregate.stable_prefix_length(ctrl)
- [ ] failure modes: new layer in wrong position, volatile input leak
- [ ] tests/test_cache_state.py: 3+ tests for the cache state machine
- [ ] per-provider TTL defaults
- [ ] DiscussionCacheState lifecycle
- [ ] invalidate + regeneration
- [ ] per-provider TTL defaults
- [ ] DiscussionCacheState lifecycle
- [ ] invalidate + regeneration
- [ ] tests/test_gui_caching.py: 3+ live_gui tests for the "Caching" panel
- [ ] panel renders provider summaries
- [ ] invalidate button
- [ ] per-discussion disable/enable
- [ ] panel renders provider summaries
- [ ] invalidate button
- [ ] per-discussion disable/enable
```
### The compaction TDD protocol
@@ -954,16 +954,16 @@ This section extends the existing workflow with the patterns surfaced by the `na
```
- [ ] tests/test_run_discussion_compaction.py: 10+ tests
- [ ] compact preserves decisions
- [ ] compact preserves constraints
- [ ] compact preserves failures
- [ ] compact preserves artifact refs
- [ ] compact removes duplicates
- [ ] compact replaces chronology with state
- [ ] compact is substantially smaller
- [ ] compact preserves capability
- [ ] compact returns 12-section structure
- [ ] compact continues until self-review passes
- [ ] compact preserves decisions
- [ ] compact preserves constraints
- [ ] compact preserves failures
- [ ] compact preserves artifact refs
- [ ] compact removes duplicates
- [ ] compact replaces chronology with state
- [ ] compact is substantially smaller
- [ ] compact preserves capability
- [ ] compact returns 12-section structure
- [ ] compact continues until self-review passes
```
### The RAG discipline TDD protocol
@@ -972,10 +972,10 @@ This section extends the existing workflow with the patterns surfaced by the `na
```
- [ ] tests/test_rag_discipline.py: 4+ tests
- [ ] RAG disabled: no {rag-context} block
- [ ] RAG results have provenance (file path + chunk)
- [ ] RAG results do not mutate disc_entries
- [ ] RAG failure returns empty (graceful)
- [ ] RAG disabled: no {rag-context} block
- [ ] RAG results have provenance (file path + chunk)
- [ ] RAG results do not mutate disc_entries
- [ ] RAG failure returns empty (graceful)
```
See `conductor/code_styleguides/knowledge_artifacts.md`, `cache_friendly_context.md`, `rag_integration_discipline.md` for the canonical styleguides.