# Profile-Centric Context + Cluster Cache Plan

This plan is a living execution document. Keep the progress checklist updated as each subtask advances.

## Execution Protocol (Mandatory)

Execute subtasks strictly one by one; do not run multiple plan subtasks concurrently.

For each subtask, use a fresh subagent session with non-inherited context and provide only the current subtask instructions plus minimal required repository context.

After each subtask, the parent agent must review/integrate the result, commit the subtask changes, and update the `Progress Tracker` before starting the next subtask.

If the runtime requires explicit delegation authorization, use this operator prompt template:

`Implement docs/2026-04-03-profile-context-cluster-cache-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.`

## Goal

Introduce a profile-centric runtime context for `clinic` that combines environment + optional cluster + optional range defaults, with explicit cached-cluster management and per-invocation overrides.

## Locked Decisions

- Naming: `profile` is the runtime context term.
- Global selector: `clinic --profile <name> ...`.
- Profile shape: partial profile (`env` required; `cluster-id`, `range-start`, `range-end` optional).
- Required-parameter precedence: `flag > env > profile`.
- Range scope: profile range applies to `metrics`, `loki`, and `events` commands.
- Cache ownership: profile-centric commands (`profile cluster ...`).
- Cache identity: cluster ID and optional alias.
- Cache refresh: on-demand refresh during explicit selection operations.
- Initial bootstrap: create `prod`/`staging`/`dev` profiles from existing env configuration.
- `env` command role: endpoint/auth management only.

## Progress Tracker

- [x] S1. Config schema + bootstrap migration.
- [x] S2. Root runtime profile selection and context plumbing.
- [x] S3. `profile` core commands (`list/current/use/set/delete`).
- [x] S4. `profile cluster` cache-management commands (`list/use/remove`).
- [x] S5. Shared resolver (`flag > env > profile`) for cluster/range defaults.
- [x] S6. Apply resolver to command families and events range integration.
- [x] S7. Cache-aware cluster metadata resolution.
- [x] S8. Docs/help/readme updates and full verification.

## Subtask Breakdown (LOC-Bounded)

### S1. Config schema + bootstrap migration

Estimated code change: 250-450 LOC.

Primary files:
- `internal/config/config.go`
- `internal/config/config_test.go`

Required changes:
- Extend `Config` with `active_profile`, `profiles`, and `cluster_cache` structures.
- Add typed structs for profile defaults and cached cluster records.
- Ensure `LoadOrInit()` bootstraps `prod/staging/dev` profiles when missing.
- Map initial `active_profile` from `active_env` when available.
- Preserve existing `environments` and `active_env` behavior for auth/env workflows.

Acceptance criteria:
- Existing config files load without manual migration.
- New config fields persist and round-trip correctly.
- Permission invariants remain unchanged (`0700` dir, `0600` file).

### S2. Root runtime profile selection and context plumbing

Estimated code change: 200-400 LOC.

Primary files:
- `internal/cmd/root.go`
- `internal/cmd/root_test.go`
- `internal/cmd/help.go`

Required changes:
- Replace global `--env` override parser with global `--profile` parser.
- Resolve selected profile at runtime, then resolve env from that profile.
- Extend `RuntimeContext` with selected profile/default data needed by command resolvers.
- Keep root error semantics clear for missing/unknown profile.

Acceptance criteria:
- `clinic --profile <name> ...` selects the profile for one invocation.
- Invocation without `--profile` uses `active_profile`.
- Root tests cover parse success/failure and fallback behavior.

### S3. `profile` core commands (`list/current/use/set/delete`)

Estimated code change: 300-500 LOC.

Primary files:
- `internal/cmd/profile.go` (new)
- `internal/cmd/help.go`
- `internal/cmd/help_test.go`
- `internal/cmd/profile_test.go` (new)

Required changes:
- Add new command family wired in root handler map.
- Implement profile listing/current profile output.
- Implement profile switching (`use`) and mutation (`set`) for env/cluster/range fields.
- Implement profile deletion with safety checks (cannot delete active profile unless first switched).
- Keep JSON output consistent with existing CLI style.

Acceptance criteria:
- Core profile commands work end-to-end against persisted config.
- Help text covers every new subcommand and expected flag usage.
- Tests verify success paths and key validation errors.

### S4. `profile cluster` cache-management commands

Estimated code change: 300-500 LOC.

Primary files:
- `internal/cmd/profile.go`
- `internal/cmd/profile_test.go`
- `internal/cmd/cluster.go` (shared lookup helpers reused)

Required changes:
- Implement `profile cluster list [--env <env>]`.
- Implement `profile cluster use --cluster-id <id> [--alias <alias>]`.
- Implement `profile cluster use --alias <alias>`.
- Implement `profile cluster remove (--cluster-id <id> | --alias <alias>)`.
- On explicit `use`, read cache first, fallback to remote lookup, refresh cached entry, and set active profile cluster default.

Acceptance criteria:
- Cache entries are env-scoped and stable across CLI runs.
- Alias lookup is deterministic within env scope.
- Explicit selection updates both cache and active profile defaults.

### S5. Shared resolver (`flag > env > profile`) for defaults

Estimated code change: 200-400 LOC.

Primary files:
- `internal/cmd/flag_env.go` (or new `internal/cmd/defaults.go`)
- `internal/cmd/env_fallback_test.go` (or new resolver-focused tests)

Required changes:
- Replace two-tier `requiredFlagOrEnv` logic with reusable 3-tier resolution.
- Support required values (`cluster-id`, `start`, `end`, `begin-ts`, `end-ts`) and optional variants.
- Preserve clear error messages for missing required flags after fallback exhaustion.

Acceptance criteria:
- Resolver unit tests validate exact precedence `flag > env > profile`.
- Existing env fallback tests remain valid or are updated with explicit profile cases.

### S6. Apply resolver to command families and events range integration

Estimated code change: 300-500 LOC.

Primary files:
- `internal/cmd/data.go`
- `internal/cmd/metrics.go`
- `internal/cmd/loki.go`
- `internal/cmd/events.go`
- `internal/cmd/cluster.go`
- `internal/cmd/*_test.go` in affected families

Required changes:
- Update all commands that currently require `cluster-id` and/or range fields to use shared resolver.
- Extend `events list` so `--begin-ts`/`--end-ts` can resolve via env/profile range defaults.
- Normalize resolved event range values to Unix seconds prior to request query encoding.

Acceptance criteria:
- Explicit flags always override env/profile defaults.
- Existing CLI env vars still work.
- Events command supports profile/env defaults for time range and passes tests.

### S7. Cache-aware cluster metadata resolution

Estimated code change: 200-450 LOC.

Primary files:
- `internal/cmd/cluster.go`
- `internal/cmd/loki.go`
- `internal/cmd/events.go`
- related tests in `cluster_test.go`, `loki_test.go`, `events_test.go`

Required changes:
- Update cluster reference resolution helpers to optionally use cached metadata before remote lookup.
- Keep exact-cluster-id matching guarantees when resolving org/parent/deploy-type metadata.
- Ensure cache miss or stale data falls back safely to current API-based flow.

Acceptance criteria:
- No regression for topology/loki/events org resolution behavior.
- Cache usage reduces repeated lookup calls where metadata is already available.
- Tests cover cache-hit and cache-miss paths.

### S8. Docs/help/readme updates and verification

Estimated code change: 200-350 LOC.

Primary files:
- `internal/cmd/help.go`
- `internal/cmd/help_test.go`
- `docs/COMMAND_SURFACE.md`
- `docs/ARCHITECTURE.md`
- `README.md`

Required changes:
- Update command usage strings to reflect global `--profile` and new `profile` command family.
- Document precedence (`flag > env > profile`) with examples.
- Document cache-management workflow and profile bootstrap behavior.

Acceptance criteria:
- Help snapshots/tests pass.
- Docs and README examples match actual command behavior.
- `make verify` passes.

## Surprises & Discoveries

- Observation: the config schema already had `ClusterCache` and `CachedClusterRecord`, so S4 only needed command wiring and cache helpers.
  Evidence: `internal/config/config.go` already stores env-scoped cached cluster records in `cluster_cache`.

## Decision Log

- Decision: `profile cluster` commands scope cache operations to the active profile's environment by default, with `--env` only on `list`.
  Rationale: this keeps cache-management actions aligned with the profile the user is managing while still allowing inspection of other env scopes.
  Date/Author: 2026-04-03 / Codex

- Decision: `use --cluster-id` first checks the env-scoped cache and only falls back to the existing exact-match cluster lookup helper on cache miss.
  Rationale: this preserves stable cache hits and avoids unnecessary remote lookups.
  Date/Author: 2026-04-03 / Codex

- Decision: Keep `requiredFlagOrEnv` as a thin wrapper over the new 3-tier resolver with an empty profile fallback until S6 wires profile defaults into the command families.
  Rationale: this makes S5 reusable without changing current command behavior before the shared call sites are updated.
  Date/Author: 2026-04-03 / Codex

## Outcomes & Retrospective

- All subtasks S1-S8 are complete.
- Profile-centric runtime selection, `profile` and `profile cluster` command families, shared `flag > env > profile` resolution, cache-aware metadata lookup, and docs/help updates all shipped with passing verification.

## Validation Ladder

Use narrow checks first, then full verification:

1. `go test ./internal/config -v`
2. `go test ./internal/cmd -run 'Root|Profile|Env' -v`
3. `go test ./internal/cmd -run 'Cluster|Data|Metrics|Loki|Events' -v`
4. `go test ./internal/cmd -run Help -v`
5. `make verify`

## Execution Notes

- Keep each PR/commit batch aligned to one subtask where possible.
- If a subtask grows clearly above the ~500 LOC target, split it before coding the next batch and append new checklist items in this file.
- Update checklist status immediately after each subtask reaches passing tests.
