# Release Notes — v0.3.41

**Released:** 2026-03-14

---

## Summary

v0.3.41 is a substantial release with improvements across both execution modes. The headline feature is **Code Mode** — a new single-loop execution engine for software engineering tasks. Alongside this, general mode has been streamlined by removing the Client validation agent (now **Manager + Worker only**), and both modes received a set of reliability and quality improvements.

---

## What's New

### Code Mode (`--code`)

Activate with `jiva chat --code` or `jiva run "..." --code`. The mode remains off by default; the existing general-purpose agent is unchanged.

**Why code mode?** The Manager/Worker architecture is designed for complex, multi-domain reasoning tasks. For pure coding work it adds unnecessary overhead (multiple LLM calls per turn, MCP subprocess round-trips for file I/O). Code mode removes that overhead without sacrificing any of Jiva's existing capabilities for non-coding sessions.

**Key properties:**
- Single model call per iteration — tool results inject directly back into the context window
- All file tools run in-process (no MCP subprocess for basic I/O)
- Up to 50 iterations per turn
- Two-phase iteration limit: 85% → "continue" nudge (tools kept); 95% → structured wrap-up message (tools stripped)
- Doom-loop detection: 3 identical tool calls in a row triggers a correction injection
- In-loop context compaction: when `promptTokens` approaches the model's context limit, conversation history is automatically summarised and replaced with a structured context message

### In-Process Tool Suite

Seven tools available in code mode, all running inside the Jiva process:

| Tool | Description |
|------|-------------|
| `read_file` | Reads files with line-number output (2000-line / 50 KB cap) and lists directories |
| `edit_file` | Multi-strategy string replacement (9 strategies) — handles indentation drift and whitespace inconsistencies |
| `write_file` | Creates or overwrites files; returns a line-count summary |
| `glob` | File pattern matching relative to the workspace root |
| `grep` | Recursive regex content search; returns file:line:content format |
| `bash` | Shell command execution in the workspace directory (30 s default, 300 s max; output truncated at 2000 lines / 50 KB) |
| `spawn_code_agent` | Delegates a focused sub-task to a child CodeAgent (max depth 2) |

### Multi-Strategy Edit Engine

The `edit_file` tool applies nine replacement strategies in order. Earlier strategies match exactly; later ones tolerate indentation and whitespace drift that is common when a model copies code from its context window with slight reformatting.

### LSP Integration

After each `edit_file` or `write_file` call, the agent notifies the appropriate language server and waits up to 3 seconds for diagnostics. Any errors are appended to the tool result before the model sees it — providing the same compiler feedback loop a developer has in an IDE.

Language servers are auto-detected from PATH. If no server is found for a file's language, the tool continues silently.

Supported out of the box: TypeScript, JavaScript, Python, Go, Rust, C, C++, and 60+ other languages via a static extension map.

### File Locking

A per-path async mutex (`FileLock`) serializes concurrent edits to the same file. This prevents interleaved writes when the model emits multiple tool calls for the same file in a single response.

### IAgent Interface

Both `DualAgent` and `CodeAgent` now implement a shared `IAgent` interface (`src/core/agent-interface.ts`). The CLI REPL, HTTP session manager, and chat routes are all agent-agnostic — they work with either mode without code changes.

### Cloud / HTTP Support

Code mode is available in cloud deployments by setting `JIVA_CODE_MODE=true`. The session manager creates `CodeAgent` instances instead of `DualAgent` when this variable is present.

---

### General Mode: Two-Agent System

The `DualAgent` class has been simplified from a three-agent (Manager + Worker + Client) to a **two-agent system (Manager + Worker)**. The Client validation agent has been removed.

**Why:** The Client agent added a full LLM call after every Worker subtask for validation and corrective strategy selection. In practice this increased latency without proportionately improving task completion — especially for the coding workflows where Code Mode is now available. The Manager already reviews Worker results during synthesis.

**Changes:**
- `ClientAgent` removed from the execution pipeline
- `applyCorrectionStrategy()` removed from `DualAgent`
- `CompletionSignal` no longer flows through the loop
- `maxIterations` default increased from 10 → 20 (compensates for removed Client retry budget)
- Conversational short-circuit: greetings and simple replies are answered by Manager directly, bypassing Worker subtask execution entirely

### reasoning_effort Support (gpt-oss-120b)

Added `reasoning_effort` support for Krutrim-hosted gpt-oss-120b via a dual strategy that works across both Krutrim and Groq:

1. **System prompt injection** — prepends `"Reasoning: <level>"` to the message array (always works; Krutrim may silently ignore the API parameter)
2. **API parameter** — sends `reasoning_effort` in the request body (supported natively by Groq; no-op if ignored)

Strategy is configurable (`api_param` | `system_prompt` | `both`); defaults to `both`.

```json
{
  "models": {
    "reasoning": {
      "defaultReasoningEffort": "high",
      "reasoningEffortStrategy": "both",
      "includeReasoning": false
    }
  }
}
```

CLI defaults: reasoning model → `"high"`, tool-calling model → `"medium"`. Connectivity tests use `"low"` to minimise token cost.

---

## Reliability Improvements

Four areas in Jiva's code mode have been identified and improved.

### Bash Output Truncation

`bash` tool output is now truncated at 2 000 lines and 50 KB before being returned to the model — the same limits as `read_file`. Previously the raw stdout/stderr (up to 10 MB) could be passed verbatim, filling the context window.

Truncation messages tell the model to redirect output to a file if it needs the full content.

### In-Loop Context Compaction

`CodeAgent` now tracks `response.usage.promptTokens` after each model call. When the token count exceeds `compactionThreshold` (default: 90 000 — safe for a 128 K context model), the in-flight message history is compressed:

1. The system prompt and the most recent 10 messages are kept intact.
2. The middle section is summarised by a separate model call using the structured compaction template (see below).
3. The summary replaces the middle section; the loop continues from the compacted context.

Compaction fires at most once per `chat()` turn to avoid thrashing.

### Structured Compaction Format

`ConversationManager.condenseConversation()` (used for cross-turn compaction and in-loop compaction) now uses a structured compaction format instead of a generic summary prompt:

```
## Goal
[What the user is trying to accomplish]

## Instructions
- [Important instructions still in scope]

## Discoveries
[Notable things learned during the conversation]

## Accomplished
[Work done / in progress / remaining]

## Relevant files / directories
[Files read, edited, or created — full paths]
```

This makes summaries actionable — a resumed session can immediately understand context and continue work.

### System Prompt — Persistence and Pre-Tool Narration

The `CodeAgent` system prompt now includes a **PERSISTENCE AND COMPLETION** section:

- *"Keep going until the user's query is completely resolved."*
- *"You MUST iterate and keep going until the problem is solved."*
- *"NEVER end your turn without having truly and completely solved the problem."*
- *"Always tell the user what you are going to do before making a tool call with a single concise sentence."*
- If the user says "resume / continue / try again", check conversation history and continue from the last incomplete step.
- Verify changes — run tests or the build after making changes when appropriate.

The 95% iteration wrap-up message explicitly prohibits tool calls and requires a structured summary with accomplished work, remaining tasks, and recommendations.

### edit_file Tool: Clearer Description and Targeted Error Recovery

Two improvements to prevent the common failure mode where gpt-oss-120b generates `edit_file` with `old_string` but no `new_string`:

1. **Improved description**: The tool description now opens with a **REQUIRED PARAMETERS** block listing all three required fields explicitly, with the note: *"Omitting new_string will fail with a validation error. new_string is never optional."*

2. **Specific correction message**: When the API rejects a call with `"missing properties: 'new_string'"`, the correction injection now names the missing field explicitly — instead of the previous generic message.

---

## Changes

### New Files

| File | Purpose |
|------|---------|
| `src/code/agent.ts` | `CodeAgent` — single-loop execution engine |
| `src/code/file-lock.ts` | Per-path async mutex |
| `src/code/tools/index.ts` | `ICodeTool` interface and tool registry |
| `src/code/tools/read.ts` | `read_file` / `list_directory` |
| `src/code/tools/edit.ts` | `edit_file` with 9-strategy replacement |
| `src/code/tools/write.ts` | `write_file` |
| `src/code/tools/glob.ts` | `glob` |
| `src/code/tools/grep.ts` | `grep` |
| `src/code/tools/bash.ts` | `bash` with output truncation |
| `src/code/tools/spawn.ts` | `spawn_code_agent` |
| `src/code/lsp/language.ts` | Extension → language ID map (60+ extensions) |
| `src/code/lsp/server.ts` | Spawn language server from PATH |
| `src/code/lsp/client.ts` | JSON-RPC LSP client (vscode-jsonrpc) |
| `src/code/lsp/manager.ts` | `LspManager` — lazy init, one client per language |
| `src/core/agent-interface.ts` | Shared `IAgent` / `AgentChatResponse` types |
| `docs/architecture/CODE_MODE.md` | Architecture reference for code mode |

### Modified Files

| File | Change |
|------|--------|
| `src/core/dual-agent.ts` | Removed `ClientAgent`; two-agent system; `maxIterations` default 10 → 20; conversational short-circuit |
| `src/core/manager-agent.ts` | Conversational short-circuit support (`directReply()`); improved synthesis prompts |
| `src/core/worker-agent.ts` | Adjusted to operate without Client validation layer |
| `src/core/config.ts` | Added `codeMode` config schema (`enabled`, `lsp.enabled`, `maxIterations`) |
| `src/core/conversation-manager.ts` | `condenseConversation()` now uses structured compaction format |
| `src/index.ts` | Exports `CodeAgent`, `LspManager`, `IAgent`, `AgentChatResponse` |
| `src/interfaces/cli/index.ts` | Added `--code` and `--no-lsp` flags; `reasoning_effort` defaults; `process.exit(0)` after REPL exits |
| `src/interfaces/cli/repl.ts` | Re-exports `IAgent` from core; parameters typed as `IAgent` |
| `src/interfaces/http/session-manager.ts` | Supports `JIVA_CODE_MODE=true` env var; `ActiveSession.agent` typed as `IAgent`; `reasoning_effort` defaults |
| `src/interfaces/http/routes/chat.ts` | `plan` field is now optional in responses (absent for CodeAgent) |
| `src/models/base.ts` | Added `reasoningEffort?: 'low' \| 'medium' \| 'high'` to `ChatCompletionOptions` |
| `src/models/krutrim.ts` | `reasoning_effort` dual-strategy (system prompt + API param); rate-limit backoff parses actual retry-after time |
| `src/models/harmony.ts` | `formatMessagesForHarmony` correctly converts `role: 'tool'` to user-role messages (fixes HTTP mode bug) |

### Bug Fixes

- **HTTP mode tool results**: `role: 'tool'` messages were forwarded to Groq without a `tools` array in HTTP mode. Fixed in `formatMessagesForHarmony` — they are now converted to user-role `<tool_result>` messages as Harmony requires.
- **Rate limit backoff**: Previously used fixed exponential backoff. Now parses the actual retry-after duration from Groq error messages and waits accordingly.
- **`/exit` hangs in code mode**: LSP child-process streams kept the Node.js event loop alive after cleanup. Fixed by calling `process.exit(0)` after `agent.cleanup()` returns.
- **`edit_file` missing `new_string`**: Targeted correction message now names the missing field explicitly instead of using a generic error message.

---

## Configuration Reference

### CLI Flags

```bash
jiva chat --code          # activate code mode
jiva chat --no-lsp        # disable LSP in code mode (also: --code --no-lsp)
```

### Config File

```json
{
  "codeMode": {
    "enabled": true,
    "lsp": { "enabled": true },
    "maxIterations": 50
  },
  "models": {
    "reasoning": {
      "defaultReasoningEffort": "high",
      "reasoningEffortStrategy": "both"
    }
  }
}
```

### Environment Variables (cloud deployments)

```bash
JIVA_CODE_MODE=true       # activate code mode
JIVA_CODE_LSP=false       # disable LSP
```

---

## Further Reading

- [Code Mode Architecture](../architecture/CODE_MODE.md) — full reference including tool parameters, LSP setup, and the edit strategy pipeline
- [Configuration Guide](../guides/CONFIGURATION.md) — code mode config options and LSP server installation
- [Cloud Run Deployment](../deployment/CLOUD_RUN_DEPLOYMENT.md) — using code mode in production
