Compare commits
1 Commits
docs/phase
...
5f775e360e
| Author | SHA1 | Date | |
|---|---|---|---|
| 5f775e360e |
@@ -13,44 +13,6 @@
|
||||
|
||||
---
|
||||
|
||||
## 2026-05-29 — Single source of truth for plan-tier taxonomy (derive admin UI + validation from `plan_limits`)
|
||||
|
||||
**Context:** A prod report ("AI sessions aren't working") traced to the owner account having no paid plan (AI is plan-gated), compounded by a real bug: the admin "Change Plan" dropdown ([`AccountDetailPage.tsx:443-445`](../frontend/src/pages/admin/AccountDetailPage.tsx)) still offered the dead `team` slug (renamed to `enterprise` in migration `4ce3e594cb87`, 2026-05-07) and omitted `starter`/`enterprise`. Selecting "Team" 400s against the hardcoded allow-list in [`admin.py:994`](../backend/app/api/endpoints/admin.py#L994). The dropdown was missed during the 2026-05-07 taxonomy reconciliation because the allowed-plan list is hand-duplicated across ≥6 backend + frontend sites. Second taxonomy-drift incident.
|
||||
|
||||
**Decision:** Option B — make `plan_limits` the single source of truth: admin dropdown + pricing/checkout derive plan options from a plans endpoint (filter `is_public`, order by `sort_order`, label from `display_name`), and backend validation checks against actual `plan_limits` rows rather than a hardcoded tuple. Implementation deferred (active work is on another branch); fully specced in [TODO.md](TODO.md). A trivial dropdown-options fix may land first to unblock the admin tool.
|
||||
|
||||
**Rejected:** Option A (patch only the `AccountDetailPage` dropdown). Fixes the symptom but leaves the duplication that has now caused two drift incidents — and there is no outage forcing a minimal diff (bug is admin-only and was already worked around via direct Pro assignment). Conflicts with the repo principle "prefer correct architecture over minimal diff."
|
||||
|
||||
**Consequences:** New plan tiers become a data change (a `plan_limits` row) instead of a multi-file code edit; UI and validation can no longer drift from the catalog. Requires a public-plans read endpoint (or extending billing state) consumed by the admin UI + pricing page. The `'team'` visibility string (`Tree.visibility` / `StepLibrary.visibility`) is a separate domain and is explicitly out of scope.
|
||||
|
||||
---
|
||||
|
||||
## 2026-05-28 — Scope Anthropic structured outputs to flat-array JSON only
|
||||
|
||||
**Context:** Optimizing the existing Claude API usage (no model change). The Anthropic path in `generate_json` (`ai_provider.py`) had no equivalent to the Gemini path's `response_mime_type="application/json"` — it prompted for JSON and relied on downstream defenses: `_strip_markdown_fences` (ai_fix), `parse_llm_json` (knowledge_flywheel), and `_try_repair_json` (kb_conversion, which balances unclosed braces on truncated output). Anthropic structured outputs (`output_config.format` with a JSON schema) guarantee valid, parseable JSON and would eliminate those band-aids. The question was which of the four `generate_json` call sites can adopt it.
|
||||
|
||||
Structured outputs has hard schema limits: **no recursive schemas**, and **every object must set `additionalProperties: false`** (so the schema must enumerate exactly the fields the model emits — a superset is impossible, an omission makes a field unproducible). Tracing the call sites against those limits:
|
||||
|
||||
- **kb_conversion** → output is `{title, description, nodes: [...]}` / `{...steps[], intake_form[]}` — **flat arrays**, references by `next_node_id`/id, no nesting. Expressible.
|
||||
- **ai_fix** → returns a fixed *node that is itself a subtree*; `_find_node_by_id` recurses `node["children"]` and the prompt requires decision nodes to have ≥2 children. **Recursive, arbitrary depth.**
|
||||
- **knowledge_flywheel flow-gen** → emits `tree_structure`, a decision-tree root with nested `children`/`options`, persisted as an opaque blob.
|
||||
- **knowledge_flywheel enhancement** → flat `new_nodes[] + modified_options[]`; expressible but low-frequency and only fence-stripped.
|
||||
|
||||
**Decision:** Apply structured outputs to **flat-array outputs only** — i.e. `kb_conversion`. Wired via an optional `schema=` param on `AIProvider.generate_json` (`None` = legacy prompt-only behavior; Anthropic maps it to `output_config.format`, Gemini ignores it), with the two KB schemas + `_schema_for_target_type()` in `kb_conversion_service.py`, gated behind `settings.AI_KB_CONVERT_STRUCTURED_OUTPUT` (default **False**) pending a live constrained-decoding smoke-test in staging. The robustness fixes that motivated the work — `_extract_text_from_response` (skip non-text blocks, log `max_tokens`/`refusal`, raise on no-text) — live in the shared provider, so **all four** callers already benefit regardless of schema adoption.
|
||||
|
||||
**Rejected:**
|
||||
- **Forcing schemas on ai_fix / flow-gen.** Their outputs are recursive/nested decision trees; a bounded-depth schema would reject valid deeper trees and break generation. Wrong architecture for marginal/zero benefit (flow-gen's tree is stored as a blob, never schema-validated downstream).
|
||||
- **Wiring the flywheel enhancement site.** Flat and technically expressible, but low call frequency and only fence-stripping today — marginal benefit against the risk of a blind (un-live-tested) `additionalProperties: false` schema.
|
||||
- **Deleting the fence-strip / repair helpers now.** `_strip_markdown_fences` / `parse_llm_json` must stay — they protect the recursive paths that can't use schemas. Only `_try_repair_json` (kb-only) becomes removable, and only *after* the flag is validated in staging.
|
||||
|
||||
**Consequences:**
|
||||
- Structured outputs is the tool for flat JSON; recursive decision-tree outputs are excluded by design. New flat-JSON `generate_json` callers can opt in via `schema=`; recursive ones should not.
|
||||
- `AI_KB_CONVERT_STRUCTURED_OUTPUT` must be smoke-tested against the live model (both target types) before production enablement. Open risk: whether Anthropic accepts optional (non-`required`) fields — if not, the schemas need every field in `required` with nullable types. The flag makes this fully reversible.
|
||||
- Deferred cleanup: once the flag is validated, remove only `_try_repair_json` from the kb_conversion Anthropic path; leave the fence-strippers.
|
||||
- Work lives on branch `feat/ai-structured-outputs` (commits `84a02a5`, `1388357`), based on `design/l1-workspace`.
|
||||
|
||||
---
|
||||
|
||||
## 2026-05-13 — Session expiration policy: 3d idle / 14d absolute defaults + per-account override
|
||||
|
||||
**Context:** User report: "I login to ResolutionFlow and never have to log back in." Investigation found refresh tokens at `REFRESH_TOKEN_EXPIRE_DAYS=7` with JTI rotation (`security.py:36`) — every `/auth/refresh` minted a fresh 7-day window. Net effect: a sliding 7-day session with no absolute cap. Visit once a week, logged in forever. Acceptable for pilot but not for MSP buyers whose SOC2 / cyber-insurance auditors require enforced session timeouts. Required for the same Phase O launch readiness as the other gates already in flight.
|
||||
|
||||
@@ -23,5 +23,3 @@ None selected. Pick from the backlog below or `03-DEVELOPMENT-ROADMAP.md`.
|
||||
- [ ] **`bg-card-hover` Tailwind class doesn't resolve.** [`frontend/src/components/layout/CommandPalette.tsx:450-451`](../frontend/src/components/layout/CommandPalette.tsx) uses `bg-card-hover` as a Tailwind utility, but Tailwind v4 generates `bg-{token}` from `--color-{token}` — and the token in [`frontend/src/index.css:15`](../frontend/src/index.css) is `--color-bg-card-hover`, which generates `bg-bg-card-hover`, not `bg-card-hover`. So those classes silently produce nothing. Other call sites (KnowledgeBaseCards, TeamSummary, ProposalBanner) use the explicit `hover:bg-[var(--color-bg-card-hover)]` form which works. Fix: change the CommandPalette classes to the explicit-var form, OR add a `--color-card-hover` semantic mapping in index.css alongside `--color-card`. Surfaced 2026-05-01 during impeccable polish sweep.
|
||||
|
||||
- [ ] **`ConcludeSessionModal` paused/escalated step forces single-artifact choice — should allow multi-select.** [`frontend/src/components/assistant/ConcludeSessionModal.tsx`](../frontend/src/components/assistant/ConcludeSessionModal.tsx) ~lines 430-474 ("Paused/Escalated: status update options"). Today the engineer clicks ONE of Ticket Notes / Client Update / Email Draft, the buttons disappear, and the result replaces them. Real MSP escalations almost always need at least two: technical notes for the next engineer's PSA AND a non-technical client update. Same for pause (client update + ticket notes for context when resuming). Recommended shape: multi-select with smart defaults — three checkboxes (`☑ Ticket Notes ☑ Client Update ☐ Email Draft`); for `escalated` pre-check Ticket Notes + Client Update; for `paused` pre-check Client Update only. One "Generate" button fires all selected in parallel via existing `aiSessionsApi.generateStatusUpdate(...)` (already supports the three `audience` values: `ticket_notes`, `client_update`, `email_draft`). Each result renders in its own card with its own Copy / Post-to-PSA / Send-Email action. Surfaced 2026-05-01. Feature work, not polish — touches streaming wiring for parallel calls.
|
||||
|
||||
- [ ] **Centralize plan-tier taxonomy — derive admin plan dropdown (and validation) from `plan_limits`, not hardcoded lists.** Chose **Option B** over a one-line patch (see [DECISIONS.md](DECISIONS.md) 2026-05-29). *Surfaced by a prod bug (2026-05-28):* the admin "Change Plan" dropdown at [`AccountDetailPage.tsx:443-445`](../frontend/src/pages/admin/AccountDetailPage.tsx) still offered `free / pro / team` — the dead `team` slug (renamed to `enterprise` in migration `4ce3e594cb87`, 2026-05-07) and missing `starter`/`enterprise`. Selecting "Team" sends `{plan:"team"}` to `PUT /admin/accounts/{id}/subscription/plan`, which 400s on `if data.plan not in ("free","pro","starter","enterprise")` ([admin.py:994](../backend/app/api/endpoints/admin.py#L994), duplicated at [:975](../backend/app/api/endpoints/admin.py#L975)). The 400 detail was swallowed by a generic `toast.error('Failed to update plan')` ([AccountDetailPage.tsx:196](../frontend/src/pages/admin/AccountDetailPage.tsx)), so it presented as "AI sessions are down" (real cause: owner account had no paid plan; AI is plan-gated). **Root cause of the root cause:** the allowed-plan list is hand-duplicated across ≥6 sites and drifted (2nd such incident). **Duplication sites to consolidate:** backend [`admin.py:975`](../backend/app/api/endpoints/admin.py#L975) + [`:994`](../backend/app/api/endpoints/admin.py#L994) (tuple, twice), [`schemas/admin.py:128`](../backend/app/schemas/admin.py) (`AdminAccountCreate.plan` Literal), frontend `AccountDetailPage.tsx` dropdown, `AccountsPage.tsx` create-account dropdown, `types/admin.ts` + `types/account.ts` + `types/billing.ts`, `hooks/useSubscription.ts` (`isPaidPlan`), `components/subscription/CheckoutButton.tsx` (`planLabels`). **Source of truth:** the `plan_limits` table (rows: free/starter/pro/enterprise) — `PlanLimitWithBillingResponse` already exposes `is_public` + `sort_order` + `display_name` for ordering/labels. **End state (B):** admin dropdown + pricing/checkout derive options from a plans endpoint backed by `plan_limits` (filter `is_public`, order by `sort_order`, label from `display_name`); backend validation checks against actual `plan_limits` rows instead of a hardcoded tuple. **Trivial first commit (land anytime to unblock the admin tool):** fix the `AccountDetailPage` dropdown to `Free / Starter / Pro / Enterprise` and surface the backend error detail in the toast. ⚠️ The `'team'` string in `Tree.visibility` / `StepLibrary.visibility` is a *separate domain* (shared-with-account) — do NOT touch it.
|
||||
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -237,10 +237,6 @@ package.json
|
||||
package-lock.json
|
||||
.worktrees/
|
||||
.gstack/
|
||||
|
||||
# Core dumps from crashed processes (e.g. core.12345)
|
||||
core.[0-9]*
|
||||
**/core.[0-9]*
|
||||
.gitnexus
|
||||
|
||||
# graphify knowledge graph outputs
|
||||
|
||||
@@ -48,15 +48,6 @@ def _to_response(session: L1WalkSession) -> WalkSessionResponse:
|
||||
async def _get_session_or_404(
|
||||
db: AsyncSession, session_id: UUID, user: User
|
||||
) -> L1WalkSession:
|
||||
"""Fetch a session by id, scoped to the caller's account.
|
||||
|
||||
Phase 1 policy (per spec §7.9): sessions are account-scoped, not
|
||||
user-scoped. Any L1 or coverage engineer in the same account can
|
||||
step/note/resolve/escalate any session — supports team coverage
|
||||
(e.g., L1 hands off mid-shift; coverage engineer takes over a call).
|
||||
For a stricter "creator-only" policy, add
|
||||
``created_by_user_id == user.id`` here.
|
||||
"""
|
||||
session = await db.get(L1WalkSession, session_id)
|
||||
if session is None or session.account_id != user.account_id:
|
||||
raise HTTPException(
|
||||
|
||||
@@ -186,6 +186,4 @@ api_router.include_router(beta_feedback.router, dependencies=_tenant_deps)
|
||||
api_router.include_router(session_branches.router, dependencies=_pro_deps)
|
||||
api_router.include_router(session_handoffs.router, dependencies=_pro_deps)
|
||||
api_router.include_router(device_types.router, dependencies=_tenant_deps)
|
||||
# L1 is a separate seat-counted SKU; subscription gating is enforced by
|
||||
# seat_enforcement (engineer + l1_seat_limit), not require_active_subscription.
|
||||
api_router.include_router(l1.router, dependencies=_tenant_deps)
|
||||
|
||||
@@ -147,40 +147,6 @@ def build_anthropic_chat_messages(
|
||||
return messages
|
||||
|
||||
|
||||
def _extract_text_from_response(response: Any, model: str) -> str:
|
||||
"""Return the first text block's text from an Anthropic message response.
|
||||
|
||||
Robustness over the naive ``response.content[0].text``:
|
||||
- Skips non-text leading blocks (e.g. ``thinking``) and returns the first
|
||||
block whose ``type == "text"``. Indexing ``content[0]`` blindly throws or
|
||||
returns garbage the moment a non-text block leads the response.
|
||||
- Surfaces truncation/refusal: when ``stop_reason`` is ``max_tokens`` or
|
||||
``refusal``, emits a structured warning so silent output corruption
|
||||
(truncated JSON, empty refusals) is observable rather than handed
|
||||
downstream to be guessed at.
|
||||
- Raises ``ValueError`` when no text block is present (e.g. a bare refusal)
|
||||
instead of returning a non-text block's attributes.
|
||||
"""
|
||||
stop_reason = getattr(response, "stop_reason", None)
|
||||
if stop_reason in ("max_tokens", "refusal"):
|
||||
logger.warning(
|
||||
"anthropic.stop_reason",
|
||||
extra={
|
||||
"event": "anthropic.stop_reason",
|
||||
"model": model,
|
||||
"stop_reason": stop_reason,
|
||||
},
|
||||
)
|
||||
|
||||
for block in response.content:
|
||||
if getattr(block, "type", None) == "text":
|
||||
return block.text
|
||||
|
||||
raise ValueError(
|
||||
f"Anthropic response contained no text block (stop_reason={stop_reason!r})"
|
||||
)
|
||||
|
||||
|
||||
def _log_anthropic_cache_usage(usage: Any, model: str) -> None:
|
||||
"""Emit a structured log line capturing cache_read / cache_creation tokens."""
|
||||
cache_read = getattr(usage, "cache_read_input_tokens", 0) or 0
|
||||
@@ -210,7 +176,6 @@ class AIProvider(ABC):
|
||||
system_prompt: str | list[SystemBlock],
|
||||
messages: list[dict[str, Any]],
|
||||
max_tokens: int = 4096,
|
||||
schema: dict[str, Any] | None = None,
|
||||
) -> tuple[str, int, int]:
|
||||
"""Generate a JSON response from the AI model.
|
||||
|
||||
@@ -220,15 +185,6 @@ class AIProvider(ABC):
|
||||
Anthropic prompt caching per module-docstring policy.
|
||||
messages: List of message dicts with "role" and "content" keys.
|
||||
max_tokens: Maximum output tokens.
|
||||
schema: Optional JSON Schema constraining the response shape.
|
||||
When provided, the Anthropic backend uses structured outputs
|
||||
(`output_config.format`) to guarantee valid, parseable JSON —
|
||||
no markdown fences, no truncated-brace repair. Must satisfy the
|
||||
structured-output schema limits (every object needs
|
||||
`additionalProperties: false`; no recursion; numeric/string
|
||||
constraints are stripped). `None` preserves the legacy
|
||||
prompt-only behavior. The Gemini backend currently ignores this
|
||||
argument (it already requests `application/json`).
|
||||
|
||||
Returns:
|
||||
Tuple of (response_text, input_tokens, output_tokens).
|
||||
@@ -275,11 +231,7 @@ class GeminiProvider(AIProvider):
|
||||
system_prompt: str | list[SystemBlock],
|
||||
messages: list[dict[str, Any]],
|
||||
max_tokens: int = 4096,
|
||||
schema: dict[str, Any] | None = None,
|
||||
) -> tuple[str, int, int]:
|
||||
# `schema` is accepted for interface parity but ignored: Gemini already
|
||||
# constrains output via response_mime_type="application/json" below.
|
||||
# Mapping JSON Schema -> Gemini response_schema is deferred.
|
||||
from google import genai
|
||||
from google.genai import types as genai_types
|
||||
|
||||
@@ -410,28 +362,18 @@ class AnthropicProvider(AIProvider):
|
||||
system_prompt: str | list[SystemBlock],
|
||||
messages: list[dict[str, Any]],
|
||||
max_tokens: int = 4096,
|
||||
schema: dict[str, Any] | None = None,
|
||||
) -> tuple[str, int, int]:
|
||||
client = _get_anthropic_client(self._api_key, self._timeout)
|
||||
normalized_system = _normalize_system_for_anthropic(system_prompt)
|
||||
|
||||
create_kwargs: dict[str, Any] = {
|
||||
"model": self._model,
|
||||
"max_tokens": max_tokens,
|
||||
"system": normalized_system,
|
||||
"messages": messages,
|
||||
}
|
||||
if schema is not None:
|
||||
# Structured outputs: constrain the response to valid JSON matching
|
||||
# the schema (Sonnet 4.6 / Haiku 4.5). Removes the need for
|
||||
# markdown-fence stripping and truncated-JSON repair downstream.
|
||||
create_kwargs["output_config"] = {
|
||||
"format": {"type": "json_schema", "schema": schema}
|
||||
}
|
||||
response = await client.messages.create(
|
||||
model=self._model,
|
||||
max_tokens=max_tokens,
|
||||
system=normalized_system,
|
||||
messages=messages,
|
||||
)
|
||||
|
||||
response = await client.messages.create(**create_kwargs)
|
||||
|
||||
text = _extract_text_from_response(response, self._model)
|
||||
text = response.content[0].text
|
||||
input_tokens = response.usage.input_tokens
|
||||
output_tokens = response.usage.output_tokens
|
||||
|
||||
|
||||
@@ -13,20 +13,13 @@ async def log_audit(
|
||||
resource_id: Optional[UUID] = None,
|
||||
details: Optional[dict] = None,
|
||||
account_id: Optional[UUID] = None,
|
||||
acting_as: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Record an audit log entry. Does not commit — caller's commit picks it up.
|
||||
|
||||
acting_as: optional tag from the session (e.g. 'l1_coverage' for engineers
|
||||
on the L1 surface, None for native l1_tech users).
|
||||
"""
|
||||
"""Record an audit log entry. Does not commit — piggybacks on the caller's commit."""
|
||||
if account_id is None:
|
||||
# Derive from the acting user's account as a fallback (one extra query).
|
||||
from sqlalchemy import select
|
||||
from app.models.user import User
|
||||
result = await db.execute(
|
||||
select(User.account_id).where(User.id == user_id)
|
||||
)
|
||||
result = await db.execute(select(User.account_id).where(User.id == user_id))
|
||||
account_id = result.scalar_one()
|
||||
|
||||
entry = AuditLog(
|
||||
@@ -36,6 +29,5 @@ async def log_audit(
|
||||
resource_type=resource_type,
|
||||
resource_id=resource_id,
|
||||
details=details,
|
||||
acting_as=acting_as,
|
||||
)
|
||||
db.add(entry)
|
||||
|
||||
@@ -155,12 +155,6 @@ class Settings(BaseSettings):
|
||||
AI_CONVERSATION_TTL_HOURS: int = 24
|
||||
AI_MAX_CALLS_PER_FLOW: int = 10
|
||||
AI_REQUEST_TIMEOUT_SECONDS: int = 120
|
||||
# When True, KB conversion constrains the Anthropic response with a JSON
|
||||
# schema (structured outputs) instead of relying on prompt-only JSON +
|
||||
# downstream fence-stripping / brace-repair. Default OFF: enable in staging
|
||||
# and smoke-test constrained decoding against the live model before turning
|
||||
# it on in production. Only affects the Anthropic backend.
|
||||
AI_KB_CONVERT_STRUCTURED_OUTPUT: bool = False
|
||||
# AI Provider selection
|
||||
AI_PROVIDER: str = "anthropic" # "gemini" or "anthropic"
|
||||
GOOGLE_AI_API_KEY: Optional[str] = None
|
||||
|
||||
@@ -202,115 +202,6 @@ the engineer attached, NOT from this schema):
|
||||
9. Return ONLY valid JSON — no markdown fences, no explanation text."""
|
||||
|
||||
|
||||
# ── Structured-output schemas ──
|
||||
#
|
||||
# These constrain the model's JSON via Anthropic structured outputs
|
||||
# (output_config.format) so the response is guaranteed valid and parseable —
|
||||
# no markdown fences, no truncated-brace repair. They must be a SUPERSET of
|
||||
# every field the corresponding system prompt instructs the model to emit:
|
||||
# additionalProperties is False everywhere, so any field the prompt asks for
|
||||
# but the schema omits would be impossible to produce.
|
||||
#
|
||||
# `type`/`field_type` are intentionally left as plain strings (no enum): the
|
||||
# downstream parser already normalizes/tolerates the type values, and an enum
|
||||
# risks constraining the model away from a value the prompt would yield.
|
||||
|
||||
_TROUBLESHOOTING_OPTION_SCHEMA: dict[str, Any] = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"label": {"type": "string"},
|
||||
"next_node_id": {"type": "string"},
|
||||
},
|
||||
"required": ["label", "next_node_id"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
_TROUBLESHOOTING_NODE_SCHEMA: dict[str, Any] = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {"type": "string"},
|
||||
"type": {"type": "string"},
|
||||
"question": {"type": "string"},
|
||||
"options": {"type": "array", "items": _TROUBLESHOOTING_OPTION_SCHEMA},
|
||||
"next_node_id": {"type": "string"},
|
||||
"confidence": {"type": "number"},
|
||||
"source_excerpt": {"type": "string"},
|
||||
},
|
||||
# Only the universal fields are required. `question`/`options`/`next_node_id`
|
||||
# vary by node type and stay optional so a resolution node need not carry
|
||||
# options and an action node need not carry a question.
|
||||
"required": ["id", "type", "confidence", "source_excerpt"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
TROUBLESHOOTING_SCHEMA: dict[str, Any] = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"title": {"type": "string"},
|
||||
"description": {"type": "string"},
|
||||
"nodes": {"type": "array", "items": _TROUBLESHOOTING_NODE_SCHEMA},
|
||||
},
|
||||
"required": ["title", "description", "nodes"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
_PROCEDURAL_STEP_SCHEMA: dict[str, Any] = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {"type": "string"},
|
||||
"type": {"type": "string"},
|
||||
"content": {"type": "string"},
|
||||
"confidence": {"type": "number"},
|
||||
"source_excerpt": {"type": "string"},
|
||||
},
|
||||
"required": ["id", "type", "content", "confidence", "source_excerpt"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
_PROCEDURAL_INTAKE_SCHEMA: dict[str, Any] = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"variable_name": {"type": "string"},
|
||||
"label": {"type": "string"},
|
||||
"field_type": {"type": "string"},
|
||||
"required": {"type": "boolean"},
|
||||
"display_order": {"type": "integer"},
|
||||
},
|
||||
"required": [
|
||||
"variable_name",
|
||||
"label",
|
||||
"field_type",
|
||||
"required",
|
||||
"display_order",
|
||||
],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
PROCEDURAL_SCHEMA: dict[str, Any] = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"title": {"type": "string"},
|
||||
"description": {"type": "string"},
|
||||
"steps": {"type": "array", "items": _PROCEDURAL_STEP_SCHEMA},
|
||||
"intake_form": {"type": "array", "items": _PROCEDURAL_INTAKE_SCHEMA},
|
||||
},
|
||||
"required": ["title", "description", "steps", "intake_form"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
|
||||
def _schema_for_target_type(target_type: str) -> dict[str, Any]:
|
||||
"""Return the structured-output schema for a KB conversion target type.
|
||||
|
||||
Mirrors the prompt selection in ``convert_document``: only
|
||||
``"troubleshooting"`` uses the decision-tree schema; everything else is
|
||||
treated as a procedural flow.
|
||||
"""
|
||||
if target_type == "troubleshooting":
|
||||
return TROUBLESHOOTING_SCHEMA
|
||||
return PROCEDURAL_SCHEMA
|
||||
|
||||
|
||||
def _build_user_message(
|
||||
source_text: str,
|
||||
source_metadata: dict[str, Any] | None,
|
||||
@@ -513,16 +404,6 @@ async def convert_document(
|
||||
model = settings.get_model_for_action("kb_convert")
|
||||
provider = get_ai_provider(model=model)
|
||||
|
||||
# Structured outputs (flagged): constrain the response to a JSON schema so
|
||||
# the model can't emit fences or truncated JSON. Falls back to prompt-only
|
||||
# JSON (schema=None) when disabled; the parse path below stays intact either
|
||||
# way as a belt-and-suspenders fallback.
|
||||
schema = (
|
||||
_schema_for_target_type(kb_import.target_type)
|
||||
if settings.AI_KB_CONVERT_STRUCTURED_OUTPUT
|
||||
else None
|
||||
)
|
||||
|
||||
try:
|
||||
raw_text, input_tokens, output_tokens = await provider.generate_json(
|
||||
system_prompt=[
|
||||
@@ -533,7 +414,6 @@ async def convert_document(
|
||||
],
|
||||
messages=[{"role": "user", "content": user_message}],
|
||||
max_tokens=16384,
|
||||
schema=schema,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error("AI conversion failed for kb_import=%s: %s", kb_import.id, e)
|
||||
|
||||
@@ -9,7 +9,6 @@ from uuid import UUID
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.audit import log_audit
|
||||
from app.models.flow_proposal import FlowProposal
|
||||
from app.models.l1_walk_session import L1WalkSession
|
||||
from app.models.user import User
|
||||
@@ -195,21 +194,6 @@ async def resolve(
|
||||
)
|
||||
# PSA close deferred to Phase 2 — no-op for now
|
||||
|
||||
await log_audit(
|
||||
db,
|
||||
user_id=session.created_by_user_id,
|
||||
action="l1.session.resolve",
|
||||
resource_type="l1_walk_session",
|
||||
resource_id=session.id,
|
||||
details={
|
||||
"session_kind": session.session_kind,
|
||||
"helpful": helpful,
|
||||
"ticket_id": session.ticket_id,
|
||||
"ticket_kind": session.ticket_kind,
|
||||
},
|
||||
account_id=session.account_id,
|
||||
acting_as=session.acting_as,
|
||||
)
|
||||
await db.flush()
|
||||
return session
|
||||
|
||||
@@ -247,21 +231,6 @@ async def escalate(
|
||||
)
|
||||
# PSA reassign deferred to Phase 2
|
||||
|
||||
await log_audit(
|
||||
db,
|
||||
user_id=session.created_by_user_id,
|
||||
action="l1.session.escalate",
|
||||
resource_type="l1_walk_session",
|
||||
resource_id=session.id,
|
||||
details={
|
||||
"session_kind": session.session_kind,
|
||||
"escalation_reason_category": reason_category,
|
||||
"ticket_id": session.ticket_id,
|
||||
"ticket_kind": session.ticket_kind,
|
||||
},
|
||||
account_id=session.account_id,
|
||||
acting_as=session.acting_as,
|
||||
)
|
||||
await db.flush()
|
||||
return session
|
||||
|
||||
@@ -303,19 +272,5 @@ async def escalate_without_walk(
|
||||
ticket_id=UUID(ticket_id),
|
||||
status="escalated",
|
||||
)
|
||||
await db.flush() # flush first so session.id is populated
|
||||
await log_audit(
|
||||
db,
|
||||
user_id=session.created_by_user_id,
|
||||
action="l1.session.escalate_no_walk",
|
||||
resource_type="l1_walk_session",
|
||||
resource_id=session.id,
|
||||
details={
|
||||
"escalation_reason_category": reason_category,
|
||||
"ticket_id": ticket_id,
|
||||
"ticket_kind": ticket_kind,
|
||||
},
|
||||
account_id=session.account_id,
|
||||
acting_as=session.acting_as,
|
||||
)
|
||||
await db.flush()
|
||||
return session
|
||||
|
||||
@@ -96,8 +96,7 @@ class TestAnthropicProvider:
|
||||
)
|
||||
|
||||
mock_response = MagicMock()
|
||||
mock_response.content = [MagicMock(type="text", text='{"result": "ok"}')]
|
||||
mock_response.stop_reason = "end_turn"
|
||||
mock_response.content = [MagicMock(text='{"result": "ok"}')]
|
||||
mock_response.usage = MagicMock(input_tokens=100, output_tokens=50)
|
||||
|
||||
mock_client = AsyncMock()
|
||||
@@ -121,170 +120,6 @@ class TestAnthropicProvider:
|
||||
messages=[{"role": "user", "content": "Hello"}],
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_generate_json_skips_non_text_blocks(self):
|
||||
"""A leading non-text block (e.g. thinking) is skipped; the first
|
||||
text block's text is returned instead of content[0].text."""
|
||||
from app.core import ai_provider
|
||||
|
||||
ai_provider._anthropic_clients.clear()
|
||||
|
||||
provider = AnthropicProvider(
|
||||
api_key="skip-key", model="claude-sonnet-4-6", timeout=31
|
||||
)
|
||||
|
||||
thinking_block = MagicMock(type="thinking", thinking="hmm...")
|
||||
text_block = MagicMock(type="text", text='{"ok": 1}')
|
||||
mock_response = MagicMock()
|
||||
mock_response.content = [thinking_block, text_block]
|
||||
mock_response.stop_reason = "end_turn"
|
||||
mock_response.usage = MagicMock(input_tokens=10, output_tokens=5)
|
||||
|
||||
mock_client = AsyncMock()
|
||||
mock_client.messages.create = AsyncMock(return_value=mock_response)
|
||||
|
||||
with patch("anthropic.AsyncAnthropic", return_value=mock_client):
|
||||
text, _, _ = await provider.generate_json(
|
||||
system_prompt="You are a helper.",
|
||||
messages=[{"role": "user", "content": "Hi"}],
|
||||
)
|
||||
|
||||
assert text == '{"ok": 1}'
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_generate_json_raises_when_no_text_block(self):
|
||||
"""A response with no text block (e.g. a bare refusal) raises a clear
|
||||
error instead of returning a non-text block's attributes."""
|
||||
from app.core import ai_provider
|
||||
|
||||
ai_provider._anthropic_clients.clear()
|
||||
|
||||
provider = AnthropicProvider(
|
||||
api_key="empty-key", model="claude-sonnet-4-6", timeout=32
|
||||
)
|
||||
|
||||
mock_response = MagicMock()
|
||||
mock_response.content = [MagicMock(type="thinking", thinking="...")]
|
||||
mock_response.stop_reason = "refusal"
|
||||
mock_response.usage = MagicMock(input_tokens=10, output_tokens=0)
|
||||
|
||||
mock_client = AsyncMock()
|
||||
mock_client.messages.create = AsyncMock(return_value=mock_response)
|
||||
|
||||
with patch("anthropic.AsyncAnthropic", return_value=mock_client):
|
||||
with pytest.raises(ValueError, match="no text block"):
|
||||
await provider.generate_json(
|
||||
system_prompt="You are a helper.",
|
||||
messages=[{"role": "user", "content": "Hi"}],
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_generate_json_logs_warning_on_truncation(self, caplog):
|
||||
"""When stop_reason is max_tokens, a warning is logged (truncation
|
||||
signal) and the partial text is still returned."""
|
||||
import logging
|
||||
|
||||
from app.core import ai_provider
|
||||
|
||||
ai_provider._anthropic_clients.clear()
|
||||
|
||||
provider = AnthropicProvider(
|
||||
api_key="trunc-key", model="claude-sonnet-4-6", timeout=33
|
||||
)
|
||||
|
||||
text_block = MagicMock(type="text", text='{"partial": tr')
|
||||
mock_response = MagicMock()
|
||||
mock_response.content = [text_block]
|
||||
mock_response.stop_reason = "max_tokens"
|
||||
mock_response.usage = MagicMock(input_tokens=10, output_tokens=4096)
|
||||
|
||||
mock_client = AsyncMock()
|
||||
mock_client.messages.create = AsyncMock(return_value=mock_response)
|
||||
|
||||
with patch("anthropic.AsyncAnthropic", return_value=mock_client):
|
||||
with caplog.at_level(logging.WARNING, logger="app.core.ai_provider"):
|
||||
text, _, _ = await provider.generate_json(
|
||||
system_prompt="You are a helper.",
|
||||
messages=[{"role": "user", "content": "Hi"}],
|
||||
)
|
||||
|
||||
assert text == '{"partial": tr'
|
||||
truncation_records = [
|
||||
r for r in caplog.records if getattr(r, "stop_reason", None) == "max_tokens"
|
||||
]
|
||||
assert truncation_records, "expected a warning record for max_tokens truncation"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_generate_json_passes_output_config_when_schema_given(self):
|
||||
"""When a JSON schema is supplied, it is forwarded as
|
||||
output_config.format so the API constrains the response shape."""
|
||||
from app.core import ai_provider
|
||||
|
||||
ai_provider._anthropic_clients.clear()
|
||||
|
||||
provider = AnthropicProvider(
|
||||
api_key="schema-key", model="claude-sonnet-4-6", timeout=34
|
||||
)
|
||||
|
||||
mock_response = MagicMock()
|
||||
mock_response.content = [MagicMock(type="text", text='{"title": "x"}')]
|
||||
mock_response.stop_reason = "end_turn"
|
||||
mock_response.usage = MagicMock(input_tokens=10, output_tokens=5)
|
||||
|
||||
mock_client = AsyncMock()
|
||||
mock_client.messages.create = AsyncMock(return_value=mock_response)
|
||||
|
||||
schema = {
|
||||
"type": "object",
|
||||
"properties": {"title": {"type": "string"}},
|
||||
"required": ["title"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
with patch("anthropic.AsyncAnthropic", return_value=mock_client):
|
||||
await provider.generate_json(
|
||||
system_prompt="You are a helper.",
|
||||
messages=[{"role": "user", "content": "Hi"}],
|
||||
max_tokens=512,
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
mock_client.messages.create.assert_called_once_with(
|
||||
model="claude-sonnet-4-6",
|
||||
max_tokens=512,
|
||||
system="You are a helper.",
|
||||
messages=[{"role": "user", "content": "Hi"}],
|
||||
output_config={"format": {"type": "json_schema", "schema": schema}},
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_generate_json_no_output_config_when_schema_none(self):
|
||||
"""With no schema, output_config is not sent (backward compatible)."""
|
||||
from app.core import ai_provider
|
||||
|
||||
ai_provider._anthropic_clients.clear()
|
||||
|
||||
provider = AnthropicProvider(
|
||||
api_key="noschema-key", model="claude-sonnet-4-6", timeout=35
|
||||
)
|
||||
|
||||
mock_response = MagicMock()
|
||||
mock_response.content = [MagicMock(type="text", text="{}")]
|
||||
mock_response.stop_reason = "end_turn"
|
||||
mock_response.usage = MagicMock(input_tokens=1, output_tokens=1)
|
||||
|
||||
mock_client = AsyncMock()
|
||||
mock_client.messages.create = AsyncMock(return_value=mock_response)
|
||||
|
||||
with patch("anthropic.AsyncAnthropic", return_value=mock_client):
|
||||
await provider.generate_json(
|
||||
system_prompt="You are a helper.",
|
||||
messages=[{"role": "user", "content": "Hi"}],
|
||||
)
|
||||
|
||||
_, call_kwargs = mock_client.messages.create.call_args
|
||||
assert "output_config" not in call_kwargs
|
||||
|
||||
|
||||
class TestGeminiProvider:
|
||||
"""Tests for GeminiProvider.generate_json."""
|
||||
@@ -339,48 +174,6 @@ class TestGeminiProvider:
|
||||
|
||||
mock_client.aio.models.generate_content.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_generate_json_accepts_and_ignores_schema(self):
|
||||
"""Gemini accepts the schema kwarg (interface parity) and still
|
||||
returns JSON; it does not error on the param."""
|
||||
provider = GeminiProvider(api_key="test-key", model="gemini-2.5-flash")
|
||||
|
||||
mock_usage = MagicMock()
|
||||
mock_usage.prompt_token_count = 5
|
||||
mock_usage.candidates_token_count = 3
|
||||
|
||||
mock_response = MagicMock()
|
||||
mock_response.text = '{"answer": 1}'
|
||||
mock_response.usage_metadata = mock_usage
|
||||
|
||||
mock_client = MagicMock()
|
||||
mock_client.aio.models.generate_content = AsyncMock(return_value=mock_response)
|
||||
|
||||
mock_genai_module = MagicMock()
|
||||
mock_genai_module.Client.return_value = mock_client
|
||||
|
||||
mock_types = MagicMock()
|
||||
mock_types.Content.side_effect = lambda **kw: kw
|
||||
mock_types.Part.side_effect = lambda **kw: kw
|
||||
mock_types.GenerateContentConfig.side_effect = lambda **kw: kw
|
||||
|
||||
mock_google = MagicMock()
|
||||
mock_google.genai = mock_genai_module
|
||||
mock_genai_module.types = mock_types
|
||||
|
||||
with patch.dict(sys.modules, {
|
||||
"google": mock_google,
|
||||
"google.genai": mock_genai_module,
|
||||
"google.genai.types": mock_types,
|
||||
}):
|
||||
text, _, _ = await provider.generate_json(
|
||||
system_prompt="Generate JSON.",
|
||||
messages=[{"role": "user", "content": "data"}],
|
||||
schema={"type": "object"},
|
||||
)
|
||||
|
||||
assert text == '{"answer": 1}'
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_generate_json_handles_none_usage(self):
|
||||
"""Token counts default to 0 when usage_metadata attributes are None."""
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
"""Tests for the structured-output JSON schemas used by KB conversion.
|
||||
|
||||
These validate that the schemas are well-formed against the Anthropic
|
||||
structured-output limits (every object carries additionalProperties: false,
|
||||
`required` is a subset of declared properties, no numeric/length constraints)
|
||||
and that the target_type -> schema selector returns the right shape. They do
|
||||
NOT exercise the live API — constrained decoding must be smoke-tested against
|
||||
a real model before AI_KB_CONVERT_STRUCTURED_OUTPUT is enabled in production.
|
||||
"""
|
||||
|
||||
from app.core.kb_conversion_service import (
|
||||
PROCEDURAL_SCHEMA,
|
||||
TROUBLESHOOTING_SCHEMA,
|
||||
_schema_for_target_type,
|
||||
)
|
||||
|
||||
# Constraints disallowed by Anthropic structured outputs (must be absent so the
|
||||
# API does not reject the schema or silently strip them).
|
||||
_DISALLOWED_KEYS = {
|
||||
"minimum",
|
||||
"maximum",
|
||||
"multipleOf",
|
||||
"minLength",
|
||||
"maxLength",
|
||||
"minItems",
|
||||
"maxItems",
|
||||
}
|
||||
|
||||
|
||||
def _assert_well_formed(schema: dict) -> None:
|
||||
"""Recursively assert a JSON schema obeys the structured-output limits."""
|
||||
if schema.get("type") == "object":
|
||||
assert schema.get("additionalProperties") is False, (
|
||||
f"object schema missing additionalProperties: false: {schema}"
|
||||
)
|
||||
props = schema.get("properties", {})
|
||||
required = set(schema.get("required", []))
|
||||
assert required <= set(props), (
|
||||
f"required keys not all declared as properties: {required - set(props)}"
|
||||
)
|
||||
for sub in props.values():
|
||||
_assert_well_formed(sub)
|
||||
elif schema.get("type") == "array":
|
||||
_assert_well_formed(schema["items"])
|
||||
|
||||
assert not (_DISALLOWED_KEYS & set(schema)), (
|
||||
f"schema uses unsupported constraint(s): {_DISALLOWED_KEYS & set(schema)}"
|
||||
)
|
||||
|
||||
|
||||
class TestStructuredOutputSchemas:
|
||||
def test_troubleshooting_schema_is_well_formed(self):
|
||||
_assert_well_formed(TROUBLESHOOTING_SCHEMA)
|
||||
|
||||
def test_procedural_schema_is_well_formed(self):
|
||||
_assert_well_formed(PROCEDURAL_SCHEMA)
|
||||
|
||||
def test_troubleshooting_schema_top_level_shape(self):
|
||||
props = TROUBLESHOOTING_SCHEMA["properties"]
|
||||
assert set(props) >= {"title", "description", "nodes"}
|
||||
node = props["nodes"]["items"]
|
||||
# Every field the troubleshooting prompt may emit must be modelled,
|
||||
# else additionalProperties: false makes them impossible to produce.
|
||||
assert set(node["properties"]) >= {
|
||||
"id",
|
||||
"type",
|
||||
"question",
|
||||
"options",
|
||||
"next_node_id",
|
||||
"confidence",
|
||||
"source_excerpt",
|
||||
}
|
||||
|
||||
def test_procedural_schema_top_level_shape(self):
|
||||
props = PROCEDURAL_SCHEMA["properties"]
|
||||
assert set(props) >= {"title", "description", "steps", "intake_form"}
|
||||
step = props["steps"]["items"]
|
||||
assert set(step["properties"]) >= {
|
||||
"id",
|
||||
"type",
|
||||
"content",
|
||||
"confidence",
|
||||
"source_excerpt",
|
||||
}
|
||||
intake = props["intake_form"]["items"]
|
||||
assert set(intake["properties"]) >= {
|
||||
"variable_name",
|
||||
"label",
|
||||
"field_type",
|
||||
"required",
|
||||
"display_order",
|
||||
}
|
||||
|
||||
|
||||
class TestSchemaSelector:
|
||||
def test_returns_troubleshooting_schema(self):
|
||||
assert _schema_for_target_type("troubleshooting") is TROUBLESHOOTING_SCHEMA
|
||||
|
||||
def test_returns_procedural_schema_for_procedural(self):
|
||||
assert _schema_for_target_type("procedural") is PROCEDURAL_SCHEMA
|
||||
|
||||
def test_defaults_to_procedural_for_unknown(self):
|
||||
# convert_document treats any non-"troubleshooting" target as procedural.
|
||||
assert _schema_for_target_type("something-else") is PROCEDURAL_SCHEMA
|
||||
@@ -89,19 +89,7 @@ def _ensure_rls_schema():
|
||||
RLS setup. Running 'alembic upgrade head' against the test DB ensures
|
||||
the FORCE ROW LEVEL SECURITY + tenant_isolation policies created in the
|
||||
L1 migrations (T5/T6) are active.
|
||||
|
||||
We drop and recreate the public schema first so that any tables left behind
|
||||
by a prior create_all-based test_db run don't conflict with alembic's
|
||||
migration tracking (alembic would see existing tables without alembic_version
|
||||
and fail with DuplicateTable errors).
|
||||
"""
|
||||
# Drop and recreate the schema to ensure a clean slate for alembic.
|
||||
with psycopg2.connect(**_admin_dsn()) as conn:
|
||||
conn.autocommit = True
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("DROP SCHEMA public CASCADE")
|
||||
cur.execute("CREATE SCHEMA public")
|
||||
|
||||
backend_dir = Path(__file__).parent.parent
|
||||
env = os.environ.copy()
|
||||
env["DATABASE_URL"] = _DATABASE_TEST_URL
|
||||
@@ -148,22 +136,19 @@ def l1_rls_seed(_ensure_rls_schema):
|
||||
user_b_tmp = str(uuid.uuid4())
|
||||
cur.execute(
|
||||
"INSERT INTO users"
|
||||
" (id, email, password_hash, name, role,"
|
||||
" is_super_admin, is_team_admin, is_service_account, must_change_password,"
|
||||
" is_active, account_id, account_role, timezone, created_at)"
|
||||
" (id, email, password_hash, name, role, is_active,"
|
||||
" account_id, account_role, created_at)"
|
||||
" VALUES"
|
||||
" (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW()),"
|
||||
" (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW())"
|
||||
" (%s, %s, %s, %s, %s, %s, %s, %s, NOW()),"
|
||||
" (%s, %s, %s, %s, %s, %s, %s, %s, NOW())"
|
||||
" ON CONFLICT (email) DO NOTHING",
|
||||
(
|
||||
user_a_tmp, "l1-rls-a@example.com", "placeholder",
|
||||
"L1 RLS User A", "engineer",
|
||||
False, False, False, False,
|
||||
True, ACCOUNT_A_ID, "engineer", "UTC",
|
||||
"L1 RLS User A", "engineer", True,
|
||||
ACCOUNT_A_ID, "engineer",
|
||||
user_b_tmp, "l1-rls-b@example.com", "placeholder",
|
||||
"L1 RLS User B", "engineer",
|
||||
False, False, False, False,
|
||||
True, ACCOUNT_B_ID, "engineer", "UTC",
|
||||
"L1 RLS User B", "engineer", True,
|
||||
ACCOUNT_B_ID, "engineer",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -3,10 +3,7 @@ import uuid
|
||||
import pytest
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.models.account import Account
|
||||
from app.models.audit_log import AuditLog
|
||||
from app.models.user import User
|
||||
from app.models.tree import Tree
|
||||
from app.models.ai_session import AISession
|
||||
@@ -776,142 +773,3 @@ async def test_escalate_without_walk_reason_is_optional(test_db: AsyncSession):
|
||||
)
|
||||
assert session.escalation_reason is None
|
||||
assert session.escalation_reason_category == "no_kb_content"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# T14 audit log tests (spec §5.6.1)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resolve_writes_audit_log_with_acting_as(test_db: AsyncSession):
|
||||
"""resolve() writes an audit_logs row with acting_as='l1_coverage' for engineers."""
|
||||
account = await _make_account(test_db)
|
||||
eng = await _make_user(
|
||||
test_db,
|
||||
account_id=account.id,
|
||||
account_role="engineer",
|
||||
can_cover_l1=True,
|
||||
)
|
||||
ticket = await _make_internal_ticket(
|
||||
test_db, account_id=account.id, user_id=eng.id
|
||||
)
|
||||
session = await start_adhoc_session(
|
||||
test_db,
|
||||
account_id=account.id,
|
||||
user=eng,
|
||||
ticket_id=str(ticket.id),
|
||||
ticket_kind="internal",
|
||||
)
|
||||
await resolve(
|
||||
test_db,
|
||||
session_id=session.id,
|
||||
helpful=True,
|
||||
resolution_notes="Coverage engineer resolved",
|
||||
)
|
||||
|
||||
result = await test_db.execute(
|
||||
select(AuditLog).where(
|
||||
AuditLog.action == "l1.session.resolve",
|
||||
AuditLog.resource_id == session.id,
|
||||
)
|
||||
)
|
||||
row = result.scalar_one()
|
||||
assert row.acting_as == "l1_coverage"
|
||||
assert row.user_id == eng.id
|
||||
assert row.account_id == account.id
|
||||
assert row.details["helpful"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resolve_writes_audit_log_native_l1_acting_as_null(
|
||||
test_db: AsyncSession,
|
||||
):
|
||||
"""resolve() writes an audit_logs row with acting_as=None for native l1_tech."""
|
||||
account = await _make_account(test_db)
|
||||
l1 = await _make_user(test_db, account_id=account.id, account_role="l1_tech")
|
||||
ticket = await _make_internal_ticket(
|
||||
test_db, account_id=account.id, user_id=l1.id
|
||||
)
|
||||
session = await start_adhoc_session(
|
||||
test_db,
|
||||
account_id=account.id,
|
||||
user=l1,
|
||||
ticket_id=str(ticket.id),
|
||||
ticket_kind="internal",
|
||||
)
|
||||
await resolve(
|
||||
test_db,
|
||||
session_id=session.id,
|
||||
helpful=False,
|
||||
resolution_notes="Native L1 resolved",
|
||||
)
|
||||
|
||||
result = await test_db.execute(
|
||||
select(AuditLog).where(
|
||||
AuditLog.action == "l1.session.resolve",
|
||||
AuditLog.resource_id == session.id,
|
||||
)
|
||||
)
|
||||
row = result.scalar_one()
|
||||
assert row.acting_as is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_escalate_writes_audit_log(test_db: AsyncSession):
|
||||
"""escalate() writes an audit_logs row with action='l1.session.escalate'."""
|
||||
account = await _make_account(test_db)
|
||||
l1 = await _make_user(test_db, account_id=account.id)
|
||||
ticket = await _make_internal_ticket(
|
||||
test_db, account_id=account.id, user_id=l1.id
|
||||
)
|
||||
session = await start_adhoc_session(
|
||||
test_db,
|
||||
account_id=account.id,
|
||||
user=l1,
|
||||
ticket_id=str(ticket.id),
|
||||
ticket_kind="internal",
|
||||
)
|
||||
await escalate(
|
||||
test_db,
|
||||
session_id=session.id,
|
||||
reason="Beyond scope",
|
||||
reason_category="out_of_scope",
|
||||
)
|
||||
|
||||
result = await test_db.execute(
|
||||
select(AuditLog).where(
|
||||
AuditLog.action == "l1.session.escalate",
|
||||
AuditLog.resource_id == session.id,
|
||||
)
|
||||
)
|
||||
row = result.scalar_one()
|
||||
assert row.details["escalation_reason_category"] == "out_of_scope"
|
||||
assert row.account_id == account.id
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_escalate_without_walk_writes_audit_log(test_db: AsyncSession):
|
||||
"""escalate_without_walk() writes an audit_logs row."""
|
||||
account = await _make_account(test_db)
|
||||
l1 = await _make_user(test_db, account_id=account.id)
|
||||
ticket = await _make_internal_ticket(
|
||||
test_db, account_id=account.id, user_id=l1.id
|
||||
)
|
||||
session = await escalate_without_walk(
|
||||
test_db,
|
||||
account_id=account.id,
|
||||
user=l1,
|
||||
ticket_id=str(ticket.id),
|
||||
ticket_kind="internal",
|
||||
reason_category="no_kb_content",
|
||||
)
|
||||
|
||||
result = await test_db.execute(
|
||||
select(AuditLog).where(
|
||||
AuditLog.action == "l1.session.escalate_no_walk",
|
||||
AuditLog.resource_id == session.id,
|
||||
)
|
||||
)
|
||||
row = result.scalar_one()
|
||||
assert row.account_id == account.id
|
||||
assert row.details["escalation_reason_category"] == "no_kb_content"
|
||||
|
||||
@@ -23,7 +23,6 @@ from pathlib import Path
|
||||
from urllib.parse import unquote, urlsplit
|
||||
|
||||
import asyncpg
|
||||
import psycopg2
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
|
||||
@@ -81,22 +80,7 @@ def _ensure_rls_schema():
|
||||
public schema using Base.metadata.create_all, which does not enable RLS
|
||||
or create DB roles. This fixture re-runs 'alembic upgrade head' so that
|
||||
the full migration-managed schema (including RLS policies) is in place.
|
||||
|
||||
We drop and recreate the public schema first so that any tables left behind
|
||||
by a prior create_all-based test_db run don't conflict with alembic's
|
||||
migration tracking.
|
||||
"""
|
||||
# Drop and recreate the schema to ensure a clean slate for alembic.
|
||||
admin_dsn = dict(
|
||||
host=_DB_HOST, port=_DB_PORT, dbname=_DB_NAME,
|
||||
user=_ADMIN_USER, password=_ADMIN_PASSWORD,
|
||||
)
|
||||
with psycopg2.connect(**admin_dsn) as conn:
|
||||
conn.autocommit = True
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("DROP SCHEMA public CASCADE")
|
||||
cur.execute("CREATE SCHEMA public")
|
||||
|
||||
backend_dir = Path(__file__).parent.parent
|
||||
env = os.environ.copy()
|
||||
env["DATABASE_URL"] = _DATABASE_TEST_URL
|
||||
@@ -147,18 +131,15 @@ async def seed_rls_test_data(admin_conn):
|
||||
user_b_id = str(uuid.uuid4())
|
||||
await admin_conn.execute(f"""
|
||||
INSERT INTO users (
|
||||
id, email, password_hash, name, role,
|
||||
is_super_admin, is_team_admin, is_service_account, must_change_password,
|
||||
is_active, account_id, account_role, timezone, created_at
|
||||
id, email, password_hash, name, role, is_active, account_id,
|
||||
account_role, created_at
|
||||
) VALUES
|
||||
('{user_a_id}', 'rls-user-a@example.com',
|
||||
'placeholder', 'RLS User A', 'engineer',
|
||||
FALSE, FALSE, FALSE, FALSE,
|
||||
TRUE, '{ACCOUNT_A_ID}', 'engineer', 'UTC', NOW()),
|
||||
'placeholder', 'RLS User A', 'engineer', TRUE,
|
||||
'{ACCOUNT_A_ID}', 'engineer', NOW()),
|
||||
('{user_b_id}', 'rls-user-b@example.com',
|
||||
'placeholder', 'RLS User B', 'engineer',
|
||||
FALSE, FALSE, FALSE, FALSE,
|
||||
TRUE, '{ACCOUNT_B_ID}', 'engineer', 'UTC', NOW())
|
||||
'placeholder', 'RLS User B', 'engineer', TRUE,
|
||||
'{ACCOUNT_B_ID}', 'engineer', NOW())
|
||||
ON CONFLICT (email) DO NOTHING
|
||||
""")
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,371 +0,0 @@
|
||||
# L1 Workspace — Phase 1 Acceptance Validation Report
|
||||
|
||||
**Date:** 2026-05-28
|
||||
**Branch:** `design/l1-workspace`
|
||||
**Last L1 commit before this report:** `6937bca` — `test(l1): E2E Playwright suite + seed L1 + coverage engineer test users`
|
||||
**Validator:** T26 acceptance subagent
|
||||
|
||||
---
|
||||
|
||||
## Summary verdict
|
||||
|
||||
**READY TO MERGE** — all Phase 1 acceptance criteria pass. Two categories of items are explicitly deferred to Phase 2/3 per the plan's out-of-scope section. One RLS test infrastructure bug was found and fixed as part of this validation pass.
|
||||
|
||||
---
|
||||
|
||||
## 1. Backend test suite
|
||||
|
||||
### 1.1 Full suite (CI-equivalent: xdist, `-n 4`)
|
||||
|
||||
Run command (mirrors CI workflow):
|
||||
```
|
||||
pytest tests/ --ignore=tests/test_l1_rls.py --ignore=tests/test_rls_isolation.py \
|
||||
-n 4 --override-ini="addopts=" -q
|
||||
```
|
||||
|
||||
| Metric | Result |
|
||||
|--------|--------|
|
||||
| Total passed | **1325** |
|
||||
| Total failed | **0** |
|
||||
| Total time | ~9m 45s |
|
||||
|
||||
Note: without `-n auto` / `-n 4`, the `test_db` fixture's schema teardown (DROP SCHEMA + CREATE SCHEMA after each test) races across tests sharing the same process, producing spurious failures. This is a pre-existing infrastructure constraint (documented in `perf(ci): pytest-xdist` commit `7f71436`). All tests pass cleanly with xdist, matching the CI configuration in `.github/workflows/ci.yml`.
|
||||
|
||||
### 1.2 L1-specific tests (xdist, `-n 4`)
|
||||
|
||||
Run command:
|
||||
```
|
||||
pytest tests/test_seat_enforcement.py tests/test_internal_ticket_service.py \
|
||||
tests/test_l1_session_service.py tests/test_l1_endpoints.py \
|
||||
tests/test_l1_session_cleanup.py -n 4 --override-ini="addopts=" -q
|
||||
```
|
||||
|
||||
| Test module | Tests | Passed |
|
||||
|-------------|-------|--------|
|
||||
| `test_seat_enforcement.py` | 6 | 6 |
|
||||
| `test_internal_ticket_service.py` | 7 | 7 |
|
||||
| `test_l1_session_service.py` | 18 | 18 |
|
||||
| `test_l1_endpoints.py` | 10 | 10 |
|
||||
| `test_l1_session_cleanup.py` | 2 | 2 |
|
||||
| **Total** | **43 (+14 deps-level)** | **57/57** |
|
||||
|
||||
(The xdist run shows 57 collected from these files.)
|
||||
|
||||
### 1.3 L1 RLS tests (isolated run)
|
||||
|
||||
Run command:
|
||||
```
|
||||
RUN_RLS_TESTS=1 pytest tests/test_l1_rls.py -v --override-ini="addopts="
|
||||
```
|
||||
|
||||
**8/8 passed.**
|
||||
|
||||
**Bug found and fixed in this pass:** The `l1_rls_seed` fixture inserted into `users` without the five NOT NULL columns added in earlier migrations (`is_super_admin`, `is_team_admin`, `is_service_account`, `must_change_password`, `timezone`). The `_ensure_rls_schema` fixture also failed when `Base.metadata.create_all`-populated tables were present in the test DB (alembic saw `teams` already exists). Both issues are fixed in `test_l1_rls.py` and `test_rls_isolation.py` (the same missing-columns bug exists in the pre-L1 `test_rls_isolation.py` and was fixed as a side effect).
|
||||
|
||||
### 1.4 Pre-existing `test_rls_isolation.py` issue (not introduced by L1)
|
||||
|
||||
`test_rls_isolation.py` uses `asyncio(loop_scope="module")` with module-scoped asyncpg fixtures. The conftest's `pytest_runtest_teardown` hook closes the event loop between tests, which causes teardown errors on the asyncpg connections when the full module runs. Individual tests pass. This is a pre-existing issue predating all L1 commits (last modified `b14a16a`); not introduced by Phase 1.
|
||||
|
||||
---
|
||||
|
||||
## 2. Frontend type-check and build
|
||||
|
||||
| Check | Result |
|
||||
|-------|--------|
|
||||
| `npx tsc -b` | **Clean — 0 errors** |
|
||||
| `npm run build` (Vite) | **Clean — build succeeded in ~69s** |
|
||||
| Chunk-size warnings | 3 warnings on pre-existing large chunks (`editor.main`, `index`, `AreaChart`) — all pre-existing, not introduced by L1 |
|
||||
|
||||
---
|
||||
|
||||
## 3. Migration roundtrip
|
||||
|
||||
### 3.1 Upgrade path
|
||||
|
||||
4 L1 migrations apply cleanly to a fresh schema in sequence:
|
||||
1. `a8186f22506d` — `add_l1_columns` (role CHECK constraint expansion, `can_cover_l1`, `l1_seats_purchased`, `l1_seat_limit`, `acting_as`)
|
||||
2. `ff6fe5895ea2` — `extend_flow_proposals_l1` (FlowProposal column extensions)
|
||||
3. `a1e6a018af02` — `create_internal_tickets` (table + RLS policy)
|
||||
4. `b3358ba0e48c` — `create_l1_walk_sessions` (table + RLS policy + check constraint)
|
||||
|
||||
All 4 apply cleanly: `alembic upgrade head` from empty schema → `b3358ba0e48c (head)` in ~2s.
|
||||
|
||||
### 3.2 Downgrade note
|
||||
|
||||
`alembic downgrade -7` (rolling back past `add_l1_columns`) fails on a seeded test database because the rollback tries to re-add the old CHECK constraint excluding `'l1_tech'`, which violates existing rows seeded with `account_role='l1_tech'`. This is **expected behavior** on a non-clean database and is not a defect in the migration itself. The top migration (`b3358ba0e48c`, create_l1_walk_sessions) roundtrips cleanly on its own.
|
||||
|
||||
---
|
||||
|
||||
## 4. Spec §15 acceptance checklist
|
||||
|
||||
### AC-1: L1 role assignable; L1 sidebar only; no engineer route reachable
|
||||
|
||||
✅ **PASS**
|
||||
|
||||
- `account_role IN ('owner', 'admin', 'engineer', 'l1_tech', 'viewer')` CHECK constraint in migration `a8186f22506d`. `require_l1`, `require_l1_or_coverage`, `require_l1_or_above` deps added in `app/api/deps.py` (lines 202–250).
|
||||
- `usePermissions.ts`: `isL1Tech`, `canUseL1Surface`, `canCoverL1` flags. Sidebar renders L1-only nav array when `isL1Tech` (`Sidebar.tsx` lines 87–89).
|
||||
- `L1RouteGuard` redirects non-L1 users to `/`. Engineer routes (`/pilot`, `/trees/new`, `/escalations`) use `require_engineer_or_admin` which returns HTTP 403 for `l1_tech`.
|
||||
- `test_l1_endpoints.py::test_intake_viewer_forbidden` (viewer → 403 on `/l1/sessions/intake`).
|
||||
|
||||
### AC-2: L1 intake creates ticket + lands in walker — OR BuildAbortedNoKB / suggest prompt
|
||||
|
||||
⚠️ **PARTIAL PASS — Phase 2 items deferred per plan**
|
||||
|
||||
- Phase 1 intake creates an internal ticket and an adhoc `L1WalkSession` (status=`active`). Confirmed by `test_l1_endpoints.py::test_intake_adhoc` and `test_l1_session_service.py::test_start_adhoc_session_no_flow_no_proposal`.
|
||||
- PSA-backed intake creates `ticket_kind='psa'` sessions (flow-variant and proposal-variant also work via direct API: `test_start_flow_session_creates_active_flow_session`, `test_start_proposal_session_creates_active_proposal_session`).
|
||||
- **Deferred:** `match_or_build` orchestrator (Phase 2) — the AI-driven flow/proposal matching that triggers BuildAbortedNoKB or SuggestPrompt is out of scope for Phase 1. Phase 1 always creates adhoc sessions; the UI flow-selection surface ships with Phase 2 alongside the AI matcher.
|
||||
|
||||
### AC-3: Walker handles flow, proposal, AND adhoc walks; all three resolve and escalate correctly
|
||||
|
||||
✅ **PASS**
|
||||
|
||||
- Three walker variants implemented: `L1WalkTreeVariant.tsx` (flow), `L1WalkAdhocVariant.tsx` (adhoc), and proposal variant handled in `L1WalkPage.tsx`.
|
||||
- `test_l1_session_service.py`: `test_resolve_flow_session_closes_ticket_no_proposal_update`, `test_resolve_proposal_helpful_flips_validated_by_outcome`, `test_resolve_adhoc_session_closes_ticket`, `test_escalate_marks_session_and_ticket_as_escalated`, `test_escalate_without_walk_creates_escalated_adhoc_session`.
|
||||
|
||||
### AC-4: Concurrent sessions supported; browser-close recoverable; abandoned sessions auto-flipped 24h
|
||||
|
||||
✅ **PASS**
|
||||
|
||||
- Concurrent sessions: `l1_walk_sessions` allows multiple `status='active'` rows per user. `test_l1_endpoints.py::test_list_active_sessions_ordered` verifies multiple sessions are returned ordered by `last_step_at DESC`.
|
||||
- Browser-close recovery: `GET /l1/sessions/{id}` returns full session state. `L1WalkPage` fetches session on mount.
|
||||
- Abandoned flip: `l1_session_cleanup.py` with APScheduler hourly job. `test_l1_session_cleanup.py::test_flip_stale_sessions_only_affects_old_active_rows` (stale → `'abandoned'`), `test_flip_stale_sessions_returns_zero_when_none_stale`.
|
||||
|
||||
### AC-5: First-run empty-state card renders on dashboard; intake still works (degrades to adhoc)
|
||||
|
||||
✅ **PASS**
|
||||
|
||||
- `EmptyStateCard.tsx` component renders when account has no flows and no KB docs.
|
||||
- `L1Dashboard.tsx` passes `isEmpty` prop based on API response. Intake remains functional (always creates adhoc session in Phase 1 — no KB required).
|
||||
|
||||
### AC-6: Escalate generates package, reassigns ticket, notifies engineers; BuildAbortedNoKB pre-fills reason
|
||||
|
||||
⚠️ **PARTIAL PASS — PSA reassign + engineer notification deferred per plan**
|
||||
|
||||
**What Phase 1 delivers:**
|
||||
- Escalation sets `session.status='escalated'`, writes `escalation_reason`, `escalation_reason_category`, stamps `resolved_at`.
|
||||
- Internal-backed tickets flipped to `status='escalated'` via `internal_ticket_service`.
|
||||
- `escalate_without_walk` endpoint captures the call with `reason_category` pre-filled (per `test_escalate_without_walk_creates_escalated_adhoc_session`).
|
||||
- `WalkModals.tsx` contains the EscalateModal with reason category selector.
|
||||
|
||||
**Explicitly deferred per plan:**
|
||||
- PSA ticket reassign (`psa_provider.reassign_ticket`) — Phase 2 comment in `l1_session_service.py` line 232.
|
||||
- `escalation_package_generator` integration (system-context `ai_session` creation for chat handoff) — Phase 2 per plan line "PSA close is intentionally deferred to Phase 2."
|
||||
- Engineer bell-badge notification via `notification_service` — Phase 2. Phase 1 plan explicitly notes "PSA reassign — Phase 1 stub; full integration with escalation_package_generator."
|
||||
|
||||
### AC-7: Resolve flips `validated_by_outcome`; review queue prioritizes outcome-validated drafts
|
||||
|
||||
✅ **PASS**
|
||||
|
||||
- `l1_session_service.py::resolve()`: `proposal.validated_by_outcome = True` when `helpful=True` (line 186). `test_resolve_proposal_helpful_flips_validated_by_outcome` and `test_resolve_proposal_not_helpful_leaves_validated_by_outcome_false` both pass.
|
||||
- `FlowProposal.validated_by_outcome` column added in migration `ff6fe5895ea2`.
|
||||
- Review queue ordering (`ORDER BY validated_by_outcome DESC`) is a read-side query change covered by FlowProposal model extension; engineer review UI is unchanged in Phase 1.
|
||||
|
||||
### AC-8: All three KB connectors configurable
|
||||
|
||||
❌ **N/A — Phase 3 (out of scope for Phase 1)**
|
||||
|
||||
Per spec §18 "Note on scope and phasing": KB connectors (IT Glue, Hudu, Microsoft Graph) are Phase 3 deliverables. Phase 1 plan explicitly lists "KB connectors (IT Glue / Hudu / Microsoft Graph)" under "Out of scope for Phase 1."
|
||||
|
||||
### AC-9: AI build refuses cleanly when KB is empty (returns `aborted_no_kb`)
|
||||
|
||||
❌ **N/A — Phase 2 (out of scope for Phase 1)**
|
||||
|
||||
`match_or_build` orchestrator and AI tree-builder are Phase 2. Per plan: "`match_or_build` orchestrator, AI tree-builder, `kb_documents` tables, KB connectors … are explicitly out of Phase 1." The `aborted_no_kb` outcome path ships with Phase 2.
|
||||
|
||||
### AC-10: Coverage flag works end-to-end with audit-log tagging (`acting_as='l1_coverage'`)
|
||||
|
||||
✅ **PASS**
|
||||
|
||||
- `users.can_cover_l1` column added in migration `a8186f22506d`.
|
||||
- `_resolve_acting_as()` in `l1_session_service.py` returns `'l1_coverage'` for engineers with flag (line 26).
|
||||
- `audit_logs.acting_as` column added in migration `a8186f22506d`.
|
||||
- `usePermissions.canCoverL1` and `canUseL1Surface` flags gate the L1 surface for coverage engineers.
|
||||
- `L1CoverageBanner.tsx` displays when engineer is using L1 surface via coverage flag.
|
||||
- E2E seed user `coverage_engineer@example.com` with `can_cover_l1=True` created in T25 Playwright seed.
|
||||
- `test_l1_session_service.py` coverage flag scenario covered via `test_escalate_without_walk_creates_escalated_adhoc_session` (acting_as verified).
|
||||
|
||||
### AC-11: Seat enforcement — invite blocks 402/422 for both L1 and engineer roles
|
||||
|
||||
✅ **PASS**
|
||||
|
||||
- `seat_enforcement.py::check_seat_available()` handles both `'engineer'` and `'l1_tech'` roles.
|
||||
- `accounts.py` endpoint: `_require_seat_available()` raises HTTP 402 when over limit; role-change check raises 422 at line 259.
|
||||
- `test_seat_enforcement.py`: `test_l1_uses_separate_seat_limit` (engineer limit hit does not block L1), `test_engineer_seat_unavailable_when_at_limit` (402 path), `test_inactive_users_not_counted`. All 6/6 pass.
|
||||
|
||||
### AC-12: RLS blocks cross-tenant reads on every new table
|
||||
|
||||
✅ **PASS**
|
||||
|
||||
- `internal_tickets` and `l1_walk_sessions` both created with `ENABLE ROW LEVEL SECURITY`, `FORCE ROW LEVEL SECURITY`, and `tenant_isolation` policy (`USING (account_id = current_setting('app.current_account_id', TRUE)::uuid)`). Verified in migrations `a1e6a018af02` and `b3358ba0e48c`.
|
||||
- `test_l1_rls.py`: all 8 tests pass:
|
||||
- `test_l1_user_cannot_read_other_accounts_internal_tickets`
|
||||
- `test_internal_tickets_account_a_can_see_own_rows`
|
||||
- `test_internal_tickets_no_context_sees_nothing`
|
||||
- `test_l1_user_cannot_read_other_accounts_walk_sessions`
|
||||
- `test_l1_walk_sessions_account_a_can_see_own_rows`
|
||||
- `test_l1_walk_sessions_no_context_sees_nothing`
|
||||
- `test_with_check_blocks_cross_tenant_insert_internal_tickets`
|
||||
- `test_with_check_blocks_cross_tenant_insert_l1_walk_sessions`
|
||||
- `kb_connector_configs`, `kb_documents`, `kb_document_chunks` tables ship in Phase 2/3 and will need RLS policies added at that time. Phase 1 tables (`internal_tickets`, `l1_walk_sessions`) are covered.
|
||||
|
||||
### AC-13: L1 seat count tracked separately from engineer seats; widget visible in admin/users UI
|
||||
|
||||
✅ **PASS**
|
||||
|
||||
- `subscriptions.l1_seat_limit` (nullable, Phase 2 populates via Stripe) and `accounts.l1_seats_purchased` columns added in `a8186f22506d`.
|
||||
- `get_seat_usage()` returns `(engineer_check, l1_tech_check)` tuple separately.
|
||||
- `SeatCounterWidget.tsx` renders separate rows for engineer and L1 seats (`<SeatRow label="L1 seats" check={usage.l1_tech} />`).
|
||||
- `test_get_seat_usage_returns_engineer_l1_tuple` passes.
|
||||
|
||||
### AC-14: L1s cannot access `/account/kb` — confirmed by route guard test
|
||||
|
||||
⚠️ **PARTIAL PASS — Phase 2 route (no `/account/kb` in Phase 1)**
|
||||
|
||||
The `/account/kb` route is a Phase 2 surface (KB management ships with Phase 2 when `kb_documents` tables are created). Phase 1 does not register `/account/kb` in `router.tsx`. The spec's criterion is satisfied vacuously — L1s cannot access a route that does not exist. When Phase 2 adds `/account/kb`, the route guard must use `require_engineer_or_admin` per spec §9.2.
|
||||
|
||||
---
|
||||
|
||||
## 5. Checklist summary
|
||||
|
||||
| AC | Status | Notes |
|
||||
|----|--------|-------|
|
||||
| 1. L1 role + sidebar + route blocking | ✅ PASS | Tests: `test_intake_viewer_forbidden`, deps, `usePermissions`, `L1RouteGuard` |
|
||||
| 2. Intake → walker (or BuildAbortedNoKB / suggest) | ⚠️ PARTIAL | Adhoc intake works; AI matcher (BuildAbortedNoKB / suggest) → Phase 2 |
|
||||
| 3. Walker: flow, proposal, adhoc + resolve/escalate | ✅ PASS | Tests: 18 session service tests + 10 endpoint tests |
|
||||
| 4. Concurrent sessions, browser-close recovery, abandoned flip | ✅ PASS | Tests: ordered-list + cleanup tests |
|
||||
| 5. First-run empty state; intake degrades to adhoc | ✅ PASS | `EmptyStateCard.tsx`, always-adhoc in Phase 1 |
|
||||
| 6. Escalate: package + PSA reassign + notify engineers | ⚠️ PARTIAL | Package stub done; PSA reassign + notifications → Phase 2 |
|
||||
| 7. Resolve flips `validated_by_outcome` | ✅ PASS | Tests: `test_resolve_proposal_helpful_flips_validated_by_outcome` |
|
||||
| 8. KB connectors (3) | ❌ N/A | Phase 3 |
|
||||
| 9. AI build refuses on empty KB | ❌ N/A | Phase 2 |
|
||||
| 10. Coverage flag + audit-log tagging | ✅ PASS | `_resolve_acting_as`, `can_cover_l1`, `acting_as` column, `L1CoverageBanner` |
|
||||
| 11. Seat enforcement: 402/422 for L1 + engineer | ✅ PASS | Tests: 6 seat enforcement tests |
|
||||
| 12. RLS on new tables | ✅ PASS | Tests: 8 L1 RLS tests |
|
||||
| 13. L1 seat count separate; widget visible | ✅ PASS | `SeatCounterWidget`, `get_seat_usage`, `test_get_seat_usage_returns_engineer_l1_tuple` |
|
||||
| 14. L1s cannot access `/account/kb` | ⚠️ PARTIAL | Route not added in Phase 1; guard must be added when Phase 2 creates the route |
|
||||
|
||||
**Totals: 9 ✅ PASS / 3 ⚠️ PARTIAL (expected per plan) / 2 ❌ N/A (Phase 2/3 deferred)**
|
||||
|
||||
All ⚠️ and ❌ items are explicitly listed as out-of-scope in the Phase 1 plan's "Out of scope for Phase 1" section.
|
||||
|
||||
---
|
||||
|
||||
## 6. Known limitations carried into Phase 2
|
||||
|
||||
The following items are explicitly out of scope for Phase 1 per the plan's "Out of scope for Phase 1" section and spec §18 "Note on scope and phasing":
|
||||
|
||||
1. **`match_or_build` orchestrator** — AI-driven flow/proposal matching. Phase 1 always creates adhoc sessions. Flow and proposal variants exist in code and are API-accessible, but the UX surface for L1s to select a flow ships with Phase 2.
|
||||
2. **BuildAbortedNoKB screen** — No KB content guard. Requires AI builder (Phase 2).
|
||||
3. **Near-miss SuggestPrompt** — `SUGGEST_THRESHOLD` near-miss UX. Phase 2.
|
||||
4. **AI tree-builder (`l1_realtime_build`)** — Not built. Phase 2.
|
||||
5. **`kb_documents`, `kb_document_chunks` tables and connectors** — Phase 2/3.
|
||||
6. **PSA ticket reassign on escalation** — `psa_provider.reassign_ticket()` stub comment in `l1_session_service.py:232`. Phase 2.
|
||||
7. **Escalation package generation** — `escalation_package_generator` integration and `ai_session` creation for chat handoff. Phase 2.
|
||||
8. **Engineer bell-badge notifications on escalation** — `notification_service` call. Phase 2.
|
||||
9. **`/account/kb` route guard test** — Route added in Phase 2; guard must use `require_engineer_or_admin`.
|
||||
10. **PSA close on resolve** — Phase 2.
|
||||
|
||||
See spec §13 "Out of scope (v1 non-goals)" for the full non-goals list and spec §18 "Note on scope and phasing" for the phase breakdown rationale.
|
||||
|
||||
---
|
||||
|
||||
## 7. Unexpected findings during validation
|
||||
|
||||
1. **RLS test fixture bug** (fixed in this commit): `test_l1_rls.py` and `test_rls_isolation.py` both had users INSERT statements missing five NOT NULL columns (`is_super_admin`, `is_team_admin`, `is_service_account`, `must_change_password`, `timezone`) added by earlier migrations. The `_ensure_rls_schema` fixture also lacked a schema DROP before the alembic upgrade, causing `DuplicateTable` errors when `Base.metadata.create_all` tables were present from prior test runs. Both fixed in this commit.
|
||||
|
||||
2. **Test isolation is xdist-dependent** (pre-existing, not introduced by L1): The `test_db` fixture drops and recreates the public schema per test function. Without xdist worker isolation, sequential tests in the same process see `UndefinedTableError` after the first test's teardown runs. This matches the known behavior documented in commit `7f71436` (perf/ci). CI uses xdist; local single-module runs work; full-suite single-process runs fail. Not a defect in Phase 1.
|
||||
|
||||
3. **Migration downgrade on seeded DB** (expected): `alembic downgrade -7` fails when `l1_tech` users exist in the test DB — the old CHECK constraint excludes `'l1_tech'`. This is correct behavior; downgrade scripts assume a fresh DB. The plain upgrade path from empty schema is clean.
|
||||
|
||||
---
|
||||
|
||||
*Report generated by T26 acceptance validation pass, 2026-05-28.*
|
||||
|
||||
---
|
||||
|
||||
## Post-Final-Review Fixes Addendum
|
||||
|
||||
All 5 issues surfaced by the final code review were addressed in individual commits on
|
||||
`2026-05-28`. Details below.
|
||||
|
||||
---
|
||||
|
||||
### Fix 1 — `audit_logs.acting_as` at L1 terminal events (Important)
|
||||
|
||||
**Issue:** Per spec §5.6.1, audit rows must be written at session terminal events
|
||||
(resolve, escalate). No rows were being written for L1 actions at all.
|
||||
|
||||
**Changes:**
|
||||
- `/backend/app/core/audit.py` — `log_audit` gains optional `acting_as: str | None`
|
||||
parameter, passed through to the `AuditLog` row.
|
||||
- `/backend/app/services/l1_session_service.py` — `resolve()`, `escalate()`, and
|
||||
`escalate_without_walk()` each call `log_audit` before/after their `db.flush()`,
|
||||
writing rows with `action=l1.session.resolve|escalate|escalate_no_walk` and
|
||||
`acting_as` from the session.
|
||||
- `/backend/tests/test_l1_session_service.py` — 4 new integration tests:
|
||||
`test_resolve_writes_audit_log_with_acting_as`,
|
||||
`test_resolve_writes_audit_log_native_l1_acting_as_null`,
|
||||
`test_escalate_writes_audit_log`,
|
||||
`test_escalate_without_walk_writes_audit_log`.
|
||||
|
||||
**Commit:** `a5f4c16`
|
||||
|
||||
---
|
||||
|
||||
### Fix 2 — Session-ownership policy documented in `_get_session_or_404` (Important)
|
||||
|
||||
**Issue:** Policy that sessions are account-scoped (not user-scoped) was implicit.
|
||||
|
||||
**Change:** Docstring added to `_get_session_or_404` in
|
||||
`/backend/app/api/endpoints/l1.py` explaining the Phase 1 account-scoped policy per
|
||||
spec §7.9, and noting where to tighten to creator-only if needed.
|
||||
|
||||
**Commit:** `939b827`
|
||||
|
||||
---
|
||||
|
||||
### Fix 3 — Router placement comment (Minor)
|
||||
|
||||
**Issue:** L1 router mounted under `_tenant_deps` without explanation.
|
||||
|
||||
**Change:** Two-line comment added in `/backend/app/api/router.py` above the
|
||||
`l1.router` include, explaining that L1 uses seat-based gating rather than
|
||||
`require_active_subscription`.
|
||||
|
||||
**Commit:** `01ab52d`
|
||||
|
||||
---
|
||||
|
||||
### Fix 4 — Toast on intake failure in L1Dashboard (Minor)
|
||||
|
||||
**Issue:** `handleStart` in `L1Dashboard.tsx` swallowed errors silently.
|
||||
|
||||
**Change:** `catch (err)` block added that surfaces a toast with the backend
|
||||
`detail` string, falling back to a generic message. Import of `toast` from
|
||||
`@/lib/toast` added.
|
||||
|
||||
**Commit:** `c803fcc`
|
||||
|
||||
---
|
||||
|
||||
### Fix 5 — 402 seat-limit handler on invite (Minor)
|
||||
|
||||
**Issue:** `accountsApi.createInvite` 402 response was handled by the generic
|
||||
`toast.error('Failed to send invitation')` branch — no seat count info surfaced.
|
||||
|
||||
**Change:** `/frontend/src/pages/AccountSettingsPage.tsx` `handleInvite` catches
|
||||
HTTP 402 with `detail.code === 'seat_limit_exceeded'` and shows a warning toast
|
||||
with the role label and `current/limit` counts. Generic error path retained for
|
||||
all other failures.
|
||||
|
||||
**Commit:** `a762a5c`
|
||||
|
||||
---
|
||||
|
||||
## Validation results (post-fix)
|
||||
|
||||
| Check | Result |
|
||||
|---|---|
|
||||
| `pytest --override-ini="addopts=" -n auto` | 1329 passed (was 1325; +4 audit tests) |
|
||||
| `npx tsc -b` | clean (no output) |
|
||||
| `npm run build` | clean, built in ~74s |
|
||||
@@ -1,266 +0,0 @@
|
||||
# L1 AI Decision-Tree Builder — Phase 2A Design
|
||||
|
||||
**Status:** Draft for review
|
||||
**Date:** 2026-05-29
|
||||
**Author:** previous session (brainstorming)
|
||||
**Predecessor:** [`2026-05-28-l1-workspace-design.md`](2026-05-28-l1-workspace-design.md) (full L1 vision), [`2026-05-28-l1-workspace-phase-1-acceptance.md`](2026-05-28-l1-workspace-phase-1-acceptance.md) (what shipped in Phase 1)
|
||||
|
||||
---
|
||||
|
||||
## 1. Goal
|
||||
|
||||
When an L1 tech describes a problem and there is **no matching authored flow or AI draft**, the platform builds a yes/no decision tree **in real time from the model's general L1 knowledge** and walks the tech through it node by node. Scoped to L1-appropriate troubleshooting: simple yes/no questions and reversible step-by-step instructions. Successful trees are captured as outcome-validated drafts for engineer review, compounding the account's knowledge base from real resolutions.
|
||||
|
||||
This **overrides** the original spec's "no empty-KB build" rule (§8.1 of the predecessor), which aborted to a degradation screen when no KB existed. Instead of aborting, we build from generic knowledge under a layered safety model.
|
||||
|
||||
KB grounding (RAG over ingested documents) is **explicitly deferred to Phase 2B** — Phase 2A builds from generic knowledge only, plus matching against already-authored flows.
|
||||
|
||||
## 2. Scope
|
||||
|
||||
**In scope (Phase 2A):**
|
||||
- `match_or_build` orchestrator inserted at L1 intake (match-first, build-on-miss).
|
||||
- `ai_tree_builder` service: node-by-node ("streaming") tree generation, constrained + escalate-early.
|
||||
- Admin-configurable L1 category allowlist (Account Owner/Admin control panel).
|
||||
- Standing AI-disclaimer banner on AI-built walks.
|
||||
- Flywheel capture: resolved AI trees become outcome-validated `FlowProposal`s.
|
||||
- Minimum escalation handoff: engineer bell-badge notification + an engineer-visible "escalated from L1" surface.
|
||||
|
||||
**Deferred:**
|
||||
- KB document ingestion + connectors (IT Glue, Hudu, SharePoint/OneDrive) — Phase 2B.
|
||||
- RAG grounding of the builder on ingested KB — Phase 2B.
|
||||
- PSA ticket reassign on escalation, escalation-package generation, AI chat handoff — later phase.
|
||||
- `BuildAbortedNoKB` screen from the original spec — **dropped** (superseded by build-from-generic).
|
||||
|
||||
## 3. Architecture (Approach C)
|
||||
|
||||
Dedicated builder for the constrained node generation; reuse existing rails for matching and capture.
|
||||
|
||||
**New services:**
|
||||
| File | Responsibility |
|
||||
|---|---|
|
||||
| `backend/app/services/match_or_build.py` | Orchestrator. `match_or_build(account_id, problem_text, ticket_ref, *, force_build=False) -> MatchOrBuildResult`. Classify → category gate → match pass → build/suggest/out-of-scope decision. |
|
||||
| `backend/app/services/ai_tree_builder.py` | Node-by-node generation. `generate_next_node(problem_text, category, walked_path) -> TreeNode`. Reuses `get_ai_provider` + `generate_json` + `parse_llm_json`. Owns the constrained system prompt and per-node validation. |
|
||||
| `backend/app/services/l1_category_service.py` | Read/write an account's enabled L1 categories; expose the default allowlist and the always-forbidden hard floor. |
|
||||
|
||||
**Reused as-is:**
|
||||
- `flow_matching_engine.find_matches()` — semantic + keyword + recency match pass.
|
||||
- `knowledge_flywheel` proposal-creation + dedupe (`_find_similar_pending_proposal`) — outcome-validated capture.
|
||||
- `notification_service` — engineer escalation notification.
|
||||
- Phase 1 `L1WalkTreeVariant` walker — its stubbed synthetic-step UI is replaced by real AI node rendering.
|
||||
|
||||
**Intake decision flow:**
|
||||
|
||||
Order matters: **match first, gate only the build path.** The category allowlist exists to bound *generic AI building* for safety — it must not block a human-authored flow that already exists for that problem. So matching against published flows runs before any category check; the category gate applies only when we fall through to building.
|
||||
|
||||
```
|
||||
POST /l1/intake (problem_statement, customer_*, force_build?)
|
||||
→ match_or_build(account_id, problem_text, problem_domain, ticket_ref, force_build):
|
||||
1. if not force_build:
|
||||
hits = flow_matching_engine.find_matches(problem_text, problem_domain, account_id)
|
||||
best = max(hits, default=None) # published flows (Trees) only
|
||||
if best and best.score >= MATCH_THRESHOLD:
|
||||
return {outcome: 'matched', flow_id, session_kind: 'flow'}
|
||||
if best and best.score >= SUGGEST_THRESHOLD:
|
||||
return {outcome: 'suggest', near_miss, can_build: true}
|
||||
2. category = classify(problem_text) # new — only on build path
|
||||
3. if category not in account.enabled_l1_categories:
|
||||
return {outcome: 'out_of_scope', category}
|
||||
4. return {outcome: 'build', session_kind: 'ai_build', category}
|
||||
```
|
||||
|
||||
**Match scope (Finding 2):** `flow_matching_engine.find_matches()` matches **published flows (`trees`) only** — it returns `{tree_id, tree_name, score, ...}` and has no notion of `FlowProposal`s. Phase 2A therefore matches against published flows only; the `matched` outcome is always `session_kind: 'flow'`. This is sufficient because the flywheel promotes good AI drafts to published flows (§6), which then become matchable on future intakes. Matching against not-yet-promoted proposals is a deferred enhancement (would require extending the engine), noted in §13.
|
||||
|
||||
Frontend dispatches on `outcome`:
|
||||
- `matched` → start a `flow` walk (Phase 1 path).
|
||||
- `suggest` → inline prompt ("Found a similar flow — use it, or build new?"); "Build new" re-calls intake with `force_build=true` (which skips the match pass and runs the category gate before building).
|
||||
- `out_of_scope` → inline prompt offering ad-hoc walk or escalate-without-walk (Phase 1 paths).
|
||||
- `build` → create an `ai_build` session, navigate to the walker, fetch the first node.
|
||||
|
||||
## 4. The streaming build & node schema
|
||||
|
||||
`ai_tree_builder.generate_next_node()` is called with the problem statement, the resolved category, and the **full walked path so far**. It returns exactly one node. Passing the whole path every call is what keeps independently-generated nodes coherent and lets the model decide when it has exhausted safe steps.
|
||||
|
||||
**Node shape (`proposed_flow_data` node, also the live `walked_path` entry):**
|
||||
```json
|
||||
// question — yes/no branch; both branches regenerate
|
||||
{ "node_type": "question", "id": "n3", "text": "Is the printer showing a 'ready' status light?",
|
||||
"yes_next": "generate", "no_next": "generate" }
|
||||
|
||||
// instruction — a single safe, reversible action; advances on acknowledgement
|
||||
{ "node_type": "instruction", "id": "n4", "text": "Unplug the printer for 30 seconds, then power it back on.",
|
||||
"next": "generate" }
|
||||
|
||||
// resolved — terminal success
|
||||
{ "node_type": "resolved", "id": "n7", "text": "Printer is back online and printing test pages." }
|
||||
|
||||
// escalate — terminal handoff (escalate-early safety valve)
|
||||
{ "node_type": "escalate", "id": "n7", "reason_category": "exhausted_safe_steps",
|
||||
"text": "This looks like a driver-level fault beyond L1 scope — escalating to engineering." }
|
||||
```
|
||||
|
||||
`"generate"` is a sentinel meaning "call `generate_next_node` again with the new answer appended." The first node is fetched synchronously on `ai_build` session creation (intake). Each subsequent node is fetched when the tech answers/acknowledges — target latency ~2–4s per node; show a per-node "Thinking through the next step…" affordance.
|
||||
|
||||
**Endpoint:** `POST /l1/sessions/{id}/next-node` body `{node_id, answer?: 'yes'|'no', acknowledged?: true, note?}`. Appends the answered node to `walked_path`, then generates and returns the next node (or a terminal node). Replaces the Phase 1 synthetic stepping in `L1WalkTreeVariant`.
|
||||
|
||||
## 5. Safety model (layered)
|
||||
|
||||
**Layer 1 — classification gate (build path only).** Runs only after the match pass misses (§3) — a human-authored flow is never blocked by category settings. `classify(problem_text)` maps the problem to a category via a lightweight model call (low token budget, returns one category key from the enabled set or `unknown`); on model failure it falls back to keyword matching against category aliases. If the result is not in the account's enabled set (or is `unknown`), intake returns `out_of_scope` (offer adhoc/escalate); no build happens.
|
||||
|
||||
**Layer 2 — constrained generation.** The `ai_tree_builder` system prompt restricts output to:
|
||||
- Safe, reversible, observe-or-restart-class steps only (toggle/restart/reconnect/re-enter, check-status questions).
|
||||
- A **hard floor of always-forbidden actions** (see §5.1) that NO category may unlock.
|
||||
- An explicit instruction to emit an `escalate` node — never guess — once it runs out of in-scope safe steps.
|
||||
|
||||
**Layer 3 — per-node validation.** Server-side, every generated node is checked before being returned:
|
||||
- Reject (and regenerate once, then escalate) nodes whose text matches forbidden-action patterns (§5.1).
|
||||
- Enforce a **depth cap** (default `L1_BUILD_MAX_DEPTH = 12`): once the walked path hits the cap, force an `escalate` node.
|
||||
- Validate node JSON shape (Pydantic); malformed → regenerate once, then escalate.
|
||||
|
||||
**Layer 4 — standing disclaimer.** Persistent banner on every `ai_build` walk:
|
||||
|
||||
> *"These are high-confidence troubleshooting steps, but they come from outside your organization's knowledge base — review them before acting. When in doubt, escalate early."*
|
||||
|
||||
### 5.1 Hard floor — always forbidden (admins cannot enable)
|
||||
Regardless of enabled categories, the builder must never produce steps that:
|
||||
- Modify the Windows registry, system files, or boot configuration.
|
||||
- Delete, format, or repartition data/disks; remove user profiles or mailboxes.
|
||||
- Change credentials, MFA, security/firewall/AV settings, or disable protections.
|
||||
- Run scripts/commands with elevated/admin privileges.
|
||||
- Touch domain controllers, DNS, DHCP, or production server config.
|
||||
- Make purchases, license changes, or anything with billing impact.
|
||||
|
||||
*(This list is a product decision — review and edit during spec review.)*
|
||||
|
||||
### 5.2 Default enabled category allowlist (admin-editable)
|
||||
Ships enabled by default; Account Owners/Admins toggle per account:
|
||||
`password_reset`, `account_lockout`, `printer`, `email_outlook_client`, `wifi_network_basics`, `vpn_connect`, `teams_zoom_av`, `browser_cache_cookies`, `peripheral_reconnect`, `os_restart_update`.
|
||||
|
||||
*(This list is a product decision — review and edit during spec review.)*
|
||||
|
||||
### 5.3 Tunables
|
||||
| Setting | Default | Notes |
|
||||
|---|---|---|
|
||||
| `MATCH_THRESHOLD` | 0.75 | Carried from predecessor spec §8.1. |
|
||||
| `SUGGEST_THRESHOLD` | 0.60 | Carried from predecessor spec §8.1. |
|
||||
| `L1_BUILD_MAX_DEPTH` | 12 | Force escalate beyond this many nodes. |
|
||||
| `get_model_for_action('l1_realtime_build')` | Sonnet | Latency-sensitive; benchmark Sonnet vs Opus during plan. |
|
||||
| Per-node max_tokens | 1024 | One node is small. |
|
||||
|
||||
## 6. Flywheel capture
|
||||
|
||||
On `resolve` of an `ai_build` session (`l1_session_service.resolve` extension):
|
||||
1. **Normalize** the `walked_path` into a complete, valid `tree_structure` (§6.1) — approval requires a dict with a real `id` (see Finding 5 / `_create_tree_from_proposal`).
|
||||
2. Create a `FlowProposal`: `source='ai_realtime_l1'`, `validated_by_outcome=true`, `proposed_flow_data={tree_structure, match_keywords}`, `l1_session_id=<this session>` (NOT `source_session_id` — see §6.2 / Finding 1), `linked_ticket_id/kind=<session ticket>`, `problem_domain=<category>`, `status='pending'`.
|
||||
3. Run the existing `_find_similar_pending_proposal` dedupe — merge (bump supporting count) if a near-duplicate pending proposal exists, else insert.
|
||||
4. Emit the existing `proposal.pending` notification to the review queue.
|
||||
|
||||
Engineers promote good proposals to authored flows in the existing review queue. Promoted flows are then found by `flow_matching_engine` on future intakes → the KB compounds. `source='ai_realtime_l1'` rows surface in the existing queue (badge them "AI · outcome-validated").
|
||||
|
||||
### 6.1 Tree normalization (Finding 5)
|
||||
The live `walked_path` holds only traversed nodes, and `"generate"` is a runtime sentinel, not a real edge — that is not a valid tree and would fail the `_create_tree_from_proposal` guard (`tree_structure` must be a dict with an `id`). At resolve time, `ai_tree_builder.normalize_walked_path(walked_path) -> tree_structure` produces a complete object:
|
||||
- Assign stable string `id`s to every node; the first node becomes the root and `tree_structure.id` = root id.
|
||||
- `question` nodes: the **traversed** branch (`yes`/`no` the tech actually chose) points to the next traversed node; the **untraversed** branch points to a terminal `{node_type: 'needs_review', text: 'Branch not explored during the originating call'}` stub.
|
||||
- `instruction` nodes point to the next traversed node.
|
||||
- The traversal ends at the real terminal node (`resolved` or `escalate`).
|
||||
This yields a structurally valid, reviewable tree: engineers fill in the `needs_review` branches when promoting. (Trees are `tree_type='troubleshooting'`.)
|
||||
|
||||
### 6.2 FlowProposal L1 source linkage (Finding 1 — Blocker)
|
||||
`FlowProposal.source_session_id` is currently `nullable=False` FK → `ai_sessions`, and the review UI (`ProposalDetail.tsx`) links the "Source Session" to `/pilot/{source_session_id}` (a FlowPilot chat surface). An L1 `ai_build` session is an `l1_walk_session`, not an `ai_session`, so it cannot populate `source_session_id`. Changes:
|
||||
- **Model/migration:** add `FlowProposal.l1_session_id` (nullable FK → `l1_walk_sessions.id`, `ondelete=SET NULL`, indexed). Make `source_session_id` **nullable**. Add CHECK `((source_session_id IS NOT NULL) <> (l1_session_id IS NOT NULL))` — exactly one source set.
|
||||
- **Review UI:** when `l1_session_id` is set (source `ai_realtime_l1`), render the "Source" block as a read-only walked-path summary (problem statement + the resolved path) instead of a `/pilot/...` link. Existing ai_session-sourced proposals are unchanged.
|
||||
- **Tree promotion:** `_create_tree_from_proposal` sets `Tree.source_session_id` from the proposal — for L1-sourced proposals leave it NULL (confirm `Tree.source_session_id` is nullable; if not, include in the migration).
|
||||
|
||||
## 7. Minimum escalation handoff
|
||||
|
||||
On `escalate` (terminal node reached, or the L1 hits the Escalate modal during an `ai_build` walk) — extends `l1_session_service.escalate`. **The engineer-visible surface is the primary, dependency-free handoff; the bell-badge notification is a thin addition that requires three specific extensions to the FlowPilot-shaped notification system (Finding 3).**
|
||||
|
||||
1. **Engineer-visible surface (primary).** Escalated L1 sessions appear in an engineer-facing list — extend the existing `/escalations` queue (`EscalationQueuePage`) with an "L1 escalations" section, backed by a new `GET /l1/escalations`. Each row: problem statement, walked-path summary, who escalated, when, reason category. Pollable; no dependency on the notification subsystem.
|
||||
|
||||
2. **Bell-badge notification (Finding 3 — three explicit changes).** The notification system is currently FlowPilot-specific:
|
||||
- `VALID_EVENTS` (`backend/app/schemas/notification.py`) has no `l1.session.escalated`. **Add it** to the set (and to the default `events_enabled` map).
|
||||
- `_build_notification_link` (`notification_service.py`) only knows `session.escalated → /pilot/{session_id}?pickup=true`. **Add** `l1.session.escalated → /escalations` and **add** a body template for the new event. The existing `session.escalated` event must NOT be reused — an L1 escalation has no ai_session and no `/pilot` pickup flow.
|
||||
- Default recipients (`_resolve_recipients`, ~line 184) are owner/admin/team_admin only — ordinary **engineers are excluded**. Since L1 escalations must reach engineers who can pick them up, the call **must pass explicit `target_user_ids`** = the account's active `engineer`-role users (plus owner/admin), not rely on the default set.
|
||||
|
||||
**Still deferred** (documented, not built): PSA ticket reassign, escalation-package markdown generation, AI chat handoff/session creation.
|
||||
|
||||
## 8. Data model & migrations
|
||||
|
||||
**Migration 1 — `ai_build` session kind.**
|
||||
- Extend `l1_walk_sessions` `ck_l1_walk_sessions_session_kind` CHECK to include `'ai_build'`.
|
||||
- Extend `ck_l1_walk_sessions_target_consistency`: for `ai_build`, both `flow_id` and `flow_proposal_id` are NULL (same as `adhoc`).
|
||||
|
||||
**Migration 2 — account L1 category settings.**
|
||||
- Add `accounts.enabled_l1_categories` `JSONB NOT NULL DEFAULT '<default allowlist>'::jsonb` (list of category keys). RLS already covers `accounts`.
|
||||
|
||||
**Migration 3 — FlowProposal L1 source linkage (Finding 1).**
|
||||
- Add `flow_proposals.l1_session_id` nullable FK → `l1_walk_sessions.id` (`ondelete=SET NULL`, indexed).
|
||||
- Make `flow_proposals.source_session_id` **nullable** (was `NOT NULL`).
|
||||
- Add CHECK `((source_session_id IS NOT NULL) <> (l1_session_id IS NOT NULL))` — exactly one source.
|
||||
- Confirm `trees.source_session_id` is nullable (L1-promoted trees leave it NULL); if not, drop its NOT NULL here.
|
||||
|
||||
No new tables — live build state rides on the existing `l1_walk_sessions.walked_path`; persisted trees ride on `FlowProposal.proposed_flow_data`.
|
||||
|
||||
## 9. API surface
|
||||
|
||||
| Method | Path | Notes | Auth |
|
||||
|---|---|---|---|
|
||||
| POST | `/l1/intake` | **Extended**: now runs `match_or_build`; response carries `outcome` (`matched`/`suggest`/`out_of_scope`/`build`). | `require_l1_or_coverage` |
|
||||
| POST | `/l1/sessions/{id}/next-node` | **New**: record answer/ack on current node, generate + return next node (or terminal). | `require_l1_or_coverage` |
|
||||
| GET | `/accounts/me/l1-categories` | **New**: list enabled + available categories + hard-floor (read-only) list. | `require_l1_or_above` (read) |
|
||||
| PATCH | `/accounts/me/l1-categories` | **New**: set enabled categories. | `require_account_owner_or_admin` (Finding 6) |
|
||||
| GET | `/l1/escalations` | **New** (or extend `/escalations`): engineer-visible escalated-from-L1 list. | `require_engineer_or_admin` |
|
||||
|
||||
**Finding 6 — new auth dep.** The category control is an owner/admin setting, but `require_engineer_or_admin` also admits `engineer`. No existing dep matches "owner or account-admin" (`require_account_owner` is owner-only; `require_admin` is super-admin-only). Add `require_account_owner_or_admin` to `deps.py`: allow `super_admin` bypass, then `account_role in ('owner', 'admin')`, else 403. Use it for the PATCH.
|
||||
|
||||
## 10. Frontend
|
||||
|
||||
- `L1WalkTreeVariant` — replace synthetic stepping with real node rendering driven by `/next-node`; render `question` (yes/no), `instruction` (acknowledge), `resolved`/`escalate` (terminal). Per-node loading affordance. Disclaimer banner mounted for `ai_build` sessions.
|
||||
- `L1Dashboard` intake handler — dispatch on `match_or_build` `outcome` (suggest prompt, out-of-scope prompt, build → walker).
|
||||
- New admin settings panel (under `/account`) — toggle enabled L1 categories; show hard-floor list as read-only "always excluded."
|
||||
- Engineer escalations surface — "L1 escalations" section/list.
|
||||
|
||||
## 11. Testing strategy
|
||||
|
||||
**Backend unit:**
|
||||
- `ai_tree_builder.generate_next_node` — returns valid node per type; escalate-early when path is deep / model signals exhaustion; regenerate-then-escalate on malformed/forbidden output; depth cap forces escalate.
|
||||
- Per-node validation — forbidden-action patterns rejected; hard-floor enforced even if a category is enabled.
|
||||
- `match_or_build` — all four outcomes at threshold boundaries (`score == MATCH_THRESHOLD`, `== SUGGEST_THRESHOLD`); **match runs before the category gate** (a matched published flow is returned even when its category is disabled — Finding 4); `force_build` skips match but still applies the category gate; `out_of_scope` only on the build path when category disabled/unknown.
|
||||
- `classify` — known categories map correctly; unknown → out_of_scope.
|
||||
- `normalize_walked_path` (Finding 5) — produces a dict with a root `id`; untraversed `question` branches become `needs_review` stubs; output passes the `_create_tree_from_proposal` validity guard.
|
||||
- Flywheel capture — resolve creates `ai_realtime_l1` proposal with `l1_session_id` set and `source_session_id` NULL (Finding 1); CHECK accepts exactly-one-source; dedupe merges near-duplicate.
|
||||
- Escalation handoff — `l1.session.escalated` accepted by the notification schema (Finding 3); link resolves to `/escalations`; explicit engineer `target_user_ids` receive it; escalated session appears in `GET /l1/escalations`.
|
||||
|
||||
**Backend integration:**
|
||||
- Full intake→build→resolve creates an outcome-validated proposal.
|
||||
- Intake→build→escalate notifies engineers and surfaces in the escalations list.
|
||||
- Migrations roundtrip; `ai_build` CHECK + target-consistency hold.
|
||||
|
||||
**Frontend e2e (extend `l1-workspace.spec.ts`):**
|
||||
- L1 intake with no match → AI build → answer nodes → resolve → proposal created.
|
||||
- L1 build → escalate node → escalate handoff.
|
||||
- Admin toggles a category off → that problem class returns out-of-scope.
|
||||
|
||||
**AI quality (plan-time):** small eval set of common L1 problems; assert trees stay in-scope, reach resolution or escalate cleanly, never emit hard-floor actions. Benchmark Sonnet vs Opus for the model-tier decision.
|
||||
|
||||
## 12. Risks & open questions
|
||||
|
||||
- **Hallucinated-but-plausible steps** for niche/company-specific apps. Mitigation: classification gate + constrained prompt + escalate-early + disclaimer. Residual risk accepted for v1; eval set bounds it.
|
||||
- **Latency on a live call.** Node-by-node means ~2–4s per branch. Mitigation: Sonnet, small per-node token budget, clear loading affordance. Benchmark at plan time.
|
||||
- **Coherence across independently-generated nodes.** Mitigation: full walked-path context every call.
|
||||
- **Classification accuracy.** A misclassify could wrongly gate a valid problem out, or let a borderline one through. Mitigation: hard floor is category-independent; out-of-scope still offers adhoc/escalate (no dead end).
|
||||
- **Open (product, for spec review):** the default category allowlist (§5.2) and the hard-floor list (§5.1) — confirm/edit. Model tier — confirm Sonnet pending benchmark.
|
||||
|
||||
## 13. Out of scope (restated)
|
||||
KB ingestion + connectors, RAG grounding, PSA reassign, escalation-package generation, AI chat handoff. Each is its own later phase with its own spec.
|
||||
|
||||
**Also deferred (surfaced in review):**
|
||||
- **Matching against unpromoted `FlowProposal`s** (Finding 2). `flow_matching_engine` matches published flows only. Extending it to also surface outcome-validated drafts before promotion is a later enhancement; Phase 2A relies on engineer promotion (draft → published flow → matchable).
|
||||
|
||||
## 14. Review revisions (2026-05-29 Codex review)
|
||||
All six findings verified against code and resolved in this spec:
|
||||
1. **Blocker — FlowProposal source linkage:** §6.2 + §8 Migration 3 (new nullable `l1_session_id`, `source_session_id` made nullable, exactly-one CHECK, review-UI link change).
|
||||
2. **High — match scope:** §3 (match published flows only; proposal-matching deferred §13).
|
||||
3. **High — escalation notification:** §7 (engineer surface is primary; three explicit notification-system changes enumerated).
|
||||
4. **Medium — gate ordering:** §3 + §5 Layer 1 (match first; category gate only on the build path).
|
||||
5. **Medium — flywheel tree shape:** §6.1 (`normalize_walked_path` produces a valid tree with root `id`; unexplored branches → `needs_review` stubs).
|
||||
6. **Medium — category write auth:** §9 (new `require_account_owner_or_admin` dep; `require_engineer_or_admin` was too broad).
|
||||
@@ -7,7 +7,7 @@ test.describe('authentication smoke tests', () => {
|
||||
test('team admin can sign in through the login form', async ({ page }) => {
|
||||
await signIn(page)
|
||||
|
||||
await expect(page).toHaveURL(/\/home$/)
|
||||
await expect(page).toHaveURL(/\/$/)
|
||||
await expect(page.getByTestId('app-shell')).toBeVisible()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -4,7 +4,7 @@ test.use({ storageState: { cookies: [], origins: [] } })
|
||||
|
||||
test.describe('public route smoke tests', () => {
|
||||
test('landing page loads', async ({ page }) => {
|
||||
await page.goto('/')
|
||||
await page.goto('/landing')
|
||||
|
||||
await expect(
|
||||
page.getByRole('link', { name: 'Start Free', exact: true }),
|
||||
@@ -17,7 +17,7 @@ test.describe('public route smoke tests', () => {
|
||||
test('protected routes redirect unauthenticated users to landing', async ({ page }) => {
|
||||
await page.goto('/sessions')
|
||||
|
||||
await expect(page).toHaveURL(/\/$/)
|
||||
await expect(page).toHaveURL(/\/landing$/)
|
||||
await expect(
|
||||
page.getByRole('link', { name: 'Sign In' }),
|
||||
).toBeVisible()
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
User-agent: *
|
||||
Allow: /
|
||||
Allow: /terms
|
||||
Allow: /policies
|
||||
Allow: /privacy
|
||||
Allow: /contact
|
||||
Allow: /contact-sales
|
||||
Allow: /pricing
|
||||
Allow: /promotions
|
||||
Allow: /templates
|
||||
Disallow: /home
|
||||
Disallow: /trees/
|
||||
Disallow: /my-trees
|
||||
Disallow: /pilot/
|
||||
Disallow: /admin/
|
||||
Disallow: /account/
|
||||
Disallow: /script-builder
|
||||
Disallow: /scripts
|
||||
Disallow: /sessions
|
||||
Disallow: /analytics
|
||||
Disallow: /escalations
|
||||
Disallow: /queue
|
||||
Disallow: /review-queue
|
||||
Disallow: /network-diagrams
|
||||
Disallow: /kb-accelerator
|
||||
Disallow: /step-library
|
||||
Disallow: /tickets
|
||||
Disallow: /shares
|
||||
Disallow: /feedback
|
||||
Disallow: /welcome
|
||||
Disallow: /flow-assist
|
||||
Disallow: /dev/
|
||||
Disallow: /flows/
|
||||
Disallow: /guides
|
||||
|
||||
Sitemap: https://resolutionflow.com/sitemap.xml
|
||||
@@ -1,57 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
<url>
|
||||
<loc>https://resolutionflow.com/</loc>
|
||||
<lastmod>2026-05-13</lastmod>
|
||||
<changefreq>weekly</changefreq>
|
||||
<priority>1.0</priority>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://resolutionflow.com/pricing</loc>
|
||||
<lastmod>2026-05-13</lastmod>
|
||||
<changefreq>monthly</changefreq>
|
||||
<priority>0.9</priority>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://resolutionflow.com/contact-sales</loc>
|
||||
<lastmod>2026-05-13</lastmod>
|
||||
<changefreq>monthly</changefreq>
|
||||
<priority>0.8</priority>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://resolutionflow.com/contact</loc>
|
||||
<lastmod>2026-05-13</lastmod>
|
||||
<changefreq>monthly</changefreq>
|
||||
<priority>0.7</priority>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://resolutionflow.com/templates</loc>
|
||||
<lastmod>2026-05-13</lastmod>
|
||||
<changefreq>weekly</changefreq>
|
||||
<priority>0.7</priority>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://resolutionflow.com/terms</loc>
|
||||
<lastmod>2026-05-13</lastmod>
|
||||
<changefreq>yearly</changefreq>
|
||||
<priority>0.4</priority>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://resolutionflow.com/privacy</loc>
|
||||
<lastmod>2026-05-13</lastmod>
|
||||
<changefreq>yearly</changefreq>
|
||||
<priority>0.4</priority>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://resolutionflow.com/policies</loc>
|
||||
<lastmod>2026-05-13</lastmod>
|
||||
<changefreq>yearly</changefreq>
|
||||
<priority>0.4</priority>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://resolutionflow.com/promotions</loc>
|
||||
<lastmod>2026-05-13</lastmod>
|
||||
<changefreq>monthly</changefreq>
|
||||
<priority>0.4</priority>
|
||||
</url>
|
||||
</urlset>
|
||||
@@ -5,8 +5,6 @@ interface PageMetaProps {
|
||||
description?: string
|
||||
ogImage?: string
|
||||
ogType?: string
|
||||
/** Canonical/Open Graph URL. Defaults to `window.location.href` in the browser. */
|
||||
url?: string
|
||||
}
|
||||
|
||||
const SITE_NAME = 'ResolutionFlow'
|
||||
@@ -22,12 +20,8 @@ export function PageMeta({
|
||||
description = DEFAULT_DESCRIPTION,
|
||||
ogImage,
|
||||
ogType = 'website',
|
||||
url,
|
||||
}: PageMetaProps) {
|
||||
const fullTitle = title ? `${title} | ${SITE_NAME}` : `${SITE_NAME} — ${DEFAULT_TAGLINE}`
|
||||
const resolvedUrl =
|
||||
url ?? (typeof window !== 'undefined' ? window.location.href : undefined)
|
||||
const twitterCard = ogImage ? 'summary_large_image' : 'summary'
|
||||
|
||||
return (
|
||||
<Helmet>
|
||||
@@ -39,11 +33,10 @@ export function PageMeta({
|
||||
<meta property="og:description" content={description} />
|
||||
<meta property="og:type" content={ogType} />
|
||||
<meta property="og:site_name" content={SITE_NAME} />
|
||||
{resolvedUrl && <meta property="og:url" content={resolvedUrl} />}
|
||||
{ogImage && <meta property="og:image" content={ogImage} />}
|
||||
|
||||
{/* Twitter */}
|
||||
<meta name="twitter:card" content={twitterCard} />
|
||||
<meta name="twitter:card" content="summary" />
|
||||
<meta name="twitter:title" content={fullTitle} />
|
||||
<meta name="twitter:description" content={description} />
|
||||
{ogImage && <meta name="twitter:image" content={ogImage} />}
|
||||
|
||||
@@ -79,7 +79,7 @@ export function pickNextStep(
|
||||
title: 'Run your first FlowPilot session',
|
||||
description: 'Paste a ticket or pick a flow to see ResolutionFlow in action.',
|
||||
ctaLabel: 'Start a session',
|
||||
ctaPath: '/home',
|
||||
ctaPath: '/',
|
||||
}
|
||||
}
|
||||
if (!status.connected_psa) {
|
||||
|
||||
@@ -51,7 +51,7 @@ export function buildChecklistItems(
|
||||
{
|
||||
key: 'ran_session',
|
||||
label: 'Run your first FlowPilot session',
|
||||
path: '/home',
|
||||
path: '/',
|
||||
done: status.ran_session,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -42,7 +42,7 @@ export function L1WalkTreeVariant({ session, onSessionUpdate, onDone }: Props) {
|
||||
|
||||
const lastError = (err: unknown): string => {
|
||||
if (typeof err === 'object' && err && 'response' in err) {
|
||||
const detail = (err as { response?: { data?: { detail?: string } } }).response?.data?.detail
|
||||
const detail = (err as any).response?.data?.detail
|
||||
if (typeof detail === 'string') return detail
|
||||
}
|
||||
return 'Unexpected error'
|
||||
|
||||
@@ -58,7 +58,7 @@ export function AppLayout() {
|
||||
}
|
||||
|
||||
const mobileNavItems = [
|
||||
{ path: '/home', label: 'Dashboard', icon: LayoutGrid },
|
||||
{ path: '/', label: 'Dashboard', icon: LayoutGrid },
|
||||
{ path: '/sessions', label: 'Session History', icon: Clock },
|
||||
{ path: '/escalations', label: 'Escalations', icon: AlertTriangle },
|
||||
{ path: '/trees', label: 'Guided Flows', icon: GitBranch },
|
||||
@@ -106,7 +106,7 @@ export function AppLayout() {
|
||||
style={{ background: 'var(--color-bg-sidebar)', borderRight: '1px solid var(--color-border-default)' }}
|
||||
>
|
||||
<div className="flex h-14 items-center justify-between px-4" style={{ borderBottom: '1px solid var(--color-border-default)' }}>
|
||||
<Link to="/home" className="flex items-center gap-2.5">
|
||||
<Link to="/" className="flex items-center gap-2.5">
|
||||
<BrandLogo size="sm" />
|
||||
<span className="text-sm font-heading font-bold text-text-heading">ResolutionFlow</span>
|
||||
</Link>
|
||||
|
||||
@@ -40,7 +40,7 @@ interface Group {
|
||||
}
|
||||
|
||||
const PAGES: PaletteItem[] = [
|
||||
{ id: 'page-dashboard', group: 'pages', title: 'Dashboard', path: '/home', icon: 'page' },
|
||||
{ id: 'page-dashboard', group: 'pages', title: 'Dashboard', path: '/', icon: 'page' },
|
||||
{ id: 'page-flows', group: 'pages', title: 'All Flows', subtitle: 'Browse your flow library', path: '/trees', icon: 'page' },
|
||||
{ id: 'page-sessions', group: 'pages', title: 'Sessions', subtitle: 'View session history', path: '/sessions', icon: 'page' },
|
||||
{ id: 'page-flowpilot', group: 'pages', title: 'FlowPilot', subtitle: 'AI troubleshooting', path: '/pilot', icon: 'page' },
|
||||
|
||||
@@ -22,7 +22,7 @@ export function ProtectedRoute({ requiredRole, children }: ProtectedRouteProps)
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return <Navigate to="/" state={{ from: location }} replace />
|
||||
return <Navigate to="/landing" state={{ from: location }} replace />
|
||||
}
|
||||
|
||||
// Enforce must_change_password — redirect unless already on /change-password
|
||||
@@ -30,24 +30,6 @@ export function ProtectedRoute({ requiredRole, children }: ProtectedRouteProps)
|
||||
return <Navigate to="/change-password" replace />
|
||||
}
|
||||
|
||||
// L1 techs are confined to their focused surface. The sidebar only exposes
|
||||
// /l1*, /guides, and /account for them, so any other authed path (the engineer
|
||||
// dashboard at /home, /pilot, /trees/*, /escalations, …) bounces to /l1. This
|
||||
// also covers post-login landing: auth sends users to /home, which is not in
|
||||
// the allowlist, so l1_tech users end up on /l1. Engineer-only AI surfaces
|
||||
// (/pilot, /assistant) would 403 at POST /api/v1/ai-sessions anyway — this
|
||||
// turns that backend error into a clean redirect. Runs before the requiredRole
|
||||
// check so L1 users never trip the engineer-route role logic.
|
||||
if (effectiveRole === 'l1_tech') {
|
||||
const L1_ALLOWED_PREFIXES = ['/l1', '/guides', '/account', '/change-password']
|
||||
const allowed = L1_ALLOWED_PREFIXES.some(
|
||||
(p) => location.pathname === p || location.pathname.startsWith(p + '/'),
|
||||
)
|
||||
if (!allowed) {
|
||||
return <Navigate to="/l1" replace />
|
||||
}
|
||||
}
|
||||
|
||||
if (requiredRole) {
|
||||
const ROLE_HIERARCHY: Record<EffectiveRole, number> = {
|
||||
super_admin: 5,
|
||||
@@ -61,6 +43,12 @@ export function ProtectedRoute({ requiredRole, children }: ProtectedRouteProps)
|
||||
}
|
||||
}
|
||||
|
||||
// L1 users landing on / (e.g. post-login) get redirected to their workspace.
|
||||
// Does not fire when already on /l1 or any other path, preventing loops.
|
||||
if (effectiveRole === 'l1_tech' && location.pathname === '/') {
|
||||
return <Navigate to="/l1" replace />
|
||||
}
|
||||
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
|
||||
@@ -256,7 +256,6 @@ export function Sidebar() {
|
||||
: 'text-text-rail-label hover:text-foreground'
|
||||
)}
|
||||
title={item.label}
|
||||
aria-label={item.label}
|
||||
>
|
||||
<span className="relative">
|
||||
<Icon size={24} strokeWidth={1.6} className={active ? 'opacity-100' : 'opacity-60 group-hover:opacity-85'} />
|
||||
|
||||
@@ -63,7 +63,7 @@ export function TopBar() {
|
||||
>
|
||||
{/* Logo area */}
|
||||
<Link
|
||||
to="/home"
|
||||
to="/"
|
||||
className="flex items-center gap-2.5 pr-4 transition-all duration-200"
|
||||
>
|
||||
<BrandLogo size="sm" />
|
||||
|
||||
@@ -71,11 +71,11 @@ const FROZEN_NOW = new Date('2026-05-06T00:00:00Z')
|
||||
|
||||
function renderAppLayout() {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={['/home']}>
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<Routes>
|
||||
<Route element={<AppLayout />}>
|
||||
<Route
|
||||
path="/home"
|
||||
index
|
||||
element={<div data-testid="child-route-content">child route</div>}
|
||||
/>
|
||||
</Route>
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom'
|
||||
|
||||
import { ProtectedRoute } from '../ProtectedRoute'
|
||||
import { useAuthStore } from '@/store/authStore'
|
||||
|
||||
/**
|
||||
* Probe component: surfaces the current pathname and `location.state.from` so
|
||||
* the test can assert both the redirect target and that the original
|
||||
* destination is preserved for post-login return.
|
||||
*/
|
||||
function LocationProbe() {
|
||||
const loc = useLocation()
|
||||
const from =
|
||||
(loc.state as { from?: { pathname?: string } } | null)?.from?.pathname ?? ''
|
||||
return (
|
||||
<>
|
||||
<div data-testid="probe-pathname">{loc.pathname}</div>
|
||||
<div data-testid="probe-from">{from}</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
describe('ProtectedRoute — unauthenticated redirect', () => {
|
||||
beforeEach(() => {
|
||||
useAuthStore.setState({
|
||||
user: null,
|
||||
token: null,
|
||||
isAuthenticated: false,
|
||||
isLoading: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('redirects unauthenticated visits to /home → / and preserves origin in state.from', () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/home']}>
|
||||
<Routes>
|
||||
<Route
|
||||
path="/home"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<div data-testid="home-content">home</div>
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route path="/" element={<LocationProbe />} />
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
)
|
||||
|
||||
// The protected page should not render.
|
||||
expect(screen.queryByTestId('home-content')).not.toBeInTheDocument()
|
||||
|
||||
// We landed on / (the public landing route), not /landing.
|
||||
expect(screen.getByTestId('probe-pathname')).toHaveTextContent('/')
|
||||
expect(screen.getByTestId('probe-from')).toHaveTextContent('/home')
|
||||
})
|
||||
})
|
||||
@@ -237,22 +237,8 @@ export function AccountSettingsPage() {
|
||||
const invitesData = await accountsApi.getInvites()
|
||||
setInvites(invitesData)
|
||||
} catch (err) {
|
||||
const resp = (err as {
|
||||
response?: {
|
||||
status?: number
|
||||
data?: { detail?: { code?: string; role?: string; current?: number; limit?: number } }
|
||||
}
|
||||
}).response
|
||||
if (resp?.status === 402 && resp?.data?.detail?.code === 'seat_limit_exceeded') {
|
||||
const d = resp.data.detail
|
||||
const label = d.role === 'l1_tech' ? 'L1' : 'Engineer'
|
||||
toast.warning(
|
||||
`${label} seats full: ${d.current}/${d.limit}. Upgrade your plan to add more.`,
|
||||
)
|
||||
} else {
|
||||
toast.error('Failed to send invitation')
|
||||
console.error(err)
|
||||
}
|
||||
toast.error('Failed to send invitation')
|
||||
console.error(err)
|
||||
} finally {
|
||||
setIsInviting(false)
|
||||
}
|
||||
|
||||
@@ -2416,7 +2416,7 @@ export default function AssistantChatPage() {
|
||||
setShowConclude(false)
|
||||
if (activeSessionStatus === 'escalated') {
|
||||
toast.info('Session escalated. Heading back to your dashboard.')
|
||||
navigate('/home')
|
||||
navigate('/')
|
||||
}
|
||||
}}
|
||||
onConclude={handleConclude}
|
||||
|
||||
@@ -7,7 +7,7 @@ export default function ContactPage() {
|
||||
<PageMeta title="Contact" description="Contact ResolutionFlow customer service, sales, billing, or security." />
|
||||
<div className="min-h-screen bg-background text-foreground">
|
||||
<div className="mx-auto max-w-3xl px-6 py-16">
|
||||
<Link to="/" className="text-sm text-muted-foreground hover:text-foreground mb-8 inline-block">← Back to home</Link>
|
||||
<Link to="/landing" className="text-sm text-muted-foreground hover:text-foreground mb-8 inline-block">← Back to home</Link>
|
||||
<h1 className="text-3xl font-bold font-heading mb-4">Contact ResolutionFlow</h1>
|
||||
<p className="text-muted-foreground mb-10">
|
||||
We respond to customer inquiries Monday through Friday during U.S. business hours, excluding federal holidays. Email is the fastest path to a response.
|
||||
|
||||
@@ -112,10 +112,10 @@ export function OAuthCallbackPage() {
|
||||
|
||||
// Invitee path lands on the dashboard with the teammate-welcome
|
||||
// marker; new self-serve owners go to the welcome wizard; returning
|
||||
// users to /home.
|
||||
let dest = '/home'
|
||||
// users to /.
|
||||
let dest = '/'
|
||||
if (decoded?.accountInviteCode) {
|
||||
dest = '/home?welcome=teammate'
|
||||
dest = '/?welcome=teammate'
|
||||
} else if (result.is_new_user) {
|
||||
dest = '/welcome'
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ export default function PoliciesPage() {
|
||||
<PageMeta title="Customer Policies" description="ResolutionFlow customer service, billing, refunds, cancellation, legal restrictions, and promotional terms." />
|
||||
<div className="min-h-screen bg-background text-foreground">
|
||||
<div className="mx-auto max-w-3xl px-6 py-16">
|
||||
<Link to="/" className="text-sm text-muted-foreground hover:text-foreground mb-8 inline-block">← Back to home</Link>
|
||||
<Link to="/landing" className="text-sm text-muted-foreground hover:text-foreground mb-8 inline-block">← Back to home</Link>
|
||||
<h1 className="text-3xl font-bold font-heading mb-4">Customer Policies</h1>
|
||||
<p className="text-muted-foreground mb-2">Last updated: May 7, 2026</p>
|
||||
<p className="text-muted-foreground mb-2"><strong className="text-foreground">Operator:</strong> ResolutionFlow, LLC (the “Company”), operator of ResolutionFlow (“Service”).</p>
|
||||
|
||||
@@ -7,7 +7,7 @@ export default function PrivacyPage() {
|
||||
<PageMeta title="Privacy Policy" description="ResolutionFlow Privacy Policy" />
|
||||
<div className="min-h-screen bg-background text-foreground">
|
||||
<div className="mx-auto max-w-3xl px-6 py-16">
|
||||
<Link to="/" className="text-sm text-muted-foreground hover:text-foreground mb-8 inline-block">← Back to home</Link>
|
||||
<Link to="/landing" className="text-sm text-muted-foreground hover:text-foreground mb-8 inline-block">← Back to home</Link>
|
||||
<h1 className="text-3xl font-bold font-heading mb-8">Privacy Policy</h1>
|
||||
<p className="text-muted-foreground mb-6">Last updated: March 21, 2026</p>
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ export default function PromotionsPage() {
|
||||
<PageMeta title="Promotions" description="Active ResolutionFlow promotional offers and their terms." />
|
||||
<div className="min-h-screen bg-background text-foreground">
|
||||
<div className="mx-auto max-w-3xl px-6 py-16">
|
||||
<Link to="/" className="text-sm text-muted-foreground hover:text-foreground mb-8 inline-block">← Back to home</Link>
|
||||
<Link to="/landing" className="text-sm text-muted-foreground hover:text-foreground mb-8 inline-block">← Back to home</Link>
|
||||
<h1 className="text-3xl font-bold font-heading mb-4">Promotions</h1>
|
||||
<p className="text-muted-foreground mb-10">Last updated: May 7, 2026</p>
|
||||
|
||||
|
||||
@@ -168,7 +168,7 @@ export default function PublicTemplatesPage() {
|
||||
{/* Header */}
|
||||
<header className="sticky top-0 z-40 border-b border-border bg-background/80">
|
||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">
|
||||
<Link to="/" className="flex items-center gap-2.5">
|
||||
<Link to="/landing" className="flex items-center gap-2.5">
|
||||
<BrandLogo size="sm" />
|
||||
<span className="font-heading text-lg font-semibold">
|
||||
<span className="text-foreground">Resolution</span>
|
||||
@@ -406,7 +406,7 @@ export default function PublicTemplatesPage() {
|
||||
<footer className="border-t border-border py-8 px-4 sm:px-6 lg:px-8">
|
||||
<div className="max-w-7xl mx-auto flex items-center justify-between">
|
||||
<Link
|
||||
to="/"
|
||||
to="/landing"
|
||||
className="text-muted-foreground text-sm hover:text-foreground transition-colors"
|
||||
>
|
||||
Powered by <span className="font-semibold">ResolutionFlow</span>
|
||||
|
||||
@@ -423,7 +423,7 @@ export default function SessionHistoryPage() {
|
||||
description="Start a FlowPilot or chat session to begin. All your sessions will appear here."
|
||||
action={
|
||||
<Link
|
||||
to="/home"
|
||||
to="/"
|
||||
className="inline-flex items-center gap-2 rounded-lg bg-primary px-5 py-2.5 text-sm font-semibold text-white hover:brightness-110 active:scale-[0.98] transition-all"
|
||||
>
|
||||
Start a Session
|
||||
|
||||
@@ -7,7 +7,7 @@ export default function TermsPage() {
|
||||
<PageMeta title="Terms of Service" description="ResolutionFlow Terms of Service" />
|
||||
<div className="min-h-screen bg-background text-foreground">
|
||||
<div className="mx-auto max-w-3xl px-6 py-16">
|
||||
<Link to="/" className="text-sm text-muted-foreground hover:text-foreground mb-8 inline-block">← Back to home</Link>
|
||||
<Link to="/landing" className="text-sm text-muted-foreground hover:text-foreground mb-8 inline-block">← Back to home</Link>
|
||||
<h1 className="text-3xl font-bold font-heading mb-8">Terms of Service</h1>
|
||||
<p className="text-muted-foreground mb-6">Last updated: March 21, 2026</p>
|
||||
|
||||
|
||||
@@ -20,7 +20,8 @@ const SUCCESS_REDIRECT_MS = 1200
|
||||
* "Already verified" state. No API call.
|
||||
* - Else fire `POST /auth/email/verify` exactly once (a `useRef` guard keeps
|
||||
* React 19 strict-mode double-invoke from double-firing the call). On
|
||||
* success, refresh the auth store and bounce to `/home`.
|
||||
* success, refresh the auth store and bounce to `/?verified=1` so the
|
||||
* dashboard surfaces a toast.
|
||||
* - On error, show "Invalid or expired token" + a "Resend" CTA that calls
|
||||
* `POST /auth/email/send-verification`.
|
||||
*/
|
||||
@@ -69,9 +70,10 @@ export function VerifyEmailPage() {
|
||||
if (cancelled) return
|
||||
setStatus('success')
|
||||
toast.success('Email verified')
|
||||
// Brief success state, then redirect to the dashboard.
|
||||
// Brief success state, then redirect with a query flag so the
|
||||
// dashboard can re-surface confirmation if it wants to.
|
||||
window.setTimeout(() => {
|
||||
navigate('/home', { replace: true })
|
||||
navigate('/?verified=1', { replace: true })
|
||||
}, SUCCESS_REDIRECT_MS)
|
||||
})
|
||||
.catch((err) => {
|
||||
@@ -124,7 +126,7 @@ export function VerifyEmailPage() {
|
||||
Redirecting you to the dashboard…
|
||||
</p>
|
||||
<Link
|
||||
to="/home"
|
||||
to="/?verified=1"
|
||||
replace
|
||||
className={cn(
|
||||
'mt-6 inline-flex items-center rounded-lg bg-primary px-6 py-2 text-sm font-semibold text-primary-foreground',
|
||||
@@ -147,7 +149,7 @@ export function VerifyEmailPage() {
|
||||
action needed.
|
||||
</p>
|
||||
<Link
|
||||
to="/home"
|
||||
to="/"
|
||||
className={cn(
|
||||
'mt-6 inline-flex items-center rounded-lg bg-primary px-6 py-2 text-sm font-semibold text-primary-foreground',
|
||||
'hover:brightness-110',
|
||||
@@ -179,7 +181,7 @@ export function VerifyEmailPage() {
|
||||
Resend verification email
|
||||
</button>
|
||||
<Link
|
||||
to="/home"
|
||||
to="/"
|
||||
className={cn(
|
||||
'inline-flex items-center justify-center rounded-lg border border-default bg-input px-6 py-2 text-sm font-medium text-foreground',
|
||||
'hover:border-border-hover',
|
||||
@@ -202,7 +204,7 @@ export function VerifyEmailPage() {
|
||||
Try the link in your verification email again.
|
||||
</p>
|
||||
<Link
|
||||
to="/home"
|
||||
to="/"
|
||||
className={cn(
|
||||
'mt-6 inline-flex items-center rounded-lg bg-primary px-6 py-2 text-sm font-semibold text-primary-foreground',
|
||||
'hover:brightness-110',
|
||||
|
||||
@@ -52,7 +52,7 @@ function renderPage(initialPath: string) {
|
||||
<MemoryRouter initialEntries={[initialPath]}>
|
||||
<Routes>
|
||||
<Route path="/verify-email" element={<VerifyEmailPage />} />
|
||||
<Route path="/home" element={<div>dashboard</div>} />
|
||||
<Route path="/" element={<div>dashboard</div>} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</HelmetProvider>,
|
||||
@@ -130,7 +130,7 @@ describe('VerifyEmailPage', () => {
|
||||
<MemoryRouter initialEntries={['/verify-email?token=valid-token']}>
|
||||
<Routes>
|
||||
<Route path="/verify-email" element={<VerifyEmailPage />} />
|
||||
<Route path="/home" element={<div>dashboard</div>} />
|
||||
<Route path="/" element={<div>dashboard</div>} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</HelmetProvider>,
|
||||
@@ -142,7 +142,7 @@ describe('VerifyEmailPage', () => {
|
||||
<MemoryRouter initialEntries={['/verify-email?token=valid-token']}>
|
||||
<Routes>
|
||||
<Route path="/verify-email" element={<VerifyEmailPage />} />
|
||||
<Route path="/home" element={<div>dashboard</div>} />
|
||||
<Route path="/" element={<div>dashboard</div>} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</HelmetProvider>,
|
||||
|
||||
@@ -3,7 +3,6 @@ import { useNavigate } from 'react-router-dom'
|
||||
import { PageMeta } from '@/components/common/PageMeta'
|
||||
import { useAuthStore } from '@/store/authStore'
|
||||
import { l1Api } from '@/api/l1'
|
||||
import { toast } from '@/lib/toast'
|
||||
import { EmptyStateCard } from '@/components/l1/EmptyStateCard'
|
||||
import { ResumeInProgress } from '@/components/l1/ResumeInProgress'
|
||||
import type { QueueRow } from '@/types/l1'
|
||||
@@ -47,11 +46,6 @@ export default function L1Dashboard() {
|
||||
customer_contact: customerContact.trim() || undefined,
|
||||
})
|
||||
navigate(`/l1/walk/${response.session_id}`)
|
||||
} catch (err) {
|
||||
const detail = (err as { response?: { data?: { detail?: string } } }).response?.data?.detail
|
||||
const msg =
|
||||
typeof detail === 'string' ? detail : 'Failed to start walk. Try again.'
|
||||
toast.error(msg)
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
|
||||
@@ -6,8 +6,8 @@ import { PageLoader } from '@/components/common/PageLoader'
|
||||
* `/welcome` index — redirect to the next incomplete step (or `/` if done /
|
||||
* dismissed). Decision table:
|
||||
*
|
||||
* onboarding_dismissed === true → /home
|
||||
* onboarding_step_completed >= 3 → /home
|
||||
* onboarding_dismissed === true → /
|
||||
* onboarding_step_completed >= 3 → /
|
||||
* onboarding_step_completed === null/0 → /welcome/step-1
|
||||
* onboarding_step_completed === 1 → /welcome/step-2
|
||||
* onboarding_step_completed === 2 → /welcome/step-3
|
||||
@@ -19,10 +19,10 @@ export function WelcomeRouter() {
|
||||
// the page loader rather than racing past the redirect.
|
||||
if (!user) return <PageLoader />
|
||||
|
||||
if (user.onboarding_dismissed) return <Navigate to="/home" replace />
|
||||
if (user.onboarding_dismissed) return <Navigate to="/" replace />
|
||||
|
||||
const completed = user.onboarding_step_completed ?? 0
|
||||
if (completed >= 3) return <Navigate to="/home" replace />
|
||||
if (completed >= 3) return <Navigate to="/" replace />
|
||||
if (completed === 2) return <Navigate to="/welcome/step-3" replace />
|
||||
if (completed === 1) return <Navigate to="/welcome/step-2" replace />
|
||||
return <Navigate to="/welcome/step-1" replace />
|
||||
|
||||
@@ -85,7 +85,7 @@ export function WelcomeStep1() {
|
||||
try {
|
||||
await onboardingApi.dismissRest()
|
||||
await fetchUser()
|
||||
navigate('/home')
|
||||
navigate('/')
|
||||
} catch {
|
||||
setError('Could not save. Please try again.')
|
||||
setSubmitting(null)
|
||||
|
||||
@@ -90,7 +90,7 @@ export function WelcomeStep2() {
|
||||
try {
|
||||
await onboardingApi.dismissRest()
|
||||
await fetchUser()
|
||||
navigate('/home')
|
||||
navigate('/')
|
||||
} catch {
|
||||
setError('Could not save. Please try again.')
|
||||
setSubmitting(null)
|
||||
|
||||
@@ -39,7 +39,7 @@ function makeEmptyRow(): InviteRow {
|
||||
*
|
||||
* 1. POST `/accounts/me/invites/bulk` with populated rows.
|
||||
* 2. PATCH `/users/me/onboarding-step` `{step: 3, action: "complete"}`.
|
||||
* 3. Navigate to `/home` and fire a "You're all set" toast.
|
||||
* 3. Navigate to `/?welcome=true` and fire a "You're all set" toast.
|
||||
*
|
||||
* Partial-failure UX: rows in `failed[]` keep their input and show an
|
||||
* inline error. The wizard does NOT auto-advance when there are failures —
|
||||
@@ -109,7 +109,7 @@ export function WelcomeStep3() {
|
||||
await onboardingApi.updateStep({ step: 3, action: 'complete' })
|
||||
await fetchUser()
|
||||
toast.success("You're all set!")
|
||||
navigate('/home')
|
||||
navigate('/?welcome=true')
|
||||
}
|
||||
|
||||
const handleSendInvites = async () => {
|
||||
@@ -177,7 +177,7 @@ export function WelcomeStep3() {
|
||||
await onboardingApi.updateStep({ step: 3, action: 'skip' })
|
||||
await fetchUser()
|
||||
toast.success("You're all set!")
|
||||
navigate('/home')
|
||||
navigate('/?welcome=true')
|
||||
} catch {
|
||||
setError('Could not save. Please try again.')
|
||||
setSubmitting(null)
|
||||
@@ -191,7 +191,7 @@ export function WelcomeStep3() {
|
||||
try {
|
||||
await onboardingApi.dismissRest()
|
||||
await fetchUser()
|
||||
navigate('/home')
|
||||
navigate('/')
|
||||
} catch {
|
||||
setError('Could not save. Please try again.')
|
||||
setSubmitting(null)
|
||||
|
||||
@@ -39,7 +39,7 @@ function renderRouter() {
|
||||
<Route path="/welcome/step-1" element={<div>step-1</div>} />
|
||||
<Route path="/welcome/step-2" element={<div>step-2</div>} />
|
||||
<Route path="/welcome/step-3" element={<div>step-3</div>} />
|
||||
<Route path="/home" element={<div>dashboard</div>} />
|
||||
<Route path="/" element={<div>dashboard</div>} />
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
)
|
||||
@@ -100,7 +100,7 @@ describe('WelcomeRouter', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('redirects to /home when onboarding_step_completed >= 3', async () => {
|
||||
it('redirects to / when onboarding_step_completed >= 3', async () => {
|
||||
useAuthStore.setState({
|
||||
user: makeUser({ onboarding_step_completed: 3 }),
|
||||
})
|
||||
@@ -110,7 +110,7 @@ describe('WelcomeRouter', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('redirects to /home when onboarding_dismissed is true', async () => {
|
||||
it('redirects to / when onboarding_dismissed is true', async () => {
|
||||
useAuthStore.setState({
|
||||
user: makeUser({
|
||||
onboarding_step_completed: 1,
|
||||
|
||||
@@ -65,7 +65,7 @@ function renderPage() {
|
||||
<Routes>
|
||||
<Route path="/welcome/step-1" element={<WelcomeStep1 />} />
|
||||
<Route path="/welcome/step-2" element={<div>step-2</div>} />
|
||||
<Route path="/home" element={<div>dashboard</div>} />
|
||||
<Route path="/" element={<div>dashboard</div>} />
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
)
|
||||
@@ -148,7 +148,7 @@ describe('WelcomeStep1', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('Skip-the-rest dismisses and navigates to /home', async () => {
|
||||
it('Skip-the-rest dismisses and navigates to /', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderPage()
|
||||
|
||||
|
||||
@@ -66,7 +66,7 @@ function renderPage() {
|
||||
<Route path="/welcome/step-2" element={<WelcomeStep2 />} />
|
||||
<Route path="/welcome/step-3" element={<div>step-3</div>} />
|
||||
<Route path="/account/integrations" element={<div>integrations</div>} />
|
||||
<Route path="/home" element={<div>dashboard</div>} />
|
||||
<Route path="/" element={<div>dashboard</div>} />
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
)
|
||||
@@ -158,7 +158,7 @@ describe('WelcomeStep2', () => {
|
||||
expect(screen.queryByTestId('welcome-step-2-connect-now')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('Skip-the-rest dismisses and navigates to /home', async () => {
|
||||
it('Skip-the-rest dismisses and navigates to /', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderPage()
|
||||
|
||||
|
||||
@@ -88,7 +88,7 @@ function renderPage() {
|
||||
<MemoryRouter initialEntries={['/welcome/step-3']}>
|
||||
<Routes>
|
||||
<Route path="/welcome/step-3" element={<WelcomeStep3 />} />
|
||||
<Route path="/home" element={<div>dashboard</div>} />
|
||||
<Route path="/" element={<div>dashboard</div>} />
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
)
|
||||
|
||||
@@ -7,7 +7,6 @@ import { RouteError } from '@/components/common/RouteError'
|
||||
import { ErrorBoundary } from '@/components/common/ErrorBoundary'
|
||||
import { PageLoader } from '@/components/common/PageLoader'
|
||||
import { lazyWithRetry } from '@/lib/lazyWithRetry'
|
||||
import { useAuthStore } from '@/store/authStore'
|
||||
import { L1RouteGuard } from '@/components/layout/L1RouteGuard'
|
||||
|
||||
const sentryCreateBrowserRouter = Sentry.wrapCreateBrowserRouterV7(createBrowserRouter)
|
||||
@@ -126,27 +125,10 @@ function page(Component: React.LazyExoticComponent<React.ComponentType>) {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Public `/` wrapper — sends authenticated users to /home before LandingPage
|
||||
* mounts, so they never see marketing-frame flicker.
|
||||
*/
|
||||
// eslint-disable-next-line react-refresh/only-export-components -- router.tsx exports a router instance, not a component
|
||||
function PublicLanding() {
|
||||
const isAuthed = useAuthStore((s) => s.isAuthenticated)
|
||||
if (isAuthed) return <Navigate to="/home" replace />
|
||||
return page(LandingPage)
|
||||
}
|
||||
|
||||
export const router = sentryCreateBrowserRouter([
|
||||
{
|
||||
path: '/',
|
||||
element: <PublicLanding />,
|
||||
errorElement: <RouteError />,
|
||||
},
|
||||
// Stale-bookmark redirect — keep one release, delete in a follow-up.
|
||||
{
|
||||
path: '/landing',
|
||||
element: <Navigate to="/" replace />,
|
||||
element: page(LandingPage),
|
||||
errorElement: <RouteError />,
|
||||
},
|
||||
{
|
||||
@@ -254,6 +236,7 @@ export const router = sentryCreateBrowserRouter([
|
||||
errorElement: <RouteError />,
|
||||
},
|
||||
{
|
||||
path: '/',
|
||||
element: (
|
||||
<ProtectedRoute>
|
||||
<AppLayout />
|
||||
@@ -261,61 +244,61 @@ export const router = sentryCreateBrowserRouter([
|
||||
),
|
||||
errorElement: <RouteError />,
|
||||
children: [
|
||||
{ path: '/home', element: page(QuickStartPage) },
|
||||
{ path: '/trees', element: page(TreeLibraryPage) },
|
||||
{ path: '/my-trees', element: page(MyTreesPage) },
|
||||
{ path: '/trees/new', element: page(TreeEditorPage) },
|
||||
{ path: '/trees/:id/edit', element: page(TreeEditorPage) },
|
||||
{ path: '/flows/new', element: page(ProceduralEditorPage) },
|
||||
{ path: '/flows/:id/edit', element: page(ProceduralEditorPage) },
|
||||
{ path: '/flows/:id/navigate', element: page(ProceduralNavigationPage) },
|
||||
{ path: '/flows/:id/maintenance', element: page(MaintenanceFlowDetailPage) },
|
||||
{ path: '/flows/:id/batches/:batchId', element: page(BatchStatusPage) },
|
||||
{ path: '/trees/:id/navigate', element: page(TreeNavigationPage) },
|
||||
{ path: '/sessions', element: page(SessionHistoryPage) },
|
||||
{ path: '/sessions/:id', element: page(SessionDetailPage) },
|
||||
{ path: '/tickets', element: page(TicketsPage) },
|
||||
{ path: '/shares', element: page(MySharesPage) },
|
||||
{ path: '/analytics', element: page(TeamAnalyticsPage) },
|
||||
{ path: '/analytics/me', element: page(MyAnalyticsPage) },
|
||||
{ path: '/feedback', element: page(FeedbackPage) },
|
||||
{ path: '/step-library', element: page(StepLibraryPage) },
|
||||
{ path: '/scripts', element: page(ScriptLibraryPage) },
|
||||
{ path: '/scripts/manage', element: page(ScriptManagePage) },
|
||||
{ path: '/script-builder', element: page(ScriptBuilderPage) },
|
||||
{ path: '/network-diagrams', element: page(NetworkDiagramsPage) },
|
||||
{ path: '/network-diagrams/new', element: page(DiagramEditorPage) },
|
||||
{ path: '/network-diagrams/:id', element: page(DiagramEditorPage) },
|
||||
{ path: '/kb-accelerator', element: page(KBAcceleratorPage) },
|
||||
{ index: true, element: page(QuickStartPage) },
|
||||
{ path: 'trees', element: page(TreeLibraryPage) },
|
||||
{ path: 'my-trees', element: page(MyTreesPage) },
|
||||
{ path: 'trees/new', element: page(TreeEditorPage) },
|
||||
{ path: 'trees/:id/edit', element: page(TreeEditorPage) },
|
||||
{ path: 'flows/new', element: page(ProceduralEditorPage) },
|
||||
{ path: 'flows/:id/edit', element: page(ProceduralEditorPage) },
|
||||
{ path: 'flows/:id/navigate', element: page(ProceduralNavigationPage) },
|
||||
{ path: 'flows/:id/maintenance', element: page(MaintenanceFlowDetailPage) },
|
||||
{ path: 'flows/:id/batches/:batchId', element: page(BatchStatusPage) },
|
||||
{ path: 'trees/:id/navigate', element: page(TreeNavigationPage) },
|
||||
{ path: 'sessions', element: page(SessionHistoryPage) },
|
||||
{ path: 'sessions/:id', element: page(SessionDetailPage) },
|
||||
{ path: 'tickets', element: page(TicketsPage) },
|
||||
{ path: 'shares', element: page(MySharesPage) },
|
||||
{ path: 'analytics', element: page(TeamAnalyticsPage) },
|
||||
{ path: 'analytics/me', element: page(MyAnalyticsPage) },
|
||||
{ path: 'feedback', element: page(FeedbackPage) },
|
||||
{ path: 'step-library', element: page(StepLibraryPage) },
|
||||
{ path: 'scripts', element: page(ScriptLibraryPage) },
|
||||
{ path: 'scripts/manage', element: page(ScriptManagePage) },
|
||||
{ path: 'script-builder', element: page(ScriptBuilderPage) },
|
||||
{ path: 'network-diagrams', element: page(NetworkDiagramsPage) },
|
||||
{ path: 'network-diagrams/new', element: page(DiagramEditorPage) },
|
||||
{ path: 'network-diagrams/:id', element: page(DiagramEditorPage) },
|
||||
{ path: 'kb-accelerator', element: page(KBAcceleratorPage) },
|
||||
// Phase 1 — FlowPilot migration. The unified chat-primary surface lives at
|
||||
// /pilot; /assistant permanently redirects. FlowPilotSessionPage (old
|
||||
// guided surface) is no longer mounted.
|
||||
{ path: '/pilot', element: page(AssistantChatPage) },
|
||||
{ path: '/pilot/:sessionId', element: page(AssistantChatPage) },
|
||||
{ path: '/assistant', element: <Navigate to="/pilot" replace /> },
|
||||
{ path: '/assistant/:sessionId', element: <AssistantSessionRedirect /> },
|
||||
{ path: '/flow-assist', element: page(FlowAssistPage) },
|
||||
{ path: '/escalations', element: page(EscalationQueuePage) },
|
||||
{ path: '/queue', element: page(SessionQueuePage) },
|
||||
{ path: '/review-queue', element: page(ReviewQueuePage) },
|
||||
{ path: '/analytics/flowpilot', element: page(FlowPilotAnalyticsPage) },
|
||||
{ path: '/dev/branching', element: page(DevBranchingPage) },
|
||||
{ path: '/guides', element: page(GuidesHubPage) },
|
||||
{ path: '/guides/:slug', element: page(GuideDetailPage) },
|
||||
{ path: 'pilot', element: page(AssistantChatPage) },
|
||||
{ path: 'pilot/:sessionId', element: page(AssistantChatPage) },
|
||||
{ path: 'assistant', element: <Navigate to="/pilot" replace /> },
|
||||
{ path: 'assistant/:sessionId', element: <AssistantSessionRedirect /> },
|
||||
{ path: 'flow-assist', element: page(FlowAssistPage) },
|
||||
{ path: 'escalations', element: page(EscalationQueuePage) },
|
||||
{ path: 'queue', element: page(SessionQueuePage) },
|
||||
{ path: 'review-queue', element: page(ReviewQueuePage) },
|
||||
{ path: 'analytics/flowpilot', element: page(FlowPilotAnalyticsPage) },
|
||||
{ path: 'dev/branching', element: page(DevBranchingPage) },
|
||||
{ path: 'guides', element: page(GuidesHubPage) },
|
||||
{ path: 'guides/:slug', element: page(GuideDetailPage) },
|
||||
// Welcome wizard (Phase 2). Mounted inside AppLayout so the email-
|
||||
// verification banner persists above each step.
|
||||
{ path: '/welcome', element: page(WelcomeRouter) },
|
||||
{ path: '/welcome/step-1', element: page(WelcomeStep1) },
|
||||
{ path: '/welcome/step-2', element: page(WelcomeStep2) },
|
||||
{ path: '/welcome/step-3', element: page(WelcomeStep3) },
|
||||
{ path: 'welcome', element: page(WelcomeRouter) },
|
||||
{ path: 'welcome/step-1', element: page(WelcomeStep1) },
|
||||
{ path: 'welcome/step-2', element: page(WelcomeStep2) },
|
||||
{ path: 'welcome/step-3', element: page(WelcomeStep3) },
|
||||
// L1 workspace routes — gated by canUseL1Surface
|
||||
{ path: '/l1', element: <L1RouteGuard>{page(L1Dashboard)}</L1RouteGuard> },
|
||||
{ path: '/l1/walk/:sessionId', element: <L1RouteGuard>{page(L1WalkPage)}</L1RouteGuard> },
|
||||
{ path: '/l1/drafts', element: <L1RouteGuard>{page(L1DraftsPage)}</L1RouteGuard> },
|
||||
{ path: '/l1/tickets', element: <L1RouteGuard>{page(L1TicketsPage)}</L1RouteGuard> },
|
||||
{ path: 'l1', element: <L1RouteGuard>{page(L1Dashboard)}</L1RouteGuard> },
|
||||
{ path: 'l1/walk/:sessionId', element: <L1RouteGuard>{page(L1WalkPage)}</L1RouteGuard> },
|
||||
{ path: 'l1/drafts', element: <L1RouteGuard>{page(L1DraftsPage)}</L1RouteGuard> },
|
||||
{ path: 'l1/tickets', element: <L1RouteGuard>{page(L1TicketsPage)}</L1RouteGuard> },
|
||||
// Admin routes
|
||||
{
|
||||
path: '/admin',
|
||||
path: 'admin',
|
||||
element: (
|
||||
<ErrorBoundary>
|
||||
<Suspense fallback={<PageLoader />}>
|
||||
@@ -344,7 +327,7 @@ export const router = sentryCreateBrowserRouter([
|
||||
},
|
||||
// Account routes
|
||||
{
|
||||
path: '/account',
|
||||
path: 'account',
|
||||
element: (
|
||||
<ErrorBoundary>
|
||||
<Suspense fallback={<PageLoader />}>
|
||||
|
||||
Reference in New Issue
Block a user