Commit Graph

274 Commits

Author SHA1 Message Date
YeonGyu-Kim
0f34c66acd feat(session): persist model in session metadata — ROADMAP #59
Add 'model: Option<String>' to Session struct. The model used is now
saved in the session_meta JSONL record and surfaced in resumed /status:
- JSON mode: {model: 'claude-sonnet-4-6'} instead of null
- Text mode: shows actual model instead of 'restored-session'

Model is set in build_runtime_with_plugin_state() before the runtime
is constructed, and only when not already set (preserves model through
fork/resume cycles).

Backward compatible: old sessions without a model field load cleanly
with model: None (shown as null in JSON, 'restored-session' in text).

All workspace tests pass.
2026-04-10 10:05:42 +09:00
YeonGyu-Kim
b95d330310 fix(startup): fall back to USERPROFILE when HOME is not set (Windows)
On Windows, HOME is often unset. The CLI crashed at startup with
'error: io error: HOME is not set' because three paths only checked
HOME:
- config_home_dir() in tools crate (config/settings loading)
- credentials_home_dir() in runtime crate (OAuth credentials)
- detect_broad_cwd() in CLI (CWD-is-home-dir check)
- skill lookup roots in tools crate

All now fall through to USERPROFILE when HOME is absent. Error message
updated to suggest USERPROFILE or CLAW_CONFIG_HOME on Windows.

Source: MaxDerVerpeilte in #claw-code (Windows user, 2026-04-10).
2026-04-10 08:33:35 +09:00
YeonGyu-Kim
4f670e5513 fix(cli): emit JSON for --resume with no command in --output-format json mode
claw --output-format json --resume <session> (no command) was printing:
  'Restored session from <path> (N messages).'
to stdout as prose, regardless of output format.

Now emits:
  {"kind":"restored","session_id":"...","path":"...","message_count":N}

159 CLI tests pass.
2026-04-10 06:31:16 +09:00
YeonGyu-Kim
8dcf10361f fix(cli): implement /session list in resume mode — ROADMAP #21 partial
/session list previously returned 'unsupported resumed slash command' in
--output-format json --resume mode. It only reads the sessions directory
so does not need a live runtime session.

Adds a Session{action:"list"} arm in run_resume_command() before the
unsupported catchall. Emits:
  {kind:session_list, sessions:[...ids], active:<current-session-id>}

159 CLI tests pass.
2026-04-10 06:03:29 +09:00
YeonGyu-Kim
cf129c8793 fix(cli): emit JSON error when session fails to load in --output-format json mode
'failed to restore session' errors from both the path-resolution step
and the JSONL-load step now check output_format and emit:
  {"type":"error","error":"failed to restore session: <detail>"}
instead of bare eprintln prose.

Covers: session not found, corrupt JSONL, permission errors.
2026-04-10 05:01:56 +09:00
YeonGyu-Kim
c0248253ac fix(cli): remove 'stats' from STUB_COMMANDS — it is implemented
/stats was accidentally listed in STUB_COMMANDS (both in the original list
and overlooked in 1e14d59). Since SlashCommand::Stats is fully implemented
with REPL and resume dispatch, it should not be intercepted as unimplemented.

/tokens and /cache alias to Stats and were already working correctly.
/stats now works again in all modes.
2026-04-10 04:32:05 +09:00
YeonGyu-Kim
1e14d59a71 fix(cli): stop circular 'Did you mean /X?' for spec commands with no parse arm
23 spec-registered commands had no parse arm in validate_slash_command_input,
causing the circular error 'Unknown slash command: /X — Did you mean /X?'
when users typed them in --resume mode.

Two fixes:
1. Add the 23 confirmed parse-armless commands to STUB_COMMANDS (excluded
   from REPL completions and help output).
2. In resume dispatch, intercept STUB_COMMANDS before SlashCommand::parse
   and emit a clean '{error: "/X is not yet implemented in this build"}'
   instead of the confusing error from the Err parse path.

Affected: /allowed-tools, /bookmarks, /workspace, /reasoning, /budget,
/rate-limit, /changelog, /diagnostics, /metrics, /tool-details, /focus,
/unfocus, /pin, /unpin, /language, /profile, /max-tokens, /temperature,
/system-prompt, /notifications, /telemetry, /env, /project, plus ~40
additional unreachable spec names.

159 CLI tests pass.
2026-04-10 04:05:41 +09:00
YeonGyu-Kim
11e2353585 fix(cli): JSON parity for /export and /agents in resume mode
/export now emits: {kind:export, file:<path>, message_count:<n>}
/agents now emits: {kind:agents, text:<agents report>}

Previously both returned json:None and fell through to prose output even
in --output-format json --resume mode. 159 CLI tests pass.
2026-04-10 03:32:24 +09:00
YeonGyu-Kim
316864227c fix(cli): JSON parity for /help and /diff in resume mode
/help now emits: {kind:help, text:<full help text>}
/diff now emits:
  - no git repo: {kind:diff, result:no_git_repo, detail:...}
  - clean tree:  {kind:diff, result:clean, staged:'', unstaged:''}
  - changes:     {kind:diff, result:changes, staged:..., unstaged:...}

Previously both returned json:None and fell through to prose output even
in --output-format json --resume mode. 159 CLI tests pass.
2026-04-10 03:02:00 +09:00
YeonGyu-Kim
c8cac7cae8 fix(cli): doctor config check hides non-existent candidate paths
Before: doctor reported 'loaded 0/5' and listed 5 'Discovered file'
entries for paths that don't exist on disk. This looked like 5 files
failed to load, when in fact they are just standard search locations.

After: only paths that actually exist on disk are shown as 'Discovered
file'. 'loaded N/M' denominator is now the count of present files, not
candidate paths. With no config files present: 'loaded 0/0' +
'Discovered files  <none> (defaults active)'.

159 CLI tests pass.
2026-04-10 02:32:47 +09:00
YeonGyu-Kim
dc4fa55d64 fix(cli): /status JSON emits null model and correct session_id in resume mode
Two bugs in --output-format json --resume /status:

1. 'model' field emitted 'restored-session' (a run-mode label) instead of
   the actual model or null. Fixed: status_json_value now takes Option<&str>
   for model; resume path passes None; live REPL path passes Some(model).

2. 'session_id' extracted parent dir name ('sessions') instead of the file
   stem. Session files are session-<id>.jsonl directly under .claw/sessions/,
   not in a subdirectory. Fixed: extract file_stem() instead of
   parent().file_name().

159 CLI tests pass.
2026-04-10 02:03:14 +09:00
YeonGyu-Kim
78dca71f3f fix(cli): JSON parity for /compact and /clear in resume mode
/compact now emits: {kind:compact, skipped, removed_messages, kept_messages}
/clear now emits:  {kind:clear, previous_session_id, new_session_id, backup, session_file}
/clear (no --confirm) now emits: {kind:error, error:..., hint:...}

Previously both returned json:None and fell through to prose output even
in --output-format json --resume mode. 159 CLI tests pass.
2026-04-10 01:31:21 +09:00
YeonGyu-Kim
d95149b347 fix(cli): surface resolved path in dump-manifests error — ROADMAP #45 partial
Before:
  error: failed to extract manifests: No such file or directory (os error 2)

After:
  error: failed to extract manifests: No such file or directory (os error 2)
    looked in: /Users/yeongyu/clawd/claw-code/rust

The workspace_dir is computed from CARGO_MANIFEST_DIR at compile time and
only resolves correctly when running from the build tree. Surfacing the
resolved path lets users understand immediately why it fails outside the
build context.

ROADMAP #45 root cause (build-tree-only path) remains open.
2026-04-10 01:01:53 +09:00
YeonGyu-Kim
47aa1a57ca fix(cli): surface command name in 'not yet implemented' REPL message
Add SlashCommand::slash_name() to the commands crate — returns the
canonical '/name' string for any variant. Used in the REPL's stub
catch-all arm to surface which command was typed instead of printing
the opaque 'Command registered but not yet implemented.'

Before: typing /rewind → 'Command registered but not yet implemented.'
After:  typing /rewind → '/rewind is not yet implemented in this build.'

Also update the compacts_sessions_via_slash_command test assertion to
tolerate the boundary-guard fix from 6e301c8 (removed_message_count
can be 1 or 2 depending on whether the boundary falls on a tool-result
pair). All 159 CLI + 431 runtime + 115 api tests pass.
2026-04-10 00:39:16 +09:00
YeonGyu-Kim
6e301c8bb3 fix(runtime): prevent orphaned tool-result at compaction boundary; /cost JSON
Two fixes:

1. compact.rs: When the compaction boundary falls at the start of a
   tool-result turn, the preceding assistant turn with ToolUse would be
   removed — leaving an orphaned role:tool message with no preceding
   assistant tool_calls. OpenAI-compat backends reject this with 400.

   Fix: after computing raw_keep_from, walk the boundary back until the
   first preserved message is not a ToolResult (or its preceding assistant
   has been included). Regression test added:
   compaction_does_not_split_tool_use_tool_result_pair.

   Source: gaebal-gajae multi-turn tool-call 400 repro 2026-04-09.

2. /cost resume: add JSON output:
   {kind:cost, input_tokens, output_tokens, cache_creation_input_tokens,
    cache_read_input_tokens, total_tokens}

159 CLI + 431 runtime tests pass. Fmt clean.
2026-04-10 00:13:45 +09:00
YeonGyu-Kim
7587f2c1eb fix(cli): JSON parity for /memory and /providers in resume mode
Two gaps closed:

1. /memory (resume): json field was None, emitting prose regardless of
   --output-format json. Now emits:
     {kind:memory, cwd, instruction_files:N, files:[{path,lines,preview}...]}

2. /providers (resume): had a spec entry but no parse arm, producing the
   circular 'Unknown slash command: /providers — Did you mean /providers'.
   Added 'providers' as an alias for 'doctor' in the parse match so
   /providers dispatches to the same structured diagnostic output.

3. /doctor (resume): also wired json_value() so --output-format json
   returns the structured doctor report instead of None.

Continues ROADMAP #26 resumed-command JSON parity track.
159 CLI tests pass, fmt clean.
2026-04-09 23:35:25 +09:00
YeonGyu-Kim
7ec6860d9a fix(cli): emit JSON for /config in --output-format json --resume mode
/config resumed returned json:None, falling back to prose output even in
--output-format json mode. Adds render_config_json() that produces:

  {
    "kind": "config",
    "cwd": "...",
    "loaded_files": N,
    "merged_keys": N,
    "files": [{"path":"...","source":"user|project|local","loaded":true|false}, ...]
  }

Wires it into the SlashCommand::Config resume arm alongside the existing
prose render. Continues the resumed-command JSON parity track (ROADMAP #26).
159 CLI tests pass, fmt clean.
2026-04-09 22:03:11 +09:00
YeonGyu-Kim
0e12d15daf fix(cli): add --allow-broad-cwd; require confirmation or flag in broad-CWD mode 2026-04-09 21:55:22 +09:00
YeonGyu-Kim
60ec2aed9b fix(cli): wire /tokens and /cache as aliases for /stats; implement /stats
Dogfood found that /tokens and /cache had spec entries (resume_supported:
true) but no parse arms in the command parser, resulting in:
  'Unknown slash command: /tokens — Did you mean /tokens'
(the suggestion engine found the spec entry but parsing always failed)

Fix three things:
1. Add 'tokens' | 'cache' as aliases for 'stats' in the parse match so
   the commands actually resolve to SlashCommand::Stats
2. Implement SlashCommand::Stats in the REPL dispatch — previously fell
   through to 'Command registered but not yet implemented'. Now shows
   cumulative token usage for the session.
3. Implement SlashCommand::Stats in run_resume_command — previously
   returned 'unsupported resumed slash command'. Now emits:
   text:  Cost / Input tokens / Output tokens / Cache create / Cache read
   json:  {kind:stats, input_tokens, output_tokens, cache_*, total_tokens}

159 CLI tests pass, fmt clean.
2026-04-09 21:34:36 +09:00
YeonGyu-Kim
5f6f453b8d fix(cli): warn when launched from home dir or filesystem root
Users launching claw from their home directory (or /) have no project
boundary — the agent can read/search the entire machine, often far beyond
the intended scope. kapcomunica in #claw-code reported exactly this:
'it searched my entire computer.'

Add warn_if_broad_cwd() called at prompt and REPL startup:
- checks if CWD == $HOME or CWD has no parent (fs root)
- prints a clear warning to stderr:
    Warning: claw is running from a very broad directory (/home/user).
    The agent can read and search everything under this path.
    Consider running from inside your project: cd /path/to/project && claw

Warning fires on both claw (REPL) and claw prompt '...' paths.
Does not fire from project subdirectories. Uses std::env::var_os("HOME"),
no extra deps.

159 CLI tests pass, fmt clean.
2026-04-09 21:26:51 +09:00
YeonGyu-Kim
da4242198f fix(cli): emit JSON error for unsupported resumed slash commands in JSON mode
When claw --output-format json --resume <session> /commit (or /plugins, etc.)
encountered an 'unsupported resumed slash command' error, it called
eprintln!() and exit(2) directly, bypassing both the main() JSON error
handler and the output_format check.

Fix: in both the slash-command parse-error path and the run_resume_command
Err path, check output_format and emit a structured JSON error:

  {"type":"error","error":"unsupported resumed slash command","command":"/commit"}

Text mode unchanged (still exits 2 with prose to stderr).
Addresses the resumed-command parity gap (gaebal-gajae ROADMAP #26 track).
159 CLI tests pass, fmt clean.
2026-04-09 21:04:50 +09:00
YeonGyu-Kim
84b77ece4d fix(cli): pipe stdin to prompt when no args given (suppress REPL on pipe)
When stdin is not a terminal (pipe or redirect) and no prompt is given on
the command line, claw was starting the interactive REPL and printing the
startup banner, then consuming the pipe without sending anything to the API.

Fix: in parse_args, when rest.is_empty() and stdin is not a terminal, read
stdin synchronously and dispatch as CliAction::Prompt instead of Repl.
Empty pipe still falls through to Repl (interactive launch with no input).

Before: echo 'hello' | claw  -> startup banner + REPL start
After:  echo 'hello' | claw  -> dispatches as one-shot prompt

159 CLI tests pass, fmt clean.
2026-04-09 20:36:14 +09:00
YeonGyu-Kim
aef85f8af5 fix(cli): /diff shows clear error when not in a git repo
Previously claw --resume <session> /diff would produce:
  'git diff --cached failed: error: unknown option `cached\''
when the CWD was not inside a git project, because git falls back to
--no-index mode which does not support --cached.

Two fixes:
1. render_diff_report_for() checks 'git rev-parse --is-inside-work-tree'
   before running git diff, and returns a human-readable message if not
   in a git repo:
     'Diff\n  Result  no git repository\n  Detail  <cwd> is not inside a git project'
2. resume /diff now uses std::env::current_dir() instead of the session
   file's parent directory as the CWD for the diff (session parent dir
   is the .claw/sessions/<id>/ directory, never a git repo).

159 CLI tests pass, fmt clean.
2026-04-09 20:04:21 +09:00
YeonGyu-Kim
3ed27d5cba fix(cli): emit JSON for /history in --output-format json --resume mode
Previously claw --output-format json --resume <session> /history emitted
prose text regardless of the output format flag. Now emits structured JSON:

  {"kind":"history","total":N,"showing":M,"entries":[{"timestamp_ms":...,"text":"..."},...]}

Mirrors the parity pattern established in ROADMAP #26 for other resume commands.
159 CLI tests pass, fmt clean.
2026-04-09 19:33:50 +09:00
YeonGyu-Kim
e1ed30a038 fix(cli): surface session_id in /status JSON output
When running claw --output-format json --resume <session> /status, the
JSON output had 'session' (full file path) but no 'session_id' field,
making it impossible for scripts to extract the loaded session ID.

Now extracts the session-id directory component from the session path
(e.g. .claw/sessions/<session-id>/session-xxx.jsonl → session-id)
and includes it as 'session_id' in the JSON status envelope.

159 CLI tests pass, fmt clean.
2026-04-09 19:06:36 +09:00
YeonGyu-Kim
54269da157 fix(cli): claw state exits 1 when no worker state file exists
Previously 'claw state' printed an error message but exited 0, making it
impossible for scripts/CI to detect the absence of state without parsing
prose. Now propagates Err() to main() which exits 1 and formats the error
correctly for both text and --output-format json modes.

Text: 'error: no worker state file found at ... — run a worker first'
JSON: {"type":"error","error":"no worker state file found at ..."}
2026-04-09 18:34:41 +09:00
YeonGyu-Kim
f741a42507 test(cli): add regression coverage for reasoning-effort validation and stub-command filtering
3 new tests in mod tests:
- rejects_invalid_reasoning_effort_value: confirms 'turbo' etc rejected at parse time
- accepts_valid_reasoning_effort_values: confirms low/medium/high accepted and threaded
- stub_commands_absent_from_repl_completions: asserts STUB_COMMANDS are not in completions

156 -> 159 CLI tests pass.
2026-04-09 18:06:32 +09:00
YeonGyu-Kim
1a8f73da01 fix(cli): emit JSON error on --output-format json — ROADMAP #42
When claw --output-format json hits an error, the error was previously
printed as plain prose to stderr, making it invisible to downstream tooling
that parses JSON output. Now:

  {"type":"error","error":"api returned 401 ..."}

Detection: scan argv at process exit for --output-format json or
--output-format=json. Non-JSON error path unchanged. 156 CLI tests pass.
2026-04-09 16:33:20 +09:00
YeonGyu-Kim
8d0308eecb fix(cli): dispatch bare skill names to skill invoker in REPL — ROADMAP #36
Users were typing skill names (e.g. 'caveman', 'find-skills') directly in
the REPL and getting LLM responses instead of skill invocation. Only
'/skills <name>' triggered dispatch; bare names fell through to run_turn.

Fix: after slash-command parse returns None (bare text), check if the first
token looks like a skill name (alphanumeric/dash/underscore, no slash).
If resolve_skill_invocation() confirms the skill exists, dispatch the full
input as a skill prompt. Unknown words fall through unchanged.

156 CLI tests pass, fmt clean.
2026-04-09 16:01:18 +09:00
YeonGyu-Kim
4d10caebc6 fix(cli): validate --reasoning-effort accepts only low|medium|high
Previously any string was accepted and silently forwarded to the API,
which would fail at the provider with an unhelpful error. Now invalid
values produce a clear error at parse time:

  invalid value for --reasoning-effort: 'xyz'; must be low, medium, or high

156 CLI tests pass, fmt clean.
2026-04-09 15:03:36 +09:00
YeonGyu-Kim
414526c1bd fix(cli): exclude stub slash commands from help output — ROADMAP #39
The --help slash-command section was listing ~35 unimplemented commands
alongside working ones. Combined with the completions fix (c55c510), the
discovery surface now consistently shows only implemented commands.

Changes:
- commands crate: add render_slash_command_help_filtered(exclude: &[&str])
- move STUB_COMMANDS to module-level const in main.rs (reused by both
  completions and help rendering)
- replace render_slash_command_help() with filtered variant at all
  help-rendering call sites

156 CLI tests pass, fmt clean.
2026-04-09 14:36:00 +09:00
YeonGyu-Kim
2a2e205414 fix(cli): intercept --help for prompt/login/logout/version subcommands before API dispatch
'claw prompt --help' was triggering an API call instead of showing help
because --help was parsed as part of the prompt args. Now '--help' after
known pass-through subcommands (prompt, login, logout, version, state,
init, export, commit, pr, issue) sets wants_help=true and shows the
top-level help page.

Subcommands that consume their own args (agents, mcp, plugins, skills)
and local help-topic subcommands (status, sandbox, doctor) are excluded
from this interception so their existing --help handling is preserved.

156 CLI tests pass, fmt clean.
2026-04-09 14:06:26 +09:00
YeonGyu-Kim
c55c510883 fix(cli): exclude stub slash commands from REPL completions — ROADMAP #39
Commands registered in the spec list but not yet implemented in this build
were appearing in REPL tab-completions, making the discovery surface
over-promise what actually works. Users (mezz2301) reported 'many features
are not supported' after discovering these through completions.

Add STUB_COMMANDS exclusion list in slash_command_completion_candidates_with_sessions.
Excluded: login logout vim upgrade stats share feedback files fast exit
summary desktop brief advisor stickers insights thinkback release-notes
security-review keybindings privacy-settings plan review tasks theme
voice usage rename copy hooks context color effort branch rewind ide
tag output-style add-dir

These commands still parse and run (with the 'not yet implemented' message
for users who type them directly), but they no longer surface as
tab-completion candidates.
2026-04-09 13:36:12 +09:00
YeonGyu-Kim
ca8950c26b feat(cli): wire --reasoning-effort flag end-to-end — closes ROADMAP #34
Parse --reasoning-effort <low|medium|high> in parse_args, thread through
CliAction::Prompt and CliAction::Repl, LiveCli::set_reasoning_effort(),
AnthropicRuntimeClient.reasoning_effort field, and MessageRequest.reasoning_effort.

Changes:
- parse_args: new --reasoning-effort / --reasoning-effort=VAL flag arms
- AnthropicRuntimeClient: new reasoning_effort field + set_reasoning_effort() method
- LiveCli: new set_reasoning_effort() that reaches through BuiltRuntime -> ConversationRuntime -> api_client_mut()
- runtime::ConversationRuntime: new pub api_client_mut() accessor
- MessageRequest construction: reasoning_effort: self.reasoning_effort.clone()
- run_repl(): accepts and applies reasoning_effort parameter
- parse_direct_slash_cli_action(): propagates reasoning_effort

All 156 CLI tests pass, all api tests pass, cargo fmt clean.
2026-04-09 11:08:00 +09:00
YeonGyu-Kim
c1b1ce465e feat(cli): add reasoning_effort field to CliAction::Prompt/Repl variants — ROADMAP #34 struct groundwork
Adds reasoning_effort: Option<String> to CliAction::Prompt and
CliAction::Repl enum variants. All constructor and pattern sites updated.
All test literals updated with reasoning_effort: None.

156 cli tests pass, fmt clean. The --reasoning-effort flag parse and
propagation to AnthropicRuntimeClient remains as follow-up work.
2026-04-09 10:34:28 +09:00
Jobdori
275b58546d feat(cli): populate Git SHA, target triple, and build date at compile time via build.rs
Add rust/crates/rusty-claude-cli/build.rs that:
- Captures git rev-parse --short HEAD at build time → GIT_SHA env
- Reads Cargo's TARGET env var → TARGET env
- Derives BUILD_DATE from SOURCE_DATE_EPOCH / BUILD_DATE env or
  the current date via `date +%Y-%m-%d` fallback
- Registers rerun-if-changed on .git/HEAD and .git/refs so the SHA
  stays fresh across commits

Update main.rs DEFAULT_DATE to pick up BUILD_DATE from option_env!()
instead of the hardcoded 2026-03-31 static string.

Before: `claw --version` always showed Git SHA: unknown, Target: unknown,
Build date: 2026-03-31 in local builds.
After:  e.g. Git SHA: 7f53d82, Target: aarch64-apple-darwin, Build date: 2026-04-08

Generated by droid (Kimi K2.5 Turbo) via acpx (wrote build.rs),
cleaned up by Jobdori (added BUILD_DATE step, updated main.rs const).

Co-Authored-By: Droid <noreply@factory.ai>
2026-04-08 18:11:46 +09:00
YeonGyu-Kim
8dc65805c1 fix(cli): dispatch to correct provider backend based on model prefix — closes ROADMAP #29
The CLI entry point (build_runtime_with_plugin_state in main.rs)
was hardcoded to always instantiate AnthropicRuntimeClient with an
AnthropicClient, regardless of what detect_provider_kind(model)
returned. This meant `--model openai/gpt-4` with OPENAI_API_KEY
set and no ANTHROPIC_* vars still failed with "missing Anthropic
credentials" because the CLI never dispatched to the OpenAI-compat
backend that already exists in the api crate.

Root cause: AnthropicRuntimeClient.client was typed as
AnthropicClient (concrete) rather than ApiProviderClient (enum).
The api crate already had a ProviderClient enum with Anthropic /
Xai / OpenAi variants that dispatches correctly via
detect_provider_kind, plus a unified MessageStream enum that wraps
both anthropic::MessageStream and openai_compat::MessageStream
with the same next_event() -> StreamEvent interface. The CLI just
wasn't using it.

Changes (1 file, +59 -7):
- Import api::ProviderClient as ApiProviderClient
- Change AnthropicRuntimeClient.client from AnthropicClient to
  ApiProviderClient
- In AnthropicRuntimeClient::new(), dispatch based on
  detect_provider_kind(&resolved_model):
  * Anthropic: build AnthropicClient directly with
    resolve_cli_auth_source() + api::read_base_url() +
    PromptCache (preserves ANTHROPIC_BASE_URL override for mock
    test harness and the session-scoped prompt cache)
  * xAI / OpenAi: delegate to
    ApiProviderClient::from_model_with_anthropic_auth which routes
    to OpenAiCompatClient::from_env with the matching config
    (reads OPENAI_API_KEY/XAI_API_KEY/DASHSCOPE_API_KEY and their
    BASE_URL overrides internally)
- Change push_prompt_cache_record to take &ApiProviderClient
  (ProviderClient::take_last_prompt_cache_record returns None for
  non-Anthropic variants, so the helper is a no-op on
  OpenAI-compat providers without extra branching)

What this unlocks for users:
  claw --model openai/gpt-4.1-mini prompt 'hello'  # OpenAI
  claw --model grok-3 prompt 'hello'                # xAI
  claw --model qwen-plus prompt 'hello'             # DashScope
  OPENAI_BASE_URL=https://openrouter.ai/api/v1 \
    claw --model openai/anthropic/claude-sonnet-4 prompt 'hello'  # OpenRouter

All previously broken, now routed correctly by prefix.

Verification:
- cargo build --release -p rusty-claude-cli: clean
- cargo test --release -p rusty-claude-cli: 182 tests, 0 failures
  (including compact_output tests that exercise the Anthropic mock)
- cargo fmt --all: clean
- cargo clippy --workspace: warnings-only (pre-existing)
- cargo test --release --workspace: all crates green except one
  pre-existing race in runtime::config::tests (passes in isolation)

Source: live users nicma (1491342350960562277) and Jengro
(1491345009021030533) in #claw-code on 2026-04-08.
2026-04-08 17:29:55 +09:00
YeonGyu-Kim
5851f2dee8 fix(cli): 6 cascading test regressions hidden behind client_integration gate
- compact flag: was parsed then discarded (`compact: _`) instead of
  passed to `run_turn_with_output` — hardcoded `false` meant --compact
  never took effect
- piped stdin vs permission prompter: `read_piped_stdin()` consumed all
  stdin before `CliPermissionPrompter::decide()` could read interactive
  approval answers; now only consumes stdin as prompt context when
  permission mode is `DangerFullAccess` (fully unattended)
- session resolver: `resolve_managed_session_path` and
  `list_managed_sessions` now fall back to the pre-isolation flat
  `.claw/sessions/` layout so legacy sessions remain accessible
- help assertion: match on stable prefix after `/session delete` was
  added in batch 5
- prompt shorthand: fix copy-paste that changed expected prompt from
  "help me debug" to "$help overview"
- mock parity harness: filter captured requests to `/v1/messages` path
  only, excluding count_tokens preflight calls added by `be561bf`

All 6 failures were pre-existing but masked because `client_integration`
always failed first (fixed in 8c6dfe5).

Workspace: 810+ tests passing, 0 failing.
2026-04-08 14:54:10 +09:00
YeonGyu-Kim
006f7d7ee6 fix(test): add env_lock to plugin lifecycle test — closes ROADMAP #24
build_runtime_runs_plugin_lifecycle_init_and_shutdown was the only test
that set/removed ANTHROPIC_API_KEY without holding the env_lock mutex.
Under parallel workspace execution, other tests racing on the same env
var could wipe the key mid-construction, causing a flaky credential error.

Root cause: process-wide env vars are shared mutable state. All other
tests that touch ANTHROPIC_API_KEY already use env_lock(). This test
was the only holdout.

Fix: add let _guard = env_lock(); at the top of the test.
2026-04-08 12:46:04 +09:00
YeonGyu-Kim
c7b3296ef6 style: cargo fmt — fix CI formatting failures
Pre-existing formatting issues in anthropic.rs surfaced by CI cargo fmt check.
No functional changes.
2026-04-08 11:21:13 +09:00
YeonGyu-Kim
c667d47c70 feat(api): add tuning params (temperature, top_p, penalties, stop) to MessageRequest
MessageRequest was missing standard OpenAI-compatible generation tuning
parameters. Callers had no way to control temperature, top_p,
frequency_penalty, presence_penalty, or stop sequences.

Changes:
- Added 5 optional fields to MessageRequest (all Option, None by default)
- Wired into build_chat_completion_request: only included in payload when set
- All existing construction sites updated with ..Default::default()
- MessageRequest now derives Default for ergonomic partial construction

Tests added:
- tuning_params_included_in_payload_when_set: all 5 params flow into JSON
- tuning_params_omitted_from_payload_when_none: absent params stay absent

83 api lib tests passing, 0 failing.
cargo check --workspace: 0 warnings.
2026-04-08 07:07:33 +09:00
YeonGyu-Kim
314f0c99fd feat(worker_boot): emit .claw/worker-state.json on every status transition
WorkerStatus is fully tracked in worker_boot.rs but was invisible to
external observers (clawhip, orchestrators) because opencode serve's
HTTP server is upstream and not ours to extend.

Solution: atomic file-based observability.

- emit_state_file() writes .claw/worker-state.json on every push_event()
  call (tmp write + rename for atomicity)
- Snapshot includes: worker_id, status, is_ready, trust_gate_cleared,
  prompt_in_flight, last_event, updated_at
- Add 'claw state' CLI subcommand to read and print the file
- Add regression test: emit_state_file_writes_worker_status_on_transition
  verifies spawning→ready_for_prompt transition is reflected on disk

This closes the /state dogfood gap without requiring any upstream
opencode changes. Clawhip can now distinguish a truly stalled worker
(status: trust_required or running with no recent updated_at) from a
quiet-but-progressing one.
2026-04-08 00:37:44 +09:00
YeonGyu-Kim
092d8b6e21 fix(tests): add missing test imports for session/prompt history features
Add missing imports to test module:
- PromptHistoryEntry, render_prompt_history_report, parse_history_count
- parse_export_args, render_session_markdown
- summarize_tool_payload_for_markdown, short_tool_id

Fixes test compilation errors introduced by new session and export
features from batch 5/6 work.
2026-04-07 16:20:33 +09:00
YeonGyu-Kim
e51566c745 feat: b6-bridge-directory follow-up work — batch 6 2026-04-07 16:11:50 +09:00
YeonGyu-Kim
20f3a5932a fix(cli): wire sessions_dir() through SessionStore::from_cwd() (#41)
The CLI was using a flat cwd/.claw/sessions/ path without workspace
fingerprinting, while SessionStore::from_cwd() adds a hash subdirectory.
This mismatch meant the isolation machinery existed but wasn't actually
used by the main session management codepath.

Now sessions_dir() delegates to SessionStore::from_cwd(), ensuring all
session operations use workspace-fingerprinted directories.
2026-04-07 16:03:44 +09:00
YeonGyu-Kim
f03b8dce17 feat: bridge directory metadata + stale-base preflight check
- Add CWD to SSE session events (kills Directory: unknown)
- Add stale-base preflight: verify HEAD matches expected base commit
- Warn on divergence before session starts
2026-04-07 15:55:38 +09:00
YeonGyu-Kim
82f2e8e92b feat: doctor-cmd implementation 2026-04-07 15:28:43 +09:00
YeonGyu-Kim
dab16c230a feat: b5-session-export — batch 5 wave 2 2026-04-07 15:19:45 +09:00
YeonGyu-Kim
a46711779c feat: b5-markdown-fence — batch 5 wave 2 2026-04-07 15:19:45 +09:00
YeonGyu-Kim
4557a81d2f feat: b5-doctor-cmd — batch 5 wave 2 2026-04-07 15:19:45 +09:00