# Changelog - @lanonasis/cli

## [3.11.2] - 2026-07-21

### 🐛 Bug Fixes

- **Memory search fallback is now explicit and CI-safe**: `memory search` reports lexical fallback metadata in JSON output, supports `--no-fallback`, `--fail-on-fallback`, and `--ci`, and redacts backend error strings before printing them.
- **Prescan installs are now self-contained**: bundled `@lanonasis/privacy-sdk` alongside `@lanonasis/secret-prescan` so global CLI reinstalls cannot leave prescan resolving through an empty or missing nested privacy SDK package.
- **Prescan bundles the corrected privacy detector**: CLI now depends on `@lanonasis/privacy-sdk@^1.0.1`, which rejects IBAN-shaped transcript noise with ISO 13616 mod-97 validation before MIRA extraction.

### 🧪 Release Verification

- Verified the 3.11.1 REPL bridge fix remains present in the rebuilt `dist/index.js`: `lanonasis repl --help` still documents `--ai-router`, `--model`, and `--config`, and the bridge still forwards those options to `@lanonasis/repl-cli`.
- Verified the 3.11.2 packed artifact includes both bundled prescan runtime packages: `@lanonasis/privacy-sdk` and `@lanonasis/secret-prescan`.

## [3.11.1] - 2026-07-16

### 🐛 Bug Fixes

- **REPL bridge now preserves concierge endpoint controls**: `lanonasis repl` forwards `--ai-router`, `--model`, and `--config` to `@lanonasis/repl-cli`, so the main CLI entry point can launch the same LZero concierge configuration exposed by `lrepl`.
- **REPL command help reflects the forwarded options**: `lanonasis repl --help` now documents the AI Router, model, and custom config flags.

### 📦 Package

- Declared `@lanonasis/repl-cli` as an optional dependency so fresh main CLI installs can resolve the REPL bridge when the companion package is available.
- Added a published `SKILL.md` so Codex/agent runtimes can discover package-specific guidance for CLI, MCP, auth, prescan, REPL bridge, and docs drift work.

### 🧪 Testing

- Added a focused bridge contract smoke test for the `lanonasis repl` forwarding surface. This is not a full end-to-end REPL reliability test.

## [3.10.1] - 2026-06-12

### 🐛 Bug Fixes

- **Prescan stays lazy-loaded**: ordinary CLI startup no longer eagerly requires optional prescan runtime packages.
- **Release metadata now follows package.json**: user-facing CLI version strings and the service-discovery user agent now read the package version instead of stale hardcoded values.
- **Prescan status explains persistence**: the no-scan state now points operators to `lanonasis prescan run <path> --save`, matching the current local report persistence behavior.

### 📦 Package

- Refreshed release metadata and build output for the 3.10.1 hotfix.

## [3.10.0] - 2026-05-26

### ✨ New Features

- **Secret prescan commands (`lanonasis prescan`)**: New command group for scanning files and directories for secrets and PII before MIRA context extraction. Provides machine-parseable output and CI-friendly exit codes.
  - `lanonasis prescan scan <path>` — Scans an entire directory tree. Reports are value-stripped (no raw secrets in output). Emits structured `---PRESCAN SUMMARY---` block for piping/scripting. Exit codes: `0`=safe, `1`=flagged, `2`=quarantined.
  - `lanonasis prescan audit <file>` — Audits a single file. Supports `--verbose` for per-detection detail including type, sensitivity, confidence, masked sample, and applicable regulations. CI-friendly exit codes.
  - `lanonasis prescan safe <file>` — Boolean gate: checks if a file is safe for MIRA extraction. Exits `0` if safe, `1` otherwise.
- **Prescan does not require authentication** — runs entirely locally against the `@lanonasis/secret-prescan` engine and `@lanonasis/privacy-sdk` pattern registry.

### 📦 Package

- Added `"private": false` to enable registry sync audit tooling to track this package across npm and GitHub Packages.

## [3.9.15] - 2026-04-04

### 🐛 Bug Fixes

- **Displayed memory ID prefixes now work across CLI memory reads and deletes**: `lanonasis memory get`, `memory update`, and `memory delete` now resolve 8+ character prefixes from the list output before calling the live API, so operators no longer need to paste full UUIDs for routine follow-up actions.
- **Legacy memory route drift no longer breaks prefix fetches**: Memory lookups now retry against the compatibility `GET /api/v1/memory/get?id=...` and delete fallback routes only when the canonical plural endpoint returns the known `Memory ID is required` validation drift.
- **MCP memory tools now accept both `id` and `memory_id`**: The bundled LanOnasis MCP server and remote MCP bridge now normalize legacy `memory_id` callers onto the live `id` contract, which restores OpenClaw and similar clients when they pass the older field name.

## [3.9.14] - 2026-04-03

### 🐛 Bug Fixes

- **Platform key project commands now hit the live auth-gateway contract**: `api-keys projects create/list` now use `/api/v1/projects` and route to `auth.lanonasis.com`, matching the current auth-gateway surface instead of the stale `/api/v1/auth/api-keys/projects` path.
- **Auth-gateway management calls no longer drift to the MCP/API host**: The CLI transport now treats `/api/v1/auth/api-keys/*` and `/api/v1/projects/*` as auth-gateway management endpoints, so token-authenticated key management requests consistently reach the auth service with the expected project scope header.
- **Stale MCP and analytics subcommands now fail honestly**: Deprecated `api-keys mcp *` and `api-keys analytics *` commands no longer call nonexistent gateway routes. They now exit immediately with explicit guidance toward the supported dashboard and service-scoping paths.

### ✨ Improvements

- **`key_context` is now exposed in CLI key management**: `api-keys create` accepts `--key-context personal|team|enterprise`, and `api-keys list/get` now display the stored key context so context-bound platform keys are visible and intentional at the CLI layer.

## [3.9.13] - 2026-04-02

### 🐛 Bug Fixes

- **JWT/password sessions now refresh through the real auth-gateway contract**: Expiring CLI sessions no longer call the nonexistent `/v1/auth/refresh` route. Refreshable JWT and OAuth sessions now use `POST /oauth/token` with `grant_type=refresh_token`, matching the live auth-gateway implementation.
- **Password login now persists refresh metadata**: Username/password authentication now saves `refresh_token` and `token_expires_at` from the login response, so successful JWT sessions can actually refresh instead of silently falling back to re-login loops.
- **MCP client refresh flow no longer drifts from the main CLI auth flow**: Removed the stale `/auth/refresh` path and incorrect `refreshToken` config key lookup in favor of the shared `CLIConfig.refreshTokenIfNeeded()` implementation.

### 🔄 Dependency Updates

- **Bundled `@lanonasis/mem-intel-sdk` updated to `2.1.0`**: Aligns the CLI with the newly published scoped intelligence query contract and predictive route support.

## [3.9.11] - 2026-03-27

### 🐛 Bug Fixes

- **`memory stats` no longer crashes on wrapped responses**: The CLI now normalizes both flat and `{ data: ... }` stats payloads and safely defaults optional fields like `total_size_bytes` and `avg_access_count` when the backend omits them.
- **Secure storage no longer initializes on every command startup**: Vendor key storage is now lazy-loaded, which prevents unnecessary keychain fallback warnings on CLI commands that do not access vendor key storage.
- **Bundled auth client updated to `@lanonasis/oauth-client@2.0.4`**: Pulls in the ESM-safe native keychain loader fix and semver-compliant optional React peer metadata.

## [3.9.8] - 2026-02-25

### ✨ New Features

- **Issue #98 (CLI Memory UX Enhancements)**:
  - Added `onasis memory create --json <json>` for direct JSON payload creation.
  - Added `onasis memory create --content-file <path>` for file-based content ingestion.
  - Added `onasis memory save-session` to persist branch/status/changed-files session context as memory.
- **Behavior methods via CLI commands**:
  - Added `onasis memory intelligence` subcommands for health check, tag suggestions, related lookup, duplicate detection, insight extraction, and pattern analysis.
  - Added `onasis memory behavior` subcommands for `record`, `recall`, and `suggest` workflow behavior operations.

### 🐛 Bug Fixes

- Normalized memory response handling for create/get/update wrappers (`{ data: ... }`) so CLI output fields like ID/Title/Type are consistently resolved.
- Ensured token refresh is executed before memory command paths to reduce intermittent re-auth prompts during active OAuth sessions.
- Aligned default semantic search thresholds to `0.55` across memory and MCP search command paths for consistent result behavior.

## [3.9.7] - 2026-02-21

### ✨ New Features

- **`onasis whoami` command**: Display full authenticated user profile including email, name, role, OAuth provider, project scope, and last login time. Fetches live data from `GET /v1/auth/me`.
- **Live profile on `auth status`**: `onasis auth status` now fetches the real user profile from the auth gateway and displays email, role, and plan — no longer relies solely on cached local state.
- **Live memory API probe on `auth status`**: After local auth check passes, `auth status` issues a real memory list request to confirm end-to-end API access, reporting `✓ accessible` or `✖ rejected (401)` with actionable guidance.
- **Manual endpoint override warning**: `auth status` now warns when `manualEndpointOverrides` is active and shows the configured endpoint URLs.

### 🐛 Bug Fixes

- **OAuth sessions no longer show "Not Authenticated"**: Fixed `auth status` incorrectly reporting unauthenticated for valid OAuth PKCE sessions — was checking `if (isAuth && user)` when `user` may be undefined for OAuth sessions.
- **`process.exit(1)` no longer kills status probe**: Added `noExit` flag to `APIClient` so callers like `auth status` can catch 401/403 from the memory probe without the interceptor terminating the process.
- **Stale auth cache cleared on 401**: When the memory API returns 401, the CLI now calls `invalidateAuthCache()` to clear the 5-minute in-memory cache and the persisted `lastValidated` timestamp, preventing the 24-hour grace bypass.
- **24-hour `lastValidated` skip removed**: Eliminated a security hole that bypassed server re-validation for 24 hours after any successful auth check.
- **7-day offline grace restricted to network errors**: The offline grace period no longer applies to explicit 401/403 auth rejections — only genuine network failures.
- **Bogus vendor key always passed auth check**: `pingAuthHealth()` was hitting the unauthenticated `/health` endpoint. Replaced with `probeVendorKeyAuth()` which calls `POST /api/v1/memories/search` — a real protected endpoint. Interprets 401/403 as auth rejection, any other response (400, 405, 5xx) as auth accepted with a backend concern.
- **`discoverServices()` overwrote manual overrides**: Fixed auto-discovery ignoring `manualEndpointOverrides`; discovery now short-circuits when manual overrides are active.
- **Stale JWT cleared on vendor key switch**: When `setVendorKey()` sets `authMethod: 'vendor_key'`, any existing JWT tokens are now removed from config to prevent auth-method confusion in the API client.
- **Zod v4 compatibility**: Fixed `z.record(z.any())` → `z.record(z.string(), z.any())` (5 instances in `tool-schemas.ts`) and `error.errors` → `error.issues` (2 instances in schema validator).
- **Inquirer v9 compatibility**: Fixed deprecated `type: 'list'` → `type: 'select'` prompt type in `welcome.ts`.

### 📡 Auth Gateway Integration (coordinated release)

These CLI changes are paired with server-side fixes in the same release:
- **Auth Gateway `requireAuth`**: Added opaque OAuth PKCE token introspection path — OAuth CLI sessions can now access `GET /v1/auth/me` and other protected endpoints.
- **Central API Gateway (`onasis-gateway`)**: `validateJWTToken()` now falls back to `POST /verify-token` when the session endpoint returns 401, enabling OAuth token passthrough for all proxied services. Added `get-me` tool to the auth-gateway MCP adapter.

### 📚 Documentation

- Updated README with `onasis whoami` command reference.
- Added `auth status` live probe behavior to authentication section.
- Added `--no-mcp` flag to memory command examples.

## [3.9.6] - 2026-02-21

### 🐛 Bug Fixes

- **Reliable Memory Auth Routing**: Memory CRUD and search operations now consistently route through the API gateway (`https://api.lanonasis.com`) to avoid MCP endpoint contract mismatches.
- **Legacy Endpoint Compatibility**: Added fallback support for deployments that still expose RPC-style memory routes (`/api/v1/memory/*`) when REST routes return `400/405`.
- **Auth Status Accuracy**: `status` now validates live auth state against the auth verify endpoint before reporting authenticated session state.
- **OAuth Session Stability**: Requests proactively refresh OAuth/JWT sessions to reduce intermittent `memory login required` errors during long-running CLI usage.
- **Response Normalization**: Memory get/list/search handlers normalize wrapped gateway responses (`{ data: ... }`) for consistent CLI behavior across environments.

### 📚 Documentation

- Clarified auth flow behavior for vendor keys and bearer tokens.
- Added release notes for endpoint override guidance and memory transport behavior.

## [3.9.3] - 2026-02-02

### ✨ Features

- **Non-Interactive Vendor Key Auth**: Added `-k, --vendor-key <key>` option to `auth login` command
  - Enables non-interactive authentication in CI/CD pipelines and automation scripts
  - Example: `onasis auth login --vendor-key <your-key>`

### 🐛 Bug Fixes

- **JWT Authentication Routing**: Fixed API routing for JWT/OAuth authenticated sessions
  - JWT tokens from username/password or OAuth login now correctly route to MCP server
  - Memory operations (list, create, search, update, delete) work with JWT authentication
  - Path translation handles endpoint differences between API and MCP servers
  - Vendor key authentication continues to route to main API server

- **Frozen Terminal During Text Input**: Fixed SSE/WebSocket event handlers interfering with inline text editor
  - Real-time update messages (📡) now only display in verbose mode
  - Prevents terminal freeze during interactive prompts (memory create, update)
  - Raw terminal mode no longer conflicts with background MCP events

- **Missing CLI Option**: The `--vendor-key` option was defined in code but not exposed in CLI
  - Now properly registered in command-line interface

### ⚠️ Known Limitations

- `memory stats` command not available with JWT authentication (MCP server limitation)
- For full API access including stats, use vendor key authentication

## [3.9.2] - 2026-02-02

### 🐛 Bug Fixes

- **Auth Method Override**: Fixed vendor key authentication not overriding previous OAuth `authMethod`
  - When users explicitly authenticate with vendor key after OAuth, the `authMethod` is now correctly set to `vendor_key`
  - This fixes "Authenticated: No" status after successful vendor key authentication
  - Reverted changes from 3.9.1 that incorrectly removed vendor key storage from OAuth flow

## [3.9.1] - 2026-02-01

### 🔐 Authentication Fixes

- **OAuth Scope Clarification**: OAuth login now clearly states it enables MCP integration only
- **Improved Error Messages**: 401 errors for OAuth users include specific guidance for direct API access
- **Removed Misleading Storage**: OAuth tokens are no longer incorrectly stored as vendor keys
- **Documentation Updates**: README and in-CLI help clarify authentication method differences

### 🐛 Bug Fixes

- Fixed confusing error message when OAuth users try to use direct CLI commands
- Removed `.lanonasis/mcp-config.json` from version control

## [3.9.0] - 2026-02-01

### 🎨 CLI UX Revolution

#### Seamless Multi-Line Text Input
- **Inline Text Editor**: Professional multi-line text input without external editors
  - Raw terminal mode for keystroke capture
  - Full editing support (arrow keys, backspace, newlines)
  - Visual feedback with line numbers and cursor indicators
  - Submit with Ctrl+D, cancel with Ctrl+C
  - Configurable fallback to external editors

#### Intelligent MCP Server Connection Management
- **Auto-Configuration**: Automatically detects and configures embedded MCP servers
- **Connection Lifecycle**: Smart server process management with health monitoring
- **Persistent Configuration**: Saves and loads user preferences across sessions
- **Connection Verification**: Validates server connectivity before operations
- **Graceful Error Handling**: Clear error messages with actionable resolution steps

#### First-Run Onboarding Experience
- **Guided Setup**: Interactive onboarding flow for new users
- **Connectivity Testing**: Automatic testing of API endpoints and services
- **Smart Defaults**: Configures optimal settings based on environment
- **User Preferences**: Captures and persists input mode, editor choice, and behavior preferences
- **Troubleshooting Guidance**: Context-aware help when issues are detected

### 🔐 Authentication Clarifications

#### OAuth vs Direct API Access
- **Clear Scope Documentation**: OAuth2 login now explicitly states it enables MCP integration
- **Improved Error Messages**: 401 errors for OAuth users include specific guidance for direct API access
- **Authentication Method Guidance**: CLI provides clear instructions for:
  - **OAuth**: Use for MCP integration and real-time features
  - **Vendor Key**: Obtain from dashboard for direct API access (`lanonasis auth login --vendor`)
  - **Credentials**: Use username/password for direct API access (`lanonasis auth login --credentials`)

#### Secure Storage Fallback
- **Keytar Optional**: When keytar (native secure storage) is unavailable, CLI gracefully falls back to encrypted file storage
- **Cross-Platform**: Encrypted storage works consistently across all platforms
- **No Data Loss**: Credentials are preserved in `~/.lanonasis/api-key.enc` with AES-256-GCM encryption

### 🐛 Critical Bug Fixes (PR #93)

#### P1: Connection Verification False Positive
- **Issue**: `verifyConnection()` returned `true` even when server was in error/stopped state
- **Fix**: Added explicit checks for error and stopped states before declaring success
- **Impact**: Users will now see accurate connection status instead of false positives

#### P2: Configuration Not Loaded Before Use
- **Issue**: `ConnectionManager.init()` method existed but was never called
- **Fix**: Added `init()` to ConnectionManager interface and call it before `connectLocal()`
- **Impact**: User configuration is now properly loaded and respected

#### P2: Empty Content Overwrites in Inline Updates
- **Issue**: When updating memories in inline mode, `defaultContent` wasn't passed to TextInputHandler
- **Fix**: Added `defaultContent` support throughout the text input pipeline
- **Impact**: Memory updates preserve existing content instead of starting with blank slate

### 🧪 Testing & Quality

- **Comprehensive Test Suite**: 168 passing tests including property-based tests
- **Zero TypeScript Errors**: All compilation errors resolved
- **No Regressions**: All existing tests continue to pass
- **Professional Documentation**: Complete inline documentation and type definitions

### 📦 Package Cleanup

- **npmignore**: Excludes test files and development artifacts from published package
- **Directory Reorganization**: Cleaner structure with examples moved to `docs/examples/`
- **Build Optimization**: Reduced package size by excluding unnecessary files

### 🔄 Breaking Changes
None - Fully backward compatible

### 📝 Technical Details

**New Implementations**:
- `TextInputHandlerImpl` ([cli/src/ux/implementations/TextInputHandlerImpl.ts](cli/src/ux/implementations/TextInputHandlerImpl.ts))
- `ConnectionManagerImpl` ([cli/src/ux/implementations/ConnectionManagerImpl.ts](cli/src/ux/implementations/ConnectionManagerImpl.ts))
- `OnboardingFlowImpl` ([cli/src/ux/implementations/OnboardingFlowImpl.ts](cli/src/ux/implementations/OnboardingFlowImpl.ts))

**Integration Points**:
- Memory commands now use inline text input by default ([cli/src/commands/memory.ts](cli/src/commands/memory.ts:116-119))
- MCP connect command uses ConnectionManager ([cli/src/commands/mcp.ts](cli/src/commands/mcp.ts:130-137))
- Init command includes onboarding flow ([cli/src/commands/init.ts](cli/src/commands/init.ts))

## [3.7.0] - 2025-11-23

### 🔐 Security Infrastructure Upgrade

#### Enhanced API Key Security with SHA-256
- **Cross-Platform SHA-256 Hashing**: Unified hash utilities for consistent API key hashing across all platforms
- **Local Hash Implementation**: Isolated hash utilities (`src/utils/hash-utils.ts`) for CLI independence
- **Double-Hash Prevention**: Smart detection of pre-hashed keys to prevent double-hashing errors
- **Server-Side Validation**: Constant-time comparison for timing-attack prevention
- **Future NPM Package Ready**: Designed for eventual migration to `@lanonasis/security` npm package

#### Technical Improvements
- **Build Stability**: Fixed TypeScript `rootDir` compilation errors
- **Zero Deprecation Warnings**: All dependencies verified for production readiness
- **Cross-Platform Compatibility**: Node.js crypto for server-side, Web Crypto API fallback for browser contexts
- **Type Safety**: Full TypeScript support with exported hash types (`ApiKeyHash`, `ApiKey`)

#### Hash Utility Functions
```typescript
// Available in CLI
ensureApiKeyHash(apiKey: string): string  // Smart hash normalization
hashApiKey(apiKey: string): string        // SHA-256 hashing
isSha256Hash(value: string): boolean      // Hash detection
```

### 🛡️ Security Features
- ✅ SHA-256 cryptographic hashing for all API keys
- ✅ Prevents plaintext key transmission
- ✅ Constant-time hash comparison
- ✅ Automatic hash detection and normalization
- ✅ Compatible with existing vendor key authentication

### 🔄 Breaking Changes
None - Fully backward compatible

### 📦 Dependencies
- No new external dependencies
- Uses native Node.js `crypto` module
- Clean build with zero deprecation warnings

## [3.0.1] - 2025-10-08

### 🚀 Major Version Bump
This is a major version release (3.0) due to the significant MCP architectural changes and new capabilities that may affect existing integrations.

### 🎉 Major Features
*Same as 2.0.9 but republished as 3.0.1 due to npm version conflict*

## [2.0.9] - 2025-10-08 (npm publish conflict)

### 🎉 Major Features

#### Enhanced Model Context Protocol (MCP) Support
- **Multi-Server Connections**: Connect to multiple MCP servers simultaneously with automatic failover
- **Advanced Error Handling**: Exponential backoff retry logic and graceful degradation  
- **Health Monitoring**: Automatic health checks with latency tracking and auto-reconnection
- **Connection Pooling**: Efficient resource management for multiple connections
- **Tool Chain Execution**: Support for sequential and parallel tool execution

#### New MCP Infrastructure
- **Enhanced MCP Client** (`src/mcp/client/enhanced-client.ts`)
  - Multi-server management with priority-based selection
  - Event-driven architecture with connection status tracking
  - Automatic failover to backup servers

- **MCP Server Implementation** (`src/mcp/server/lanonasis-server.ts`)
  - Full MCP protocol compliance (tools, resources, prompts)
  - 16 registered tools for memory, topic, and system operations
  - Resource providers for data access
  - Interactive prompts for user guidance

- **Transport Support** (`src/mcp/transports/transport-manager.ts`)
  - StdIO transport for local processes
  - WebSocket transport with auto-reconnection
  - SSE (Server-Sent Events) for streaming
  - Authentication support (Bearer, API Key, Basic)

- **Schema Validation** (`src/mcp/schemas/tool-schemas.ts`)
  - Zod-based validation for all MCP tools
  - Type-safe operations with clear error messages
  - Comprehensive schemas for memory, topic, API key, and system operations

### 🛠 Technical Improvements
- **Build System**: New MCP-specific build scripts (`build:mcp`, `dev:mcp`, `test:mcp`)
- **Module Structure**: Dedicated `/src/mcp/` directory with clean separation of concerns
- **Error Recovery**: Improved error handling throughout the MCP stack
- **Type Safety**: Full TypeScript support with proper type definitions

### 🐛 Bug Fixes
- Fixed authentication flow issues with proper token validation
- Resolved double slash URL construction in CLI auth
- Fixed memory command authentication requirements
- Corrected error messages to show correct authentication command

### 📚 Documentation
- Enhanced README with MCP usage examples
- Added MCP Server Mode documentation
- Updated command reference with new MCP features
- Created comprehensive MCP enhancement summary

### ⚠️ Breaking Changes
- HTTP transport temporarily disabled in favor of WebSocket/StdIO (more reliable)
- Some API key operations pending full implementation

### 🔄 Dependencies
- Updated to latest @modelcontextprotocol/sdk
- Added ws for WebSocket support
- Added zod for schema validation

## [2.0.8] - Previous Version
- Authentication system improvements
- CLI guided setup enhancements
- Performance optimizations

## [2.0.7] - Previous Version
- Memory management improvements
- Topic organization features
- Bug fixes and stability improvements

---

For full release notes and migration guides, visit: https://docs.lanonasis.com/cli/changelog
