# SEF Namespace Consolidation: Regression Risk Analysis

## Executive Summary

There are **4 regression categories** across 3 severity levels. None require changes to
`tools/*.py` or `workflow/*.py`. All risks are containable with backward-compatible patterns.
The safest migration takes 4 weeks and produces zero breaking changes for existing users.

---

## Risk Category 1 — CRITICAL: Hardcoded Tool Names in Tool Output Strings

**Files affected:** `workflow_tools.py`, `context_tools.py`, `compliance.py`, `ai_pattern_detector.py`, `discovery_audit.py`

**What breaks:** These files emit tool names as instructional strings in their output. Claude
reads those strings and tries to call the tool by name. After renaming, those names will point
to tools that no longer exist.

**Exact locations:**

```python
# workflow_tools.py line 141
lines.append(f'  `start_parallel_validation("{story_id}")`')

# workflow_tools.py line 147
lines.append(f'  Command: `set_active_agent("{next_agent}")`')

# workflow_tools.py lines 191-192
f'  → Tester: `set_active_agent("tester")`\n'
f'  → Security Owner: `set_active_agent("security_owner")`\n'

# workflow_tools.py line 304
lines.append('  → `set_active_agent("scrum_master")`')

# workflow_tools.py lines 80, 106, 167, 257, 341, 378, 506
f"{Status.WARNING} No active story. Use init_workflow() first."

# context_tools.py line 52
"call `set_active_agent(agent_name)` or `set_active_agent(number)`"

# compliance.py line 142
"Activate an agent first: `set_active_agent(agent_name)` or `set_active_agent(number)`"

# ai_pattern_detector.py line 601
"Activate an agent first: `set_active_agent(agent_name)` or `set_active_agent(number)`"

# discovery_audit.py lines 249, 255
"Run: scan_health() to generate docs/TECH_DEBT.md"
```

**Impact:** Claude receives an instruction to call `set_active_agent("tester")`, calls it, gets
`tool not found`, and either halts or hallucinates a recovery. This is a silent runtime failure.
No error at startup. Breaks during real workflow execution.

**Mitigation:** Define a module-level constant for each renamed tool string before migration.
Update all string references to use the constant. Single change, zero hunting later.

```python
# Add to constants.py or a new tool_names.py
TOOL_AGENT_ACTIVATE = 'agent(action="activate", name="{name}")'
TOOL_WORKFLOW_INIT = 'workflow(action="init", story_id="{story_id}")'
TOOL_SCAN_HEALTH = 'scan(target="health", directory="{directory}")'
TOOL_WORKFLOW_PARALLEL = 'workflow(action="parallel_start", story_id="{story_id}")'
```

---

## Risk Category 2 — HIGH: Hardcoded Tool Names in Rules Markdown and Agent Prompts

**Files affected:**
- `rules/common/core_protocol.md` (lines 19, 29)
- `rules/operations/discovery.md` (line 37)
- `rules/operations/platform.md` (lines 39, 162, 176)
- `rules/quality/documentation_standards.md` (lines 32, 53)
- `rules/quality/defect_prevention.md` (line 13)
- `rules/development/implementation.md` (line 84)
- `prompts/start_agent.py` — `LOGGING_PROTOCOL` string (line 41)

**What breaks:** These files are injected directly into Claude's context as agent rules.
When Claude reads "`validate_compliance` flags violations" and then looks for that tool, it
won't find it. Same for `log_escalation`, `scan_health`, `scan_debt`. The model may hallucinate
the old tool names anyway, which means it calls a deprecated tool instead of the new namespaced
one, or fails silently.

**Exact string in `start_agent.py` that will break:**

```python
LOGGING_PROTOCOL = "--- LOGGING PROTOCOL ---\n
Log all state changes:
1) `log_escalation`,
2) `log_ownership_transfer`,
3) `log_debt_found`,
4) `log_replan_triggered`,
5) `log_phase_complete`.
```

After consolidation, this instructs agents to call 5 tools that no longer exist under those names.
Every logging action across all 13 agents breaks silently.

**Mitigation:** Update the markdown files and the `LOGGING_PROTOCOL` string in the same PR
that ships the new namespaced tools. Do not ship the tool changes without the rules updates.
Treat them as a single atomic commit.

Updated `LOGGING_PROTOCOL`:

```python
LOGGING_PROTOCOL = "--- LOGGING PROTOCOL ---\n
Log all state changes with log(event=...):
1) `log(event=\"escalation\", level=..., reason=..., to_agents=...)`,
2) `log(event=\"ownership\", to_owner=..., reason=...)`,
3) `log(event=\"debt\", debt_type=..., severity=..., location=...)`,
4) `log(event=\"replan\", trigger=..., impact=...)`,
5) `log(event=\"phase\", phase=..., outcome=..., next_phase=...)`.
```

---

## Risk Category 3 — MEDIUM: `**kwargs` Parameter Routing in Dispatcher Functions

**What breaks:** The consolidation plan uses dispatcher functions with `**kwargs` to route
action parameters to internal implementations. `**kwargs` discards Python's type safety.
Mypy/Pyright will not catch misrouted arguments. A typo like `action="parrallel_start"` silently
falls through to the error branch instead of raising at import time.

**Example risk:**

```python
# This passes Pyright with no errors but fails silently at runtime
workflow(action="paralel_start", story_id="STORY-001")  # typo
# Returns: "Unknown action: paralel_start"
# No traceback. No IDE warning. Just silent misdirection.
```

**Mitigation:** Use a `Literal` type for action parameters and a `TypedDict` for kwargs.
This restores Pyright coverage on the dispatcher surface.

```python
from typing import Literal

WorkflowAction = Literal[
    "init", "state", "next", "parallel_start", "parallel_complete"
]

@mcp.tool()
def workflow(
    action: WorkflowAction,
    story_id: str = "",
    agent: str = "",
    status: str = "passed",
    notification: str = "",
    completed_task: str = "",
) -> str:
    """Workflow state machine..."""
```

Explicit named parameters over `**kwargs`. More verbose but Pyright-safe. Your existing
`validate_compliance` tool will flag `**kwargs` as a type-safety violation anyway.

---

## Risk Category 4 — LOW: PyPI Users on Existing Installs

**What breaks:** Any team that has pinned `sef-agents` and hardcoded MCP tool names in their
own `AGENTS.md`, cursor rules, or scripts will have those references break on upgrade.

**Impact:** Low probability during early distribution. High impact per affected team.

**Mitigation:** Semantic versioning with a deprecation cycle.

```
v2.x  — Ship namespaced tools. Keep old flat names as deprecated aliases.
         Old names emit a deprecation warning in their return string.
         Zero breaking changes.

v3.0  — Remove deprecated aliases. Bump major version.
         Changelog explicitly lists removed names.
         Migration guide: one-line sed replacement for each tool.
```

Deprecation alias pattern in `server.py`:

```python
@mcp.tool()
def log_escalation(level: str, reason: str, to_agents: str, story_id: str = "") -> str:
    """[DEPRECATED v2.0] Use log(event='escalation', ...) instead."""
    import warnings
    return (
        "⚠️ DEPRECATED: `log_escalation` removed in v3.0. "
        "Use: log(event='escalation', level=..., reason=..., to_agents=...)\n\n"
        + handoff_tools.log_event("escalation", story_id=story_id,
                                   level=level, reason=reason, to_agents=to_agents)
    )
```

The deprecation warning in the return string is visible to Claude, which then corrects
its future calls automatically. No human intervention needed for self-healing.

---

## Safe Migration Sequence

### Week 1 — Ship Deprecation Aliases (Zero Risk)
Register namespaced tools alongside existing flat tools.
Old tools return deprecation notices but still function.
Run full test suite. No changes to `tools/*.py`.

### Week 2 — Update Rules and Prompts (Medium Risk, Contained)
Update `LOGGING_PROTOCOL` in `start_agent.py`.
Update all 8 rules markdown references.
Update `AGENTS.md` generator with new tool names.
Ship as a single atomic commit with the Week 1 changes.

### Week 3 — Fix Hardcoded Strings in Tool Outputs (Medium Risk)
Update all `workflow_tools.py`, `context_tools.py`, `compliance.py`,
`ai_pattern_detector.py`, `discovery_audit.py` output strings.
Use the `tool_names.py` constants approach.
Run integration test: activate each agent, run a full phase, verify log output.

### Week 4 — Validation
Run `scan_health` on the SEF codebase itself.
Verify `validate_compliance` passes on `server.py`.
Confirm `handoff_log.jsonl` entries use new tool names.
Tag as `v2.0.0`.

### Month 2 — Remove Aliases
Tag as `v3.0.0`. Publish migration guide.

---

## What Does NOT Regress (Safe to Proceed Immediately)

| Component | Safe Because |
|---|---|
| `tools/*.py` implementations | Not touched. Internal logic unchanged. |
| `workflow/state_machine.py` | Not touched. State schema unchanged. |
| `.sef_cache/` disk state | JSON schema unchanged. Existing states load normally. |
| `security/*.py` | Not touched. Scan logic unchanged. |
| `utils/handoff_logger.py` | Not touched. JSONL format unchanged. |
| `models/*.py` | Not touched. |
| `config/*.yaml` | Not touched. |
| Playwright browser tools | Not touched. |
| Jira/Confluence export | Not touched. |
| `handoff_log.jsonl` format | JSON schema unchanged. Existing logs stay valid. |

---

## Pre-Migration Checklist

Before writing a single line:

- [ ] Run `grep -rn "set_active_agent\|init_workflow\|validate_compliance\|scan_health\|log_escalation\|run_security_audit" sef_agents/` and save the output. This is your regression test list.
- [ ] Add `Literal` types for all action parameters before writing dispatchers.
- [ ] Create `tool_names.py` with string constants before touching any output strings.
- [ ] Confirm test coverage on `workflow_tools.py` before modifying its output strings.
- [ ] Draft the `CHANGELOG.md` entry before cutting the release.