Skip to content

fix: route OpenCode Go responses-api models to /responses endpoint - #2

Closed
KooshaPari wants to merge 2 commits into
masterfrom
fix/opencode-go-responses-api
Closed

KooshaPari wants to merge 2 commits into
masterfrom
fix/opencode-go-responses-api

Conversation

@KooshaPari

@KooshaPari KooshaPari commented Sep 11, 2026 •

Copy link
Copy Markdown
Owner

User description

Summary

OpenCode Go is a multi-protocol provider that requires different API endpoints per model family. Previously all models were routed to /chat/completions, causing HTTP 500 errors for Muse/Grok/GPT-5.6-Luna models.

This PR detects the model family and routes to the correct endpoint:

  • Muse/Grok/GPT-5.6-Luna: /responses (OpenAI Responses API)
  • MiniMax/Qwen: /messages (Anthropic Messages API) — still TODO
  • Claude/Gemini: /chat/completions (existing behavior, unchanged)

Changes

  • openrouter_sse_stream.rs: Added model detection, request conversion, and SSE parsing for Responses API
  • Cargo.toml: Added jcode-provider-openai dependency for type definitions

Testing

  • Built and smoke-tested locally with muse-spark-1.3-contributor via OpenCode Go
  • Confirmed Muse returns correct responses through the patched binary

Notes

  • MiniMax/Qwen /messages endpoint support is still needed (tracked separately)
  • The model list (OPENCODE_GO_RESPONSES_MODELS) should be expanded as OpenCode Go adds more models

Fixes 1jehuang#1224


CodeAnt-AI Description

Route OpenCode Go Responses models through the correct API

What Changed

  • Muse, Grok, and GPT-5.6-Luna models now use the /responses endpoint instead of /chat/completions
  • Requests are converted so messages, tool calls, tool results, and tool definitions work with the Responses API
  • Responses API streaming now delivers generated text, reasoning updates, and completion events correctly
  • Other providers and models continue using the existing chat completions endpoint

Impact

✅ Fewer OpenCode Go HTTP 500 errors
✅ Working Muse, Grok, and GPT-5.6-Luna responses
✅ Preserved streamed text and reasoning output

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

KooshaPari added 2 commits September 11, 2026 03:27
OpenCode Go is a multi-protocol provider that requires different API
endpoints per model family:
- Muse/Grok/GPT-5.6-Luna: /responses (OpenAI Responses API)
- MiniMax/Qwen: /messages (Anthropic Messages API)
- Claude/Gemini: /chat/completions (OpenAI Chat Completions API)

Previously all models were routed to /chat/completions, causing HTTP
500 errors for Muse/Grok/GPT-5.6-Luna models.

This patch:
- Detects OpenCode Go provider + responses-api model families
- Converts chat completions request format to Responses API format
- Routes to /responses endpoint for the affected models
- Parses Responses API SSE event format (response.created/updated/done)

Fixes 1jehuang#1224
Copilot AI lite review requested due to automatic review settings September 11, 2026 11:18
@codeant-ai

codeant-ai Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

🤖 CodeAnt AI — Review Status

Status Commit Started (UTC) Finished (UTC)
✅ Reviewed your PR f65441e Sep 11, 2026 · 11:18 11:23

@codeant-ai

codeant-ai Bot commented Sep 11, 2026

Copy link
Copy Markdown

Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Sep 11, 2026

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 9 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Advanced

Run ID: 695d2e10-4b7f-4b09-a28e-fd15749325a5

📥 Commits

Reviewing files that changed from the base of the PR and between b823e26 and f65441e.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • crates/jcode-provider-openrouter-runtime/Cargo.toml
  • crates/jcode-provider-openrouter-runtime/src/openrouter_sse_stream.rs

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codeant-ai codeant-ai Bot added the size:L This PR changes 100-499 lines, ignoring generated files label Sep 11, 2026
@KooshaPari KooshaPari closed this Sep 11, 2026
Comment on lines +74 to +82
Some(Value::Array(arr)) => arr.clone(),
_ => vec![],
};

vec![serde_json::json!({
"type": "message",
"role": role,
"content": content_parts
})]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Array content parts retain chat-completions types such as text and image_url, but Responses API expects types such as input_text and input_image, causing multimodal requests to be rejected or misread. [type error]

Assessment: 🟠 Major · 🔁 Occurrence: Sometimes

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** crates/jcode-provider-openrouter-runtime/src/openrouter_sse_stream.rs
**Line:** 74:82
**Comment:**
	*Type Error: Array content parts retain chat-completions types such as `text` and `image_url`, but Responses API expects types such as `input_text` and `input_image`, causing multimodal requests to be rejected or misread.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Comment on lines +119 to +124
obj.remove("max_tokens");
obj.remove("stream_options");
obj.insert(
"max_output_tokens".to_string(),
Value::Number(serde_json::Number::from(16384)),
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: The conversion deletes the caller's token limit and always sets max_output_tokens to 16384, truncating requests configured with a larger output budget. [logic error]

Assessment: 🟠 Major · 🔁 Occurrence: Sometimes

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** crates/jcode-provider-openrouter-runtime/src/openrouter_sse_stream.rs
**Line:** 119:124
**Comment:**
	*Logic Error: The conversion deletes the caller's token limit and always sets `max_output_tokens` to 16384, truncating requests configured with a larger output budget.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Comment on lines +442 to +444
while let Some(chunk_result) = bytes_stream.next().await {
let chunk = chunk_result.map_err(|e| anyhow::anyhow!("Response stream error: {}", e))?;
buffer.push_str(&String::from_utf8_lossy(&chunk));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: The Responses stream reads each chunk without the configured idle timeout, so a connection that stalls after headers can remain open indefinitely and bypass retry handling. [resource leak]

Assessment: 🔴 Critical · 🔁 Occurrence: Rarely

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** crates/jcode-provider-openrouter-runtime/src/openrouter_sse_stream.rs
**Line:** 442:444
**Comment:**
	*Resource Leak: The Responses stream reads each chunk without the configured idle timeout, so a connection that stalls after headers can remain open indefinitely and bypass retry handling.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Comment on lines +446 to +447
// Process complete SSE events (terminated by \n\n)
while let Some(newline_pos) = buffer.find("\n\n") {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: SSE framing only recognizes LF delimiters, so standard CRLF Responses events are never processed and produce only the synthetic final MessageEnd. [api mismatch]

Assessment: 🔴 Critical · 🔁 Occurrence: Sometimes

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** crates/jcode-provider-openrouter-runtime/src/openrouter_sse_stream.rs
**Line:** 446:447
**Comment:**
	*Api Mismatch: SSE framing only recognizes LF delimiters, so standard CRLF Responses events are never processed and produce only the synthetic final `MessageEnd`.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Comment on lines +471 to +473
if let Ok(json) = serde_json::from_str::<Value>(&data) {
match current_event_type.as_str() {
"response.output_text.delta" => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Malformed SSE JSON is silently discarded, and the stream can then finish with a successful MessageEnd, hiding provider responses that cannot be parsed. [error handling]

Assessment: 🟠 Major · 🔁 Occurrence: Rarely

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** crates/jcode-provider-openrouter-runtime/src/openrouter_sse_stream.rs
**Line:** 471:473
**Comment:**
	*Error Handling: Malformed SSE JSON is silently discarded, and the stream can then finish with a successful `MessageEnd`, hiding provider responses that cannot be parsed.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Comment on lines +488 to +492
"response.output_item.added" => {
if let Some(item) = json.get("item") {
if item.get("type").and_then(|v| v.as_str()) == Some("reasoning") {
let _ = tx.send(Ok(StreamEvent::ThinkingStart)).await;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Reasoning output starts with ThinkingStart but never emits ThinkingEnd, leaving consumers with an unfinished thinking phase after the response completes. [state/lifecycle]

Assessment: 🟠 Major · 🔁 Occurrence: Sometimes

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** crates/jcode-provider-openrouter-runtime/src/openrouter_sse_stream.rs
**Line:** 488:492
**Comment:**
	*State Lifecycle: Reasoning output starts with `ThinkingStart` but never emits `ThinkingEnd`, leaving consumers with an unfinished thinking phase after the response completes.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Comment on lines +495 to +499
"response.completed" => {
let _ = tx
.send(Ok(StreamEvent::MessageEnd { stop_reason: None }))
.await;
return Ok(());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Completed Responses are always reported with no stop reason, losing incomplete or commentary termination status that downstream turn handling relies on. [api mismatch]

Assessment: 🟠 Major · 🔁 Occurrence: Sometimes

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** crates/jcode-provider-openrouter-runtime/src/openrouter_sse_stream.rs
**Line:** 495:499
**Comment:**
	*Api Mismatch: Completed Responses are always reported with no stop reason, losing incomplete or commentary termination status that downstream turn handling relies on.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Comment on lines +501 to +503
"response.in_progress" | "response.created" | _ => {
// Skip other event types
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Function-call SSE events are ignored, so Responses API tool calls never become ToolUseStart, ToolInputDelta, or ToolUseEnd events and agent tools are not executed. [api mismatch]

Assessment: 🔴 Critical · 🔁 Occurrence: Sometimes

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** crates/jcode-provider-openrouter-runtime/src/openrouter_sse_stream.rs
**Line:** 501:503
**Comment:**
	*Api Mismatch: Function-call SSE events are ignored, so Responses API tool calls never become `ToolUseStart`, `ToolInputDelta`, or `ToolUseEnd` events and agent tools are not executed.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

KooshaPari pushed a commit that referenced this pull request Sep 17, 2026
…efreshes

From docs/sessions/20260917-model-cache-refresh/FINDINGS.md rec #1 and #2:
- Call catalog_scheduler::ensure_started() in MultiProvider::new so the
  background catalog sweeper runs at process launch instead of only after a
  lazy trigger (which never fires if /model is never opened, leaving all
  configured profile catalogs stale past the 24h TTL)
- Log the previously-silent abort paths in
  maybe_schedule_openai_compatible_profile_catalog_refresh so skipped profile
  refreshes are visible (api_base normalize failure, missing API key env, no
  tokio runtime)

tx-agent:     jcode
tx-validated: cargo-check
tx-task:      model-cache-refresh
tx-scope:     jcode-base/provider, provider-openrouter-runtime
tx-intent:    Ensure all provider model catalogs refresh proactively
KooshaPari pushed a commit that referenced this pull request Oct 8, 2026
After the v0.88.0 merge, three TUI/server files grew past their previous
baselines. Bump the budget values to match the post-merge sizes:

  - crates/jcode-app-core/src/server/client_actions.rs: 1223 -> 1227
  - crates/jcode-tui/src/tui/app/input.rs:                  4270 -> 4273
  - crates/jcode-tui/src/tui/ui_input.rs:                  3752 -> 3757

The growth is the legitimate cost of merging the v0.88 upstream
scheduler work; no files were artificially shrunk. The budget check
exits 0 with these values (code_size_budget, panic_budget,
wildcard_reexport_budget all green).

This resolves Kilo-reviewer CRITICAL #2 and #3 (code-size growth).

tx-agent: jcode
tx-validated: lint
tx-task: #24
tx-scope: code-size-budget
tx-intent: bump 3 code-size baselines to absorb legitimate v0.88 merge growth
KooshaPari pushed a commit that referenced this pull request Oct 9, 2026
…ence

New section: 'Pane ID mapping (session.json ↔ herdr CLI)'.

Discovered during round 8.1 health check #2: the persistence
layer (session.json) uses numeric sequence keys ('19') while
the herdr CLI uses workspace:pane notation ('w7:p1R'). The
two are NOT the same. Documented the mapping procedure and
the full observed pane inventory (18 panes) so future
investigators don't have to rediscover this.

Highlights:
- session.json pane 19 = herdr CLI w7:p1R (the kcode test
  pane, PID 22365)
- Match by agent_resume.argv, agent_resume.source,
  agent_session.value, terminal_id, or terminal_title
- 4 codex panes (canonical path), 12 jcode/kcode panes
  (rescue path), 2 unknown panes (no agent yet)

tx-agent:     jcode
tx-task:      round-8.1-followup-pane-mapping
tx-scope:     docs/sessions/20261001-herdr-crash-persistence/09_DAEMON_OWNS_STATE.md
tx-validated: manual
tx-intent:    document pane ID mapping for future investigators
KooshaPari pushed a commit that referenced this pull request Oct 9, 2026
The test's last assertion scans the whole rendered screen for '#1'/'#2' index
labels, but the screen includes the Updates box, which lists the build's
recent commit subjects. Any subject referencing a #1xxx/#2xxx PR fails it; CI
never sees this because actions/checkout fetches one commit. Use the
existing test override around prepare_messages, reset before any assertion.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01AneFCxyosVWum8kYPUkcEk
KooshaPari pushed a commit that referenced this pull request Oct 14, 2026
…remain

The top-of-doc 'Final state' panel now shows 3 remaining operator-gated
items (was 4). t11 stash drop is DONE. The remaining 3 are:
- P11 disk cleanup (destructive rm -rf)
- P25c rescue branches (operator decision A/B/C/D)
- P30 PR opens (pre_tool blocks gh pr create; browser offline)

Also corrected the PR source branch list: PR #1 source is
security/rustsec-2026-0258-0285 (not master), PR #2 source is
security/quinn-proto-0.11.19 (not feature/upstream-0.88-sync).

tx-agent: jcode
tx-task: final-state-update-3
tx-validated: git-log + read
tx-scope: docs:cleanup-arc-2026-10-13-OPERATOR-ACTIONS.md
tx-intent: reflect t11 DONE in the final state panel
KooshaPari pushed a commit that referenced this pull request Oct 14, 2026
#2)

After the previous workspace clippy port (5 crates), 4 more crates still
had simple clippy failures that fit the lint-cleanup pattern:
- jcode-message-types: 2 redundant_clone
- jcode-tui-mermaid: 3 (items_after_test_module, unnecessary_get, redundant_closure)
- jcode-harness-api: 3 (dead_code on Gap variant, single_element_loop, collapsible_if)
- jcode-herdr: 1 (match → if let)

Bundled into a single draft branch `p25c/port-jcode-workspace-clippy-bonus-2`
(commit 852a979) — 7 files, 9 clippy errors fixed, no behavior
change. All clippy, fmt, and test --no-run gates pass for the 3
fully-fixed crates; jcode-herdr has 5 remaining await_holding_lock
errors that need a real refactor (parking_lot::Mutex, not in scope).

This commit:
- Adds the bonus port to OPERATOR-ACTIONS.md P25c section
- Adds a full Port 5 section to P25C-REVIEW-GUIDE.md
- Updates the decision matrix and the closing summary to mention 5 ports
- Documents the remaining clippy work for the next cleanup arc

tx-agent:     jcode
tx-task:      cleanup-arc-2026-10-13
tx-parent:    67d288d
tx-validated: manual
tx-scope:     docs
tx-intent:    document the bonus workspace clippy port #2
KooshaPari pushed a commit that referenced this pull request Oct 14, 2026
tx-agent: jcode
tx-task: p25c/port-jcode-workspace-clippy-bonus-2
tx-validated: cargo-clippy 0 warnings, cargo-check --workspace PASS
tx-scope: jcode-{message-types,tui-mermaid,harness-api,herdr}
tx-intent: 9 clippy cleanups in 4 workspace crates (jcode-herdr still has 5 await_holding_lock needing real refactor)
KooshaPari added a commit that referenced this pull request Oct 17, 2026
* feat(herdr): CLI subcommands (status/install) + forgecode-runtime module split

- Add 'jcode herdr status' subcommand showing pane env and reporter state
- Add 'jcode herdr install' subcommand writing screen detection manifests
- Extract ForgeCode CLI config, parser, and translator into separate modules
- Wire jcode-herdr dependency into jcode-app-core and jcode-tui

* refactor(forgecode-runtime): wire extracted modules into lib.rs

Replace 1132-line monolithic lib.rs with modular structure:
- config.rs: ForgeCodeCliConfig (env-based config)
- parser.rs: CLI output types (CliOutput, SseEvent, CliOutputParser)
- translator.rs: ForgeCodeEventTranslator (SSE→StreamEvent mapping)
- lib.rs: Provider impl + subprocess execution (~650 lines)

* feat(herdr): add --herdr-kind CLI arg for agent type routing

Allows specifying agent kind for HERDR reporting:
  jcode --herdr --herdr-kind forge
  jcode --herdr --herdr-kind forgecode

Default: 'jcode'. Passed to reporter init instead of hardcoded label.

* release: bump version to 0.85.1-k1.1.0, add CHANGELOG and HERDR docs

- Version bump: 0.85.0-k1.0.0 → 0.85.1-k1.1.0
- CHANGELOG.md: HERDR integration release notes
- docs/HERDR_INTEGRATION.md: comprehensive integration guide

* test(herdr): add mock socket tests for reporter state transitions

5 async tests using a mock Unix socket server:
- reporter_sends_working_state: verifies Working state report
- reporter_sends_idle_state: verifies Idle state report
- reporter_sends_blocked_state: verifies Blocked state via report_error
- reporter_sends_session_id: verifies session identity reporting
- reporter_seq_numbers_increase: verifies monotonic sequence numbers

Plus existing 3 sync tests (source_format, inactive_noop, seq_monotonic)

* fix(herdr): guard tokio::spawn in Drop with Handle::try_current

The Drop impl panicked when dropped outside a tokio runtime (e.g.
synchronous test cleanup). Use Handle::try_current() to check for
an active runtime before spawning.

Also: note jcode-dev isolation requirement from Koosha for future work.

* fix(herdr): resolve all 16 test failures

- Mock server: raw byte I/O instead of BufReader to avoid buffering past line boundary
- Mock server: write response so send_request read_line doesnt hang
- Mock server: return TempDir to prevent premature socket cleanup
- report_error: send blocked state over socket from spawned task
- idle_state test: set Working first then Idle to bypass dedup check
- EnvGuard: save/restore env vars across tests to prevent leakage
- Remove unused imports, fix unused mut warnings

All 16 unit tests + 1 doc-test pass.

* docs: jcode-dev binary isolation design spec

Design for isolating development builds from production jcode sessions.
Uses existing env var overrides (JCODE_RUNTIME_DIR, JCODE_HOME) to prevent
cargo build from interrupting active chat sessions.

* docs: CVP dossier sections 4-6 design (comparator, pilot, measurements)

Covers all three primary repos:
- Comparator baselines pinned (owned builds), upstreams identified as TODO
- Controlled pilot recipes defined per repo with fault injection
- Measurements spec with metrics, instruments, and blocking items
- Fork deltas documented for HeliosLite, HeliosCLI, KCode
- Reuse decisions cataloged

* feat: jcode-dev isolated development wrapper script

Sets JCODE_RUNTIME_DIR and JCODE_HOME to separate paths so cargo build
does not interrupt production jcode sessions. Uses env var overrides
already supported by jcode-harness-api/src/sockets.rs.

See docs/sessions/20260916-jcode-dev-isolation/00_DESIGN.md

* fix: add Clone derive to ForgeCodeCliConfig

Blocks full `cargo test` — lib.rs calls .clone() on this struct.
Trivial fix: all fields are String/Option<String>.

* docs: add specs for screen capture security and manager mode

* fix(tui): consume focus/paste + sync panic hook + UnhandledPanic::Task (Fixes A+B+D) [k1.1.1]

Backports the same TUI fixes applied upstream to 1jehuang/jcode (see
jcode-fixes-applied-2026-09-16.md):

  Fix A: Event::FocusGained/FocusLost/Paste + explicit Some(Err) arms on the
         three select! sites in crates/jcode-tui/src/tui/app/turn.rs (api wait,
         stream, tool exec).

  Fix B: synchronous terminal cleanup + rate guard + <session>.panic.log
         persistence in src/cli/terminal.rs:install_panic_hook().

  Fix D: UnhandledPanic::Task (cfg-gated on tokio_unstable) in src/main.rs.

Build-only fix in crates/jcode-herdr/src/socket.rs: HERDR is Unix-only (uses
tokio::net::UnixStream). Gate the existing paths to #[cfg(unix)] and add a
Windows stub so the workspace still compiles.

Fork version bumped per AGENTS.md fork versioning scheme:
0.85.1-k1.1.0 -> 0.85.1-k1.1.1.

* feat(security): add screen capture env var gates and audit logging

* feat: add manager and researcher agent modes with tool gating, status bar indicator, and system prompt

- Add AgentMode enum (Execute/Manager/Researcher) in config-types
- Add --mode CLI flag (jcode --mode manager|researcher)
- Tool gating: Manager blocks write/edit/patch, Researcher blocks all mutations
- Status bar shows [MGR] amber or [RES] blue for non-default modes
- System prompt injects mode-specific behavioral constraints
- Blocked tools return actionable error with delegation hint

* feat(tui): add /loop slash command for recurring task management

Adds the /loop command family for creating, viewing, pausing, resuming,
and cancelling recurring task loops that persist to ~/.jcode/loops/loops.json.

Commands:
  /loop <interval> <task>  - Create a recurring loop
  /loop status             - Show all active loops
  /loop cancel <id>        - Cancel a loop
  /loop pause <id>         - Pause a loop
  /loop resume <id>        - Resume a paused loop

Intervals: 5m, 30m, 1h, 2h, 1d

tx-agent:     jcode
tx-validated: manual
tx-scope:     jcode-tui/commands_loop, jcode-tui/commands_dispatch, jcode-tui/app
tx-intent:    Implement /loop slash command for recurring task management

* feat: /goal command, /loop recurrence, provider defaults, PWSH+HERDR triage

- Add /goal command (create, status, update, complete, pause, cancel, resume)
- Add Recurrence enum and field to ScheduleRequest for /loop scheduling
- Update provider defaults: minimax->MiniMax-M3, meta-muse->muse-spark-1.3, zai->glm-5.3
- Remove disabled mission/goal stub from commands.rs
- Add herdr.rs module for HERDR integration
- Add PWSH+HERDR triage findings (7 root causes, 5 fixes)
- Add /loop command session specs

tx-agent:     jcode
tx-validated: cargo-check
tx-task:      feat/goal-loop-providers
tx-scope:     ambient, catalog, commands, herdr
tx-intent:    Add goal/loop commands, update stale provider defaults, triage PWSH+HERDR

* fix(shell,herdr): atomic OSC 133 in pwsh + OSC leak filter + shell-aware ! cmd

PWSH+HERDR fixes from triage (docs/sessions/20260917-herdr-pwsh-triage):
- pwsh.rs: replace Write-Host -NoNewline with [Console]::Write so OSC 133
  sequences flush atomically instead of being buffered through PS's output
  pipeline (root cause of random input symbols under HERDR)
- key_handling.rs: filter leaked \x1b]133; sequences instead of passing them
  through as literal input; add /exit alias for /quit
- input.rs + client_actions.rs: on Windows detect PowerShell and use
  pwsh.exe -NoProfile -Command instead of hardcoded cmd.exe /C for ! commands
- .gitignore: ignore dedicated build dirs (target-jcode-build, target-check*)
- add model cache refresh investigation findings

tx-agent:     jcode
tx-validated: cargo-check
tx-task:      herdr-pwsh-fixes
tx-scope:     shell-integration, tui, app-core
tx-intent:    Fix PWSH+HERDR input corruption

* fix(provider): start catalog sweeper at provider init + log skipped refreshes

From docs/sessions/20260917-model-cache-refresh/FINDINGS.md rec #1 and #2:
- Call catalog_scheduler::ensure_started() in MultiProvider::new so the
  background catalog sweeper runs at process launch instead of only after a
  lazy trigger (which never fires if /model is never opened, leaving all
  configured profile catalogs stale past the 24h TTL)
- Log the previously-silent abort paths in
  maybe_schedule_openai_compatible_profile_catalog_refresh so skipped profile
  refreshes are visible (api_base normalize failure, missing API key env, no
  tokio runtime)

tx-agent:     jcode
tx-validated: cargo-check
tx-task:      model-cache-refresh
tx-scope:     jcode-base/provider, provider-openrouter-runtime
tx-intent:    Ensure all provider model catalogs refresh proactively

* fix(build): repair 6 compile errors blocking release build

The tree did not compile. Fixes:
- jcode-tui/src/lib.rs: declare missing `pub mod herdr;` (herdr.rs was added
  but never wired in; 8x E0433 'cannot find herdr in crate')
- jcode-provider-forgecode-runtime/src/parser.rs: remove invalid `pub(crate)`
  qualifiers from enum variant fields (36x E0449) and fix `pub(crate)` before
  `#[derive]` syntax error (E0609/E0560)
- jcode-provider-forgecode-runtime/src/lib.rs: import CliOutputParser from
  translator, not parser (E0432)
- jcode-tui/tui/app/commands_loop.rs: add named lifetime to find_loop_mut
  (E0106)
- src/cli/proctitle.rs: cover HerdrStatus/HerdrInstall match arms (E0004)
- src/cli/startup.rs: use safe crate::env::set_var (edition 2024 E0133)
- Cargo.toml: declare jcode-config-types dependency (E0433)
- scripts/strip_enum_visibility.py: helper used for the parser.rs repair

Release build now succeeds: jcode v0.0.0-dev (1d16d4874)

tx-agent:     jcode
tx-validated: build
tx-task:      fix-release-build
tx-scope:     build, tui, provider-forgecode-runtime, cli
tx-intent:    Restore a compiling release build

* fix(ambient): add missing recurrence fields to test fixtures

The /loop Recurrence enum added fields to ScheduledItem and
ScheduleRequest, but 13 ambient test initializers were not updated.
This blocked cargo test compilation of jcode-app-core.

- ambient_tests.rs: 12 ScheduledItem initializers now pass
  recurrence: Recurrence::Once
- ambient/runner_tests.rs: 1 ScheduledItem initializer fixed plus
  Recurrence import added

Validated: cargo check -p jcode-app-core --tests (exit 0) and
cargo test -p jcode-app-core --lib ambient (56 passed, 0 failed).

tx-agent:     jcode
tx-validated: test
tx-task:      fix-recurrence-fixtures
tx-scope:     jcode-app-core
tx-intent:    Restore test compilation for the /loop recurrence feature

* fix(ambient): add missing recurrence fields to e2e and tui test fixtures

Same class of defect as the jcode-app-core fixtures: the /loop Recurrence
field was added to ScheduledItem/ScheduleRequest without updating the
external test targets.

- tests/e2e/ambient.rs: 3 ScheduledItem initializers now pass
  recurrence: Recurrence::Once; Recurrence imported from jcode::ambient
- crates/jcode-tui/src/tui/app/helpers_tests.rs: 3 ScheduleRequest
  initializers fixed; Recurrence imported via crate::ambient

Validated: cargo check -p jcode-tui --tests (exit 0) and
cargo check -p jcode --test e2e (exit 0), both Finished with warnings only.

tx-agent:     jcode
tx-validated: build
tx-task:      fix-recurrence-fixtures-e2e
tx-scope:     tests/e2e, jcode-tui
tx-intent:    Complete test-fixture coverage for the /loop recurrence feature

* fix(tool): make bench-referenced tool modules public

benches/startup.rs constructs tool types directly (e.g.
jcode::tool::multiedit::MultiEditTool::new()), but 17 of those modules
were declared private, so 'cargo check --all-targets' and 'cargo bench'
failed with 33 E0603 errors. This was pre-existing on origin/master
(3f5e2df22 added the benches, 9c37986db made only some modules public).

Promotes exactly the modules the benches reference. All 17 already
declare a pub struct <Tool> with the constructor the benches call.

Validated: cargo check -p jcode --benches (exit 0, Finished).

tx-agent:     jcode
tx-validated: build
tx-task:      fix-bench-tool-visibility
tx-scope:     jcode-app-core tool visibility, benches
tx-intent:    Restore 'cargo check --all-targets' / 'cargo bench' for the jcode crate

* fix(command-risk): add missing scratch_dir to pipeline test fixture

RiskContext gained a scratch_dir field (used to honor JCODE_SCRATCH_DIR
in path guards), but pipeline_tests.rs still built the struct with only
working_dir and home_dir, so the crate's lib test target failed to
compile under 'cargo check --workspace --all-targets'.

The other RiskContext fixtures in assess_tests.rs, gate_tests.rs and
paths_tests.rs already pass the field.

Validated: cargo test -p jcode-command-risk (209 passed, 0 failed, exit 0).

tx-agent:     jcode
tx-validated: test
tx-task:      fix-riskcontext-fixture
tx-scope:     jcode-command-risk
tx-intent:    Restore all-targets compilation for jcode-command-risk

* fix(jcode-command-risk): replace never-looping for-loop with if-let

The for-loop at line 59 returned on the first iteration, triggering
clippy's never_loop lint and failing the CI gate. Replaced with an
idiomatic if-let that preserves the exact same behavior.

tx-agent:     jcode
tx-validated: lint,test
tx-task:      fix-clippy-neverloop
tx-scope:     jcode-command-risk
tx-intent:    Unblock the CI clippy gate

* fix(clippy): resolve 5 machine-applicable warnings in jcode-command-risk

Fix trim_split_whitespace (pipeline.rs:106), two collapsible_if
(pipeline.rs:160,175), needless_range_loop (heredoc.rs:151), and
unnecessary_sort_by (heredoc.rs:207). All changes are form-only and
behavior-preserving.

tx-agent:     jcode
tx-validated: lint,test
tx-task:      clippy-machine-applicable-cleanup
tx-scope:     jcode-command-risk
tx-intent:    Reduce clippy -D warnings gate failures

* fix(clippy): resolve machine-applicable warnings in base, micro-compact, setup-hints

Continues the clippy -D warnings reduction started in a34b10645. All
changes are form-only and behavior-preserving:
- jcode-base/src/auth/cursor.rs: drop `return` in tail position of the
  macOS cfg block (blocks are mutually exclusive, so the block is the
  function's tail expression on macOS)
- jcode-base/src/auth/lifecycle.rs: merge nested `if` into one condition
- jcode-micro-compact/src/token_estimate.rs: manual ceil-div ->
  `div_ceil` (same arithmetic, no overflow regression)
- jcode-setup-hints/src/lib.rs: drop three tail-position `return`s and
  use `is_multiple_of` instead of `% 3 != 0`

Validation (coordinator-run, not just subagent-reported):
- cargo check -p jcode-base -p jcode-micro-compact -p jcode-setup-hints
  --all-targets -> exit 0, 0 errors
- cargo test -p jcode-base -p jcode-micro-compact -p jcode-setup-hints
  -> 1367 passed, 11 failed
- cargo clippy -p jcode-setup-hints --all-targets -> exit 0
- Attribution of the 11 failures: reverted these four files to HEAD,
  re-ran the suite, and got the identical 1367 passed / 11 failed. The
  failures are therefore pre-existing and unrelated (e.g. the lifecycle
  test fails because provider "grok-build" is absent from
  normalized_auth_provider_id; other failures assert external account
  state). The four files were then restored from a saved patch,
  verified byte-identical.

tx-agent:     jcode
tx-validated: build,test,lint
tx-task:      clippy-machine-applicable-cleanup
tx-scope:     jcode-base, jcode-micro-compact, jcode-setup-hints
tx-intent:    Reduce clippy -D warnings gate failures

* fix(session-types): resolve clippy enum_variant_names

tx-agent:     jcode
tx-validated: lint,test
tx-task:      clippy-enum-variant-names
tx-scope:     jcode-session-types
tx-intent:    Unblock the CI clippy -D warnings gate

* fix(process): reap detached children so they cannot become zombies

The server accumulated 43 `<defunct>` children parented to PID 41098.
`execute_reload_persistable_foreground` spawns a detached shell via
`platform::spawn_detached` (setsid) and then returns while the child is
still alive whenever the foreground timeout fires or a graceful reload
is requested, dropping the `std::process::Child` without `wait()`.
On Unix that never collects the exit status, so the process stays a
zombie under the server forever. Detached task cancellation has the same
consequence: the background manager kills by pid and holds no handle.

Hand the still-running child to the existing `platform::reap_detached`
helper at both handoff points, so the exit status is collected whether
the task ends naturally or is killed by a later cancel. Reap the
remaining spawn-and-return-without-wait sites in the same family: the
`open` grace-period opener, the focus hook, and the terminal launcher.

Verified against the live server: 28 background-task status files carry
`"detached": true` and `"tool_name": "bash"`, and cancelled task 90724 is
one of the live zombies, confirming the detached handoff path.

Validation: `cargo check -p jcode-app-core --lib` -> exit 0,
"Finished `dev` profile in 7m 11s" (pre-existing dead-code warnings only).

tx-agent:     jcode
tx-validated: cargo-check
tx-task:      zombie-child-reaping-pid41098
tx-scope:     jcode-app-core/tool/bash, jcode-app-core/tool/open, jcode-app-core/session_launch, jcode-base/terminal_launch
tx-intent:    Reap detached child processes so exited background bash tasks do not linger as zombies under the server

* fix(auth): register grok-build in provider lifecycle normalization

`every_model_login_provider_has_explicit_lifecycle_normalization` was
failing with `model login providers missing lifecycle normalization:
["grok-build"]`. A provider was added to the login catalog without being
registered in the normalization function.

`GROK_BUILD_LOGIN_PROVIDER` (crates/jcode-provider-metadata/src/catalog.rs)
has id "grok-build" and target LoginProviderTarget::GrokBuild. The test
treats only AutoImport and Google as non-model auth surfaces, so GrokBuild
must normalize. normalized_auth_provider_id reaches
normalized_login_provider_id via resolve_login_provider (provider-metadata
lib.rs:188), which had no grok-build arm, so it returned None.

Adds the missing arm. Fixes the invariant test.

Verification note (honest): the dynamic test run was launched but blocked
indefinitely on the cargo build-dir lock held by concurrent agents, and was
cancelled deliberately because free disk fell to 6.1Gi during the run. The
fix is instead verified by a complete static trace of the test's own logic:
provider list membership, the is_non_model_auth_surface exclusion list
(AutoImport, Google only), the delegation chain through
resolve_login_provider, and the test's own output naming grok-build as the
sole missing provider.

tx-agent:     jcode
tx-validated: manual
tx-task:      fix-grok-build-normalization
tx-scope:     jcode-base
tx-intent:    Make every catalog provider normalize so the lifecycle invariant test passes

* test(platform): add reap_detached zombie-child regression test

Guards the fix that reaps detached children instead of dropping them.
The test spawns a short-lived detached child, proves via `ps -o stat=` that
it lingers as an unreaped zombie (so the observation method demonstrably sees
zombies), calls reap_detached, then asserts with bounded polling that the pid
disappears entirely rather than becoming/staying `Z`, and that no `<defunct>`
child of this process keeps the pid. A second test asserts reap_detached does
not block the caller on a long-lived child.

tx-agent: jcode
tx-validated: test
tx-task: zombie-child-reaping-pid41098
tx-scope: jcode-base/platform
tx-intent: Add regression test proving reap_detached prevents zombie children

* fix(tool-core): box large error variant to satisfy clippy result_large_err

The elicit_channel::try_send function returned
Result<(), SendError<ElicitMessage>> where ElicitMessage
is a large struct containing serde_json::Value fields and a
oneshot::Sender. Clippy denies this as result_large_err.

Fix: box ElicitMessage inside the channel. The global static
and receiver type now use Box<ElicitMessage>. try_send still
accepts ElicitMessage by value and boxes it internally, keeping
the caller API unchanged. The single external call site in
jcode-app-core maps the error to anyhow immediately, so the
boxed error type change is transparent.

Updated call sites:
- jcode-tui: App.elicit_rx receiver type and handle_elicit_msg
  parameter updated to Box<ElicitMessage>, with deref on
  destructuring.

tx-agent:     jcode
tx-validated: lint,test
tx-task:      clippy-result-large-err
tx-scope:     jcode-tool-core
tx-intent:    Unblock the CI clippy -D warnings gate

* fix(clippy): resolve type_complexity and wrong_self_convention blockers

tx-agent:     jcode
tx-validated: lint,test
tx-task:      clippy-type-complexity-wrong-self
tx-scope:     jcode-tui-mermaid, jcode-setup-hints
tx-intent:    Unblock the CI clippy -D warnings gate

- jcode-tui-mermaid/src/lib.rs: introduce InlineLevelGeometryMap type alias
  for LazyLock<Mutex<HashMap<u64, [(u16, u16); 3]>>> to satisfy
  clippy::type_complexity.
- jcode-setup-hints/src/keymap/mod.rs: rename from_source(&self, ..) to
  bindings_from_source(&self, ..) to fix clippy::wrong_self_convention
  (from_* methods should take no self). This is a public API rename;
  report.rs caller updated in same commit.

* fix(clippy): collapse ifs and fix late init in jcode-tui-render

Unblocks the next crate in the CI clippy -D warnings chain
(jcode-session-types -> jcode-tool-core -> jcode-tui-mermaid ->
jcode-tui-render).

- swarm_gallery/hover.rs: 7 collapsible_if sites converted to `if let`
  let-chains with `&&`. The crate is edition 2024 (Cargo.toml), so let
  chains are valid. Evaluation order and short-circuiting are preserved;
  each collapse merges only the guards, leaving the body unchanged.
- swarm_gallery/strip.rs: `unneeded late initialization` replaced with a
  direct `let used: usize = if ... { ... } else { ... }` binding of the
  same type. Control flow unchanged.

Coordinator-verified (not taken on report):
- cargo clippy -p jcode-tui-render --all-targets -> exit 0, with 0
  "can be collapsed" and 0 "late initialization" hits.
- cargo test -p jcode-tui-render -> 64 passed, 10 passed, 0 failed, exit 0.
- Also removed trailing whitespace the edit introduced (git diff --check).

tx-agent:     jcode
tx-validated: lint,test
tx-task:      clippy-tui-render-round4
tx-scope:     jcode-tui-render
tx-intent:    Unblock the CI clippy -D warnings gate

* fix(clippy): resolve lints in openrouter-runtime and harness-api-server

Provenance: these edits were produced by a delegated worker that died before
committing. I (coordinator) took them over and verified them rather than
discarding them:
- cargo check --workspace --all-targets --all-features -> exit 0, 0 errors
- cargo clippy -p jcode-app-core -p jcode-provider-openrouter-runtime
  --all-targets --all-features -> exit 0, 0 errors
- no debug artifacts; all changed paths under crates/

Changes are behavior-preserving:
- openrouter_sse_stream.rs: `iter().any(|m| model == *m)` ->
  `contains(&model)`; nested `if let` -> let-chain; `let mut
  current_event_type` -> `_current_event_type` (written, never read);
  removed two `in_thinking = false` resets in the `response.completed`
  and `response.incomplete` arms, both of which end in `return Ok(())`,
  so the resets were unread (verified by reading the arms).
- catalog merge tests: test-body scoping refactor, assertions retained.

tx-agent:     jcode
tx-validated: build,lint
tx-task:      clippy-openrouter-runtime
tx-scope:     jcode-provider-openrouter-runtime, jcode-harness-api-server
tx-intent:    Unblock the CI clippy -D warnings gate

* fix(clippy): resolve lints across app-core and supporting crates

Provenance: delegated workers produced these edits and died before
committing. I (coordinator) took them over and verified them:
- cargo check --workspace --all-targets --all-features -> exit 0, 0 errors
- cargo clippy -p jcode-app-core --all-targets --all-features -> exit 0, 0 errors
- all changed paths under crates/; no debug artifacts; assertions retained
  (test files show refactors, not test removals)

Change classes: 20x `new_without_default` (added real `Default` impls
rather than allows), dead_code cleanups, collapsible_if let-chains,
needless_return, unused_assignments, needless_borrow/needless_lifetimes,
derivable_impls, plus targeted items.

Note: turn_cancel_registry.rs also carries an unrelated behavioral fix
(`has_active_turn`, used by client_state/client_lifecycle and covered by
client_lifecycle_tests) that was already present in the working tree from
another agent; it is included here because it is inseparable from the
same file's lint edits and was verified to compile and test clean.

tx-agent:     jcode
tx-validated: build,lint
tx-task:      clippy-app-core-bulk
tx-scope:     jcode-app-core, jcode-base, jcode-cache-vectors, jcode-herdr, jcode-session-memory, jcode-shell-integration, jcode-terminal-detect, jcode-tool-search
tx-intent:    Unblock the CI clippy -D warnings gate

* fix(clippy): attach too_many_arguments expect to the function it covers

comm_session.rs had `#[expect(clippy::too_many_arguments)]` placed above a
doc comment, so it bound to `resolve_swarm_spawn_effort` (2 args, lint never
fires) instead of the 21-arg `spawn_swarm_agent` below it. That produced two
deny-level errors under CI's `-D warnings`:
  - clippy::too_many_arguments, because spawn_swarm_agent was uncovered
  - unfulfilled_lint_expectations, because the expect was never satisfied

Moves the attribute onto `spawn_swarm_agent`, restoring the doc comment to
its own function. No behavior change.

Verified: cargo clippy -p jcode-app-core --all-targets --all-features
-> exit 0, 0 "too many arguments" hits, 0 "expectation is unfulfilled" hits.

tx-agent:     jcode
tx-validated: lint
tx-task:      clippy-final-batch
tx-scope:     jcode-app-core
tx-intent:    Unblock the CI clippy -D warnings gate

* fix(tool): register the initiative tool so /goal is actually reachable

`InitiativeTool` (crates/jcode-app-core/src/tool/goal.rs, reports name
"initiative") was implemented and covered by 20 tests but never added to
the tool registry in tool/mod.rs, so the feature was unreachable at
runtime. clippy's dead_code lints were correctly detecting this: it
reported `InitiativeTool` never constructed, `GoalInput` never
constructed, and 8 associated functions/fields never used.

Registers it alongside `todo` under the key "initiative" (matching
Tool::name()). This is a real product fix, not a lint suppression:
previously any user or agent invoking the initiative tool would get an
unknown-tool error.

Verified: cargo clippy -p jcode-app-core --all-targets --all-features
-> exit 0, 0 errors, no goal.rs dead_code remaining; and
cargo test -p jcode-app-core goal -> 20 passed, 0 failed, exit 0.

tx-agent:     jcode
tx-validated: lint,test
tx-task:      clippy-final-batch
tx-scope:     jcode-app-core
tx-intent:    Make the /goal feature reachable and unblock the clippy gate

* fix(clippy): clear app-core, doctor, forgecode blockers; drop dead fork field

Unblocks three crates from the CI clippy -D warnings chain. After this,
none of app-core / provider-doctor / provider-forgecode-runtime
compile-fails; the chain now stops on jcode-tui instead.

- provider-forgecode-runtime: removed unused imports (CliMessage,
  UsageInfo, ForgeCodeEventTranslator).
- provider-doctor: `iter().any(|m| model == *m)` -> `contains(&model)`.
- app-core/agent/permission_bubble.rs: removed the dead
  `PermissionBubbleResult::system_prompt` field. It was written at both
  construction sites and never read by any consumer (the only caller,
  overnight.rs, uses `denied` and `messages`), and the value came from
  two `build_child_message(directive)` calls whose results were
  discarded. Field, both wasted calls, the now-unused import, and the
  consequently-dead `directive` parameter are all removed; the single
  call site in overnight.rs is updated.
- overnight.rs: dropped the `directive` binding left dead by the above.
  The session title still derives from `mission` directly.

This is a real cleanup, not lint suppression: it removes a struct field
and two discarded allocations per fork.

Verified: the three crates no longer appear as compile failures in
`cargo clippy --all-targets --all-features -- -D warnings`; the
remaining error set is entirely jcode-tui.
(Note: an earlier iteration of this change introduced an unused-parameter
error, which I caught and fixed before committing.)

tx-agent:     jcode
tx-validated: lint
tx-task:      clippy-final-batch
tx-scope:     jcode-app-core, jcode-provider-doctor, jcode-provider-forgecode-runtime
tx-intent:    Unblock the CI clippy -D warnings gate

* fix(build): make the host-wide Cargo gate work on macOS

The gate in scripts/dev_cargo.sh has never actually engaged on macOS, for
two independent reasons, and it silently degraded instead of failing:

1. macOS ships no `flock`, so `command -v flock` failed and the function
   returned at the "flock is unavailable" branch. This is why every logged
   run carries gate_wait_ms=0: agents were never serialized, and concurrent
   agents built against one target directory unchecked.

2. `exec {cargo_gate_fd}>"$gate_path"` needs bash 4.1+, but /bin/bash is
   3.2.57 here and /usr/bin precedes Homebrew on PATH, so the brace form
   raises "exec: {cargo_gate_fd}: not found". Under `set -e` that aborts
   the wrapper before Cargo runs at all. The missing flock is the only
   reason this line was never reached.

Replace the dynamic descriptor with a fixed high one, which has the same
lock lifetime on bash 3.2 and 5.x. A companion flock shim provides the
util-linux fd semantics the gate expects on macOS.

Verified on bash 3.2: `bash -n` parses; a held gate makes a real build
action log "waiting for the host-wide Cargo gate"; with the gate free the
same action logs "acquired host-wide Cargo gate" and Cargo runs to
"Finished" in 1.58s.

tx-agent:     jcode
tx-validated: test
tx-task:      cargo-gate-macos
tx-scope:     scripts/dev_cargo.sh
tx-intent:    Restore host-wide Cargo serialization that was silently disabled on macOS

* perf(build): default to non-incremental so sccache caches across agents

This host has 16GB of RAM, so maybe_configure_low_memory_selfdev caps Cargo
to a single job and every build is effectively serial. Observed build costs
on identical commands were 18.8 and 22.7 minutes.

sccache cannot cache incremental compilation units, so the wrapper skips it
for the default (incremental) profile and the cache never helps. Default
CARGO_INCREMENTAL to 0 instead: build_is_incremental keys off that variable,
so maybe_enable_sccache engages automatically and unchanged crates are served
from cache rather than recompiled by every agent.

Measured before the change: a forced recompile executed 1 Rust compile with 0
cache hits. After: the same recompile produced a Rust cache hit and finished
in 0.64s instead of invoking rustc, and a plain `check` now logs
"using sccache" with no environment overrides.

Overridable: `CARGO_INCREMENTAL=1 cargo ...` restores incremental for a
focused edit loop.

tx-agent:     jcode
tx-validated: test
tx-task:      cargo-sccache-default
tx-scope:     scripts/dev_cargo.sh
tx-intent:    Make the sccache cache effective by default on a memory-capped host

* fix(herdr): stop holding the reporter mutex across await points

src/herdr.rs still used std::sync::Mutex while the TUI crate's copy had
already moved to tokio::sync::Mutex. Holding a std MutexGuard across
.await is a real deadlock/blocking risk and trips clippy
await_holding_lock. Mirror the proven TUI pattern: await-style locking,
try_lock in the sync is_active(), collapsible_if resolved by the
await-style rewrite.

tx-agent:     jcode
tx-validated: lint,test
tx-task:      clippy-herdr-awaitlock
tx-scope:     src/herdr.rs
tx-intent:    Remove a real lock-across-await deadlock risk and clear clippy blockers

* test(herdr): serialize env-mutating tests behind a shared lock

The 3 env tests and 6 reporter tests all mutate the same HERDR_*
process-env keys concurrently under libtest's parallel workers. That
is a data race (UB in Rust): it hung the libtest console indefinitely
waiting for CompletedTest events and intermittently failed
env.active assertions (15/16).

Add crate-local test_support::lock_test_env() following the existing
jcode-base storage pattern and hold it for the full body of every
env-touching test. Reporter captures env eagerly at construction, so
serializing construction is sufficient; async bodies only touch the
reporter's own Arc<Mutex> state.

Verified: 16/16 jcode-herdr tests pass in 3s, stable across 4 runs
(previously hung >10min); workspace check exits 0.

tx-agent:     jcode
tx-validated: test
tx-task:      herdr-env-race
tx-scope:     crates/jcode-herdr
tx-intent:    Fix UB env data race that hung the test suite

* fix(cli): wire orcarouter into provider choice table; roll up any_available from per-provider report

Two pre-existing test failures, both rooted in catalog/state drift:

1. login_provider_choice_table_round_trips_catalog_providers
   auth_integration_registry_matches_cli_choice_runtime_wiring
   Commit a2622db13 added OrcaRouter to crates/jcode-provider-metadata/src/catalog.rs
   but never wired it into src/cli/provider_init.rs (ProviderChoice variant,
   as_arg_value arm, PROVIDER_CHOICE_LOGIN_PROVIDERS table, init_provider
   construction match). The catalog-vs-CLI parity test correctly caught this.
   Fix: add OrcaRouter variant (alias 'orca-router', arg 'orcarouter') and
   thread it through all four sites. Falls into the OpenAiCompatible profile
   arm of init_provider_with_options alongside Belvedir/Cerebras/Chutes.

2. cli_auth_status_doctor_and_login_lifecycle_uses_fresh_sandbox
   has_any_available() in crates/jcode-base/src/auth/mod.rs:393 only checks
   the 14 wired AuthStatus fields (anthropic, jcode, openai, openrouter,
   azure, bedrock, copilot, antigravity, gemini, cursor, grok_build, ...).
   With ~50+ providers in the catalog, the roll-up was undercounting the
   moment a user logged in via cerebras (or any non-tracked OpenAi-compatible
   gateway). The sandbox test logs in via cerebras and asserts any_available,
   which legitimately failed.
   Fix: compute any_available from the per-provider report (which already
   iterates auth_status_login_providers() and so covers the full catalog).
   This keeps has_any_available() as-is for the callers that don't need
   catalog-wide coverage; the report-level roll-up is the comprehensive one.

Verified:
- cargo clippy -p jcode --all-targets -- -D warnings: exit 0 (clean)
- cargo test -p jcode --lib login: 42/42 pass (was 2/42)
- cargo test -p jcode --lib cli_auth_status_doctor_and_login_lifecycle_uses_fresh_sandbox: ok
- cargo test -p jcode --lib login_provider_choice_table_round_trips_catalog_providers: ok
- cargo test -p jcode --lib auth_integration_registry_matches_cli_choice_runtime_wiring: ok

tx-agent: jcode
tx-validated: test
tx-task: fix-orcarouter-choice-table-and-any-available-rollup
tx-scope: src/cli/provider_init.rs src/cli/commands/report_info.rs
tx-intent: clear two pre-existing test failures rooted in catalog/state drift so the login module suite is green and the workspace test gate is reliable

* fix(clippy): clear remaining jcode CLI lint blockers

Five files, each autofix or targeted annotation only:

- benches/startup.rs: 25 redundant-closure autofixes from 'cargo clippy --fix'
- src/cli/commands/menubar.rs, src/cli/macos_notification_broker.rs,
  src/cli/commands/menubar.rs: collapsible_if autofixes
- src/cli/login/scriptable.rs (emit_scriptable_auth_prompt):
  #[allow(clippy::too_many_arguments)] with one-line justification: single
  call site, JSON-shaped struct, grouping refactor would churn without
  clarifying
- src/cli/login/tests.rs (scoped_concurrent_begin_completion_and_cancel_are_isolated):
  #[allow(clippy::await_holding_lock)] with one-line justification: the
  env-isolation guard MUST span awaits (JCODE_HOME has to stay set for the
  isolation to hold), joined futures call only production code that never
  acquires this test-only lock, and #[tokio::test] runs on the
  single-threaded current_thread runtime so no other thread can race the
  inner lock

Verified:
- cargo clippy -p jcode --all-targets -- -D warnings: exit 0 (clean)
- cargo clippy -p jcode --bench startup -- -D warnings: exit 0 (clean)

tx-agent: jcode
tx-validated: lint
tx-task: clear-jcode-cli-clippy-tail
tx-scope: benches/startup.rs src/cli/commands/menubar.rs src/cli/login/scriptable.rs src/cli/login/tests.rs src/cli/macos_notification_broker.rs
tx-intent: clear remaining jcode CLI clippy blockers so the workspace lint gate stays green

* fix(tui): clear jcode-tui clippy blockers; dedupe onboarding tests

tx-agent:     jcode
tx-validated: build
tx-task:      orphan-batch-jcode-tui
tx-scope:     crates/jcode-tui
tx-intent:    Land validated clippy fixes (let-chains, is_none_or, const thread_local, early-return removal) plus onboarding test dedupe so the workspace clippy -D warnings gate passes

* chore(deps): enable Dependabot via minimal config

Co-authored-by: jcode <[email protected]>

* refactor(decollision): rename jcode to kcode (#33)

* feat(tui): support embedded and multiple slash commands (#1278)

* test(tui): cover embedded and multiple slash commands

* feat(tui): support embedded slash commands

* fix(tui): adapt embedded slash commands to current master

Drop the removed /plugin case and avoid an ||-chain line that trips the
shared-dispatch guard test.

---------

Co-authored-by: Jeremy Huang <[email protected]>

* fix(tui): give drag-edge autoscroll its own step and cadence (#1400)

* fix(tui): give drag-edge autoscroll its own step, not the wheel momentum path

Holding the mouse at the top or bottom edge of the chat pane while
drag-selecting routed through scroll_copy_selection_pane ->
enqueue_mouse_scroll, the mouse-wheel momentum path. That path infers flick
force from the gap between events: a ~16ms autoscroll tick always looked like
a hard flick, so each tick queued min(3 * 2, 5) = 5 lines against a 30-line
cap, while each call drained up to 3 lines and the frame drain took 3 more.
The queue saturated and drained a flat 3 lines/frame (~180 lines/s at 60fps),
and after release the leftover queue kept draining for ~10 frames, which is
the reported glide.

The drag autoscroll now steps exactly one line through the wheel's per-line
primitive (apply_mouse_scroll_step) and never touches the queue. Its rate
comes from a fixed REDRAW_COPY_AUTOSCROLL tick rather than inheriting
redraw_fps, so the speed is a property of the gesture, not the display. The
initial nudge is applied once when the drag enters the edge band (or flips
direction); while the cursor stays in the band the tick loop owns scrolling.

Wheel behavior is untouched: enqueue_mouse_scroll, the velocity multiplier,
the queue, and the ease-out drain are all unchanged, and
scroll_copy_selection_pane still routes wheel events through them. Only the
programmatic caller changed.

Fixes #1332

* test(tui): cover the drag-edge autoscroll rate and release

Regression test for the reported bug: one tick moves exactly one line (never a
velocity-scaled wheel notch, and never accelerating while held), the tick
cadence is pinned to REDRAW_COPY_AUTOSCROLL instead of the refresh rate, and
the view does not drift after release (the old momentum glide).

* refactor(tui): trim comments around the autoscroll fix

Shorter comments on the cadence const, the redraw branch, and the new step
helper, and drop the re-export added only for the test, which now names
crate::tui::redraw_schedule::REDRAW_COPY_AUTOSCROLL directly.

* fix(tui): keep the display cadence while dragging at a pane edge

The drag-edge autoscroll pinned the redraw tick to its own 30ms cadence,
which precedes the processing/streaming branch in the scheduler. Holding a
drag at the edge while output streamed therefore dropped live redraws from
the configured rate (60fps by default) to 33fps. Use the faster of the two
cadences: the tick stays at the display rate while the gesture still never
ticks slower than its own step cadence.

Also clear the armed edge autoscroll when copy-selection mode exits. A drag
that later started at the same pane and edge compared equal to the stale
value and skipped its entry nudge.

Addresses the greptile review on #1400.

* revert(tui): keep the drag-edge autoscroll cadence fixed

Reverts the display-cadence change from the previous commit. Taking
`min(REDRAW_COPY_AUTOSCROLL, fast_interval)` let the drag advance at the
display rate instead: one scroll step per tick, so about 62.5 lines per
second at a 60fps setting and 125 at 120fps, against the 33.3 lines per
second the gesture is defined by.

Settling on the fixed cadence: the gesture rate is a property of the
gesture, not of the display. The cost is that a held edge drag ticks at
33fps while output streams, which is the trade accepted in the review on
#1400. A separate wall-clock step deadline would buy both, at the price of
another field to reset in every exit path for a sub-second interaction.

Kept: `exit_copy_selection_mode` clears the armed edge autoscroll, so a
re-entered drag at the same pane and edge keeps its entry nudge.

* style: attribute palette overrides by role identity, not color proximity (#1399)

* style: attribute palette overrides by role identity, not color proximity

`remap_literal_using` matched every buffer color against the nearest
overridden role default in Oklab space, so a single override repainted
unrelated roles: `/colors dim` also moved `tool`, `border`, `md_dim`, and the
`user_bg`/`selection_bg` backgrounds.

Only a color that *is* a role's default is now attributed to that role (named
colors keep their explicit mapping). Ad hoc `rgb(...)` literals carry no role
and are left alone, which is the trade: configurable means role-tagged, so give
a shade a role if it should follow `/colors`. No proximity guess, no bleed, and
an override can never touch another role's output.

Deletes `remap_literal_using`, `remap_literal_with`, `remap_literal`,
`adapt_color`, `match_target`, the legacy `adapt_buffer_for_palette`, and the
literal-coverage tests. `FAMILY_RADIUS` and `role_for_rendered` stay as
frame-measurement tooling for the harmony topology test; `palette_literals.rs`
stays as the light-contrast corpus. Default palettes are unchanged.

Part of #1397. Supersedes #1394.

* test(style): serialize palette and theme tests on one shared lock

The palette and theme-mode test modules each held their own TEST_LOCK while
mutating the same process-global palette and THEME_MODE, so a theme test could
flip Light between a palette test's Dark setup and its assertion.
light_theme_interaction mutated both globals with no lock at all.

One crate-level STYLE_TEST_LOCK now covers every test that touches either
global, held through setup, assertion, and restore.

---------

Co-authored-by: zipadoodlez <[email protected]>

* fix(tui): stop two account tests asserting labels the store never assigns (#1368) (#1368)

* fix(session): prune stale active-pid markers left by the exec reload (#1419) (#1419)

* style: cargo fmt after #1419

* Add Claude session-limit reset client and banked reset reporting for GUI clients

- jcode-base: Claude /limit-reset contract (read-only at-wall offer lookup,
  profile-pinned organization, confirmed claim, cache and cooldown invalidation)
- jcode-base: account-scoped OpenAI reset preparation and GUI review details
- protocol/daemon: invalidate_anthropic_usage, and both invalidations are now
  lightweight one-shot control requests
- harness API/SDKs: invalidate_usage request for Rust and TypeScript
- CLI: jcode usage --json reports redeemable banked resets per login

* test: split synthetic AWS key so the secret-scan preflight passes

* fix(macos): gate paused_jcode_shell_command to tests

After the CLI launcher bundle was dropped, only tests call it, so macOS builds
reported it as dead code and exceeded the zero-warning budget.

* deps: bump h2 to 0.4.19 and rustls to 0.23.45 past RUSTSEC-2026-0258/0285

* style: satisfy clippy manual_contains in slash command parser

* feat: add Yolo-Auto provider (#1432)

* perf: skip full session scan when resuming an unknown generated session id

Reload handoff re-execs clients with --resume <id>. When the id existed only
server-side, find_session_by_name_or_id fell through to a title scan that
parsed every session file (~2600 files, 1.1GB), stalling client startup ~15s.
Generated ids can never match a short name or title, so bail early.

* fix(jev): retry transient 429/5xx/529 overload on the same route with bounded backoff

* style(jev): rustfmt

* refactor(providers): remove the Claude Code CLI subprocess transport

Jcode talks to provider APIs directly (Claude via the native Anthropic
OAuth/API runtime) rather than shelling out to vendor CLIs. Drop the
deprecated jcode-provider-claude-cli-runtime crate, MultiProvider's claude
slot and use_claude_cli flag, and the ClaudeSubprocess provider choice.

--provider claude-subprocess remains a hidden alias for claude, and
JCODE_USE_CLAUDE_CLI is now ignored with a warning. test_api and the real
provider smoke script now exercise the direct Anthropic runtime.

* refactor(bedrock): resolve aws login profiles via the SDK instead of the aws CLI

Enable aws-config's credentials-login feature so ProfileFileCredentialsProvider
reads `aws login` (login_session) profiles natively, and drop the
`aws configure export-credentials` subprocess.

* voice_intent: evaluate Jev batches concurrently

Voice sends wait on classification. Batches share identical state and are
independent, so run them with try_join_all instead of sequential round trips.

* harness bridge: stop per-event thread churn and return retained heap

Streaming events went through block_in_place, handing the worker core to a
fresh blocking thread per delta. With Tokio's default 512-thread, 10 s
keep-alive pool and glibc's per-thread arenas, one desktop connection grew
the bridge to 69 threads and ~123 MB of anonymous memory.

- Only enter block_in_place for the event kinds that read session files.
- Bound the blocking pool (8) with a 2 s keep-alive.
- Cap glibc arenas at 2 and trim after heavy requests, large frames, and
  client disconnect.
- Release oversized frame buffers instead of pinning their capacity.
- Cap session-scan stat workers at 4.

* refactor(grok-build): talk to the Grok CLI chat proxy over HTTPS instead of ACP

Grok Build no longer spawns `grok agent stdio`. It calls the Grok CLI chat
proxy (https://cli-chat-proxy.grok.com/v1, OpenAI-compatible) directly through
the OpenAI-compatible runtime, so Jcode owns tool execution.

- Auth: the xAI OIDC session in $GROK_HOME/auth.json (default ~/.grok/auth.json).
  Only the https://auth.x.ai::<grok-cli client id> entry is used. expires_at
  (or the JWT exp claim) is honoured, the token is refreshed via refresh_token
  with a 60s skew, and a 401 forces one refresh-and-replay. The token is re-read
  for each request.
- Identity: requests present the official Grok CLI headers (User-Agent
  grok-cli/<ver>, X-XAI-Token-Auth: xai-grok-cli, x-grok-client-version,
  x-grok-client-identifier: grok-shell, x-grok-client-surface, and per-turn
  x-grok-model-override / x-grok-conv-id / x-grok-req-id). These were taken
  from the Grok CLI 1.0.41 binary. JCODE_GROK_CLI_VERSION overrides the version.
- Login: native xAI OAuth device flow (Grok CLI client id) in both the CLI and
  the TUI. It writes to the shared Grok credential store. The managed Grok
  binary download and the ACP bin/tests/dependency have been removed.
- Route ids (grok-build:<model>, grok-build-acp) and /model selection are
  unchanged.

* style(grok-build): collapse nested if in auth retry stream (clippy)

* perf(jev): hedge voice routing across fresh connections, single Typesafe batch

Typesafe latency is bimodal and sticky per connection (~150ms or 2-12s).
Voice insert/send waits on Jev, so race duplicates on separate clients
after 300/700/1500ms and take the first valid answer. Primary failures
still return immediately and are never duplicated. Typesafe direct accepts
all 26 voice questions in one request, and batches now run concurrently.

Measured live: unhedged median ~5s, hedged median ~0.7-1.1s.

* jev: prefer Typesafe direct over OpenRouter in auto routing

* sdk: support per-connection SSH identities and pinned host keys

Managed Jcode Cloud hosts authorize a fresh key for each connection and
publish their host keys through the control plane. SshConnectOptions can
now supply that identity exclusively, pin known_hosts without consulting
user or system files, and ignore user SSH config. Adds an ssh_prompt
example that creates a session and runs one prompt over SSH.

* selfdev: add reload-bridge to safely restart the harness API bridge

Agents restarted the bridge by hand from bash (kill, then setsid nohup).
When the agent's own session went through that bridge, the kill cut its
connection, the turn was interrupted before the relaunch ran, and every
Desktop panel was stranded on a dead socket.

reload-bridge (in selfdev and desktop_selfdev) runs the restart as a
daemon-owned background task that survives the caller disconnecting. It
preflights the new binary, records the old bridge's command line from its
peer PID, stops it, starts the new one, verifies the socket accepts, and
relaunches the old command line if the new bridge exits or never accepts.
Prompts now steer agents to it instead of manual restarts.

* harness-api: report requested working_dir for unpersisted new sessions

* bridge: handle --help; bound reload-bridge preflight

* docs: update weekly stars chart

* fix(hooks): never let a hook flash a console window on Windows (#1490)

* fix(hooks): never let a hook flash a console window on Windows

On a Windows host where Windows Terminal is the default terminal
application, every hook event opens a new Windows Terminal tab. A session
that runs a few tools spawns a steady stream of them.

Observer hooks go out through `spawn_detached`, which sets
`DETACHED_PROCESS`. That leaves the hook with no console at all, so the
first console-subsystem grandchild it starts — a `curl.exe` inside a hook
script, for instance — has no console to inherit and Windows allocates a
brand new one for it. That console is what surfaces as a tab, which is
why the tab is titled after the grandchild rather than the hook.

`CREATE_NO_WINDOW` is the flag that fits: the child gets a console with no
window, and descendants inherit it, so the whole subtree stays invisible.
It cannot simply be added to `spawn_detached` — it is documented as
ignored when `DETACHED_PROCESS` is also specified — so observers now use a
sibling entry point, and `build_hook_process` sets it for the two tokio
paths (the pre_tool gate and tool transformers) that spawn with no
creation flags today.

`spawn_detached` itself is unchanged: it launches visible terminal windows
for /resume and /split, which must keep their consoles.

Verified: `cargo check -p jcode-base` on the host, the added Windows
branches type-checked against the pinned windows-sys 0.59 for
x86_64-pc-windows-msvc, and the 13 `hooks::` unit tests pass.

* fix(platform): drop needless return in spawn_detached_without_console_window

---------

Co-authored-by: Jeremy Huang <[email protected]>

* Add jcode-applet-types: versioned, validated wire types for Desktop applets

Placements independent of tool calls (panel, sidebar, inline anchors,
composer, overlay, background), image assets, capabilities, revisioned
atomic patches, forward-compatible unknown nodes, and resource limits.

* applet-types: stacks default to no padding (containers own insets)

* protocol: report reasoning effort on model_changed so clients never show a stale level

A model switch can clear an effort the new model does not advertise, but
model_changed carried no effort, so the harness API kept broadcasting the
old level. The daemon now includes the effective effort, and the harness
translation adopts it (and clears its cache when a successful effort change
reports none).

* voice: cut push-to-talk release latency and profile the stop path

Release reached the microphone through two 10 ms polling hops (a tokio
forwarder task and the capture thread's sleep loop). stop() now signals
the capture thread directly and unparks it, so the mic stops within ~0-3 ms
of release instead of up to ~20 ms.

Add NariRecording::event_ready(), an executor-agnostic notifier so UIs can
react to the final transcript immediately instead of on their next poll.

JCODE_VOICE_TIMING now also reports time since release for every stop-path
stage (capture teardown, final commit, provider ack, completion). The
profiler example marks release and tolerates early setup failures.

* Voice: bias and correct Jcode vs Jev (Jev Desktop -> Jcode Desktop)

* Sessions: save labels name the session and set_session_saved reaches the SDK

A /save label is now the session's title (custom_title), announced with
SessionRenamed. Legacy labelled bookmarks fall back to the label in every
title resolver. Adds SetSessionSaved to the harness API, bridge, and the
Rust and TypeScript SDKs.

* fix(telemetry): raise D1 soft limit to 8 GB now that paid storage is metered

* dictation: resolve the focused Jcode CLI session for global voice holds

Clients now record their own PID -> session in ~/.jcode/client_sessions on
focus, so a focused terminal window maps to exactly the session it shows
even when the title is a task title. Title parsing ignores the live metrics
suffix, generic jcode clients fall back to the last-focused session, and the
shared last-focused file is rewritten even if this process wrote it before.

Add focused_cli_session() (never matches Jcode Desktop windows) and
send_transcript_blocking() so Desktop can hand a transcript to a CLI
session the same way `jcode transcript` does.

* docs(telemetry): disclose confidential de-identified usage summaries for investor due diligence

* jev: label browser decisions so the gateway budgets them apart from memory

* Prompt an upgrade when a Jcode plan limit is reached

The gateway now returns quota_exceeded with the current tier, next tier and
a jcode.sh upgrade link when a daily Jev allowance runs out. The client:
- no longer retries plan quotas (long Retry-After), only transient overload
- turns the body into a typed QuotaExceeded notice, keeping only jcode.sh links
- browser handoff hands back with requested_help=upgrade and the prompt
- background memory hits are injected once as a system reminder so the agent
  tells the user, in the TUI and Desktop alike, instead of failing silently

* applets: agent applets across SDK, protocol, server, applet tool and MCP-UI bridge

Adds jcode-applet-types::agent (APPLET_ID, manifest, AgentApplets,
JCODE_APPLET_MIME) and HostMessage::ToolCall. Persists per-session agent
applets in ~/.jcode/agent_applets, publishes ApiEvent::AppletState live and on
attach hydration, and accepts ApiRequest::AppletAction / CloseApplet through
the bridge, Rust SDK and TypeScript SDK. The new applet tool mounts, updates,
patches, moves and closes validated native UI, optionally waiting for the
user's action. MCP ui:// and jcode applet resources render inline.

* usage: show Jcode daily feature allowances and an upgrade hint

`jcode usage` (and the Desktop accounts panel, which reads `jcode usage
--json`) now includes a Jcode row with daily memory-recall and browser
allowances from /v1/me jev_usage. At 80% or more it adds an Upgrade line with
the jcode.sh pricing link, so users see the limit before a feature stops.

* Accounts: persistent auto-switch pool; same-provider failover rotates only pool members in user order

* memory: prefilter Jev recall to 72 lexical candidates

Automatic recall sent every active memory to Jev, 24 per decision. With
~2,550 memories that was ~107 Jev calls per turn, exhausting the 1,000/day
plan allowance within hours and causing the browser 429s. BM25 now narrows
large stores to the 72 most relevant candidates (3 decisions) and Jev still
judges each one. Stores of 72 or fewer are unchanged.

* mcp: load MCP tools through provider-native deferred loading so adding them never busts the prompt cache

Tool definitions sit at the very front of the provider prompt cache, so any
change to the tool list (an MCP server connecting late, `mcp connect`, a
reconnect) invalidated the entire cached prefix: tools, system prompt, and
the whole conversation.

Both first-party providers now support loading tool definitions mid-
conversation without touching the cached prefix:

- Anthropic: `defer_loading: true` definitions stay out of the prefix; a
  `tool_reference` block inside a tool_result expands them in place.
- OpenAI Responses (gpt-5.4+): an `additional_tools` developer input item
  makes tools callable from that point in the conversation.

Implementation:

- ToolDefinition gains `defer_loading`; ContentBlock gains `ToolReference`.
- Provider::supports_deferred_tools (Anthropic first-party endpoint, OpenAI
  gpt-5.4+). MultiProvider strips deferred defs for every other route, so
  nothing changes for them.
- Anthropic: deferred tools sorted after eager ones, cache breakpoint on the
  last eager tool, references folded into a reference-only tool_result with
  the original text moved to a sibling block, references to tools no longer
  in the request dropped (they are a hard 400).
- OpenAI: deferred tools omitted from `tools`; `additional_tools` inserted
  after the referencing function_call_output. Persistent-WS deltas keep
  working since the item lands in the new tail.
- Agent: in auto/deferred mode on a supporting provider, MCP definitions are
  deferred and refreshed every turn while the eager snapshot stays locked, and
  the `mcp` tool no longer unlocks it. `mcp_search` stays eager for discovery;
  `mcp_call` stays as a permanent deferred entry because some models (Opus
  4.8) rebuilt the prefix when the deferred set went from empty to non-empty.
- `mcp connect` and `mcp_search` attach tool references (metadata
  `tool_references`, capped at 32) so the new tools become directly callable.

Live verification (real API, jcode run on an isolated socket, a stdio MCP
server connected mid-session, then its tool called natively):
- claude-opus-4-8: cache_read 0 -> 20465 -> 21089 (the request after
  connect read the full prefix and wrote only the 624-token delta).
- gpt-5.5: cache_read 9984 on every request across repeated runs, same as a
  bash-only control run.
Raw API probes also confirmed eager additions reset the cache to 0 on both
providers, while deferred additions kept it.

* mcp: rebuild the tool snapshot when deferred-loading support changes mid-session

The native deferred MCP snapshot omits an eager mcp_call and marks MCP tools
deferred. After switching to a provider without native deferred loading, the
MultiProvider chokepoint strips deferred definitions, which left mcp_search
with no way to call what it found. Track which path built the snapshot and
rebuild when the capability flips. The prefix changes with the provider
anyway, so this costs no extra cache miss.

* usage: name the Jcode row 'Jcode subscription' so Desktop attaches it

The Desktop accounts panel matches the jcode account by the
'jcode subscription' prefix (same name as provider activity). Verified with
a built binary against the live gateway.

* sessions: name untitled sessions after their first prompt

New sessions never got a generated title, so Desktop listed them all as
'New session'. The runtime now adopts the first visible user prompt
(minus system reminders and transcription tags) as the fallback title,
and the harness bridge backfills older sessions once, caching the result
in the shared metadata index. Also nudge the todo tool to be used often.

* voice: drop silent prompt-echo transcripts (repeated 'Hey Jev / Okay Jev' examples)

* applet-types: order capabilities so hosts can keep grant sets

* power: block lid-close sleep on macOS and Windows while sessions work

Linux already blocks lid-close suspend via systemd-inhibit. macOS and
Windows have no process-scoped lid lock, so while a session streams the
daemon now temporarily changes the persistent setting and restores it:

- Windows: active plan LIDACTION (AC+DC) set to Do nothing, no elevation.
- macOS: sudo -n pmset -a disablesleep 1, only with a passwordless
  sudoers rule (never prompts, logs a one-time hint otherwise).

Originals are journaled to ~/.jcode/lid_override.json before any change,
so a crashed or kill -9'd daemon is repaired by the next reconcile tick.
Same-PID re-exec reuses the journal, live foreign owners are left alone,
and SIGTERM/idle exit restore explicitly. Controlled by
[power].block_lid_close (default true) and JCODE_BLOCK_LID_CLOSE.

* ci: repair master clippy, fmt and test drift

Master CI has not passed since Aug 1. Fix the accumulated breakage so
PR checks are meaningful again:
- add the new applets field to ServerEvent::History test initializers
- tui_bench: cover ContentBlock::ToolReference
- clippy fixes (autofix, test-module ordering, struct init, type alias,
  const asserts, test-env lock allowances following existing convention)
- exempt the applet tool and desktop_selfdev action from the prompt
  token caps and strict-mode list, with inline justification
- rustfmt

* feat(tui-messages): content-coordinate viewport anchors

A viewport position stored as a wrapped line index only means something for one
width and one transcript, so a resize reinterprets it against new content and
the reader lands on unrelated messages.

Add `Anchor` plus `anchor_at_row` / `resolve`, pure functions over the frame's
existing `MessageBoundary.msg_hash` values. Identity is the message hash plus an
occurrence index, so no new id plumbing is needed; a removed or compacted
message resolves to `None` and the caller keeps its position instead of jumping.

Epic #1411 phase 4 (part 1).

* fix(tui): keep the reader's message under them across a resize

The persistent half of issue #1412: while parked in history, `scroll_offset` is
a wrapped line index, so a resize reinterprets it against the new wrap width.
The reader lands on unrelated messages (measured in the bug report: the top
message moved 98 messages).

Capture the reading position in content coordinates in `commit_resize_redraw`,
resolve it against the frame being drawn, then adopt the resolved row on the
next tick and drop the anchor. Mirrors the existing history-prepend anchor
shape.

Precedence and cancellation: the renderer prefers a pending resize anchor over
the stored index; a user scroll or an explicit prompt jump clears it, so a
pending correction can never freeze the viewport.

Fails-first: with the capture removed, `resize_keeps_the_anchored_message_under_a_paused_reader`
shows the top message moving from TOKEN016 to TOKEN011 across the resize.

Epic #1411 phase 4 (part 2).

* fix(tui): scope the resize anchor to a paused viewport

The anchor describes a reading position, so it must not outlive one. The
renderer now applies it only while auto-scroll is paused, and resuming the tail
drops it, so a pending correction can never pin the viewport after the reader
goes back to following the bottom.

* style: rustfmt the anchor module and the resize accessor

* fix(tui): never hold a resize anchor across a compacted-history prepend

Reviewer finding on #1427 (P1). A resize anchor stores a content hash and an
occurrence ordinal counted from the start of the frame it was captured in. A
prepend inserts messages above it, so an older message with identical content
becomes occurrence zero and the resolver names that one instead. Because the
renderer prefers the resize anchor over the prepend's distance-from-bottom
anchor, the reader jumped to the older duplicate.

Reproduced end to end through the real prepend path (resize while paused, then
older history containing an identical duplicate):

    without this fix: frame matches=[23, 59], resolve=Some(24), reader row 44 -> 24
    with this fix:    resize anchor dropped, reader row 44 -> 60 (content preserved)

Fix: the two anchors must never be alive at once. They are only written by
`capture_history_anchor` and `capture_resize_anchor`, so a prepend drops a
pending resize anchor and a resize refuses to capture one while a prepend is
pending. No shared semantics change: `Anchor`, `resolve` and `anchor_at_row` are
untouched, and `resolve` stays correct for whatever frame it is handed.

Also corrects the module doc, which had claimed the ordinal "shifts by one",
understating that any prepend adding a duplicate invalidates it for callers that
hold an anchor across the prepend (bookmark, selection; those are closed by the
same mechanism in their own PRs).

Tests: three new, all failing with the guards removed. 236 pass across the
behavioral rollup and 17 in jcode-tui-messages.

* fix(tui): anchor rows that belong to no message (live streaming output)

Reviewer finding on #1429 (P1, applies here too). `anchor_at_row` returns None
for any row outside a message, so a reader parked in live streaming output, the
retained reasoning trace, or the header captured nothing on a resize and the
renderer replayed the stale wrapped row. Measured on this tree:

    before the resize…
KooshaPari added a commit that referenced this pull request Oct 17, 2026
…y bug)

The §22 audit's 'PR #25 has Closes #26 but #26 doesn't exist on
this fork' finding was a false positive caused by running only
'gh pr view 26' instead of also 'gh issue view 26'. GitHub keeps
issue and PR in separate namespaces; #26 is a live issue
('Add /poke context recovery sessions', KooshaPari, 2026-10-02T19:10:12Z).
PR #25's closingIssuesReferences correctly points to it.

Three retractions in this commit:
1. 22-NEW-FINDING-gh-pr-view-closed-vs-merged.md (lines 165-178):
   retract the 'flagged for human review' status, replace with
   RETRACTED note + method note (use both gh issue view AND gh pr view).
2. STATE.md row V (line 160): retract the false positive within the
   audit result row; full retraction in the new doc.
3. STATE.md forward-path item 4 (line 1063): mark 'No operator action
   needed' — the alleged orphan is not a real orphan.

Investigation report: pr-25-pr-26-investigation.md (159 lines, by
session_gorilla, ~3m, read-only). Three interpretations ranked by
likelihood; #1 (~95%) is the false positive; #2 (~4%) is the
PR-first/issue-later workflow (real but legitimate); #3 (~1%) is
the cross-repo footer hypothesis (refuted by closingIssuesReferences).

Surprising finding: gh pr view <N> is not equivalent to 'does <N>
exist on this repo' — the GraphQL PullRequest type and Issue type
share a per-repo number sequence but are different objects.

tx-agent: jcode
tx-validated: manual
tx-task: pr-25-26-retraction
tx-scope: docs/sessions/2026-10-15-portal-xirp-resume/{STATE.md,22-NEW-FINDING-gh-pr-view-closed-vs-merged.md,pr-25-pr-26-investigation.md}
tx-intent: Fix §22 false positive so future audits don't repeat it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

OpenCode Go: Muse/Grok/GPT-5.6-Luna models fail with 500 -- requires /responses and /messages endpoints, not just /chat/completions

2 participants