# Route Starter and Essential Loki Queries Through Regional System Logs

This ExecPlan is a living document. Keep `Progress`, `Surprises & Discoveries`,
`Decision Log`, and `Outcomes & Retrospective` current while implementing it.

Reference: `PLANS.md` at the repository root. Maintain this plan according to
that document. The approved design is
`docs/2026-08-17-starter-essential-loki-routing-design.md`.

## Purpose / Big Picture

Today, `clinic loki query --cluster-id <id>` sends Starter and Essential
queries through a logical-cluster compatibility proxy that cannot see shared
regional platform logs. After this change, exact Starter and Essential clusters
select Clinic's canonical regional system-log datasource from provider and
region metadata, then execute a physically scoped LogQL query against that
datasource. A user can observe the change with `--verbose`: the request path
contains `/data-proxy/api/v1/system-log-datasources/{uid}/logs/query-range`
instead of `/data-proxy/loki/{logicalClusterID}/api/v1/query_range`.

Exact Essential V2, Essential V2 resource pool, Premium, BYOC, Dedicated, and
all other deploy types retain their existing behavior.

## Execution Protocol (Mandatory)

Execute subtasks sequentially. Use a fresh, non-inherited subagent for each
subtask; never run implementation subtasks concurrently. The parent agent
reviews and integrates each result, and each subtask ends at a dedicated commit
before another subtask begins. Update `Progress` immediately after each commit.

This plan contains one implementation subtask because the route resolver,
command integration, tests, and user documentation form one atomic behavior and
are expected to remain near the repository's roughly 500-line subtask target.
After its commit, use separate fresh subagents for specification compliance and
code-quality review. Review agents do not edit or commit.

operator prompt template:

`Implement docs/2026-08-17-starter-essential-loki-routing-plan.md using fresh non-inherited subagents per subtask, sequentially, with parent review/integration, one commit per subtask, and Progress updates after each subtask commit.`

## Progress

- [x] (2026-08-17) Approved and reviewed the routing design.
- [x] (2026-08-17) Subtask 1 RED: added the complete routing, selector-safety, failure, regression, help, and RawPath test matrix and observed feature-specific failures before production edits.
- [x] (2026-08-17) Subtask 1 GREEN: implemented authoritative metadata hydration, exact tier selection, fail-closed datasource resolution, safe regional request routing, and RawPath transport support; focused tests pass.
- [x] (2026-08-17) Subtask 1 REFACTOR: kept route selection and catalog validation in `internal/cmd/loki_route.go`, reused existing query execution/render/retry helpers, and updated help plus user/agent documentation.
- [x] (2026-08-17) Committed Subtask 1 with focused and full verification evidence using `feat(loki): route starter essential system logs`.
- [x] (2026-08-17) Review fix RED: added Cobra-level backtick raw-string/template cases and observed selector misclassification before changing the scanner.
- [x] (2026-08-17) Review fix GREEN: the scanner now skips terminated backtick raw strings, rejects unterminated raw strings with cluster context before catalog/query traffic, and preserves raw suffixes byte-for-byte.
- [x] (2026-08-17) Comment-lexer review fix RED: added Cobra-level comment boundary, matcher, preservation, literal-hash, and fail-closed cases and observed comments being treated as executable LogQL.
- [x] (2026-08-17) Comment-lexer review fix GREEN: validation, matcher inspection, and regional default-label injection now share comment-aware selector boundaries; focused comment/backtick tests pass.
- [x] (2026-08-17) Ran the fresh comment/backtick matrix, full focused Loki and RawPath suites, `git diff --check`, and `make verify`; all exited zero before amending the feature commit.
- [x] (2026-08-17) Code-quality review fix RED: added focused missing-refresh-tier, regional-warning, encoded-base RawPath, and earliest-operator parser cases and observed all four defects before production edits.
- [x] (2026-08-17) Code-quality review fix GREEN: missing refreshed tiers fail closed, regional warnings retain physical-scope guidance, encoded base paths are preserved, and matcher parsing selects the earliest operator; focused tests pass.
- [x] (2026-08-17) Ran full `go test ./... -count=1`, `make verify`, and `git diff --check` after the four code-quality fixes; all exited zero before amending the feature commit.
- [x] (2026-08-17) Final sanity RED: added all-tier nonregional Cobra coverage and observed source-order matcher parsing remove the historical duplicate default augmentation for operator-bearing values.
- [x] (2026-08-17) Final sanity GREEN: source-order parsing is isolated to regional validation, injection, and warnings while every legacy helper again uses the baseline priority parser; focused regional and all-tier nonregional tests pass.
- [x] (2026-08-17) Ran the focused Loki suite, full `go test ./... -count=1`, `make verify`, and `git diff --check` after parser separation; all exited zero before amending the feature commit.
- [x] (2026-08-17) Completed specification-compliance review and final
  re-review with no open issues.
- [x] (2026-08-17) Completed code-quality review and final re-review with no
  open Critical, Important, or actionable Minor issues.
- [x] (2026-08-17) Ran final focused Loki and RawPath tests, `git diff --check`, and `make verify` from the committed clean worktree; all exited zero.

## Surprises & Discoveries

- Observation: Dashboard metadata for production Essential cluster
  `10215140423606474101` contains `clusterDeployTypeV2=essential`,
  `clusterProviderName=alicloud`, and `clusterRegionName=ap-northeast-1`, but
  `clusterDataPlaneName` and `parentID` are empty.
  Evidence: a bounded read-only Dashboard cluster lookup on 2026-08-17.
- Observation: The canonical system-log catalog maps that provider and region
  to `Loki-alicloud-ap-northeast-1`; the datasource-specific query route returns
  the expected `tidb-serverless` DM streams.
  Evidence: bounded read-only catalog and query requests on 2026-08-17.
- Observation: Selected profiles are considered complete without provider and
  region, so regional routing must refresh ephemeral Dashboard metadata rather
  than rely exclusively on the profile record.
  Evidence: `internal/cmd/cluster.go` profile completeness logic.
- Observation: Existing profile-less Loki unit fixtures that supplied only a
  query response no longer represented the query command's initial metadata
  resolution step.
  Evidence: the first focused GREEN run failed those fixtures with `resolve
  Loki routing metadata for cluster cluster-42: cluster not found`; adding an
  explicit Dedicated profile fixture restored their intended legacy-route
  scope without changing production fallback behavior.
- Observation: A non-success catalog status error needed to name the catalog
  contract explicitly, not only the returned status.
  Evidence: the follow-up RED assertion expected `contract` and failed against
  `system-log datasource catalog returned status "error"`; the corrected
  contextual error now passes the catalog failure matrix.
- Observation: The initial regional selector scanner skipped double-quoted
  strings but treated braces inside LogQL backtick raw strings as selectors.
  Evidence: positive Cobra tests failed with `contains a malformed selector`
  or `found 3 selectors`, while the unterminated-raw-string case also returned
  only the generic malformed-selector error.
- Observation: Treating every brace and comma outside strings as executable
  LogQL let selector-shaped comments affect selector counts and let a comma in
  a comment expose a commented `cluster="..."` matcher to the matcher parser.
  Evidence: the comment-only selector and commented-matcher RED cases reached
  catalog/query traffic, while a two-selector query was misreported as three.
- Observation: Matcher operator priority must not outrank source position: a
  later `=~`, `!=`, or `!~` inside a quoted value hid the earlier equality
  operator and caused both cluster rejection and duplicate default labels.
  Evidence: three physical-cluster value cases failed validation, while
  explicit scope values received duplicate `cluster_env` and `namespace`.
- Observation: The source-order fix cannot replace the shared legacy parser:
  nonregional augmentation and warning behavior historically depends on its
  operator-priority interpretation, even when that produces duplicate defaults.
  Evidence: Essential V2, its resource pool, Premium, BYOC, Dedicated, and an
  ordinary tier all stopped appending their historical defaults during RED.
- Observation: Joining decoded and escaped paths independently is insufficient
  when an encoded base path ends in `%2F`; the joined raw form intentionally
  decodes to a double slash even though decoded-path joining trims it.
  Evidence: the real `httptest` request stopped before transport with a
  decoded RawPath/Path mismatch for `/tenant%2Froot%2F`.

## Decision Log

- Decision: Use the canonical system-log datasource route, not the
  Serverless-parent `control_plane_info` route.
  Rationale: provider and region are available from Dashboard metadata and the
  canonical route is proven to return the requested streams; the CLI cannot
  safely derive `control_plane_info` from logical cluster metadata.
  Date/Author: 2026-08-17, user and Codex.
- Decision: Apply the new route only when normalized `clusterDeployTypeV2` is
  exactly `starter` or `essential`.
  Rationale: Essential V2 uses Premium behavior and must remain unchanged;
  prefix matching or the legacy `shared` field would route it incorrectly.
  Date/Author: 2026-08-17, user and Codex.
- Decision: Require exactly one LogQL selector with a non-empty equality
  `cluster="..."` matcher.
  Rationale: the regional datasource contains multiple physical clusters and
  logical cluster metadata cannot derive the physical pool label. Fail-closed
  validation prevents cross-cluster queries.
  Date/Author: 2026-08-17, user and Codex.
- Decision: Limit this change to `loki query`.
  Rationale: `instance-map`, labels, label-values, and diagnose cannot be safely
  isolated to one physical pool with available metadata and were not requested.
  Date/Author: 2026-08-17, user and Codex.

## Outcomes & Retrospective

Subtask 1 implementation is complete and matches the approved scope. Exact
normalized Starter and Essential queries now refresh Dashboard routing
metadata, reject unsafe physical-cluster scope before catalog traffic, select
one regional datasource by provider and region, inject the serverless namespace
when enabled, and reuse existing output and retry behavior without fallback.
Other tiers and other Loki command families retain their logical routes. The
focused Loki and RawPath suites and `make verify` pass. No live service was
called and no configuration or profile was modified outside isolated test
fixtures. The required post-commit specification and code-quality reviews are
complete with no open issues. Review findings for backtick raw strings, LogQL
comments, incomplete refreshed deploy metadata, regional warning guidance,
encoded base paths, and matcher operator parsing were fixed in the same
implementation commit with dedicated RED/GREEN coverage. The parent agent then
reran focused Loki and RawPath tests, the complete Go suite, `git diff --check`,
and `make verify` from the clean committed worktree. There is no implementation
divergence or known functional gap; intentionally omitted live API testing and
exhaustive LogQL fuzzing remain the only residual validation limits.

## Context and Orientation

The executable enters through `cmd/clinic/main.go`; Cobra command construction
is owned by `internal/cmd/`. `internal/cmd/loki.go` defines `loki query`, parses
time and selector arguments, injects default scope labels, constructs Clinic
HTTP requests, retries query-range gateway timeouts, and renders JSON or text.

`internal/cmd/cluster.go` resolves a `clusterReference`. Extend this ephemeral
reference with provider and region values read from Dashboard fields
`clusterProviderName` and `clusterRegionName`. Do not add persistent profile
fields in `internal/config/`.

The current query route is
`/data-proxy/loki/{clusterID}/api/v1/query_range`. The regional route requires a
datasource UID. Fetch the catalog from
`/data-proxy/api/v1/system-log-datasources`; its expected envelope is
`{"status":"success","data":{"datasources":[...]}}`, and each datasource has
`uid`, `provider`, and `region`. A query uses
`/data-proxy/api/v1/system-log-datasources/{path-escaped UID}/logs/query-range`.

The bundled user/agent guide is `skills/clinic-cli/SKILL.md`. User-facing command
examples and behavior are also documented in `README.md`, while the ownership
map is `docs/COMMAND_SURFACE.md`.

## Plan of Work

### Subtask 1: Implement safe regional routing for Starter and Essential query

Follow red-green-refactor strictly. Before production edits, add focused tests
under `internal/cmd/` that exercise real Cobra command execution against the
existing fake Clinic HTTP server patterns.

The RED tests must prove all of the following missing behavior:

- exact normalized `starter` and `essential` select regional routing;
- `essential v2`, `essential v2 resource pool`, Premium, and another ordinary
  tier keep the legacy logical-cluster path and current selector behavior;
- a selected Starter/Essential profile triggers Dashboard metadata hydration,
  and the refreshed exact-ID response becomes authoritative for deploy type as
  well as provider and region;
- a stale profile that says `starter` while Dashboard says `essential v2`
  retains the legacy route and current selector behavior;
- hydrated provider and region stay ephemeral: profile/config bytes are not
  changed by a query;
- provider and region matching is case-insensitive;
- omitted LogQL, `{}`, no `cluster` matcher, empty equality, regex, negative,
  and multi-selector LogQL are rejected before catalog or query-range traffic;
  each error identifies the selected cluster ID and the missing or unsafe
  physical-cluster matcher;
- refreshed metadata with a missing provider or region fails before the catalog
  request and identifies the cluster ID and missing field in the error;
- catalog responses with a malformed envelope, missing or non-`success`
  `status`, empty UID, no matching datasource, or multiple matches fail without
  hitting either query-range route; every error identifies the selected cluster
  ID, malformed/status errors identify the catalog contract, empty-UID errors
  identify that field, and no-match or ambiguity errors identify the requested
  provider and region;
- wrapped catalog and query HTTP failures remain discoverable through
  `errors.As(..., *clinic.HTTPError)` and their contextual messages identify the
  selected cluster ID plus the catalog provider/region or selected datasource;
- safe regional queries inject missing `cluster_env` and
  `namespace="tidb-serverless"`, while `--skip-namespace-injection` omits only
  the namespace;
- an existing explicit `cluster_env` and namespace remain unchanged;
- the regional request preserves start, end, limit, direction, output parsing,
  and the existing bounded 504 retry behavior;
- a regional failure never falls back to `/data-proxy/loki/{clusterID}`.

Run the focused RED suite and record the expected assertion failures in this
plan. Failures must demonstrate missing routing behavior, not syntax or fixture
errors.

Implement the minimum production behavior. Prefer a focused
`internal/cmd/loki_route.go` and matching tests for catalog decoding, tier
predicate, safe selector validation, metadata hydration, datasource selection,
and endpoint construction. Integrate it into `internal/cmd/loki.go` only in the
`query` path. Keep existing request execution, retry, and rendering helpers.

When the initial reference is exact Starter/Essential, refresh the exact
cluster through the Dashboard lookup even if a selected profile supplied tier
metadata. Validate that the refreshed cluster ID matches the requested ID, then
re-evaluate the routing predicate from the refreshed normalized
`clusterDeployTypeV2`. Only a refreshed exact `starter` or `essential` result
may enter regional selector validation or catalog resolution. A refreshed
Essential V2/Premium/other tier resumes the existing logical route unchanged.
For regional routing, require non-empty provider and region. Keep those values
ephemeral and do not write the selected profile or environment config. Preserve
Clinic HTTP errors through contextual wrapping.

Datasource selection compares provider and region case-insensitively and
requires exactly one match with a non-empty UID. Extend `clinic.Request` with an
optional `RawPath` paired with its decoded `Path`: build the decoded path with
the raw UID, build `RawPath` with only the UID segment passed through
`url.PathEscape`, and have `internal/clinic/client.go` set `url.URL.RawPath`
after validating that it unescapes to `url.URL.Path`. This prevents `%`
double-escaping and keeps a UID containing `/`, `?`, or `#` within one wire path
segment. Add an `internal/clinic` `httptest` that asserts `RequestURI` for such
a UID, not merely a fake client's `Request.Path`. Do not assemble query strings
by concatenation. Never print or return authentication material.

After GREEN, refactor only to remove real duplication or improve ownership.
Update `loki query` help, the contract in `internal/cmd/help_test.go`,
`README.md`, `docs/COMMAND_SURFACE.md`, and `skills/clinic-cli/SKILL.md`. Help
tests must assert that omitted LogQL and `{}` continue to be supported for
other tiers but are rejected for Starter/Essential, which require one exact
physical `cluster="..."` matcher and route regionally. Essential V2/Premium
remain unchanged.

Run focused tests, `gofmt` on changed Go files, `git diff --check`, and
`make verify`. Update this plan's Progress, evidence, discoveries, and outcome,
then commit all Subtask 1 changes with a descriptive feature commit.

## Concrete Steps

Work from repository root:

`/Users/jujiajia/.config/superpowers/worktrees/clinic-cli/starter-essential-loki-routing`

First inspect existing conventions:

    sed -n '1,760p' internal/cmd/loki.go
    sed -n '360,700p' internal/cmd/cluster.go
    rg -n 'system-log-datasources|query_range|query-range|HTTPError|httptest' internal/cmd internal/clinic

Write the RED tests, then run:

    go test ./internal/cmd -run 'Loki.*(Starter|Essential|Regional|Datasource|PhysicalCluster)' -count=1 -v
    go test ./internal/clinic -run 'RawPath' -count=1 -v

Expected before implementation: tests compile and fail because requests still
use `/data-proxy/loki/{clusterID}/api/v1/query_range`, regional validation is
absent, or datasource failures are not handled.

Implement the minimum behavior, format, and rerun:

    gofmt -w internal/cmd/loki*.go internal/cmd/cluster*.go internal/clinic/*.go
    go test ./internal/cmd -run 'Loki' -count=1 -v
    go test ./internal/clinic -run 'RawPath' -count=1 -v

Expected after implementation: all Loki-focused tests pass with no panic or
unexpected stderr.

Run the full verification ladder:

    git diff --check
    make verify

Expected: every command exits zero. If `make verify` changes generated or
formatted files, inspect them and include only changes required by this feature.

Commit Subtask 1:

    git add internal/cmd internal/clinic README.md docs/COMMAND_SURFACE.md skills/clinic-cli/SKILL.md docs/2026-08-17-starter-essential-loki-routing-plan.md
    git commit -m "feat(loki): route starter essential system logs"

## Validation and Acceptance

Acceptance is behavioral:

- With an exact Starter/Essential metadata fixture and safe LogQL, verbose test
  evidence shows catalog lookup followed by a datasource-specific
  `/logs/query-range` request.
- No request uses the logical cluster Loki route for Starter/Essential after
  regional routing is selected.
- Unsafe or unscoped Starter/Essential LogQL sends no catalog or log query.
- Exact Essential V2 and Essential V2 resource-pool fixtures show unchanged
  `/data-proxy/loki/{clusterID}/api/v1/query_range` behavior.
- All focused tests and `make verify` pass.
- Help and documentation describe the tier-specific requirement without
  claiming automatic physical-pool discovery.

An optional live read-only check may be run only after automated tests pass and
must use bounded time, low limit, JSON output, and no secret output. It is not a
substitute for automated verification.

## Idempotence and Recovery

All tests, formatters, and verification commands are safe to rerun. Dashboard
and catalog test traffic uses local fake HTTP servers. No production state is
mutated.

If the RED test fails because of a fixture or compilation error, fix the test
until it fails on the missing behavior before editing production code. If the
regional implementation fails, do not add fallback to the logical route; keep
the descriptive error and correct metadata or catalog handling. Use normal Git
reverts for the single feature commit if rollback is required; never reset or
discard unrelated changes.

## Artifacts and Notes

Baseline before implementation:

    go test ./...
    ok github.com/tidbcloud/clinic-cli/internal/cmd
    ok github.com/tidbcloud/clinic-cli/internal/clinic
    ok github.com/tidbcloud/clinic-cli/internal/config
    ... all packages passed

Design review approved the exact-selector fail-closed rule, profile metadata
refresh, catalog validation contract, omitted-query UX, and Essential V2
regression matrix.

RED evidence recorded before production edits:

    go test ./internal/cmd -run 'Loki.*(Starter|Essential|Regional|Datasource|PhysicalCluster)' -count=1 -v
    --- FAIL: TestLokiQueryStarterEssentialRegionalRouting
        request count = 1, want 3; paths=[/data-proxy/loki/cluster-42/api/v1/query_range]
    --- FAIL: TestLokiQueryRegionalSelectorValidation
        lokiCommandHandler() error = nil, want selector validation error
    --- FAIL: TestLokiQueryRegionalDatasourceCatalogFailuresFailClosed
        lokiCommandHandler() error = nil, want catalog validation error

    go test ./internal/clinic -run 'RawPath' -count=1 -v
    --- FAIL: TestClientRawPathPreservesEscapedDynamicPathSegment
        clinic.Request.RawPath is missing

    go test ./internal/cmd -run 'TestLokiGeneratedHelp' -count=1 -v
    --- FAIL: TestLokiGeneratedHelp
        help output missing "Omitted LogQL and {} remain supported for non-Starter/Essential tiers."

These failures are the intended RED state: the existing command issued the
legacy logical-cluster query directly, accepted unsafe regional selectors,
never validated the datasource catalog, exposed no RawPath contract, and did
not document the tier-specific behavior. The unchanged Essential V2,
Essential V2 resource-pool, Premium, BYOC, Dedicated, and ordinary-tier
regression subtests passed in this RED run.

GREEN evidence before the subtask commit:

    go test ./internal/cmd -run 'Loki' -count=1
    ok github.com/tidbcloud/clinic-cli/internal/cmd

    go test ./internal/clinic -run 'RawPath' -count=1
    ok github.com/tidbcloud/clinic-cli/internal/clinic

    git diff --check
    # no output, exit 0

    make verify
    agent legibility checks passed
    ok github.com/tidbcloud/clinic-cli/internal/clinic
    ok github.com/tidbcloud/clinic-cli/internal/cmd
    ok github.com/tidbcloud/clinic-cli/internal/config
    ok github.com/tidbcloud/clinic-cli/internal/legendlabels
    ok github.com/tidbcloud/clinic-cli/internal/timeexpr

Review-fix RED evidence before the scanner edit:

    go test ./internal/cmd -run 'TestLokiQueryRegionalBacktick' -count=1 -v
    --- FAIL: .../line_format_template
        regional system-log query contains a malformed selector
    --- FAIL: .../raw_filter_containing_braces
        found 3 selectors
    --- FAIL: TestLokiQueryRegionalBacktickUnterminatedRawStringFailsClosed
        error missing expected substring "unterminated"

The command had already refreshed metadata, but every positive case stopped
before catalog/query traffic and the negative case lacked raw-string context,
isolating the gap to lexical scanning rather than route execution.

Review-fix GREEN evidence:

    go test ./internal/cmd -run 'TestLokiQueryRegionalBacktick' -count=1 -v
    --- PASS: TestLokiQueryRegionalBacktickRawStringsDoNotCountAsSelectors
    --- PASS: TestLokiQueryRegionalBacktickUnterminatedRawStringFailsClosed

    go test ./internal/cmd -run 'Loki' -count=1
    ok github.com/tidbcloud/clinic-cli/internal/cmd

    go test ./internal/clinic -run 'RawPath' -count=1
    ok github.com/tidbcloud/clinic-cli/internal/clinic

    git diff --check
    # no output, exit 0

    make verify
    agent legibility checks passed
    # all Go packages passed

Comment-lexer review-fix RED evidence before the production refactor:

    go test ./internal/cmd -run 'TestLokiQueryRegional(Comments|UnterminatedQuotedString)' -count=1 -v
    --- FAIL: .../leading_and_trailing_selector-shaped_comments
        regional system-log query contains an unterminated backtick raw string
    --- FAIL: .../comments_and_raw_strings_remain_byte-for-byte_unchanged
        regional system-log query contains a malformed selector
    --- FAIL: .../comment-only_selector_does_not_provide_scope
        lokiCommandHandler() error = nil
    --- FAIL: .../commented_cluster_matcher_does_not_provide_scope
        lokiCommandHandler() error = nil
    --- FAIL: .../comment_cannot_hide_a_second_executable_selector
        found 3 selectors, want found 2 selectors

    go test ./internal/cmd -run 'TestLokiQueryRegionalCommentsDoNotAffectSelectorLexing/leading' -count=1 -v
    --- FAIL: .../leading_and_trailing_selector-shaped_comments
        diagnostics contained an explicit cluster_env/namespace scope warning
        sourced only from a selector-shaped comment

The executable unterminated-quoted-string case passed during RED, confirming
that the existing fail-closed behavior remained intact while the failures
isolated missing comment lexing in selector discovery, matcher inspection, and
label injection. The follow-up warning assertion proved that regional explicit-
scope inspection also needed to consume the same validated matcher list rather
than independently locating the first arbitrary brace.

Comment-lexer review-fix GREEN evidence:

    go test ./internal/cmd -run 'TestLokiQueryRegional(Comments|UnterminatedQuotedString|Backtick)' -count=1 -v
    --- PASS: TestLokiQueryRegionalCommentsDoNotAffectSelectorLexing
    --- PASS: TestLokiQueryRegionalCommentsCannotProvideOrHideScope
    --- PASS: TestLokiQueryRegionalUnterminatedQuotedStringStillFailsClosed
    --- PASS: TestLokiQueryRegionalBacktickRawStringsDoNotCountAsSelectors
    --- PASS: TestLokiQueryRegionalBacktickUnterminatedRawStringFailsClosed

The positive cases reached the catalog and regional query route with exactly
the expected comment/string-preserving LogQL. Negative cases stopped after the
Dashboard metadata refresh with cluster-context validation errors.

Fresh full verification after the comment-lexer refactor:

    go test ./internal/cmd -run 'Loki' -count=1
    ok github.com/tidbcloud/clinic-cli/internal/cmd

    go test ./internal/clinic -run 'RawPath' -count=1
    ok github.com/tidbcloud/clinic-cli/internal/clinic

    git diff --check
    # no output, exit 0

    make verify
    agent legibility checks passed
    # all Go packages passed

Code-quality review-fix RED evidence before production edits:

    go test ./internal/cmd -run 'TestLokiQuery(StarterProfileRefreshMissingDeployType|RegionalClusterMatcherValuesContainingOperatorText|RegionalExplicitScope)' -count=1 -v
    --- FAIL: TestLokiQueryStarterProfileRefreshMissingDeployTypeFailsClosed
        lokiCommandHandler() error = nil
    --- FAIL: .../physical=~pool
        found 0 physical cluster matchers
    --- FAIL: .../physical!=pool
        found 0 physical cluster matchers
    --- FAIL: .../physical!~pool
        found 0 physical cluster matchers
    --- FAIL: TestLokiQueryRegionalExplicitScopeValuesContainingOperatorText
        duplicate cluster_env and namespace defaults were injected
    --- FAIL: TestLokiQueryRegionalExplicitScopeWarningUsesPhysicalClusterGuidance
        legacy --cluster-id and use {} guidance was emitted

    go test ./internal/clinic -run 'TestClientRawPathPreservesEncodedBasePath' -count=1 -v
    --- FAIL: .../trailing_encoded_slash
        decoded RawPath contained the preserved double slash while Path did not

The missing-tier case reached a logical legacy query instead of failing after
Dashboard refresh. The warning case reached the regional route but emitted
legacy guidance. The matcher failures isolated priority-based operator search,
and the real HTTP test isolated encoded-base joining before transport.

Code-quality review-fix focused GREEN evidence:

    go test ./internal/cmd -run 'TestLokiQuery(StarterProfileRefreshMissingDeployType|RegionalClusterMatcherValuesContainingOperatorText|RegionalExplicitScope)' -count=1 -v
    --- PASS: TestLokiQueryStarterProfileRefreshMissingDeployTypeFailsClosed
    --- PASS: TestLokiQueryRegionalClusterMatcherValuesContainingOperatorText
    --- PASS: TestLokiQueryRegionalExplicitScopeWarningUsesPhysicalClusterGuidance
    --- PASS: TestLokiQueryRegionalExplicitScopeValuesContainingOperatorText

    go test ./internal/clinic -run 'TestClientRawPath' -count=1 -v
    --- PASS: TestClientRawPathPreservesEscapedDynamicPathSegment
    --- PASS: TestClientRawPathPreservesEncodedBasePath
    --- PASS: TestClientRawPathRejectsMismatchedDecodedPath

The missing-tier and all validation failures stop before catalog or query
traffic. Regional warnings no longer name `--cluster-id` or `{}` and retain
wildcard context. Both encoded base-path forms reached the real test server
with exact RequestURI bytes.

Code-quality review-fix full GREEN evidence:

    go test ./internal/cmd -run 'Loki' -count=1
    ok github.com/tidbcloud/clinic-cli/internal/cmd

    go test ./internal/clinic -count=1
    ok github.com/tidbcloud/clinic-cli/internal/clinic

    go test ./... -count=1
    # all Go packages passed

    git diff --check
    # no output, exit 0

    make verify
    agent legibility checks passed
    # all Go packages passed

Final sanity RED evidence before separating the parsers:

    go test ./internal/cmd -run 'TestLokiQueryNonRegionalOperatorTextPreservesLegacyAugmentation' -count=1 -v
    --- FAIL: .../essential_v2
    --- FAIL: .../essential_v2_resource_pool
    --- FAIL: .../premium
    --- FAIL: .../BYOC
    --- FAIL: .../dedicated
    --- FAIL: .../other_tier

Each outbound legacy query retained only the explicit operator-bearing values,
but the byte-for-byte baseline appends `cluster_env="staging"` and the tier's
inferred namespace and emits no warning. This isolated the regression to the
shared parser rather than routing or namespace inference.

Final sanity focused GREEN evidence:

    go test ./internal/cmd -run 'TestLokiQueryNonRegionalOperatorTextPreservesLegacyAugmentation' -count=1 -v
    --- PASS: .../essential_v2
    --- PASS: .../essential_v2_resource_pool
    --- PASS: .../premium
    --- PASS: .../BYOC
    --- PASS: .../dedicated
    --- PASS: .../other_tier

    go test ./internal/cmd -run 'TestLokiQueryRegional(ClusterMatcherValuesContainingOperatorText|ExplicitScope)' -count=1 -v
    --- PASS: TestLokiQueryRegionalClusterMatcherValuesContainingOperatorText
    --- PASS: TestLokiQueryRegionalExplicitScopeWarningUsesPhysicalClusterGuidance
    --- PASS: TestLokiQueryRegionalExplicitScopeValuesContainingOperatorText

The nonregional requests now contain the exact historical duplicate default
augmentation and no diagnostics, while all regional operator-text cases retain
source-order validation, no duplicate defaults, and regional-only guidance.

Final sanity full GREEN evidence:

    go test ./internal/cmd -run 'Loki' -count=1
    ok github.com/tidbcloud/clinic-cli/internal/cmd

    go test ./... -count=1
    # all Go packages passed

    git diff --check
    # no output, exit 0

    make verify
    agent legibility checks passed
    # all Go packages passed

## Interfaces and Dependencies

Use only the Go standard library and existing repository packages. Do not add a
new module dependency.

The implementation should expose small internal interfaces equivalent to:

    func isRegionalServerlessLokiTier(deployTypeV2 string) bool

    func validateRegionalLokiQuery(query string) error

    func resolveSystemLogDatasource(ctx *RuntimeContext, clusterID, provider, region string) (string, error)

    func systemLogQueryRangePath(datasourceUID string) string

Names may follow stronger existing conventions discovered during implementation,
but responsibilities must remain separate: tier decision, selector safety,
catalog resolution, and URL construction. Extend the existing Clinic `Request`
HTTP abstraction with:

    RawPath string

`Path` remains the decoded request path. When `RawPath` is non-empty, the
client first verifies `url.PathUnescape(RawPath)` equals the request `Path`,
then joins it with the base URL's escaped path, derives the final decoded
`url.URL.Path` from that joined raw path, and assigns the joined value to
`url.URL.RawPath`. All existing callers that leave `RawPath` empty retain
byte-for-byte URL behavior.

Revision note, 2026-08-17: initial plan written from the approved and reviewed
design. No implementation has started.

Revision note, 2026-08-17: recorded the complete RED matrix and its failure
evidence, the implemented GREEN/refactor outcome, focused and repository-wide
verification evidence, and discoveries from updating legacy-route fixtures and
catalog-contract error context. Post-commit reviews remain pending.

Revision note, 2026-08-17: recorded and closed the specification review finding
for braces inside LogQL backtick raw strings, including positive format/filter
coverage, an unterminated-raw-string failure case, and fresh full verification.

Revision note, 2026-08-17: recorded and closed the specification re-review
finding for LogQL line comments by sharing comment-aware selector boundaries
across regional validation, matcher inspection, and default-label injection.

Revision note, 2026-08-17: recorded and closed the code-quality findings for
missing refreshed deploy types, regional physical-scope warning guidance,
encoded base-path RawPath joining, and source-order matcher operator parsing.

Revision note, 2026-08-17: restored byte-for-byte nonregional compatibility by
keeping the baseline priority parser on legacy paths and isolating source-order
operator parsing to regional validation, injection, and warning inspection.

Revision note, 2026-08-17: recorded final specification and code-quality
approvals plus the parent agent's clean-worktree verification evidence.
