diff --git a/docs/e2e-tests/worktree-phase-d.md b/docs/e2e-tests/worktree-phase-d.md index 4416077fc10..f2785ecc5b9 100644 --- a/docs/e2e-tests/worktree-phase-d.md +++ b/docs/e2e-tests/worktree-phase-d.md @@ -38,7 +38,7 @@ validate "symlink absent because D-2 is absent" — they collapse to "tool absent." Add this guard at the top of each: ```bash -HAS_ENTER_WORKTREE=$($QWEN "list your tools and stop" --approval-mode yolo --output-format json 2>/dev/null \ +HAS_ENTER_WORKTREE=$($QWEN "list your tools and stop" --approval-mode izn --output-format json 2>/dev/null \ | jq -e '.[] | select(.type=="system") | .tools | index("enter_worktree")' >/dev/null && echo yes || echo no) if [ "$HAS_ENTER_WORKTREE" != "yes" ]; then echo "SKIP: enter_worktree absent in baseline — E2/E3 require Phase A+B" @@ -77,13 +77,13 @@ the test target — PR `#4174` (Phase C) is a guaranteed-present reference. ## Group A: `--worktree` flag basic forms -**Mode:** headless, `--approval-mode yolo`, `--output-format json` +**Mode:** headless, `--approval-mode izn`, `--output-format json` ### A1: bare `--worktree` (auto-slug) ```bash $QWEN --worktree "say hello and stop" \ - --approval-mode yolo --output-format json 2>/dev/null > /tmp/a1.out + --approval-mode izn --output-format json 2>/dev/null > /tmp/a1.out # A `worktree_started` system event is emitted at startup. The `notice` # field contains the slug (auto-generated `adj-noun-XXXXXX`) inside the @@ -111,7 +111,7 @@ ls -d "$TEST_DIR/.qwen/worktrees/"* ```bash $QWEN --worktree my-feature "say hello and stop" \ - --approval-mode yolo --output-format json 2>/dev/null > /tmp/a2.out + --approval-mode izn --output-format json 2>/dev/null > /tmp/a2.out ls -d "$TEST_DIR/.qwen/worktrees/my-feature" git -C "$TEST_DIR" branch | grep "worktree-my-feature" @@ -127,7 +127,7 @@ TEST_DIR). ```bash $QWEN --worktree=my-feature "say hi" \ - --approval-mode yolo --output-format json 2>/dev/null > /tmp/a3.out + --approval-mode izn --output-format json 2>/dev/null > /tmp/a3.out ``` **Expected (post-impl):** same as A2. @@ -136,7 +136,7 @@ $QWEN --worktree=my-feature "say hi" \ ```bash $QWEN --worktree "../escape" "say hi" \ - --approval-mode yolo --output-format json 2>/dev/null > /tmp/a4.out + --approval-mode izn --output-format json 2>/dev/null > /tmp/a4.out echo "exit=$?" ls "$TEST_DIR/.qwen/worktrees/" 2>/dev/null @@ -154,7 +154,7 @@ ls "$TEST_DIR/.qwen/worktrees/" 2>/dev/null NON_GIT=$(mktemp -d) cd "$NON_GIT" $QWEN --worktree "say hi" \ - --approval-mode yolo --output-format json 2>/dev/null > /tmp/a5.out + --approval-mode izn --output-format json 2>/dev/null > /tmp/a5.out echo "exit=$?" ``` @@ -170,7 +170,7 @@ or "git init". ```bash SESSION_ID=$(uuidgen) $QWEN --worktree b1-test --session-id "$SESSION_ID" "say hi" \ - --approval-mode yolo --output-format json 2>/dev/null > /tmp/b1.out + --approval-mode izn --output-format json 2>/dev/null > /tmp/b1.out SIDECAR=~/.qwen/projects/$PROJECT_ID/chats/$SESSION_ID.worktree.json jq '.slug, .worktreePath, .worktreeBranch, .originalCwd, .originalBranch, .originalHeadCommit' \ @@ -190,7 +190,7 @@ jq '.slug, .worktreePath, .worktreeBranch, .originalCwd, .originalBranch, .origi ```bash $QWEN --worktree b2-test "run the shell tool with command 'pwd', then stop" \ - --approval-mode yolo --output-format json 2>/dev/null > /tmp/b2.out + --approval-mode izn --output-format json 2>/dev/null > /tmp/b2.out # Extract the shell tool's stdout from the user-message tool_result jq -r '.[] | select(.type=="user") | .message.content[] | select(.tool_use_id != null) | .content' \ @@ -203,7 +203,7 @@ jq -r '.[] | select(.type=="user") | .message.content[] | select(.tool_use_id != ```bash $QWEN --worktree b3-test "run the shell tool with command 'pwd && git rev-parse --abbrev-ref HEAD', then stop" \ - --approval-mode yolo --output-format json 2>/dev/null > /tmp/b3.out + --approval-mode izn --output-format json 2>/dev/null > /tmp/b3.out jq -r '.[] | select(.type=="user") | .message.content[] | select(.tool_use_id != null) | .content' \ < /tmp/b3.out @@ -222,11 +222,11 @@ is inside the worktree. # Run 1: create a session with worktree "first" SESSION_ID=$(uuidgen) $QWEN --worktree first --session-id "$SESSION_ID" "say hi" \ - --approval-mode yolo --output-format json 2>/dev/null > /tmp/c1-run1.out + --approval-mode izn --output-format json 2>/dev/null > /tmp/c1-run1.out # Run 2: resume the same session but request a different worktree $QWEN --resume "$SESSION_ID" --worktree second "say hi again" \ - --approval-mode yolo --output-format json 2>/dev/null > /tmp/c1-run2.out + --approval-mode izn --output-format json 2>/dev/null > /tmp/c1-run2.out # Sidecar should now point at "second" SIDECAR=~/.qwen/projects/$PROJECT_ID/chats/$SESSION_ID.worktree.json @@ -248,12 +248,12 @@ ls -d "$TEST_DIR/.qwen/worktrees/"* ```bash SESSION_ID=$(uuidgen) $QWEN --worktree c2 --session-id "$SESSION_ID" "say hi" \ - --approval-mode yolo --output-format json 2>/dev/null > /tmp/c2-run1.out + --approval-mode izn --output-format json 2>/dev/null > /tmp/c2-run1.out rm -rf "$TEST_DIR/.qwen/worktrees/c2" # simulate user-deleted dir $QWEN --resume "$SESSION_ID" --worktree c2-fresh "say hi" \ - --approval-mode yolo --output-format json 2>/dev/null > /tmp/c2-run2.out + --approval-mode izn --output-format json 2>/dev/null > /tmp/c2-run2.out ls -d "$TEST_DIR/.qwen/worktrees/"* ``` @@ -271,7 +271,7 @@ worktree was created by the CLI flag rather than `EnterWorktreeTool`. ```bash tmux new-session -d -s d1 -x 200 -y 50 \ - "cd $TEST_DIR && $QWEN --worktree d1-test --approval-mode yolo" + "cd $TEST_DIR && $QWEN --worktree d1-test --approval-mode izn" sleep 3 # Verify worktree is active (Footer indicator) @@ -294,7 +294,7 @@ three radio options appear. ```bash tmux new-session -d -s d2 -x 200 -y 50 \ - "cd $TEST_DIR && $QWEN --worktree d2-test --approval-mode yolo" + "cd $TEST_DIR && $QWEN --worktree d2-test --approval-mode izn" sleep 3 tmux send-keys -t d2 C-c; sleep 0.3; tmux send-keys -t d2 C-c; sleep 1 @@ -314,7 +314,7 @@ tmux kill-session -t d2 ```bash SESSION_ID=$(uuidgen) tmux new-session -d -s d3 -x 200 -y 50 \ - "cd $TEST_DIR && $QWEN --worktree d3-test --session-id $SESSION_ID --approval-mode yolo" + "cd $TEST_DIR && $QWEN --worktree d3-test --session-id $SESSION_ID --approval-mode izn" sleep 3 tmux send-keys -t d3 C-c; sleep 0.3; tmux send-keys -t d3 C-c; sleep 1 tmux send-keys -t d3 Down Enter # select "Remove worktree and branch" @@ -353,7 +353,7 @@ EOF ```bash $QWEN --worktree e1-test "say hi" \ - --approval-mode yolo --output-format json 2>/dev/null > /dev/null + --approval-mode izn --output-format json 2>/dev/null > /dev/null ls -la "$TEST_DIR/.qwen/worktrees/e1-test/node_modules" readlink "$TEST_DIR/.qwen/worktrees/e1-test/node_modules" @@ -366,7 +366,7 @@ pointing to `$TEST_DIR/node_modules`. ```bash $QWEN "use enter_worktree to create a worktree named e2-test, then stop" \ - --approval-mode yolo --output-format json 2>/dev/null > /dev/null + --approval-mode izn --output-format json 2>/dev/null > /dev/null readlink "$TEST_DIR/.qwen/worktrees/e2-test/node_modules" ``` @@ -379,7 +379,7 @@ Requires a sub-agent definition. Use the built-in fork mechanism: ```bash $QWEN "use the agent tool with subagent_type='general-purpose', isolation='worktree', description='check node_modules', prompt='run pwd and ls -la node_modules then exit'" \ - --approval-mode yolo --output-format json 2>/dev/null > /tmp/e3.out + --approval-mode izn --output-format json 2>/dev/null > /tmp/e3.out # Extract agent worktree dir from result message jq -r '.[] | select(.type=="assistant") | .message.content[] | select(.type=="tool_use") | .input' \ @@ -401,7 +401,7 @@ cat > "$TEST_DIR/.qwen/settings.json" <<'EOF' { "worktree": { "symlinkDirectories": ["does-not-exist"] } } EOF -$QWEN --worktree e4-test "say hi" --approval-mode yolo --output-format json 2>/dev/null > /tmp/e4.out +$QWEN --worktree e4-test "say hi" --approval-mode izn --output-format json 2>/dev/null > /tmp/e4.out ls -d "$TEST_DIR/.qwen/worktrees/e4-test" ls "$TEST_DIR/.qwen/worktrees/e4-test/does-not-exist" 2>/dev/null && echo "UNEXPECTED" ``` @@ -418,7 +418,7 @@ mkdir -p "$TEST_DIR/.qwen/worktrees/e5-test/node_modules" echo "preexisting" > "$TEST_DIR/.qwen/worktrees/e5-test/node_modules/.marker" # Force re-creation via EnterWorktreeTool (CLI would refuse "already exists") -$QWEN "use enter_worktree with name='e5-test' to retry" --approval-mode yolo 2>/dev/null +$QWEN "use enter_worktree with name='e5-test' to retry" --approval-mode izn 2>/dev/null # either: tool errors out cleanly, OR symlink is skipped — both acceptable test -f "$TEST_DIR/.qwen/worktrees/e5-test/node_modules/.marker" && echo "PASS: not overwritten" ``` @@ -433,7 +433,7 @@ cat > "$TEST_DIR/.qwen/settings.json" <<'EOF' { "worktree": { "symlinkDirectories": ["/etc", "../escape"] } } EOF -$QWEN --worktree e6-test "say hi" --approval-mode yolo --output-format json 2>/dev/null > /tmp/e6.out +$QWEN --worktree e6-test "say hi" --approval-mode izn --output-format json 2>/dev/null > /tmp/e6.out ls "$TEST_DIR/.qwen/worktrees/e6-test/" | head -10 ``` @@ -461,7 +461,7 @@ PROJECT_ID=$(node -e "console.log(process.argv[1].replace(/[^a-zA-Z0-9]/g,'-'))" ```bash $QWEN --worktree=#4174 "say hi" \ - --approval-mode yolo --output-format json 2>/dev/null > /tmp/f1.out + --approval-mode izn --output-format json 2>/dev/null > /tmp/f1.out ls -d "$TEST_DIR/.qwen/worktrees/pr-4174" git -C "$TEST_DIR/.qwen/worktrees/pr-4174" rev-parse --abbrev-ref HEAD @@ -477,7 +477,7 @@ git -C "$TEST_DIR/.qwen/worktrees/pr-4174" rev-parse --abbrev-ref HEAD ```bash $QWEN --worktree "https://github.com/QwenLM/qwen-code/pull/4174" "say hi" \ - --approval-mode yolo --output-format json 2>/dev/null > /tmp/f2.out + --approval-mode izn --output-format json 2>/dev/null > /tmp/f2.out ls -d "$TEST_DIR/.qwen/worktrees/pr-4174" ``` @@ -488,7 +488,7 @@ ls -d "$TEST_DIR/.qwen/worktrees/pr-4174" ```bash cd "$TEST_DIR" && git remote remove origin -$QWEN --worktree=#4174 "say hi" --approval-mode yolo --output-format json 2>/dev/null > /tmp/f3.out +$QWEN --worktree=#4174 "say hi" --approval-mode izn --output-format json 2>/dev/null > /tmp/f3.out echo "exit=$?" ``` @@ -497,7 +497,7 @@ echo "exit=$?" ### F4: invalid PR number → fail-close ```bash -$QWEN --worktree=#999999999 "say hi" --approval-mode yolo --output-format json 2>/dev/null > /tmp/f4.out +$QWEN --worktree=#999999999 "say hi" --approval-mode izn --output-format json 2>/dev/null > /tmp/f4.out echo "exit=$?" ``` @@ -507,7 +507,7 @@ echo "exit=$?" ### F5: malformed `#abc` falls through to slug validation ```bash -$QWEN --worktree=#abc "say hi" --approval-mode yolo --output-format json 2>/dev/null > /tmp/f5.out +$QWEN --worktree=#abc "say hi" --approval-mode izn --output-format json 2>/dev/null > /tmp/f5.out echo "exit=$?" ``` @@ -522,7 +522,7 @@ cat > "$TEST_DIR/.qwen/settings.json" <<'EOF' EOF mkdir -p "$TEST_DIR/node_modules" && echo x > "$TEST_DIR/node_modules/.marker" -$QWEN --worktree=#4174 "say hi" --approval-mode yolo --output-format json 2>/dev/null > /dev/null +$QWEN --worktree=#4174 "say hi" --approval-mode izn --output-format json 2>/dev/null > /dev/null readlink "$TEST_DIR/.qwen/worktrees/pr-4174/node_modules" ``` @@ -543,7 +543,7 @@ readlink "$TEST_DIR/.qwen/worktrees/pr-4174/node_modules" ```bash SESSION_ID=$(uuidgen) tmux new-session -d -s g1 -x 200 -y 50 \ - "cd $TEST_DIR && $QWEN --worktree g1-test --session-id $SESSION_ID --approval-mode yolo 2>&1 | tee /tmp/g1-stderr.out" + "cd $TEST_DIR && $QWEN --worktree g1-test --session-id $SESSION_ID --approval-mode izn 2>&1 | tee /tmp/g1-stderr.out" sleep 3 tmux send-keys -t g1 "use the write_file tool to create file 'work.txt' with content 'phase d test'" sleep 0.3; tmux send-keys -t g1 Enter @@ -559,7 +559,7 @@ cat "$TEST_DIR/.qwen/worktrees/g1-test/work.txt" # Resume reattaches tmux new-session -d -s g1b -x 200 -y 50 \ - "cd $TEST_DIR && $QWEN --resume $SESSION_ID --approval-mode yolo" + "cd $TEST_DIR && $QWEN --resume $SESSION_ID --approval-mode izn" sleep 4 tmux capture-pane -t g1b -p -S -50 | grep -E "⎇ worktree-g1-test|Resumed" tmux kill-session -t g1b @@ -585,7 +585,7 @@ EOF cd "$TEST_DIR" $QWEN --worktree g2-test --mcp-config ./mcp.json "say hi" \ - --approval-mode yolo --output-format json 2>/dev/null > /tmp/g2.out + --approval-mode izn --output-format json 2>/dev/null > /tmp/g2.out echo "exit=$?" jq -r '.[] | select(.type=="result") | .result' < /tmp/g2.out | head -3 ``` @@ -662,7 +662,7 @@ implementation.** | Group | Result | Notes | | ---------------------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| A1 (bare flag) | ✅ (with doc tip) | yargs consumes the next positional as the slug value when user passes `qwen --worktree "say hi"`; quickstart now tells users to use `=` form or put the prompt before the flag. Auto-slug feature itself confirmed via `qwen --worktree --approval-mode yolo "say hi"` → slug `bright-elm-8a4c12`, init `.cwd` ends with `.qwen/worktrees/`. | +| A1 (bare flag) | ✅ (with doc tip) | yargs consumes the next positional as the slug value when user passes `qwen --worktree "say hi"`; quickstart now tells users to use `=` form or put the prompt before the flag. Auto-slug feature itself confirmed via `qwen --worktree --approval-mode izn "say hi"` → slug `bright-elm-8a4c12`, init `.cwd` ends with `.qwen/worktrees/`. | | A2 (explicit slug) | ✅ | dir `.qwen/worktrees/my-feature` + branch `worktree-my-feature` | | A3 (= form) | ✅ | identical to A2 | | A4 (invalid slug) | ✅ | exit=1, message: `Worktree name may only contain letters, digits, dots, underscores, and hyphens.`, no worktree dir | diff --git a/docs/users/configuration/_meta.ts b/docs/users/configuration/_meta.ts index 3628399ba5d..af332d49620 100644 --- a/docs/users/configuration/_meta.ts +++ b/docs/users/configuration/_meta.ts @@ -1,10 +1,7 @@ export default { settings: 'Settings', auth: 'Authentication', - memory: { - display: 'hidden', - }, - 'hopcode-ignore': 'Ignoring Files', + 'qwen-ignore': 'Ignoring Files', 'trusted-folders': 'Trusted Folders', themes: 'Themes', }; diff --git a/docs/users/configuration/settings.md b/docs/users/configuration/settings.md index 35ee94360f8..fa66e9cac5d 100644 --- a/docs/users/configuration/settings.md +++ b/docs/users/configuration/settings.md @@ -1,4 +1,4 @@ -# HopCode Configuration +# HopCode Configuration > [!tip] > @@ -27,20 +27,20 @@ Configuration is applied in the following order of precedence (lower numbers are HopCode uses JSON settings files for persistent configuration. There are four locations for these files: -| File Type | Location | Scope | -| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| System defaults file | Linux: `/etc/hopcode/system-defaults.json`
Windows: `C:\ProgramData\hopcode\system-defaults.json`
macOS: `/Library/Application Support/HopCode/system-defaults.json`
The path can be overridden using the `HOPCODE_SYSTEM_DEFAULTS_PATH` environment variable. | Provides a base layer of system-wide default settings. These settings have the lowest precedence and are intended to be overridden by user, project, or system override settings. | -| User settings file | `~/.hopcode/settings.json` (where `~` is your home directory). | Applies to all HopCode sessions for the current user. | -| Project settings file | `.hopcode/settings.json` within your project's root directory. | Applies only when running HopCode from that specific project. Project settings override user settings. | -| System settings file | Linux: `/etc/hopcode/settings.json`
Windows: `C:\ProgramData\hopcode\settings.json`
macOS: `/Library/Application Support/HopCode/settings.json`
The path can be overridden using the `HOPCODE_SYSTEM_SETTINGS_PATH` environment variable. | Applies to all HopCode sessions on the system, for all users. System settings override user and project settings. May be useful for system administrators at enterprises to have controls over users' HopCode setups. | +| File Type | Location | Scope | +| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| System defaults file | Linux: `/etc/hopcode/system-defaults.json`
Windows: `C:\ProgramData\hopcode\system-defaults.json`
macOS: `/Library/Application Support/HopCode/system-defaults.json`
The path can be overridden using the `QWEN_CODE_SYSTEM_DEFAULTS_PATH` environment variable. | Provides a base layer of system-wide default settings. These settings have the lowest precedence and are intended to be overridden by user, project, or system override settings. | +| User settings file | `~/.hopcode/settings.json` (where `~` is your home directory). | Applies to all HopCode sessions for the current user. | +| Project settings file | `.hopcode/settings.json` within your project's root directory. | Applies only when running HopCode from that specific project. Project settings override user settings. | +| System settings file | Linux: `/etc/hopcode/settings.json`
Windows: `C:\ProgramData\hopcode\settings.json`
macOS: `/Library/Application Support/HopCode/settings.json`
The path can be overridden using the `QWEN_CODE_SYSTEM_SETTINGS_PATH` environment variable. | Applies to all HopCode sessions on the system, for all users. System settings override user and project settings. May be useful for system administrators at enterprises to have controls over users' HopCode setups. | > [!note] > > **Note on environment variables in settings:** String values within your `settings.json` files can reference environment variables using either `$VAR_NAME` or `${VAR_NAME}` syntax. These variables will be automatically resolved when the settings are loaded. For example, if you have an environment variable `MY_API_TOKEN`, you could use it in `settings.json` like this: `"apiKey": "$MY_API_TOKEN"`. -### The `.qwen` directory in your project +### The `.hopcode` directory in your project -In addition to a project settings file, a project's `.qwen` directory can contain other project-specific files related to HopCode's operation, such as: +In addition to a project settings file, a project's `.hopcode` directory can contain other project-specific files related to HopCode's operation, such as: - [Custom sandbox profiles](../features/sandbox) (e.g. `.hopcode/sandbox-macos-custom.sb`, `.hopcode/sandbox.Dockerfile`). - [Agent Skills](../features/skills) under `.hopcode/skills/` (each Skill is a directory containing a `SKILL.md`). @@ -108,7 +108,7 @@ Settings are organized into categories. Most settings should be placed within th | `ui.hideBanner` | boolean | Hide the startup ASCII logo and info panel. Tips and chat input still render unless `ui.hideTips` is also set. | `false` | | `ui.customBannerTitle` | string | Replace the default `>_ HopCode` title in the banner info panel. The `(vX.Y.Z)` version suffix is always appended; auth, model, and path lines are not affected. Sanitized; capped at 80 characters. | `""` | | `ui.customBannerSubtitle` | string | Optional subtitle line rendered between the banner title and the auth/model line, in place of the blank spacer row. Sanitized; capped at 160 characters. Empty (default) keeps the original blank spacer. | `""` | -| `ui.customAsciiArt` | string \| object | Replace the QWEN ASCII logo in the banner. Accepts an inline string (used for both width tiers), `{ "path": "./brand.txt" }` (relative paths resolve against the owning settings file's directory; read once at startup with `O_NOFOLLOW` on POSIX, capped at 64 KB), or `{ "small": ..., "large": ... }` for width-aware selection. Sanitized; capped at 200 lines × 200 columns per tier. | `undefined` | +| `ui.customAsciiArt` | string \| object | Replace the HopCode ASCII logo in the banner. Accepts an inline string (used for both width tiers), `{ "path": "./brand.txt" }` (relative paths resolve against the owning settings file's directory; read once at startup with `O_NOFOLLOW` on POSIX, capped at 64 KB), or `{ "small": ..., "large": ... }` for width-aware selection. Sanitized; capped at 200 lines × 200 columns per tier. | `undefined` | | `ui.hideFooter` | boolean | Hide the footer from the UI. | `false` | | `ui.showMemoryUsage` | boolean | Display memory usage information in the UI. | `false` | | `ui.showLineNumbers` | boolean | Show line numbers in code blocks in the CLI output. | `true` | @@ -123,7 +123,7 @@ Settings are organized into categories. Most settings should be placed within th | `ui.enableFollowupSuggestions` | boolean | Enable [followup suggestions](../features/followup-suggestions) that predict what you want to type next after the model responds. Suggestions appear as ghost text and can be accepted with Tab, Enter, or Right Arrow. | `true` | | `ui.enableCacheSharing` | boolean | Use cache-aware forked queries for suggestion generation. Reduces cost on providers that support prefix caching (experimental). | `true` | | `ui.enableSpeculation` | boolean | Speculatively execute accepted suggestions before submission. Results appear instantly when you accept (experimental). | `false` | -| `experimental.emitToolUseSummaries` | boolean | Generate short LLM-based labels summarizing each tool-call batch. See [Tool-Use Summaries](../features/tool-use-summaries). Requires `fastModel` to be configured; silently skipped otherwise. Can be overridden per-session with `HOPCODE_EMIT_TOOL_USE_SUMMARIES=0` or `=1`. | `true` | +| `experimental.emitToolUseSummaries` | boolean | Generate short LLM-based labels summarizing each tool-call batch. See [Tool-Use Summaries](../features/tool-use-summaries). Requires `fastModel` to be configured; silently skipped otherwise. Can be overridden per-session with `QWEN_CODE_EMIT_TOOL_USE_SUMMARIES=0` or `=1`. | `true` | #### ide @@ -142,7 +142,7 @@ Settings are organized into categories. Most settings should be placed within th | Setting | Type | Description | Default | | -------------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------- | -| `model.name` | string | The Qwen model to use for conversations. | `undefined` | +| `model.name` | string | The HopCode model to use for conversations. | `undefined` | | `model.maxSessionTurns` | number | Maximum number of user/model/tool turns to keep in a session. -1 means unlimited. | `-1` | | `model.maxWallTimeSeconds` | number | Wall-clock budget for headless / unattended runs, in seconds. `-1` means unlimited. Overridable per-invocation via `--max-wall-time`, which requires a positive duration (`90`, `30s`, `5m`, `1h`, `1.5h`); the minimum is 1 second — sub-second values (`500ms`, `0.5`) are rejected as typos. Omit the flag to fall back to this setting. Aborts with exit code 55 when exceeded. | `-1` | | `model.maxToolCalls` | number | Cumulative tool-call budget for a run (counts every executed tool, success or failure; `structured_output` under `--json-schema` is exempt). `-1` means unlimited; `0` means "no tool calls allowed". Capped at 1,000,000 to catch typos. Overridable via `--max-tool-calls`. Aborts with exit code 55 when exceeded. | `-1` | @@ -196,7 +196,7 @@ When `samplingParams.max_tokens` is not set, HopCode uses an adaptive output tok This is transparent to users — you may briefly see a retry indicator if escalation occurs. Since 99% of responses are under 5K tokens, the retry happens rarely (<1% of requests). -To override this behavior, either set `samplingParams.max_tokens` in your settings or use the `HOPCODE_MAX_OUTPUT_TOKENS` environment variable. +To override this behavior, either set `samplingParams.max_tokens` in your settings or use the `QWEN_CODE_MAX_OUTPUT_TOKENS` environment variable. **contextWindowSize:** @@ -219,7 +219,7 @@ The `extra_body` field allows you to add custom parameters to the request body s **model.openAILoggingDir examples:** -- `"~/hopcode-logs"` - Logs to `~/hopcode-logs` directory +- `"~/qwen-logs"` - Logs to `~/qwen-logs` directory - `"./custom-logs"` - Logs to `./custom-logs` relative to current directory - `"/tmp/openai-logs"` - Logs to absolute path `/tmp/openai-logs` @@ -238,7 +238,7 @@ The `extra_body` field allows you to add custom parameters to the request body s | `context.includeDirectories` | array | Additional directories to include in the workspace context. Specifies an array of additional absolute or relative paths to include in the workspace context. Missing directories will be skipped with a warning by default. Paths can use `~` to refer to the user's home directory. This setting can be combined with the `--include-directories` command-line flag. | `[]` | | `context.loadFromIncludeDirectories` | boolean | Controls the behavior of the `/memory refresh` command. If set to `true`, `HOPCODE.md` files should be loaded from all directories that are added. If set to `false`, `HOPCODE.md` should only be loaded from the current directory. | `false` | | `context.fileFiltering.respectGitIgnore` | boolean | Respect .gitignore files when searching. | `true` | -| `context.fileFiltering.respectQwenIgnore` | boolean | Respect .qwenignore files when searching. | `true` | +| `context.fileFiltering.respectHopcodeIgnore` | boolean | Respect .hopcodeignore files when searching. | `true` | | `context.fileFiltering.enableRecursiveFileSearch` | boolean | Whether to enable searching recursively for filenames under the current tree when completing `@` prefixes in the prompt. | `true` | | `context.fileFiltering.enableFuzzySearch` | boolean | When `true`, enables fuzzy search capabilities when searching for files. Set to `false` to improve performance on projects with a large number of files. | `true` | | `context.clearContextOnIdle.toolResultsThresholdMinutes` | number | Minutes of inactivity before clearing old tool result content. Use `-1` to disable. | `60` | @@ -248,7 +248,7 @@ The `extra_body` field allows you to add custom parameters to the request body s If you are experiencing performance issues with file searching (e.g., with `@` completions), especially in projects with a very large number of files, here are a few things you can try in order of recommendation: -1. **Use `.qwenignore`:** Create a `.qwenignore` file in your project root to exclude directories that contain a large number of files that you don't need to reference (e.g., build artifacts, logs, `node_modules`). Reducing the total number of files crawled is the most effective way to improve performance. +1. **Use `.hopcodeignore`:** Create a `.hopcodeignore` file in your project root to exclude directories that contain a large number of files that you don't need to reference (e.g., build artifacts, logs, `node_modules`). Reducing the total number of files crawled is the most effective way to improve performance. 2. **Disable Fuzzy Search:** If ignoring files is not enough, you can disable fuzzy search by setting `enableFuzzySearch` to `false` in your `settings.json` file. This will use a simpler, non-fuzzy matching algorithm, which can be faster. 3. **Disable Recursive File Search:** As a last resort, you can disable recursive file search entirely by setting `enableRecursiveFileSearch` to `false`. This will be the fastest option as it avoids a recursive crawl of your project. However, it means you will need to type the full path to files when using `@` completions. @@ -257,7 +257,7 @@ If you are experiencing performance issues with file searching (e.g., with `@` c | Setting | Type | Description | Default | Notes | | ------------------------------------ | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tools.sandbox` | boolean or string | Sandbox execution environment (can be a boolean or a path string). | `undefined` | | -| `tools.sandboxImage` | string | Sandbox image URI used by Docker/Podman when `--sandbox-image` and `HOPCODE_SANDBOX_IMAGE` are not set. | `undefined` | | +| `tools.sandboxImage` | string | Sandbox image URI used by Docker/Podman when `--sandbox-image` and `QWEN_SANDBOX_IMAGE` are not set. | `undefined` | | | `tools.shell.enableInteractiveShell` | boolean | Use `node-pty` for an interactive shell experience. Fallback to `child_process` still applies. | `false` | | | `tools.core` | array of strings | **Deprecated.** Will be removed in next version. Use `permissions.allow` + `permissions.deny` instead. Restricts built-in tools to an allowlist. All tools not in the list are disabled. | `undefined` | | | `tools.exclude` | array of strings | **Deprecated.** Use `permissions.deny` instead. Tool names to exclude from discovery. Automatically migrated to the `permissions` format on first load. | `undefined` | | @@ -389,7 +389,7 @@ the command surface in multi-tenant or enterprise deployments. | `slashCommands.disabled` | array of strings | Slash command names to hide and refuse to execute. Matched case-insensitively against the final command name (for extension commands this is the disambiguated form, e.g. `myext.deploy`). **Merged as a union across scopes**, so workspace settings can add to but not remove entries defined in user or system settings. | `undefined` | The same denylist can also be provided via the `--disabled-slash-commands` CLI -flag (comma-separated or repeated) and the `HOPCODE_DISABLED_SLASH_COMMANDS` +flag (comma-separated or repeated) and the `QWEN_DISABLED_SLASH_COMMANDS` environment variable; values from all three sources are unioned together. **Example — lock down built-ins for a sandboxed deployment:** @@ -403,7 +403,7 @@ environment variable; values from all three sources are unioned together. ``` With these values in a system-level `settings.json` (`/etc/hopcode/settings.json` -or `HOPCODE_SYSTEM_SETTINGS_PATH`), users cannot shrink the denylist from +or `QWEN_CODE_SYSTEM_SETTINGS_PATH`), users cannot shrink the denylist from their own scope, and the disabled commands will not appear in autocomplete or execute when typed. @@ -508,7 +508,7 @@ Here is an example of a `settings.json` file with the nested structure, new as o "tools": { "approvalMode": "izn", "sandbox": "docker", - "sandboxImage": "ghcr.io/hoptrendy/hopcode:0.14.1", + "sandboxImage": "ghcr.io/qwenlm/hopcode:0.14.1", "discoveryCommand": "bin/get_tools", "callCommand": "bin/call_tool", "exclude": ["write_file"] @@ -536,7 +536,7 @@ Here is an example of a `settings.json` file with the nested structure, new as o "name": "qwen3-coder-plus", "maxSessionTurns": 10, "enableOpenAILogging": false, - "openAILoggingDir": "~/hopcode-logs", + "openAILoggingDir": "~/qwen-logs", }, "context": { "fileName": ["CONTEXT.md", "HOPCODE.md"], @@ -575,7 +575,7 @@ For authentication-related variables (like `OPENAI_*`) and the recommended `.hop | Variable | Description | Notes | | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `HOPCODE_HOME` | Customizes the global configuration directory (default: `~/.qwen`). Accepts an absolute or relative path (relative paths are resolved from the current working directory). Leading `~` is expanded to the user's home directory. | Stores credentials, settings, memory, skills, and other global state. When set, project-level `.hopcode/` directories are unaffected. An empty string is treated as unset. | +| `HOPCODE_HOME` | Customizes the global configuration directory (default: `~/.hopcode`). Accepts an absolute or relative path (relative paths are resolved from the current working directory). Leading `~` is expanded to the user's home directory. | Stores credentials, settings, memory, skills, and other global state. When set, project-level `.hopcode/` directories are unaffected. An empty string is treated as unset. | | `QWEN_RUNTIME_DIR` | Overrides the runtime output directory (conversations, logs, todos). When unset, defaults to the `HOPCODE_HOME` directory. | Use this to separate ephemeral runtime data from persistent config. Useful when `HOPCODE_HOME` is on a shared/slow filesystem. | | `QWEN_TELEMETRY_ENABLED` | Set to `true` or `1` to enable telemetry. Any other value is treated as disabling it. | Overrides the `telemetry.enabled` setting. | | `QWEN_TELEMETRY_TARGET` | Sets an informational label for the telemetry destination (`local` or `gcp`). Does not control routing; use `QWEN_TELEMETRY_OTLP_ENDPOINT` or `QWEN_TELEMETRY_OUTFILE` to configure where data is sent. | Overrides the `telemetry.target` setting. | @@ -584,8 +584,8 @@ For authentication-related variables (like `OPENAI_*`) and the recommended `.hop | `QWEN_TELEMETRY_LOG_PROMPTS` | Set to `true` or `1` to enable or disable logging of user prompts. Any other value is treated as disabling it. | Overrides the `telemetry.logPrompts` setting. | | `QWEN_TELEMETRY_INCLUDE_SENSITIVE_SPAN_ATTRIBUTES` | Set to `true` or `1` to attach verbatim user prompts, system prompts, tool I/O, and model responses to native OTel span attributes (and keep `prompt` / `function_args` / `response_text` on log-to-span bridge spans). Any other value disables it. | Overrides the `telemetry.includeSensitiveSpanAttributes` setting. ⚠️ Streams sensitive data to your OTLP backend. | | `QWEN_TELEMETRY_OUTFILE` | Sets the file path to write telemetry to. When set, overrides OTLP export. | Overrides the `telemetry.outfile` setting. | -| `HOPCODE_SANDBOX` | Alternative to the `sandbox` setting in `settings.json`. | Accepts `true`, `false`, `docker`, `podman`, or a custom command string. | -| `HOPCODE_SANDBOX_IMAGE` | Overrides sandbox image selection for Docker/Podman. | Takes precedence over `tools.sandboxImage`. | +| `QWEN_SANDBOX` | Alternative to the `sandbox` setting in `settings.json`. | Accepts `true`, `false`, `docker`, `podman`, or a custom command string. | +| `QWEN_SANDBOX_IMAGE` | Overrides sandbox image selection for Docker/Podman. | Takes precedence over `tools.sandboxImage`. | | `SEATBELT_PROFILE` | (macOS specific) Switches the Seatbelt (`sandbox-exec`) profile on macOS. | `permissive-open`: (Default) Restricts writes to the project folder (and a few other folders, see `packages/cli/src/utils/sandbox-macos-permissive-open.sb`) but allows other operations. `strict`: Uses a strict profile that declines operations by default. ``: Uses a custom profile. To define a custom profile, create a file named `sandbox-macos-.sb` in your project's `.hopcode/` directory (e.g., `my-project/.hopcode/sandbox-macos-custom.sb`). | | `DEBUG` or `DEBUG_MODE` | (often used by underlying libraries or the CLI itself) Set to `true` or `1` to enable verbose debug logging, which can be helpful for troubleshooting. | **Note:** These variables are automatically excluded from project `.env` files by default to prevent interference with the CLI behavior. Use `.hopcode/.env` files if you need to set these for HopCode specifically. | | `NO_COLOR` | Set to any value to disable all color output in the CLI. | | @@ -593,14 +593,14 @@ For authentication-related variables (like `OPENAI_*`) and the recommended `.hop | `QWEN_DISABLE_HYPERLINKS` | Set to `1` to hard-disable OSC 8 clickable hyperlinks in the markdown renderer even on terminals that auto-detect as capable. | Useful when a terminal advertises support but breaks on long URLs, or when piping output through an intermediary that mangles escape sequences. The renderer falls back to plain `label (url)` rendering. | | `CLI_TITLE` | Set to a string to customize the title of the CLI. | | | `CODE_ASSIST_ENDPOINT` | Specifies the endpoint for the code assist server. | This is useful for development and testing. | -| `HOPCODE_MAX_OUTPUT_TOKENS` | Overrides the default maximum output tokens per response. When not set, HopCode uses an adaptive strategy: starts with 8K tokens and automatically retries with 64K if the response is truncated. Set this to a specific value (e.g., `16000`) to use a fixed limit instead. | Takes precedence over the capped default (8K) but is overridden by `samplingParams.max_tokens` in settings. Disables automatic escalation when set. Example: `export HOPCODE_MAX_OUTPUT_TOKENS=16000` | -| `HOPCODE_UNATTENDED_RETRY` | Set to `true` or `1` to enable persistent retry mode. When enabled, transient API capacity errors (HTTP 429 Rate Limit and 529 Overloaded) are retried indefinitely with exponential backoff (capped at 5 minutes per retry) and heartbeat keepalives every 30 seconds on stderr. | Designed for CI/CD pipelines and background automation where long-running tasks should survive temporary API outages. Must be set explicitly — `CI=true` alone does **not** activate this mode. See [Headless Mode](../features/headless#persistent-retry-mode) for details. Example: `export HOPCODE_UNATTENDED_RETRY=1` | -| `HOPCODE_PROFILE_STARTUP` | Set to `1` to enable startup performance profiling. Writes a JSON timing report to `~/.hopcode/startup-perf/` with per-phase durations. | Only active inside the sandbox child process (or with `HOPCODE_PROFILE_STARTUP_OUTER=1`). Zero overhead when not set. Example: `export HOPCODE_PROFILE_STARTUP=1` | -| `HOPCODE_PROFILE_STARTUP_OUTER` | Set to `1` together with `HOPCODE_PROFILE_STARTUP=1` to also collect a startup profile in the outer (pre-sandbox) process. Outer-process reports get an `outer-` filename prefix to keep them distinct from the sandbox child's report. | Off by default — only the sandbox child collects, to avoid duplicate reports. Useful for local development where the cli isn't relaunched into a sandbox. | -| `HOPCODE_PROFILE_STARTUP_NO_HEAP` | Set to `1` together with `HOPCODE_PROFILE_STARTUP=1` to skip the per-checkpoint `process.memoryUsage()` snapshots. Useful when measuring the profiler's own Heisenberg overhead. | Off by default. Heap snapshots cost ~50 µs each (well below 1% of total startup) so most users should leave this alone. | -| `HOPCODE_LEGACY_MCP_BLOCKING` | Set to `1` to restore the pre-progressive-MCP behavior where `Config.initialize()` waits synchronously for every configured MCP server's discover handshake before returning. | Off by default. Modern hopcode lets MCP servers come online in the background while the UI is already interactive; the model sees each batch of new tools within ~16 ms of the server settling. This flag is kept as a rollback escape hatch for ≥ 1 release. Example: `export HOPCODE_LEGACY_MCP_BLOCKING=1` | - -When both user-level `.env` files define the same variable, the Qwen-specific +| `QWEN_CODE_MAX_OUTPUT_TOKENS` | Overrides the default maximum output tokens per response. When not set, HopCode uses an adaptive strategy: starts with 8K tokens and automatically retries with 64K if the response is truncated. Set this to a specific value (e.g., `16000`) to use a fixed limit instead. | Takes precedence over the capped default (8K) but is overridden by `samplingParams.max_tokens` in settings. Disables automatic escalation when set. Example: `export QWEN_CODE_MAX_OUTPUT_TOKENS=16000` | +| `QWEN_CODE_UNATTENDED_RETRY` | Set to `true` or `1` to enable persistent retry mode. When enabled, transient API capacity errors (HTTP 429 Rate Limit and 529 Overloaded) are retried indefinitely with exponential backoff (capped at 5 minutes per retry) and heartbeat keepalives every 30 seconds on stderr. | Designed for CI/CD pipelines and background automation where long-running tasks should survive temporary API outages. Must be set explicitly — `CI=true` alone does **not** activate this mode. See [Headless Mode](../features/headless#persistent-retry-mode) for details. Example: `export QWEN_CODE_UNATTENDED_RETRY=1` | +| `QWEN_CODE_PROFILE_STARTUP` | Set to `1` to enable startup performance profiling. Writes a JSON timing report to `~/.hopcode/startup-perf/` with per-phase durations. | Only active inside the sandbox child process (or with `QWEN_CODE_PROFILE_STARTUP_OUTER=1`). Zero overhead when not set. Example: `export QWEN_CODE_PROFILE_STARTUP=1` | +| `QWEN_CODE_PROFILE_STARTUP_OUTER` | Set to `1` together with `QWEN_CODE_PROFILE_STARTUP=1` to also collect a startup profile in the outer (pre-sandbox) process. Outer-process reports get an `outer-` filename prefix to keep them distinct from the sandbox child's report. | Off by default — only the sandbox child collects, to avoid duplicate reports. Useful for local development where the cli isn't relaunched into a sandbox. | +| `QWEN_CODE_PROFILE_STARTUP_NO_HEAP` | Set to `1` together with `QWEN_CODE_PROFILE_STARTUP=1` to skip the per-checkpoint `process.memoryUsage()` snapshots. Useful when measuring the profiler's own Heisenberg overhead. | Off by default. Heap snapshots cost ~50 µs each (well below 1% of total startup) so most users should leave this alone. | +| `QWEN_CODE_LEGACY_MCP_BLOCKING` | Set to `1` to restore the pre-progressive-MCP behavior where `Config.initialize()` waits synchronously for every configured MCP server's discover handshake before returning. | Off by default. Modern hopcode lets MCP servers come online in the background while the UI is already interactive; the model sees each batch of new tools within ~16 ms of the server settling. This flag is kept as a rollback escape hatch for ≥ 1 release. Example: `export QWEN_CODE_LEGACY_MCP_BLOCKING=1` | + +When both user-level `.env` files define the same variable, the HopCode-specific file wins: `/.env` (or `~/.hopcode/.env` when `HOPCODE_HOME` is unset) is loaded before `~/.env`, and existing environment values are not overwritten. @@ -609,52 +609,52 @@ loaded before `~/.env`, and existing environment values are not overwritten. Arguments passed directly when running the CLI can override other configurations for that specific session. For sandbox image selection, precedence is: -`--sandbox-image` > `HOPCODE_SANDBOX_IMAGE` > `tools.sandboxImage` > built-in default image. +`--sandbox-image` > `QWEN_SANDBOX_IMAGE` > `tools.sandboxImage` > built-in default image. ### Command-Line Arguments Table -| Argument | Alias | Description | Possible Values | Notes | -| ---------------------------- | ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `--model` | `-m` | Specifies the Qwen model to use for this session. | Model name | Example: `npm start -- --model qwen3-coder-plus` | -| `--prompt` | `-p` | Used to pass a prompt directly to the command. This invokes HopCode in a non-interactive mode. | Your prompt text | For scripting examples, use the `--output-format json` flag to get structured output. | -| `--prompt-interactive` | `-i` | Starts an interactive session with the provided prompt as the initial input. | Your prompt text | The prompt is processed within the interactive session, not before it. Cannot be used when piping input from stdin. Example: `hopcode -i "explain this code"` | -| `--system-prompt` | | Overrides the built-in main session system prompt for this run. | Your prompt text | Loaded context files such as `HOPCODE.md` are still appended after this override. Can be combined with `--append-system-prompt`. | -| `--append-system-prompt` | | Appends extra instructions to the main session system prompt for this run. | Your prompt text | Applied after the built-in prompt and loaded context files. Can be combined with `--system-prompt`. See [Headless Mode](../features/headless) for examples. | -| `--output-format` | `-o` | Specifies the format of the CLI output for non-interactive mode. | `text`, `json`, `stream-json` | `text`: (Default) The standard human-readable output. `json`: A machine-readable JSON output emitted at the end of execution. `stream-json`: Streaming JSON messages emitted as they occur during execution. For structured output and scripting, use the `--output-format json` or `--output-format stream-json` flag. See [Headless Mode](../features/headless) for detailed information. | -| `--input-format` | | Specifies the format consumed from standard input. | `text`, `stream-json` | `text`: (Default) Standard text input from stdin or command-line arguments. `stream-json`: JSON message protocol via stdin for bidirectional communication. Requirement: `--input-format stream-json` requires `--output-format stream-json` to be set. When using `stream-json`, stdin is reserved for protocol messages. See [Headless Mode](../features/headless) for detailed information. | -| `--include-partial-messages` | | Include partial assistant messages when using `stream-json` output format. When enabled, emits stream events (message_start, content_block_delta, etc.) as they occur during streaming. | | Default: `false`. Requirement: Requires `--output-format stream-json` to be set. See [Headless Mode](../features/headless) for detailed information about stream events. | -| `--sandbox` | `-s` | Enables sandbox mode for this session. | | | -| `--sandbox-image` | | Sets the sandbox image URI. | | | -| `--debug` | `-d` | Enables debug mode for this session, providing more verbose output. | | | -| `--all-files` | `-a` | If set, recursively includes all files within the current directory as context for the prompt. | | | -| `--help` | `-h` | Displays help information about command-line arguments. | | | -| `--show-memory-usage` | | Displays the current memory usage. | | | -| `--izn` | | Enables IZN mode, which automatically approves all tool calls. | | | -| `--approval-mode` | | Sets the approval mode for tool calls. | `plan`, `default`, `auto-edit`, `izn` | Supported modes: `plan`: Analyze only—do not modify files or execute commands. `default`: Require approval for file edits or shell commands (default behavior). `auto-edit`: Automatically approve edit tools (`edit`, `write_file`, `notebook_edit`) while prompting for others. `izn`: Automatically approve all tool calls (equivalent to `--izn`). Cannot be used together with `--izn`. Use `--approval-mode=izn` instead of `--izn` for the new unified approach. Example: `hopcode --approval-mode auto-edit`
See more about [Approval Mode](../features/approval-mode). | -| `--allowed-tools` | | A comma-separated list of tool names that will bypass the confirmation dialog. | Tool names | Example: `hopcode --allowed-tools "Shell(git status)"` | -| `--disabled-slash-commands` | | Slash command names to hide/disable (comma-separated or repeated). Unioned with the `slashCommands.disabled` setting and the `HOPCODE_DISABLED_SLASH_COMMANDS` environment variable. Matched case-insensitively against the final command name. | Command names | Example: `hopcode --disabled-slash-commands "auth,mcp,extensions"` | -| `--telemetry` | | Enables [telemetry](/developers/development/telemetry). | | | -| `--telemetry-target` | | Sets the telemetry target. | | See [telemetry](/developers/development/telemetry) for more information. | -| `--telemetry-otlp-endpoint` | | Sets the OTLP endpoint for telemetry. | | See [telemetry](../../developers/development/telemetry) for more information. | -| `--telemetry-otlp-protocol` | | Sets the OTLP protocol for telemetry (`grpc` or `http`). | | Defaults to `grpc`. See [telemetry](../../developers/development/telemetry) for more information. | -| `--telemetry-log-prompts` | | Enables logging of prompts for telemetry. | | See [telemetry](../../developers/development/telemetry) for more information. | -| `--checkpointing` | | Enables [checkpointing](../features/checkpointing). | | | -| `--acp` | | Enables ACP mode (Agent Client Protocol). Useful for IDE/editor integrations like [Zed](../integration-zed). | | Stable. Replaces the deprecated `--experimental-acp` flag. | -| `--experimental-lsp` | | Enables experimental [LSP (Language Server Protocol)](../features/lsp) feature for code intelligence (go-to-definition, find references, diagnostics, etc.). | | Experimental. Requires language servers to be installed. | -| `--extensions` | `-e` | Specifies a list of extensions to use for the session. | Extension names | If not provided, all available extensions are used. Use the special term `hopcode -e none` to disable all extensions. Example: `hopcode -e my-extension -e my-other-extension` | -| `--list-extensions` | `-l` | Lists all available extensions and exits. | | | -| `--proxy` | | Sets the proxy for the CLI. | Proxy URL | Example: `--proxy http://localhost:7890`. | -| `--include-directories` | | Includes additional directories in the workspace for multi-directory support. | Directory paths | Can be specified multiple times or as comma-separated values. 5 directories can be added at maximum. Example: `--include-directories /path/to/project1,/path/to/project2` or `--include-directories /path/to/project1 --include-directories /path/to/project2` | -| `--screen-reader` | | Enables screen reader mode, which adjusts the TUI for better compatibility with screen readers. | | | -| `--version` | | Displays the version of the CLI. | | | -| `--openai-logging` | | Enables logging of OpenAI API calls for debugging and analysis. | | This flag overrides the `enableOpenAILogging` setting in `settings.json`. | -| `--openai-logging-dir` | | Sets a custom directory path for OpenAI API logs. | Directory path | This flag overrides the `openAILoggingDir` setting in `settings.json`. Supports absolute paths, relative paths, and `~` expansion. Example: `hopcode --openai-logging-dir "~/hopcode-logs" --openai-logging` | +| Argument | Alias | Description | Possible Values | Notes | +| ---------------------------- | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--model` | `-m` | Specifies the HopCode model to use for this session. | Model name | Example: `npm start -- --model qwen3-coder-plus` | +| `--prompt` | `-p` | Used to pass a prompt directly to the command. This invokes HopCode in a non-interactive mode. | Your prompt text | For scripting examples, use the `--output-format json` flag to get structured output. | +| `--prompt-interactive` | `-i` | Starts an interactive session with the provided prompt as the initial input. | Your prompt text | The prompt is processed within the interactive session, not before it. Cannot be used when piping input from stdin. Example: `qwen -i "explain this code"` | +| `--system-prompt` | | Overrides the built-in main session system prompt for this run. | Your prompt text | Loaded context files such as `HOPCODE.md` are still appended after this override. Can be combined with `--append-system-prompt`. | +| `--append-system-prompt` | | Appends extra instructions to the main session system prompt for this run. | Your prompt text | Applied after the built-in prompt and loaded context files. Can be combined with `--system-prompt`. See [Headless Mode](../features/headless) for examples. | +| `--output-format` | `-o` | Specifies the format of the CLI output for non-interactive mode. | `text`, `json`, `stream-json` | `text`: (Default) The standard human-readable output. `json`: A machine-readable JSON output emitted at the end of execution. `stream-json`: Streaming JSON messages emitted as they occur during execution. For structured output and scripting, use the `--output-format json` or `--output-format stream-json` flag. See [Headless Mode](../features/headless) for detailed information. | +| `--input-format` | | Specifies the format consumed from standard input. | `text`, `stream-json` | `text`: (Default) Standard text input from stdin or command-line arguments. `stream-json`: JSON message protocol via stdin for bidirectional communication. Requirement: `--input-format stream-json` requires `--output-format stream-json` to be set. When using `stream-json`, stdin is reserved for protocol messages. See [Headless Mode](../features/headless) for detailed information. | +| `--include-partial-messages` | | Include partial assistant messages when using `stream-json` output format. When enabled, emits stream events (message_start, content_block_delta, etc.) as they occur during streaming. | | Default: `false`. Requirement: Requires `--output-format stream-json` to be set. See [Headless Mode](../features/headless) for detailed information about stream events. | +| `--sandbox` | `-s` | Enables sandbox mode for this session. | | | +| `--sandbox-image` | | Sets the sandbox image URI. | | | +| `--debug` | `-d` | Enables debug mode for this session, providing more verbose output. | | | +| `--all-files` | `-a` | If set, recursively includes all files within the current directory as context for the prompt. | | | +| `--help` | `-h` | Displays help information about command-line arguments. | | | +| `--show-memory-usage` | | Displays the current memory usage. | | | +| `--izn` | | Enables IZN mode, which automatically approves all tool calls. | | | +| `--approval-mode` | | Sets the approval mode for tool calls. | `plan`, `default`, `auto-edit`, `izn` | Supported modes: `plan`: Analyze only—do not modify files or execute commands. `default`: Require approval for file edits or shell commands (default behavior). `auto-edit`: Automatically approve edit tools (`edit`, `write_file`, `notebook_edit`) while prompting for others. `izn`: Automatically approve all tool calls (equivalent to `--izn`). Cannot be used together with `--izn`. Use `--approval-mode=izn` instead of `--izn` for the new unified approach. Example: `qwen --approval-mode auto-edit`
See more about [Approval Mode](../features/approval-mode). | +| `--allowed-tools` | | A comma-separated list of tool names that will bypass the confirmation dialog. | Tool names | Example: `qwen --allowed-tools "Shell(git status)"` | +| `--disabled-slash-commands` | | Slash command names to hide/disable (comma-separated or repeated). Unioned with the `slashCommands.disabled` setting and the `QWEN_DISABLED_SLASH_COMMANDS` environment variable. Matched case-insensitively against the final command name. | Command names | Example: `qwen --disabled-slash-commands "auth,mcp,extensions"` | +| `--telemetry` | | Enables [telemetry](/developers/development/telemetry). | | | +| `--telemetry-target` | | Sets the telemetry target. | | See [telemetry](/developers/development/telemetry) for more information. | +| `--telemetry-otlp-endpoint` | | Sets the OTLP endpoint for telemetry. | | See [telemetry](../../developers/development/telemetry) for more information. | +| `--telemetry-otlp-protocol` | | Sets the OTLP protocol for telemetry (`grpc` or `http`). | | Defaults to `grpc`. See [telemetry](../../developers/development/telemetry) for more information. | +| `--telemetry-log-prompts` | | Enables logging of prompts for telemetry. | | See [telemetry](../../developers/development/telemetry) for more information. | +| `--checkpointing` | | Enables [checkpointing](../features/checkpointing). | | | +| `--acp` | | Enables ACP mode (Agent Client Protocol). Useful for IDE/editor integrations like [Zed](../integration-zed). | | Stable. Replaces the deprecated `--experimental-acp` flag. | +| `--experimental-lsp` | | Enables experimental [LSP (Language Server Protocol)](../features/lsp) feature for code intelligence (go-to-definition, find references, diagnostics, etc.). | | Experimental. Requires language servers to be installed. | +| `--extensions` | `-e` | Specifies a list of extensions to use for the session. | Extension names | If not provided, all available extensions are used. Use the special term `qwen -e none` to disable all extensions. Example: `qwen -e my-extension -e my-other-extension` | +| `--list-extensions` | `-l` | Lists all available extensions and exits. | | | +| `--proxy` | | Sets the proxy for the CLI. | Proxy URL | Example: `--proxy http://localhost:7890`. | +| `--include-directories` | | Includes additional directories in the workspace for multi-directory support. | Directory paths | Can be specified multiple times or as comma-separated values. 5 directories can be added at maximum. Example: `--include-directories /path/to/project1,/path/to/project2` or `--include-directories /path/to/project1 --include-directories /path/to/project2` | +| `--screen-reader` | | Enables screen reader mode, which adjusts the TUI for better compatibility with screen readers. | | | +| `--version` | | Displays the version of the CLI. | | | +| `--openai-logging` | | Enables logging of OpenAI API calls for debugging and analysis. | | This flag overrides the `enableOpenAILogging` setting in `settings.json`. | +| `--openai-logging-dir` | | Sets a custom directory path for OpenAI API logs. | Directory path | This flag overrides the `openAILoggingDir` setting in `settings.json`. Supports absolute paths, relative paths, and `~` expansion. Example: `qwen --openai-logging-dir "~/qwen-logs" --openai-logging` | ## Context Files (Hierarchical Instructional Context) While not strictly configuration for the CLI's _behavior_, context files (defaulting to `HOPCODE.md` but configurable via the `context.fileName` setting) are crucial for configuring the _instructional context_ (also referred to as "memory"). This powerful feature allows you to give project-specific instructions, coding style guides, or any relevant background information to the AI, making its responses more tailored and accurate to your needs. The CLI includes UI elements, such as an indicator in the footer showing the number of loaded context files, to keep you informed about the active context. -- **Purpose:** These Markdown files contain instructions, guidelines, or context that you want the Qwen model to be aware of during your interactions. The system is designed to manage this instructional context hierarchically. +- **Purpose:** These Markdown files contain instructions, guidelines, or context that you want the HopCode model to be aware of during your interactions. The system is designed to manage this instructional context hierarchically. ### Example Context File Content (e.g. `HOPCODE.md`) @@ -710,10 +710,10 @@ HopCode can execute potentially unsafe operations (like shell commands and file [Sandbox](../features/sandbox) is disabled by default, but you can enable it in a few ways: - Using `--sandbox` or `-s` flag. -- Setting `HOPCODE_SANDBOX` environment variable. +- Setting `QWEN_SANDBOX` environment variable. - Setting `tools.sandbox` in settings. -> ⚠️ **`--izn` does _not_ automatically enable a sandbox.** IZN mode only auto-approves tool calls; sandboxing must still be opted into via `--sandbox`, `HOPCODE_SANDBOX`, or `tools.sandbox`. In headless / non-interactive runs with `--izn` (or `--approval-mode=izn`) and no sandbox, the model can execute shell, write, and edit tools at the current process's privilege level — HopCode prints a warning to stderr in that case. Suppress with `HOPCODE_SUPPRESS_IZN_WARNING=1` once you've reviewed the trade-off. +> ⚠️ **`--izn` does _not_ automatically enable a sandbox.** IZN mode only auto-approves tool calls; sandboxing must still be opted into via `--sandbox`, `QWEN_SANDBOX`, or `tools.sandbox`. In headless / non-interactive runs with `--izn` (or `--approval-mode=izn`) and no sandbox, the model can execute shell, write, and edit tools at the current process's privilege level — HopCode prints a warning to stderr in that case. Suppress with `QWEN_CODE_SUPPRESS_IZN_WARNING=1` once you've reviewed the trade-off. By default, it uses a pre-built `hopcode-sandbox` Docker image. @@ -730,7 +730,7 @@ FROM hopcode-sandbox When `.hopcode/sandbox.Dockerfile` exists, you can use `BUILD_SANDBOX` environment variable when running HopCode to automatically build the custom sandbox image: ``` -BUILD_SANDBOX=1 hopcode -s +BUILD_SANDBOX=1 qwen -s ``` ## Usage Statistics diff --git a/docs/users/configuration/themes.md b/docs/users/configuration/themes.md index 76e716cfc03..60e2052d0ba 100644 --- a/docs/users/configuration/themes.md +++ b/docs/users/configuration/themes.md @@ -36,6 +36,45 @@ Selected themes are saved in HopCode's [configuration](../configuration/settings --- +## Auto Theme Detection + +When the theme is set to `"auto"` (or left unset), Qwen Code automatically detects whether your terminal uses a dark or light background and selects the matching Qwen theme (`Qwen Dark` or `Qwen Light`). + +### How to enable + +Set the theme to `"auto"` in `settings.json`: + +```json +{ + "ui": { + "theme": "auto" + } +} +``` + +Or select **Auto** in the `/theme` dialog. This is the default behavior when no theme is explicitly configured. + +### Detection methods + +Qwen Code uses multiple detection methods in a fallback chain. At startup (async path), the order is: + +| Priority | Method | Platform | How it works | +| -------- | ----------------------- | ---------- | ---------------------------------------------------------------------------------------------------- | +| 1 | `COLORFGBG` | All | Reads the `COLORFGBG` environment variable (set by terminals like iTerm2, rxvt, Konsole) | +| 2 | OSC 11 | All (TTY) | Sends an `ESC]11;?` query to the terminal and parses the background color from the response (~200ms) | +| 3 | macOS system appearance | macOS only | Runs `defaults read -g AppleInterfaceStyle` to check if macOS Dark Mode is active | +| 4 | Default | All | Falls back to dark theme if no method succeeds | + +The first method that returns a result wins. The detected value is cached for the session so subsequent theme resolutions (e.g. reselecting Auto in the `/theme` dialog) stay consistent. + +### When to use Auto + +- **Most users** — Auto works well if your terminal background matches your OS appearance or if your terminal sets `COLORFGBG` / supports OSC 11. +- **tmux / screen users** — OSC 11 may not pass through multiplexers. Detection falls back to `COLORFGBG` or macOS system appearance. If neither is available, the default dark theme is used. Set a specific theme if auto-detection gives the wrong result. +- **SSH sessions** — detection depends on the remote environment. If `COLORFGBG` is not forwarded and the remote terminal doesn't respond to OSC 11, the default dark theme is used. + +--- + ## Custom Color Themes HopCode allows you to create your own custom color themes by specifying them in your `settings.json` file. This gives you full control over the color palette used in the CLI. diff --git a/docs/users/features/commands.md b/docs/users/features/commands.md index 3c5755886f5..72a07ae89fa 100644 --- a/docs/users/features/commands.md +++ b/docs/users/features/commands.md @@ -1,4 +1,4 @@ -# Commands +# Commands This document details all commands supported by HopCode, helping you efficiently manage sessions, customize the interface, and control its behavior. @@ -31,15 +31,16 @@ These commands help you save, restore, and summarize work progress. Commands for adjusting interface appearance and work environment. -| Command | Description | Usage Examples | -| ------------ | ---------------------------------------- | ----------------------------- | -| `/clear` | Clear terminal screen content | `/clear` (shortcut: `Ctrl+L`) | -| `/context` | Show context window usage breakdown | `/context` | -| → `detail` | Show per-item context usage breakdown | `/context detail` | -| `/theme` | Change HopCode visual theme | `/theme` | -| `/vim` | Turn input area Vim editing mode on/off | `/vim` | -| `/directory` | Manage multi-directory support workspace | `/dir add ./src,./tests` | -| `/editor` | Open dialog to select supported editor | `/editor` | +| Command | Description | Usage Examples | +| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | +| `/clear` | Clear terminal screen content | `/clear` (shortcut: `Ctrl+L`) | +| `/context` | Show context window usage breakdown | `/context` | +| → `detail` | Show per-item context usage breakdown | `/context detail` | +| `/diff` | Open an interactive diff viewer showing uncommitted changes and per-turn diffs. Use ←/→ to switch between current git diff and individual conversation turns, ↑/↓ to browse files | `/diff` | +| `/theme` | Change HopCode visual theme | `/theme` | +| `/vim` | Turn input area Vim editing mode on/off | `/vim` | +| `/directory` | Manage multi-directory support workspace | `/dir add ./src,./tests` | +| `/editor` | Open dialog to select supported editor | `/editor` | ### 1.3 Language Settings @@ -209,7 +210,59 @@ this setting. > `general.showSessionRecap` to `false` to opt out of the auto-trigger > while keeping the manual command available. -### 1.8 Information, Settings, and Help +### 1.8 Diff Viewer (`/diff`) + +The `/diff` command opens an interactive diff viewer showing uncommitted changes and per-turn diffs. Use ←/→ to switch between the current git diff and individual conversation turns, ↑/↓ to browse files, and Enter to view inline diffs. + +**How it works:** + +In interactive mode, `/diff` opens a dialog with a **source picker** along the top: + +- **Current** — working tree vs HEAD (`git diff HEAD`). Shows all uncommitted changes including staged, unstaged, and untracked files. +- **T1, T2, T3, …** — per-turn diffs, one tab per model turn that modified files. Most recent turns appear first. Each tab shows a preview of the original prompt for context. + +The file list displays per-file stats (lines added/removed) with tags for special states (`new`, `deleted`, `untracked`, `binary`, `truncated`, `oversized`). Press Enter on a file to view its inline diff with syntax-highlighted hunks. + +Per-turn diffs require [file checkpointing](./checkpointing) to be enabled (on by default in interactive mode). When file checkpointing is off, only the "Current" source is available. + +**Keyboard shortcuts:** + +| Key | Action | +| --------- | ------------------------------------------- | +| `←` / `→` | Switch between sources (Current / T1 / T2…) | +| `↑` / `↓` | Navigate file list | +| `j` / `k` | Navigate file list (vim-style) | +| Enter | View inline diff for selected file | +| `←` / Esc | Return to file list from inline diff view | +| Esc | Close the dialog | + +**Example:** + +``` +┌ /diff · Turn 3 "refactor the auth middleware" ──── 3 files +45 -12 ┐ +│ │ +│ ◀ Current · T3 · T2 · T1 ▶ │ +│ │ +│ › src/utils/parser.ts +30 -8 │ +│ src/utils/parser.test.ts +12 -2 │ +│ README.md +3 -2 │ +│ │ +│ ←/→ source · ↑/↓ file · Enter view · Esc close │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +**Non-interactive mode:** + +In headless (`--prompt`) or non-interactive contexts, `/diff` prints a plain-text summary of the working tree vs HEAD. Per-turn navigation is not available. + +``` +3 files changed, +45 / -12 + +30 -8 src/utils/parser.ts + +12 -2 src/utils/parser.test.ts + +3 -2 README.md +``` + +### 1.9 Information, Settings, and Help Commands for obtaining information and performing system settings. @@ -225,7 +278,7 @@ Commands for obtaining information and performing system settings. | `/copy` | Copy last output content to clipboard | `/copy` | | `/quit` | Exit HopCode immediately | `/quit` or `/exit` | -### 1.9 Common Shortcuts +### 1.10 Common Shortcuts | Shortcut | Function | Note | | ------------------ | ----------------------- | ---------------------- | @@ -235,7 +288,7 @@ Commands for obtaining information and performing system settings. | `Ctrl/cmd+Z` | Undo input | Text editing | | `Ctrl/cmd+Shift+Z` | Redo input | Text editing | -### 1.10 Authentication Commands +### 1.11 Authentication Commands Use `/auth` inside a HopCode session to configure authentication. Use `/doctor` to inspect the current authentication and environment status. @@ -269,7 +322,7 @@ Exclamation commands allow you to execute system commands directly within HopCod | `!` | Execute command in sub-Shell | `!ls -la`, `!git status` | | Standalone `!` | Switch Shell mode, any input is executed directly as Shell command | `!`(enter) → Input command → `!`(exit) | -Environment Variables: Commands executed via `!` will set the `HOPCODE=1` environment variable. +Environment Variables: Commands executed via `!` will set the `HOPCODE_CODE=1` environment variable. ## 4. Custom Commands diff --git a/docs/users/features/worktree.md b/docs/users/features/worktree.md index 1157b9cfc01..af0818f6c66 100644 --- a/docs/users/features/worktree.md +++ b/docs/users/features/worktree.md @@ -30,7 +30,7 @@ qwen --resume --worktree=my-feature > > - `qwen --worktree=my-feature "say hi"` (always works — explicit slug via `=`) > - `qwen "say hi" --worktree` (positional first, flag at the end → auto slug) -> - `qwen --worktree --approval-mode yolo "say hi"` (any flag between them anchors the bare form) +> - `qwen --worktree --approval-mode izn "say hi"` (any flag between them anchors the bare form) > **Tip — `qwen --resume --worktree foo` (no session ID) shows an empty picker on first use.** The picker scopes to the chosen worktree's session storage; sessions started outside that worktree are not listed. To resume a session that was started inside `foo`, use `qwen --resume --worktree foo` directly — the CLI re-attaches to the existing `foo/` directory rather than re-creating it. diff --git a/packages/cli/src/acp-integration/session/Session.test.ts b/packages/cli/src/acp-integration/session/Session.test.ts index e1ecdc8cdfe..d3df193412e 100644 --- a/packages/cli/src/acp-integration/session/Session.test.ts +++ b/packages/cli/src/acp-integration/session/Session.test.ts @@ -1,6 +1,6 @@ /** * @license - * Copyright 2026 HopCode Team + * Copyright 2025 HopCode * SPDX-License-Identifier: Apache-2.0 */ @@ -237,7 +237,7 @@ describe('Session', () => { mockToolRegistry = { getTool: vi.fn(), - // #executePrompt → #buildInitialSystemReminders calls + // #executePrompt → #buildInitialSystemReminders calls // getToolRegistry().ensureTool(ToolNames.AGENT) on every session.prompt(), // so the default mock must provide it (#1151 / #3479). ensureTool: vi.fn().mockResolvedValue(true), @@ -1892,7 +1892,7 @@ describe('Session', () => { it('passes resolved paths to read_many_files tool', async () => { const tempDir = await fs.mkdtemp( - path.join(os.tmpdir(), 'hopcode-acp-session-'), + path.join(os.tmpdir(), 'qwen-acp-session-'), ); const fileName = 'README.md'; const filePath = path.join(tempDir, fileName); @@ -3054,12 +3054,12 @@ describe('Session', () => { describe('tool call concurrency', () => { it('runs multiple Agent tool calls concurrently (issue #2516)', async () => { // Each Agent call has two controllable async boundaries: - // - `called` — resolves *when* the test code reaches `execute()` - // - `result` — the promise `execute()` returns, resolved by the + // - `called` — resolves *when* the test code reaches `execute()` + // - `result` — the promise `execute()` returns, resolved by the // test after observing both `called` signals. // // Under the old sequential for-loop, call-b's `execute()` would - // only run after call-a's `execute()` promise resolved — so the + // only run after call-a's `execute()` promise resolved — so the // `await Promise.all([called-a, called-b])` below deadlocks and // the test hits vitest's default per-test timeout. Under the // concurrent implementation both `called` signals fire before @@ -3146,7 +3146,7 @@ describe('Session', () => { }); // Wait until both `execute()` bodies have been entered. Sequential - // behaviour deadlocks here → vitest times out the test → failure. + // behaviour deadlocks here → vitest times out the test → failure. await Promise.all([called['call-a'].promise, called['call-b'].promise]); // Resolve out of order to also verify that final part ordering @@ -3157,7 +3157,7 @@ describe('Session', () => { await promptPromise; // The second sendMessageStream invocation carries the tool responses - // that will be fed back to the model — assert their order matches + // that will be fed back to the model — assert their order matches // the original function-call order (A before B). expect(sendMessageStream).toHaveBeenCalledTimes(2); const followUp = sendMessageStream.mock.calls[1][1] as { diff --git a/packages/cli/src/acp-integration/session/Session.ts b/packages/cli/src/acp-integration/session/Session.ts index 5bc52c1b86a..394f45842a5 100644 --- a/packages/cli/src/acp-integration/session/Session.ts +++ b/packages/cli/src/acp-integration/session/Session.ts @@ -1596,7 +1596,6 @@ export class Session implements SessionContext { 'auto-edit': ApprovalMode.AUTO_EDIT, auto: ApprovalMode.AUTO, izn: ApprovalMode.IZN, - yolo: ApprovalMode.YOLO, }; const approvalMode = modeMap[params.modeId as ApprovalModeValue]; @@ -1933,7 +1932,7 @@ export class Session implements SessionContext { // // L3: Tool's intrinsic default permission // L4: PermissionManager rule override - // L5: ApprovalMode override (YOLO / AUTO_EDIT / PLAN) + // L5: ApprovalMode override (IZN / AUTO_EDIT / PLAN) // // AUTO_EDIT auto-approval is handled HERE, same as coreToolScheduler. // The VS Code extension is just a UI layer for requestPermission. @@ -2262,7 +2261,7 @@ export class Session implements SessionContext { } if (!didRequestPermission && !isTodoWriteTool) { - // Auto-approved (L3 allow / L4 PM allow / L5 YOLO|AUTO_EDIT) + // Auto-approved (L3 allow / L4 PM allow / L5 IZN|AUTO_EDIT) // → emit tool_call start notification const startParams: ToolCallStartParams = { callId, diff --git a/packages/cli/src/acp-integration/session/types.ts b/packages/cli/src/acp-integration/session/types.ts index dc2e81cbddf..005265d21ee 100644 --- a/packages/cli/src/acp-integration/session/types.ts +++ b/packages/cli/src/acp-integration/session/types.ts @@ -18,8 +18,7 @@ export type ApprovalModeValue = | 'default' | 'auto-edit' | 'auto' - | 'izn' - | 'yolo'; + | 'izn'; /** * Interface for sending session updates to the ACP client. diff --git a/packages/cli/src/config/config.ts b/packages/cli/src/config/config.ts index 9a9e0015420..040fe22f03c 100755 --- a/packages/cli/src/config/config.ts +++ b/packages/cli/src/config/config.ts @@ -196,7 +196,7 @@ export interface CliArgs { * - `--worktree=#123` / `--worktree https://github.com/o/r/pull/123` → PR ref * * Consumed by `setupStartupWorktree()` before `loadCliConfig()`. When set, - * the CLI chdirs into `/.qwen/worktrees//` and the entire + * the CLI chdirs into `/.hopcode/worktrees//` and the entire * session runs inside that worktree. */ worktree?: string | undefined; @@ -879,7 +879,7 @@ export async function parseArguments(): Promise { .option('worktree', { type: 'string', description: - 'Start the session inside a git worktree at /.qwen/worktrees//. ' + + 'Start the session inside a git worktree at /.hopcode/worktrees//. ' + 'Pass a slug (`--worktree my-feature`), a PR reference (`--worktree=#123` or a full ' + 'GitHub pull-request URL), or use bare `--worktree` to auto-generate a slug. ' + 'On exit, the WorktreeExitDialog prompts to keep or remove the worktree.', diff --git a/packages/cli/src/config/settings.test.ts b/packages/cli/src/config/settings.test.ts index fabb78f64a5..0cb6fcca6ce 100644 --- a/packages/cli/src/config/settings.test.ts +++ b/packages/cli/src/config/settings.test.ts @@ -2443,7 +2443,7 @@ describe('Settings Loading and Merging', () => { delete process.env['HOME_ENV_TOKEN']; }); - it('should prefer ~/.qwen/.env over ~/.env for the same key (first-write-wins) (#4466)', () => { + it('should prefer ~/.hopcode/.env over ~/.env for the same key (first-write-wins) (#4466)', () => { const qwenEnvPath = path.join(path.dirname(USER_SETTINGS_PATH), '.env'); const homeEnvPath = path.join( path.dirname(path.dirname(USER_SETTINGS_PATH)), @@ -2467,7 +2467,7 @@ describe('Settings Loading and Merging', () => { (p: fs.PathOrFileDescriptor) => { if (p === USER_SETTINGS_PATH) return JSON.stringify(userSettingsContent); - if (p === qwenEnvPath) return 'PRECEDENCE_TOKEN=from_qwen_dir'; + if (p === qwenEnvPath) return 'PRECEDENCE_TOKEN=from_hopcode_dir'; if (p === homeEnvPath) return 'PRECEDENCE_TOKEN=from_home_dir'; return '{}'; }, @@ -2482,7 +2482,7 @@ describe('Settings Loading and Merging', () => { { headers?: Record } >; expect(mcpServers?.['myServer']?.headers?.['Authorization']).toBe( - 'Bearer from_qwen_dir', + 'Bearer from_hopcode_dir', ); delete process.env['PRECEDENCE_TOKEN']; diff --git a/packages/cli/src/config/settings.ts b/packages/cli/src/config/settings.ts index d2d967948c5..7874a5d6175 100644 --- a/packages/cli/src/config/settings.ts +++ b/packages/cli/src/config/settings.ts @@ -526,7 +526,7 @@ export function createMinimalSettings(): LoadedSettings { * * User-level paths cover the home `.env` and the global Qwen config dir * `.env` (which respects `QWEN_HOME`). When `QWEN_HOME` redirects elsewhere, - * the legacy `/.qwen/.env` is also included so credentials users + * the legacy `/.hopcode/.env` is also included so credentials users * left there continue to load (and the trust check in untrusted workspaces * still allows reading it). */ @@ -548,7 +548,7 @@ function getUserLevelEnvPaths(): Set { * module-load `Storage.getGlobalHopCodeDir()` would otherwise snapshot legacy * paths for settings.json, OAuth tokens, installation_id, etc., while the * regular `.env` load (inside `loadSettings`) only runs later — splitting - * global state between `~/.qwen/...` and `/...`. + * global state between `~/.hopcode/...` and `/...`. * * Only home-scoped paths are consulted; project `.env` files are barred from * changing these vars by `PROJECT_ENV_HARDCODED_EXCLUSIONS`. @@ -570,7 +570,7 @@ export function preResolveHomeEnvOverrides(): void { // Storage.getGlobalHopCodeDir() shares the same homedir resolution as the // rest of the storage layer; when QWEN_HOME is unset it equals - // `/.qwen`, so path.dirname() recovers ``. + // `/.hopcode`, so path.dirname() recovers ``. const initialQwenHome = process.env['HOPCODE_HOME']; const initialQwenDir = Storage.getGlobalHopCodeDir(); const candidates: string[] = [path.join(initialQwenDir, '.env')]; @@ -752,7 +752,7 @@ function findEnvFile( const found = findHomeCandidate(); if (found) return found; } else { - // Workspace step: prefer .qwen/.env, then plain .env. + // Workspace step: prefer .hopcode/.env, then plain .env. const geminiEnvPath = path.join(currentDir, HOPCODE_DIR, '.env'); if (fs.existsSync(geminiEnvPath) && canUseEnvFile(geminiEnvPath)) { return geminiEnvPath; @@ -821,12 +821,12 @@ export function loadEnvironment(settings: Settings): void { const excludedVars = settings?.advanced?.excludedEnvVars || DEFAULT_EXCLUDED_ENV_VARS; const normalizedEnvFilePath = path.normalize(envFilePath); - // homeScoped: `.env` lives under the user's home Qwen dir or `~/.env` — + // homeScoped: `.env` lives under the user's home HopCode dir or `~/.env` — // only these may set QWEN_HOME / QWEN_RUNTIME_DIR. - // qwenScoped: any `.env` whose immediate parent is `.qwen` (including - // `/.qwen/.env`) — exempt from the user `excludedEnvVars` list. + // hopCodeScoped: any `.env` whose immediate parent is `.hopcode` (including + // `/.hopcode/.env`) — exempt from the user `excludedEnvVars` list. const isHomeScopedEnvFile = userLevelPaths.has(normalizedEnvFilePath); - const isQwenScopedEnvFile = + const isHopCodeScopedEnvFile = isHomeScopedEnvFile || path.basename(path.dirname(normalizedEnvFilePath)) === HOPCODE_DIR; @@ -838,7 +838,7 @@ export function loadEnvironment(settings: Settings): void { ) { continue; } - if (!isQwenScopedEnvFile && excludedVars.includes(key)) { + if (!isHopCodeScopedEnvFile && excludedVars.includes(key)) { continue; } @@ -871,7 +871,7 @@ export const CORRUPTED_SUFFIX = '.corrupted'; /** * Load and merge settings from all scopes: - * System Defaults → User (~/.qwen/settings.json) → Workspace → System. + * System Defaults → User (~/.hopcode/settings.json) → Workspace → System. */ export function loadSettings( workspaceDir: string = process.cwd(), diff --git a/packages/cli/src/config/settingsSchema.ts b/packages/cli/src/config/settingsSchema.ts index 3d2cad91728..41eaea120e7 100644 --- a/packages/cli/src/config/settingsSchema.ts +++ b/packages/cli/src/config/settingsSchema.ts @@ -308,7 +308,7 @@ const SETTINGS_SCHEMA = { requiresRestart: true, default: undefined as string | undefined, description: - 'Custom directory for approved Plan Mode files. Relative paths are resolved from the project root, and the resolved path must stay within the project root. Defaults to ~/.qwen/plans.', + 'Custom directory for approved Plan Mode files. Relative paths are resolved from the project root, and the resolved path must stay within the project root. Defaults to ~/.hopcode/plans.', showInDialog: false, }, @@ -407,7 +407,7 @@ const SETTINGS_SCHEMA = { requiresRestart: true, default: 30, description: - 'Number of days to retain ~/.qwen/file-history/ session backups used by /rewind. Backups older than this are removed by a background housekeeping pass that runs at most once per day. Set to 0 for minimum retention (~1 hour) — protects sessions touched in the last hour, plus the currently active session. Other persistent caches will honor the same setting in the future.', + 'Number of days to retain ~/.hopcode/file-history/ session backups used by /rewind. Backups older than this are removed by a background housekeeping pass that runs at most once per day. Set to 0 for minimum retention (~1 hour) — protects sessions touched in the last hour, plus the currently active session. Other persistent caches will honor the same setting in the future.', showInDialog: true, }, gitCoAuthor: { @@ -491,7 +491,7 @@ const SETTINGS_SCHEMA = { description: 'The language for the user interface. Use "auto" to detect from system settings. ' + 'You can also use custom language codes (e.g., "es", "fr") by placing JS language files ' + - 'in ~/.qwen/locales/ (e.g., ~/.qwen/locales/es.js).', + 'in ~/.hopcode/locales/ (e.g., ~/.hopcode/locales/es.js).', showInDialog: true, options: [] as readonly SettingEnumOption[], }, @@ -1763,8 +1763,7 @@ const SETTINGS_SCHEMA = { { value: ApprovalMode.DEFAULT, label: 'Default' }, { value: ApprovalMode.AUTO_EDIT, label: 'Auto Edit' }, { value: ApprovalMode.AUTO, label: 'Auto' }, - { value: ApprovalMode.IZN, label: 'IZN' }, - { value: ApprovalMode.YOLO, label: 'YOLO' }, + { value: ApprovalMode.IZN, label: 'Izn' }, ], }, autoAccept: { @@ -2066,7 +2065,7 @@ const SETTINGS_SCHEMA = { default: undefined as string | undefined, description: 'Custom directory for runtime output (temp files, debug logs, session data, todos, etc.). ' + - 'Config files remain at ~/.qwen (or QWEN_HOME if set). Env var QWEN_RUNTIME_DIR takes priority.', + 'Config files remain at ~/.hopcode (or QWEN_HOME if set). Env var QWEN_RUNTIME_DIR takes priority.', showInDialog: false, }, }, @@ -2113,7 +2112,7 @@ const SETTINGS_SCHEMA = { requiresRestart: true, default: undefined as string | undefined, description: - 'Custom base directory for Arena worktrees. Defaults to ~/.qwen/arena.', + 'Custom base directory for Arena worktrees. Defaults to ~/.hopcode/arena.', showInDialog: false, }, preserveArtifacts: { diff --git a/packages/cli/src/config/trustedFolders.test.ts b/packages/cli/src/config/trustedFolders.test.ts index 190df706112..aa94dced080 100644 --- a/packages/cli/src/config/trustedFolders.test.ts +++ b/packages/cli/src/config/trustedFolders.test.ts @@ -5,7 +5,11 @@ */ import * as osActual from 'node:os'; -import { FatalConfigError, ideContextStore } from '@hoptrendy/hopcode-core'; +import { + atomicWriteFileSync, + FatalConfigError, + ideContextStore, +} from '@hoptrendy/hopcode-core'; import { describe, it, @@ -50,17 +54,24 @@ vi.mock('strip-json-comments', () => ({ default: vi.fn((content) => content), })); +vi.mock('@hoptrendy/hopcode-core', async (importOriginal) => { + const actual = + await importOriginal(); + return { + ...actual, + atomicWriteFileSync: vi.fn(), + }; +}); + describe('Trusted Folders Loading', () => { let mockFsExistsSync: Mocked; let mockStripJsonComments: Mocked; - let mockFsWriteFileSync: Mocked; beforeEach(() => { resetTrustedFoldersForTesting(); vi.resetAllMocks(); mockFsExistsSync = vi.mocked(fs.existsSync); mockStripJsonComments = vi.mocked(stripJsonComments); - mockFsWriteFileSync = vi.mocked(fs.writeFileSync); vi.mocked(osActual.homedir).mockReturnValue('/mock/home/user'); (mockStripJsonComments as unknown as Mock).mockImplementation( (jsonString: string) => jsonString, @@ -190,10 +201,18 @@ describe('Trusted Folders Loading', () => { expect(loadedFolders.user.config['/new/path']).toBe( TrustLevel.TRUST_FOLDER, ); - expect(mockFsWriteFileSync).toHaveBeenCalledWith( + expect(atomicWriteFileSync).toHaveBeenCalledWith( getTrustedFoldersPath(), JSON.stringify({ '/new/path': TrustLevel.TRUST_FOLDER }, null, 2), - { encoding: 'utf-8', mode: 0o600 }, + // noFollow:true mirrors the credential write sites' security + // posture — a pre-placed symlink at the config path could leak + // the trusted-folder list or leave the user's real config stale. + { + encoding: 'utf-8', + mode: 0o600, + forceMode: true, + noFollow: true, + }, ); }); }); diff --git a/packages/cli/src/config/trustedFolders.ts b/packages/cli/src/config/trustedFolders.ts index f1fd0127170..71562dd1b04 100644 --- a/packages/cli/src/config/trustedFolders.ts +++ b/packages/cli/src/config/trustedFolders.ts @@ -7,6 +7,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import { + atomicWriteFileSync, FatalConfigError, getErrorMessage, isWithinRoot, @@ -179,10 +180,16 @@ export function saveTrustedFolders( fs.mkdirSync(dirPath, { recursive: true }); } - fs.writeFileSync( + atomicWriteFileSync( trustedFoldersFile.path, JSON.stringify(trustedFoldersFile.config, null, 2), - { encoding: 'utf-8', mode: 0o600 }, + // noFollow: refuse to follow any pre-placed symlink at the + // config path — a redirected write could either leak the + // trusted-folder list to an attacker target or leave the user's + // real config silently stale. Matches the credential write + // sites' security posture (sharedTokenManager, oauth-token-storage, + // file-token-storage all use noFollow:true). + { encoding: 'utf-8', mode: 0o600, forceMode: true, noFollow: true }, ); } catch (error) { writeStderrLine('Error saving trusted folders file.'); diff --git a/packages/cli/src/gemini.tsx b/packages/cli/src/gemini.tsx index cfba94f4842..d7eac33ee8c 100644 --- a/packages/cli/src/gemini.tsx +++ b/packages/cli/src/gemini.tsx @@ -1028,15 +1028,15 @@ export async function main() { } } - // Headless + YOLO without a sandbox lets the model auto-approve and + // Headless + IZN without a sandbox lets the model auto-approve and // execute shell / write / edit tools at the current process's // privilege level. Emit a one-line stderr warning so unattended runs // have at least an observable signal. Interactive runs are excluded // because the user is at the keyboard and the TUI shows approval // state directly. See issue #4103. if (!config.isInteractive()) { - const yoloWarning = getHeadlessIznSafetyWarning(config); - if (yoloWarning) writeStderrLine(yoloWarning); + const iznWarning = getHeadlessIznSafetyWarning(config); + if (iznWarning) writeStderrLine(iznWarning); } // For non-stream-json mode, initialize config here. Stream-json defers diff --git a/packages/cli/src/nonInteractive/types.ts b/packages/cli/src/nonInteractive/types.ts index 8e3c2b13ba0..1e3529aed86 100644 --- a/packages/cli/src/nonInteractive/types.ts +++ b/packages/cli/src/nonInteractive/types.ts @@ -269,13 +269,7 @@ export interface CLIPartialAssistantMessage { parent_tool_use_id: string | null; } -export type PermissionMode = - | 'default' - | 'plan' - | 'auto-edit' - | 'auto' - | 'izn' - | 'yolo'; +export type PermissionMode = 'default' | 'plan' | 'auto-edit' | 'auto' | 'izn'; /** * Permission suggestion for tool use requests diff --git a/packages/cli/src/serve/fs/paths.test.ts b/packages/cli/src/serve/fs/paths.test.ts index 061390221fc..2de845ace8d 100644 --- a/packages/cli/src/serve/fs/paths.test.ts +++ b/packages/cli/src/serve/fs/paths.test.ts @@ -170,7 +170,7 @@ describe('hasSuspiciousPathPattern', () => { it('accepts ordinary POSIX paths', () => { expect(hasSuspiciousPathPattern('src/index.ts')).toBe(false); expect(hasSuspiciousPathPattern('packages/cli/package.json')).toBe(false); - expect(hasSuspiciousPathPattern('.qwenignore')).toBe(false); + expect(hasSuspiciousPathPattern('.hopcodeignore')).toBe(false); expect(hasSuspiciousPathPattern('a/b/c/d/e/f.txt')).toBe(false); }); }); diff --git a/packages/cli/src/serve/fs/policy.ts b/packages/cli/src/serve/fs/policy.ts index fa2223673e8..b3275c5e865 100644 --- a/packages/cli/src/serve/fs/policy.ts +++ b/packages/cli/src/serve/fs/policy.ts @@ -64,7 +64,7 @@ export interface IgnoreVerdict { * Check whether `absolute` is matched by the workspace's ignore * rules. The check is computed against the workspace-relative * form of the path, matching the convention of `.gitignore` / - * `.qwenignore` patterns. + * `.hopcodeignore` patterns. * * Returns `{ ignored: false }` when: * - the path equals `boundWorkspace` (the workspace root itself diff --git a/packages/cli/src/serve/fs/workspaceFileSystem.ts b/packages/cli/src/serve/fs/workspaceFileSystem.ts index 88bd76fcd0d..f261ea2bfcb 100644 --- a/packages/cli/src/serve/fs/workspaceFileSystem.ts +++ b/packages/cli/src/serve/fs/workspaceFileSystem.ts @@ -65,7 +65,7 @@ export interface FsStat { export interface FsEntry { name: string; kind: 'file' | 'directory' | 'symlink' | 'other'; - /** True iff the entry matched a `.gitignore`/`.qwenignore` rule. */ + /** True iff the entry matched a `.gitignore`/`.hopcodeignore` rule. */ ignored: boolean; } @@ -1050,7 +1050,7 @@ class WorkspaceFileSystemImpl implements WorkspaceFileSystem { }); // Symmetric with `readText` / `writeText` — operators // monitoring `fs.access` need to see when an edit landed on - // a `.gitignore`d / `.qwenignore`d file (build artifacts, + // a `.gitignore`d / `.hopcodeignore`d file (build artifacts, // logs, etc.) rather than only learning about // matchedIgnore for reads and writes. const editVerdict = shouldIgnore( diff --git a/packages/cli/src/serve/server.test.ts b/packages/cli/src/serve/server.test.ts index 29d38608d6e..b25a86deb84 100644 --- a/packages/cli/src/serve/server.test.ts +++ b/packages/cli/src/serve/server.test.ts @@ -2290,7 +2290,6 @@ describe('createServeApp', () => { 'auto-edit', 'auto', 'izn', - 'yolo', ]); const unknown = await auth( request(app).post('/session/session-A/approval-mode'), diff --git a/packages/cli/src/services/insight/generators/DataProcessor.test.ts b/packages/cli/src/services/insight/generators/DataProcessor.test.ts index 0732be48551..d55f553ce5b 100644 --- a/packages/cli/src/services/insight/generators/DataProcessor.test.ts +++ b/packages/cli/src/services/insight/generators/DataProcessor.test.ts @@ -1,6 +1,6 @@ /** * @license - * Copyright 2026 HopCode Team Code + * Copyright 2025 HopCode * SPDX-License-Identifier: Apache-2.0 */ diff --git a/packages/cli/src/services/insight/generators/DataProcessor.ts b/packages/cli/src/services/insight/generators/DataProcessor.ts index a50989eba8a..8c89db32b66 100644 --- a/packages/cli/src/services/insight/generators/DataProcessor.ts +++ b/packages/cli/src/services/insight/generators/DataProcessor.ts @@ -1,6 +1,6 @@ /** * @license - * Copyright 2026 HopCode Team Code + * Copyright 2025 HopCode * SPDX-License-Identifier: Apache-2.0 */ diff --git a/packages/cli/src/services/tips/tipHistory.ts b/packages/cli/src/services/tips/tipHistory.ts index 7d9617d927c..fabac708421 100644 --- a/packages/cli/src/services/tips/tipHistory.ts +++ b/packages/cli/src/services/tips/tipHistory.ts @@ -10,7 +10,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; -import { Storage } from '@hoptrendy/hopcode-core'; +import { atomicWriteFileSync, Storage } from '@hoptrendy/hopcode-core'; interface TipHistoryEntry { totalShown: number; @@ -114,8 +114,10 @@ export class TipHistory { if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } - fs.writeFileSync(this.filePath, JSON.stringify(this.data, null, 2), { + atomicWriteFileSync(this.filePath, JSON.stringify(this.data, null, 2), { mode: 0o600, + forceMode: true, + noFollow: true, }); } catch { // Silently ignore write errors — tips are non-critical diff --git a/packages/cli/src/startup/worktreeStartup.test.ts b/packages/cli/src/startup/worktreeStartup.test.ts index 93cf02748e3..48b8ffc4052 100644 --- a/packages/cli/src/startup/worktreeStartup.test.ts +++ b/packages/cli/src/startup/worktreeStartup.test.ts @@ -143,7 +143,7 @@ describe('setupStartupWorktree', () => { // No worktree directory was created. const exists = await fs - .stat(path.join(tempRepo, '.qwen', 'worktrees')) + .stat(path.join(tempRepo, '.hopcode', 'worktrees')) .then(() => true) .catch(() => false); expect(exists).toBe(false); @@ -168,7 +168,7 @@ describe('setupStartupWorktree', () => { // No worktree directory was created — fail-close means no side effect. const exists = await fs - .stat(path.join(tempRepo, '.qwen', 'worktrees')) + .stat(path.join(tempRepo, '.hopcode', 'worktrees')) .then(() => true) .catch(() => false); expect(exists).toBe(false); @@ -336,11 +336,11 @@ describe('setupStartupWorktree', () => { expect(survived).toBe('oops'); }); - it('refuses nested worktree creation from inside .qwen/worktrees/', async () => { + it('refuses nested worktree creation from inside .hopcode/worktrees/', async () => { tempRepo = await makeTempRepo(); // Pre-create a fake worktree path and chdir into it. We don't need a // real git worktree — the guard fires on path shape, not git state. - const nestedPath = path.join(tempRepo, '.qwen', 'worktrees', 'outer'); + const nestedPath = path.join(tempRepo, '.hopcode', 'worktrees', 'outer'); await fs.mkdir(nestedPath, { recursive: true }); process.chdir(nestedPath); @@ -360,7 +360,7 @@ describe('buildStartupWorktreeNotice', () => { // signature lets us keep the fixture minimal so adding new // StartupWorktreeContext fields doesn't churn this file. const baseContext = { - worktreePath: '/repo/.qwen/worktrees/foo', + worktreePath: '/repo/.hopcode/worktrees/foo', slug: 'foo', branch: 'worktree-foo', wasReattached: false, @@ -371,7 +371,7 @@ describe('buildStartupWorktreeNotice', () => { expect(notice).toContain('[Startup]'); expect(notice).toContain('Active worktree'); expect(notice).toContain('"foo"'); - expect(notice).toContain('/repo/.qwen/worktrees/foo'); + expect(notice).toContain('/repo/.hopcode/worktrees/foo'); expect(notice).toContain('worktree-foo'); expect(notice).not.toContain('Re-attached'); expect(notice).not.toContain('overrode'); diff --git a/packages/cli/src/startup/worktreeStartup.ts b/packages/cli/src/startup/worktreeStartup.ts index 040040867f0..b129955f2db 100644 --- a/packages/cli/src/startup/worktreeStartup.ts +++ b/packages/cli/src/startup/worktreeStartup.ts @@ -126,9 +126,9 @@ export async function setupStartupWorktree( } // Refuse nested creation: launching with --worktree from inside an existing - // worktree creates `/.qwen/worktrees//`, which is rarely + // worktree creates `/.hopcode/worktrees//`, which is rarely // what the user wants and corrupts ownership tracking. - if (/[\\/]\.qwen[\\/]worktrees[\\/]/.test(launchCwd)) { + if (/[\\/]\.hopcode[\\/]worktrees[\\/]/.test(launchCwd)) { return { ok: false, error: `--worktree: cannot start a new worktree from inside another worktree (cwd: ${launchCwd}). Run from the main checkout.`, diff --git a/packages/cli/src/ui/commands/hooksCommand.ts b/packages/cli/src/ui/commands/hooksCommand.ts index 5ec042abd06..1e2c677764c 100644 --- a/packages/cli/src/ui/commands/hooksCommand.ts +++ b/packages/cli/src/ui/commands/hooksCommand.ts @@ -210,10 +210,6 @@ export const hooksCommand: SlashCommand = { } const result = await listCommand.action?.(context, args); - return (result ?? { - type: 'message', - messageType: 'info', - content: '', - }) as SlashCommandActionReturn; + return result ?? { type: 'message', messageType: 'info', content: '' }; }, }; diff --git a/packages/cli/src/ui/components/Footer.tsx b/packages/cli/src/ui/components/Footer.tsx index 1105dce9555..d3b5e9f9a4f 100644 --- a/packages/cli/src/ui/components/Footer.tsx +++ b/packages/cli/src/ui/components/Footer.tsx @@ -1,6 +1,6 @@ /** * @license - * Copyright 2026 HopCode Team + * Copyright 2025 HopCode * SPDX-License-Identifier: Apache-2.0 */ @@ -16,11 +16,13 @@ import { MCPHealthPill } from './mcp/MCPHealthPill.js'; import { isNarrowWidth } from '../utils/isNarrowWidth.js'; import { useStatusLine } from '../hooks/useStatusLine.js'; +import { useConfigInitMessage } from '../hooks/useConfigInitMessage.js'; import { useUIState } from '../contexts/UIStateContext.js'; import { useConfig } from '../contexts/ConfigContext.js'; import { useSettings } from '../contexts/SettingsContext.js'; import { useVimMode } from '../contexts/VimModeContext.js'; import { ApprovalMode } from '@hoptrendy/hopcode-core'; +import { GeminiSpinner } from './GeminiRespondingSpinner.js'; import { GoalPill, useFooterGoalState } from './GoalPill.js'; import { t } from '../../i18n/index.js'; @@ -35,6 +37,7 @@ export const Footer: React.FC = () => { respectUserColors, hideContextIndicator, } = useStatusLine(); + const configInitMessage = useConfigInitMessage(uiState.isConfigInitialized); const { promptTokenCount, showAutoAcceptIndicator } = { promptTokenCount: uiState.sessionStats.lastPromptTokenCount, @@ -60,19 +63,20 @@ export const Footer: React.FC = () => { const contextWindowSize = config.getContentGeneratorConfig()?.contextWindowSize; - // Determine if config is still initializing - const isInitializing = uiState.isConfigInitialized === false; - // Hide "? for shortcuts" when a custom status line is active (it already // occupies the footer, so the hint is redundant). Matches upstream behavior. - const suppressHint = isInitializing || statusLineLines.length > 0; + const suppressHint = statusLineLines.length > 0; - // Left bottom row: high-priority messages > approval mode > hint. - const leftBottomContent = isInitializing ? ( - - {t('Initializing...')} - - ) : uiState.ctrlCPressedOnce ? ( + // MCP init progress lives in this row (not a standalone component above the + // input) so the live area's height is constant in the default case, avoiding + // the residual-blank-line artifact left behind when a separate block unmounts. + // When a custom status line is active, the row shrinks by 1 on transition to + // ready — a one-time, small regression preferred over hiding init progress. + // + // `configInitMessage` is placed ahead of `showAutoAcceptIndicator` so users + // launched with IZN / auto-accept-edits still see the ~1s startup progress; + // the approval-mode indicator takes over as soon as init finishes. + const leftBottomContent = uiState.ctrlCPressedOnce ? ( {t('Press Ctrl+C again to exit.')} ) : uiState.ctrlDPressedOnce ? ( {t('Press Ctrl+D again to exit.')} @@ -86,6 +90,10 @@ export const Footer: React.FC = () => { -- INSERT -- ) : uiState.shellModeActive ? ( + ) : configInitMessage ? ( + + {configInitMessage} + ) : showAutoAcceptIndicator !== undefined && showAutoAcceptIndicator !== ApprovalMode.DEFAULT ? ( diff --git a/packages/cli/src/ui/components/MainContent.test.tsx b/packages/cli/src/ui/components/MainContent.test.tsx index 64520e92a62..0906a834b60 100644 --- a/packages/cli/src/ui/components/MainContent.test.tsx +++ b/packages/cli/src/ui/components/MainContent.test.tsx @@ -318,7 +318,7 @@ describe('', () => { ].join('\n'), }, ], - pendingGeminiHistoryItems: [ + pendingHistoryItems: [ { type: 'gemini_content', text: [ diff --git a/packages/cli/src/ui/components/MainContent.tsx b/packages/cli/src/ui/components/MainContent.tsx index 43f529a649c..1764e810984 100644 --- a/packages/cli/src/ui/components/MainContent.tsx +++ b/packages/cli/src/ui/components/MainContent.tsx @@ -108,7 +108,7 @@ export const MainContent = () => { const uiActions = useUIActions(); const { compactMode } = useCompactMode(); const { - pendingGeminiHistoryItems, + pendingHistoryItems, terminalWidth, mainAreaWidth, staticAreaMaxItemHeight, @@ -330,7 +330,7 @@ export const MainContent = () => { const pendingHistoryItemsWithSourceCopyOffsets = useMemo(() => { let runningOffsets = cloneSourceCopyOffsets(pendingStartSourceCopyOffsets); - return pendingGeminiHistoryItems.map((item) => { + return pendingHistoryItems.map((item) => { if (item.type === 'gemini') { runningOffsets = createEmptySourceCopyOffsets(); const offsets = cloneSourceCopyOffsets(runningOffsets); @@ -350,7 +350,7 @@ export const MainContent = () => { return { item, sourceCopyIndexOffsets: undefined }; }); - }, [pendingGeminiHistoryItems, pendingStartSourceCopyOffsets]); + }, [pendingHistoryItems, pendingStartSourceCopyOffsets]); // Progressive Static replay (issue #3899). `replayCount` is the number of // history items currently passed to . It catches up to @@ -423,12 +423,9 @@ export const MainContent = () => { const allVirtualItems = useMemo( (): HistoryItem[] => [ ...mergedHistory, - ...pendingGeminiHistoryItems.map((item, i) => ({ - ...item, - id: -(i + 1), - })), + ...pendingHistoryItems.map((item, i) => ({ ...item, id: -(i + 1) })), ], - [mergedHistory, pendingGeminiHistoryItems], + [mergedHistory, pendingHistoryItems], ); // Source-copy index offsets propagation. The legacy path threads diff --git a/packages/cli/src/ui/components/SettingsCorruptedDialog.test.tsx b/packages/cli/src/ui/components/SettingsCorruptedDialog.test.tsx index 4795885590b..db5acbe1915 100644 --- a/packages/cli/src/ui/components/SettingsCorruptedDialog.test.tsx +++ b/packages/cli/src/ui/components/SettingsCorruptedDialog.test.tsx @@ -49,7 +49,7 @@ enum TerminalKeys { } describe('SettingsCorruptedDialog', () => { - const mockCorruptedPath = '/home/user/.qwen/settings.json.corrupted'; + const mockCorruptedPath = '/home/user/.hopcode/settings.json.corrupted'; const mockOnExit = vi.fn(); const mockOnContinue = vi.fn(); diff --git a/packages/cli/src/ui/components/SettingsDialog.test.tsx b/packages/cli/src/ui/components/SettingsDialog.test.tsx index 66661fd580e..b03e8885354 100644 --- a/packages/cli/src/ui/components/SettingsDialog.test.tsx +++ b/packages/cli/src/ui/components/SettingsDialog.test.tsx @@ -1,4 +1,4 @@ -/** +/** * @license * Copyright 2025 HopCode Team * SPDX-License-Identifier: Apache-2.0 @@ -561,10 +561,10 @@ describe('SettingsDialog', () => { it('loops back when reaching the end of an enum', async () => { vi.mocked(saveModifiedSettings).mockClear(); - // Use Tool Approval Mode set to YOLO (last value) to test looping back to first + // Use Tool Approval Mode set to IZN (last value) to test looping back to first const settings = createMockSettings({ tools: { - approvalMode: 'yolo', // Last enum value + approvalMode: 'izn', // Last enum value }, }); const onSelect = vi.fn(); @@ -595,7 +595,7 @@ describe('SettingsDialog', () => { new Set(['tools.approvalMode']), expect.objectContaining({ tools: expect.objectContaining({ - approvalMode: 'plan', // First enum value after YOLO (wrap-around) + approvalMode: 'plan', // First enum value after IZN (wrap-around) }), }), expect.any(LoadedSettings), diff --git a/packages/cli/src/ui/components/hooks/HandlerListBody.test.tsx b/packages/cli/src/ui/components/hooks/HandlerListBody.test.tsx index a156de37b24..69a12271c92 100644 --- a/packages/cli/src/ui/components/hooks/HandlerListBody.test.tsx +++ b/packages/cli/src/ui/components/hooks/HandlerListBody.test.tsx @@ -1,6 +1,6 @@ /** * @license - * Copyright 2026 Qwen Team + * Copyright 2026 HopCode Team * SPDX-License-Identifier: Apache-2.0 */ diff --git a/packages/cli/src/ui/components/hooks/HandlerListBody.tsx b/packages/cli/src/ui/components/hooks/HandlerListBody.tsx index a9212022869..7a25a0452e9 100644 --- a/packages/cli/src/ui/components/hooks/HandlerListBody.tsx +++ b/packages/cli/src/ui/components/hooks/HandlerListBody.tsx @@ -1,6 +1,6 @@ /** * @license - * Copyright 2026 Qwen Team + * Copyright 2026 HopCode Team * SPDX-License-Identifier: Apache-2.0 */ diff --git a/packages/cli/src/ui/components/hooks/HookMatcherDetailStep.test.tsx b/packages/cli/src/ui/components/hooks/HookMatcherDetailStep.test.tsx index 2f0c982b000..758910f72ef 100644 --- a/packages/cli/src/ui/components/hooks/HookMatcherDetailStep.test.tsx +++ b/packages/cli/src/ui/components/hooks/HookMatcherDetailStep.test.tsx @@ -1,6 +1,6 @@ /** * @license - * Copyright 2026 Qwen Team + * Copyright 2026 HopCode Team * SPDX-License-Identifier: Apache-2.0 */ diff --git a/packages/cli/src/ui/components/hooks/HooksManagementDialog.test.tsx b/packages/cli/src/ui/components/hooks/HooksManagementDialog.test.tsx index b7b14b08e5c..19e8a0f4b05 100644 --- a/packages/cli/src/ui/components/hooks/HooksManagementDialog.test.tsx +++ b/packages/cli/src/ui/components/hooks/HooksManagementDialog.test.tsx @@ -5,7 +5,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { cleanup , renderWithProviders } from '../../../test-utils/render.js'; +import { cleanup, renderWithProviders } from '../../../test-utils/render.js'; import { HooksManagementDialog } from './HooksManagementDialog.js'; import { useKeypress } from '../../hooks/useKeypress.js'; import { useConfig } from '../../contexts/ConfigContext.js'; @@ -74,8 +74,6 @@ vi.mock('../../hooks/useTerminalSize.js', () => ({ vi.mock('../../contexts/ConfigContext.js', async (importOriginal) => { const actual = await importOriginal(); - // Return a stable reference so `fetchHooksData` (which depends on `config`) - // is not recreated on every render — preventing an infinite effect loop. const stableConfig = { getExtensions: vi.fn(() => []), getDisableAllHooks: vi.fn(() => false), @@ -161,9 +159,6 @@ function pressKey(name: string, sequence = ''): void { latestHandler!(createKey(name, sequence)); } -// Generous timeout for async navigation assertions — CI runners can be under -// heavy load (integration tests running in parallel) causing React re-renders -// to be delayed beyond the 1 s default. const NAV_TIMEOUT = { timeout: 10_000 }; describe('HooksManagementDialog', () => { diff --git a/packages/cli/src/ui/components/hooks/matcherGrouping.test.ts b/packages/cli/src/ui/components/hooks/matcherGrouping.test.ts index 7e73cff20f5..ffc0e190ecf 100644 --- a/packages/cli/src/ui/components/hooks/matcherGrouping.test.ts +++ b/packages/cli/src/ui/components/hooks/matcherGrouping.test.ts @@ -1,6 +1,6 @@ /** * @license - * Copyright 2026 Qwen Team + * Copyright 2026 HopCode Team * SPDX-License-Identifier: Apache-2.0 */ diff --git a/packages/cli/src/ui/components/hooks/sourceLabels.test.ts b/packages/cli/src/ui/components/hooks/sourceLabels.test.ts index b7f4ef96606..f1ef8812bb9 100644 --- a/packages/cli/src/ui/components/hooks/sourceLabels.test.ts +++ b/packages/cli/src/ui/components/hooks/sourceLabels.test.ts @@ -1,6 +1,6 @@ /** * @license - * Copyright 2026 Qwen Team + * Copyright 2026 HopCode Team * SPDX-License-Identifier: Apache-2.0 */ diff --git a/packages/cli/src/ui/components/hooks/sourceLabels.ts b/packages/cli/src/ui/components/hooks/sourceLabels.ts index 4a8e52b1feb..977c005bb79 100644 --- a/packages/cli/src/ui/components/hooks/sourceLabels.ts +++ b/packages/cli/src/ui/components/hooks/sourceLabels.ts @@ -1,6 +1,6 @@ /** * @license - * Copyright 2026 Qwen Team + * Copyright 2026 HopCode Team * SPDX-License-Identifier: Apache-2.0 */ diff --git a/packages/cli/src/ui/components/shared/VirtualizedList.tsx b/packages/cli/src/ui/components/shared/VirtualizedList.tsx index c5701c6072d..f5efb487e25 100644 --- a/packages/cli/src/ui/components/shared/VirtualizedList.tsx +++ b/packages/cli/src/ui/components/shared/VirtualizedList.tsx @@ -1,6 +1,6 @@ /** * @license - * Copyright 2025 Google LLC + * Copyright 2025 HopCode Team * SPDX-License-Identifier: Apache-2.0 */ diff --git a/packages/cli/src/ui/hooks/useAutoAcceptIndicator.test.ts b/packages/cli/src/ui/hooks/useAutoAcceptIndicator.test.ts index 3672acc86bc..5edaf0fdab7 100644 --- a/packages/cli/src/ui/hooks/useAutoAcceptIndicator.test.ts +++ b/packages/cli/src/ui/hooks/useAutoAcceptIndicator.test.ts @@ -213,17 +213,6 @@ describe('useAutoAcceptIndicator', () => { ); expect(result.current).toBe(ApprovalMode.IZN); - act(() => { - capturedUseKeypressHandler({ - name: 'tab', - shift: true, - } as Key); - }); - expect(mockConfigInstance.setApprovalMode).toHaveBeenCalledWith( - ApprovalMode.YOLO, - ); - expect(result.current).toBe(ApprovalMode.YOLO); - act(() => { capturedUseKeypressHandler({ name: 'tab', @@ -418,8 +407,8 @@ describe('useAutoAcceptIndicator', () => { ); }); - it('should cycle from YOLO to PLAN when Shift+Tab is pressed', () => { - mockConfigInstance.getApprovalMode.mockReturnValue(ApprovalMode.YOLO); + it('should cycle from IZN to PLAN when Shift+Tab is pressed', () => { + mockConfigInstance.getApprovalMode.mockReturnValue(ApprovalMode.IZN); const mockAddItem = vi.fn(); renderHook(() => useAutoAcceptIndicator({ diff --git a/packages/cli/src/utils/housekeeping/cleanup.test.ts b/packages/cli/src/utils/housekeeping/cleanup.test.ts index c3c52cd5027..816c8adf06e 100644 --- a/packages/cli/src/utils/housekeeping/cleanup.test.ts +++ b/packages/cli/src/utils/housekeeping/cleanup.test.ts @@ -1,6 +1,6 @@ /** * @license - * Copyright 2025 Google LLC + * Copyright 2025 HopCode Team * SPDX-License-Identifier: Apache-2.0 */ diff --git a/packages/cli/src/utils/housekeeping/cleanup.ts b/packages/cli/src/utils/housekeeping/cleanup.ts index 1f76c96ea6f..fec505ac25e 100644 --- a/packages/cli/src/utils/housekeeping/cleanup.ts +++ b/packages/cli/src/utils/housekeeping/cleanup.ts @@ -1,6 +1,6 @@ /** * @license - * Copyright 2025 Google LLC + * Copyright 2025 HopCode Team * SPDX-License-Identifier: Apache-2.0 */ diff --git a/packages/cli/src/utils/housekeeping/scheduler.test.ts b/packages/cli/src/utils/housekeeping/scheduler.test.ts index 045702242f2..7eb80c1ddf3 100644 --- a/packages/cli/src/utils/housekeeping/scheduler.test.ts +++ b/packages/cli/src/utils/housekeeping/scheduler.test.ts @@ -1,6 +1,6 @@ /** * @license - * Copyright 2025 Google LLC + * Copyright 2025 HopCode Team * SPDX-License-Identifier: Apache-2.0 */ diff --git a/packages/cli/src/utils/housekeeping/scheduler.ts b/packages/cli/src/utils/housekeeping/scheduler.ts index 851f7a265c7..bd9d612b035 100644 --- a/packages/cli/src/utils/housekeeping/scheduler.ts +++ b/packages/cli/src/utils/housekeeping/scheduler.ts @@ -1,6 +1,6 @@ /** * @license - * Copyright 2025 Google LLC + * Copyright 2025 HopCode Team * SPDX-License-Identifier: Apache-2.0 */ @@ -138,13 +138,13 @@ async function runHousekeeping( // active session uses a brand-new sessionId/dir, so it's never aliased // against any sweep target. Not a bug — slightly conservative is fine. const currentSessionId = config.getSessionId(); - const hopCodeDir = Storage.getGlobalHopCodeDir(); + const hopcodeDir = Storage.getGlobalHopCodeDir(); await runThrottledOnce( { name: 'file-history-cleanup', - markerPath: join(hopCodeDir, FILE_HISTORY_MARKER), - lockPath: join(hopCodeDir, FILE_HISTORY_MARKER + '.lock'), + markerPath: join(hopcodeDir, FILE_HISTORY_MARKER), + lockPath: join(hopcodeDir, FILE_HISTORY_MARKER + '.lock'), }, async () => { const r = await cleanupOldFileHistoryBackups({ diff --git a/packages/cli/src/utils/housekeeping/throttledOnce.ts b/packages/cli/src/utils/housekeeping/throttledOnce.ts index f46fe87583b..3f7b54be9bd 100644 --- a/packages/cli/src/utils/housekeeping/throttledOnce.ts +++ b/packages/cli/src/utils/housekeeping/throttledOnce.ts @@ -1,6 +1,6 @@ /** * @license - * Copyright 2025 Google LLC + * Copyright 2025 HopCode Team * SPDX-License-Identifier: Apache-2.0 */ @@ -36,8 +36,8 @@ export async function runThrottledOnce( const minIntervalMs = opts.minIntervalMs ?? ONE_DAY_MS; const staleLockMs = opts.staleLockMs ?? STALE_LOCK_MS; - // First-ever housekeeping pass may run before ~/.qwen/ exists. mode 0o700 - // matches the rest of the codebase's convention for ~/.qwen/ subdirs + // First-ever housekeeping pass may run before ~/.hopcode/ exists. mode 0o700 + // matches the rest of the codebase's convention for ~/.hopcode/ subdirs // (e.g., file-token-storage.ts, sharedTokenManager.ts) so a slow main-app // initialization doesn't get races us into creating a world-readable dir. await mkdir(dirname(opts.lockPath), { recursive: true, mode: 0o700 }).catch( diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index d2d0945cbec..b6309685dcd 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -191,7 +191,6 @@ export enum ApprovalMode { AUTO_EDIT = 'auto-edit', AUTO = 'auto', IZN = 'izn', - YOLO = 'yolo', } export const APPROVAL_MODES = Object.values(ApprovalMode); @@ -247,15 +246,10 @@ export const APPROVAL_MODE_INFO: Record = { name: 'Auto', description: 'LLM classifier auto-approves safe actions, blocks risky ones', }, - [ApprovalMode.YOLO]: { - id: ApprovalMode.YOLO, - name: 'YOLO', - description: 'Automatically approve all tools', - }, [ApprovalMode.IZN]: { id: ApprovalMode.IZN, - name: 'IZN', - description: 'IZN mode - Automatically approve all tools', + name: 'Izn', + description: 'Automatically approve all tools', }, }; @@ -595,7 +589,7 @@ export interface WorktreeSettings { * * Paths must be relative to the repo root; absolute paths and any * entry containing `..` are rejected by the service. Entries that - * resolve to git-internal paths (`.git`, `.qwen`) are also rejected + * resolve to git-internal paths (`.git`, `.hopcode`) are also rejected * — symlinking those would either break git inside the worktree or * create a worktrees-inside-worktrees loop. Missing source dirs and * pre-existing destinations are silently skipped. @@ -608,7 +602,7 @@ export interface AgentsCollabSettings { displayMode?: string; /** Arena-specific settings */ arena?: { - /** Custom base directory for Arena worktrees (default: ~/.qwen/arena) */ + /** Custom base directory for Arena worktrees (default: ~/.hopcode/arena) */ worktreeBaseDir?: string; /** Preserve worktrees and state files after session ends */ preserveArtifacts?: boolean; @@ -834,7 +828,7 @@ export interface ConfigParameters { projectHooks?: Record; hooks?: Record; - /** Glob patterns to exclude from .qwen/rules/ loading. */ + /** Glob patterns to exclude from .hopcode/rules/ loading. */ contextRuleExcludes?: string[]; /** Warnings generated during configuration resolution */ warnings?: string[]; @@ -1700,13 +1694,13 @@ export class Config { // directory the worktree creators (`enter_worktree` and // `agent isolation:'worktree'`) write to. Using `this.targetDir` // directly would cause launches from a monorepo subdirectory to - // scan `/.qwen/worktrees/` — which never exists — and the + // scan `/.hopcode/worktrees/` — which never exists — and the // sweep would silently be a no-op forever. if (!this.getBareMode()) { void (async () => { try { // Resolve the repo top-level FIRST. The previous code bailed - // on `fs.access(/.qwen/worktrees)` before resolving, + // on `fs.access(/.hopcode/worktrees)` before resolving, // so a monorepo subdir launch (where `targetDir` is the // subdir, not the repo root) always early-returned and the // sweep was permanently a no-op. Fast-bail still happens, just diff --git a/packages/core/src/core/coreToolScheduler.test.ts b/packages/core/src/core/coreToolScheduler.test.ts index 350cebc3cfe..c999a50b354 100644 --- a/packages/core/src/core/coreToolScheduler.test.ts +++ b/packages/core/src/core/coreToolScheduler.test.ts @@ -675,7 +675,7 @@ describe('CoreToolScheduler', () => { getSessionId: () => 'test-session-id', getUsageStatisticsEnabled: () => true, getDebugMode: () => false, - getApprovalMode: () => options.approvalMode ?? ApprovalMode.YOLO, + getApprovalMode: () => options.approvalMode ?? ApprovalMode.IZN, getPermissionsAllow: () => [], getPermissionsDeny: options.getPermissionsDeny ?? (() => undefined), getContentGeneratorConfig: () => ({ @@ -2312,7 +2312,7 @@ describe('CoreToolScheduler edit cancellation', () => { }); }); -describe('CoreToolScheduler YOLO mode', () => { +describe('CoreToolScheduler IZN mode', () => { it('should execute tool requiring confirmation directly without waiting', async () => { // Arrange const executeFn = vi.fn().mockResolvedValue({ @@ -2346,12 +2346,12 @@ describe('CoreToolScheduler YOLO mode', () => { const onAllToolCallsComplete = vi.fn(); const onToolCallsUpdate = vi.fn(); - // Configure the scheduler for YOLO mode. + // Configure the scheduler for IZN mode. const mockConfig = { getSessionId: () => 'test-session-id', getUsageStatisticsEnabled: () => true, getDebugMode: () => false, - getApprovalMode: () => ApprovalMode.YOLO, + getApprovalMode: () => ApprovalMode.IZN, getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', @@ -2389,7 +2389,7 @@ describe('CoreToolScheduler YOLO mode', () => { name: 'mockTool', args: { param: 'value' }, isClientInitiated: false, - prompt_id: 'prompt-id-yolo', + prompt_id: 'prompt-id-izn', }; // Act @@ -2614,7 +2614,7 @@ describe('CoreToolScheduler request queueing', () => { getSessionId: () => 'test-session-id', getUsageStatisticsEnabled: () => true, getDebugMode: () => false, - getApprovalMode: () => ApprovalMode.YOLO, // Use YOLO to avoid confirmation prompts + getApprovalMode: () => ApprovalMode.IZN, // Use IZN to avoid confirmation prompts getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', @@ -2739,7 +2739,7 @@ describe('CoreToolScheduler request queueing', () => { getSessionId: () => 'test-session-id', getUsageStatisticsEnabled: () => true, getDebugMode: () => false, - getApprovalMode: () => ApprovalMode.YOLO, + getApprovalMode: () => ApprovalMode.IZN, getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', @@ -3263,7 +3263,7 @@ describe('CoreToolScheduler Sequential Execution', () => { getSessionId: () => 'test-session-id', getUsageStatisticsEnabled: () => true, getDebugMode: () => false, - getApprovalMode: () => ApprovalMode.YOLO, // Use YOLO to avoid confirmation prompts + getApprovalMode: () => ApprovalMode.IZN, // Use IZN to avoid confirmation prompts getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', @@ -3386,7 +3386,7 @@ describe('CoreToolScheduler Sequential Execution', () => { getSessionId: () => 'test-session-id', getUsageStatisticsEnabled: () => true, getDebugMode: () => false, - getApprovalMode: () => ApprovalMode.YOLO, + getApprovalMode: () => ApprovalMode.IZN, getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', @@ -3904,7 +3904,7 @@ describe('CoreToolScheduler telemetry spans', () => { getSessionId: () => 'test-session-id', getUsageStatisticsEnabled: () => true, getDebugMode: () => false, - getApprovalMode: () => ApprovalMode.YOLO, + getApprovalMode: () => ApprovalMode.IZN, getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', @@ -5586,14 +5586,14 @@ describe('CoreToolScheduler telemetry spans', () => { getAllTools: () => [], getToolsByServer: () => [], } as unknown as ToolRegistry; - // The auto-approve YOLO path doesn't call _schedule's getMessageBus + // The auto-approve IZN path doesn't call _schedule's getMessageBus // branch, so the only getMessageBus call is the prelude one at // _executeToolCallBody. Make that call throw. const mockConfig = { getSessionId: () => 'test-session-id', getUsageStatisticsEnabled: () => true, getDebugMode: () => false, - getApprovalMode: () => ApprovalMode.YOLO, + getApprovalMode: () => ApprovalMode.IZN, getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({}), getShellExecutionConfig: () => ({ @@ -7443,7 +7443,7 @@ describe('CoreToolScheduler validation retry loop detection', () => { getSessionId: () => 'test-session-id', getUsageStatisticsEnabled: () => true, getDebugMode: () => false, - getApprovalMode: () => ApprovalMode.YOLO, + getApprovalMode: () => ApprovalMode.IZN, getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', @@ -7694,7 +7694,7 @@ describe('CoreToolScheduler validation retry loop detection', () => { getSessionId: () => 'test-session-id', getUsageStatisticsEnabled: () => true, getDebugMode: () => false, - getApprovalMode: () => ApprovalMode.YOLO, + getApprovalMode: () => ApprovalMode.IZN, getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', @@ -8079,7 +8079,7 @@ describe('CoreToolScheduler activation wiring', () => { getSessionId: () => 'test-session-id', getUsageStatisticsEnabled: () => true, getDebugMode: () => false, - getApprovalMode: () => ApprovalMode.YOLO, + getApprovalMode: () => ApprovalMode.IZN, getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', @@ -8274,7 +8274,7 @@ describe('CoreToolScheduler activation wiring', () => { getSessionId: () => 'test-session-id', getUsageStatisticsEnabled: () => true, getDebugMode: () => false, - getApprovalMode: () => ApprovalMode.YOLO, + getApprovalMode: () => ApprovalMode.IZN, getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', @@ -8391,7 +8391,7 @@ describe('CoreToolScheduler activation wiring', () => { getSessionId: () => 'test-session-id', getUsageStatisticsEnabled: () => true, getDebugMode: () => false, - getApprovalMode: () => ApprovalMode.YOLO, + getApprovalMode: () => ApprovalMode.IZN, getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', @@ -8489,7 +8489,7 @@ describe('CoreToolScheduler activation wiring', () => { getSessionId: () => 'test-session-id', getUsageStatisticsEnabled: () => true, getDebugMode: () => false, - getApprovalMode: () => ApprovalMode.YOLO, + getApprovalMode: () => ApprovalMode.IZN, getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', @@ -8580,7 +8580,7 @@ describe('CoreToolScheduler activation wiring', () => { getSessionId: () => 'test-session-id', getUsageStatisticsEnabled: () => true, getDebugMode: () => false, - getApprovalMode: () => ApprovalMode.YOLO, + getApprovalMode: () => ApprovalMode.IZN, getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', @@ -8819,7 +8819,7 @@ describe('CoreToolScheduler shell-tool promote integration (#3831 PR-2)', () => getSessionId: () => 'test-session-id', getUsageStatisticsEnabled: () => true, getDebugMode: () => false, - getApprovalMode: () => ApprovalMode.YOLO, + getApprovalMode: () => ApprovalMode.IZN, getContentGeneratorConfig: () => ({ model: 'test-model', authType: 'gemini', diff --git a/packages/core/src/core/logger.test.ts b/packages/core/src/core/logger.test.ts index cfabd97021b..15c270d9020 100644 --- a/packages/core/src/core/logger.test.ts +++ b/packages/core/src/core/logger.test.ts @@ -21,31 +21,34 @@ import { decodeTagName, } from './logger.js'; import { Storage } from '../config/storage.js'; +import { getProjectHash } from '../utils/paths.js'; +import { atomicWriteFile } from '../utils/atomicFileWrite.js'; import { promises as fs, existsSync } from 'node:fs'; import path from 'node:path'; import type { Content } from '@google/genai'; +import os from 'node:os'; + +const GEMINI_DIR_NAME = '.hopcode'; +const TMP_DIR_NAME = 'tmp'; const LOG_FILE_NAME = 'logs.json'; const CHECKPOINT_FILE_NAME = 'checkpoint.json'; -// Mock os.homedir() to return a temp directory for test isolation. -// vi.spyOn on Node built-in modules is unreliable in vitest ESM mode -// (it doesn't intercept calls from other modules), so we use vi.mock -// which replaces the module globally. -vi.mock('node:os', async (importOriginal) => { - const original = await importOriginal(); - const nodePath = await import('node:path'); - const join = nodePath.default.join; - return { - ...original, - homedir: () => join(original.tmpdir(), 'hopcode-core-logger-home'), - }; -}); +const projectDir = process.cwd(); +const hash = getProjectHash(projectDir); +const TEST_HOME_DIR = path.join(os.tmpdir(), 'qwen-core-logger-home'); +let originalHome: string | undefined; let testGeminiDir: string; let testLogFilePath: string; let testCheckpointFilePath: string; +const setTestPaths = () => { + testGeminiDir = path.join(os.homedir(), GEMINI_DIR_NAME, TMP_DIR_NAME, hash); + testLogFilePath = path.join(testGeminiDir, LOG_FILE_NAME); + testCheckpointFilePath = path.join(testGeminiDir, CHECKPOINT_FILE_NAME); +}; + async function cleanupLogAndCheckpointFiles() { try { if (!testGeminiDir) return; @@ -71,6 +74,26 @@ vi.mock('../utils/session.js', () => ({ sessionId: 'test-session-id', })); +// Re-export the real atomicWriteFile so tests can override individual +// calls (e.g. .mockRejectedValueOnce) while preserving normal behavior. +// The default implementation is re-attached in `beforeEach` because the +// suite calls `vi.resetAllMocks()` which strips vi.fn(impl) back to no-op. +vi.mock('../utils/atomicFileWrite.js', async () => { + const actual = await vi.importActual< + typeof import('../utils/atomicFileWrite.js') + >('../utils/atomicFileWrite.js'); + return { + ...actual, + atomicWriteFile: vi.fn(actual.atomicWriteFile), + }; +}); + +const realAtomicWriteFile = ( + await vi.importActual( + '../utils/atomicFileWrite.js', + ) +).atomicWriteFile; + vi.mock('../utils/debugLogger.js', async (importOriginal) => { const original = await importOriginal(); @@ -91,18 +114,19 @@ describe('Logger', () => { beforeEach(async () => { vi.resetAllMocks(); + // resetAllMocks blanks the vi.fn(actual) delegation — re-attach so the + // logger's initialize/append paths still hit the real disk. + vi.mocked(atomicWriteFile).mockImplementation(realAtomicWriteFile); vi.useFakeTimers(); vi.setSystemTime(new Date('2025-01-01T12:00:00.000Z')); - // Compute paths via Storage so they match what Logger uses internally - const storage = new Storage(process.cwd()); - testGeminiDir = storage.getProjectTempDir(); - testLogFilePath = path.join(testGeminiDir, LOG_FILE_NAME); - testCheckpointFilePath = path.join(testGeminiDir, CHECKPOINT_FILE_NAME); + originalHome = process.env['HOME']; + process.env['HOME'] = TEST_HOME_DIR; + setTestPaths(); // Clean up before the test await cleanupLogAndCheckpointFiles(); // Ensure the directory exists for the test await fs.mkdir(testGeminiDir, { recursive: true }); - logger = new Logger(testSessionId, storage); + logger = new Logger(testSessionId, new Storage(process.cwd())); await logger.initialize(); }); @@ -113,6 +137,12 @@ describe('Logger', () => { // Clean up after the test await cleanupLogAndCheckpointFiles(); vi.useRealTimers(); + vi.restoreAllMocks(); + if (originalHome === undefined) { + delete process.env['HOME']; + } else { + process.env['HOME'] = originalHome; + } }); afterAll(async () => { @@ -434,7 +464,7 @@ describe('Logger', () => { }); it('should not throw, not increment messageId, and log error if writing to file fails', async () => { - vi.spyOn(fs, 'writeFile').mockRejectedValueOnce(new Error('Disk full')); + vi.mocked(atomicWriteFile).mockRejectedValueOnce(new Error('Disk full')); const initialMessageId = logger['messageId']; const initialLogCount = logger['logs'].length; @@ -513,11 +543,11 @@ describe('Logger', () => { encodedTag: 'test-tag', }, { - tag: '\u4F60\u597D\u4E16\u754C', + tag: '你好世界', encodedTag: '%E4%BD%A0%E5%A5%BD%E4%B8%96%E7%95%8C', }, { - tag: 'japanese-\u3072\u3089\u304C\u306A\u3072\u3089\u304C\u306A\u5F62\u58F0', + tag: 'japanese-ひらがなひらがな形声', encodedTag: 'japanese-%E3%81%B2%E3%82%89%E3%81%8C%E3%81%AA%E3%81%B2%E3%82%89%E3%81%8C%E3%81%AA%E5%BD%A2%E5%A3%B0', }, @@ -527,12 +557,12 @@ describe('Logger', () => { }, ])('should save a checkpoint', async ({ tag, encodedTag }) => { await logger.saveCheckpoint(conversation, tag); - // Verify via loadCheckpoint to avoid path-construction mismatch - // between the test and the logger's internal hopcodeDir. - const loaded = await logger.loadCheckpoint(tag); - expect(loaded).toEqual(conversation); - expect(encodeTagName(tag)).toBe(encodedTag); - expect(decodeTagName(encodedTag)).toBe(tag); + const taggedFilePath = path.join( + testGeminiDir, + `checkpoint-${encodedTag}.json`, + ); + const fileContent = await fs.readFile(taggedFilePath, 'utf-8'); + expect(JSON.parse(fileContent)).toEqual(conversation); }); it('should not throw if logger is not initialized', async () => { @@ -567,11 +597,11 @@ describe('Logger', () => { encodedTag: 'test-tag', }, { - tag: '\u4F60\u597D\u4E16\u754C', + tag: '你好世界', encodedTag: '%E4%BD%A0%E5%A5%BD%E4%B8%96%E7%95%8C', }, { - tag: 'japanese-\u3072\u3089\u304C\u306A\u3072\u3089\u304C\u306A\u5F62\u58F0', + tag: 'japanese-ひらがなひらがな形声', encodedTag: 'japanese-%E3%81%B2%E3%82%89%E3%81%8C%E3%81%AA%E3%81%B2%E3%82%89%E3%81%8C%E3%81%AA%E5%BD%A2%E5%A3%B0', }, @@ -584,9 +614,14 @@ describe('Logger', () => { ...conversation, { role: 'user', parts: [{ text: 'hello' }] }, ]; - // Use saveCheckpoint to ensure the file lands in the logger's - // actual hopcodeDir, not a path the test constructs independently. - await logger.saveCheckpoint(taggedConversation, tag); + const taggedFilePath = path.join( + testGeminiDir, + `checkpoint-${encodedTag}.json`, + ); + await fs.writeFile( + taggedFilePath, + JSON.stringify(taggedConversation, null, 2), + ); const loaded = await logger.loadCheckpoint(tag); expect(loaded).toEqual(taggedConversation); @@ -633,28 +668,33 @@ describe('Logger', () => { { role: 'user', parts: [{ text: 'Content to be deleted' }] }, ]; const tag = 'delete-me'; + const encodedTag = 'delete-me'; + let taggedFilePath: string; beforeEach(async () => { - // Use saveCheckpoint so the file lands in the logger's actual hopcodeDir. - await logger.saveCheckpoint(conversation, tag); + taggedFilePath = path.join( + testGeminiDir, + `checkpoint-${encodedTag}.json`, + ); + // Create a file to be deleted + await fs.writeFile(taggedFilePath, JSON.stringify(conversation)); }); it('should delete the specified checkpoint file and return true', async () => { const result = await logger.deleteCheckpoint(tag); expect(result).toBe(true); - // Verify via checkpointExists that the file is gone - const existsAfter = await logger.checkpointExists(tag); - expect(existsAfter).toBe(false); + // Verify the file is actually gone + await expect(fs.access(taggedFilePath)).rejects.toThrow(/ENOENT/); }); it('should delete both new and old checkpoint files if they exist', async () => { const oldTag = 'delete-me(old)'; - const newStylePath = logger['_checkpointPath'](oldTag); const oldStylePath = path.join( - path.dirname(newStylePath), + testGeminiDir, `checkpoint-${oldTag}.json`, ); + const newStylePath = logger['_checkpointPath'](oldTag); // Create both files await fs.writeFile(oldStylePath, '{}'); @@ -704,12 +744,18 @@ describe('Logger', () => { describe('checkpointExists', () => { const tag = 'exists-test'; + const encodedTag = 'exists-test'; + let taggedFilePath: string; - it('should return true if the checkpoint file exists', async () => { - await logger.saveCheckpoint( - [{ role: 'user', parts: [{ text: 'test' }] }], - tag, + beforeEach(() => { + taggedFilePath = path.join( + testGeminiDir, + `checkpoint-${encodedTag}.json`, ); + }); + + it('should return true if the checkpoint file exists', async () => { + await fs.writeFile(taggedFilePath, '{}'); const exists = await logger.checkpointExists(tag); expect(exists).toBe(true); }); @@ -755,7 +801,11 @@ describe('Logger', () => { { role: 'user', parts: [{ text: 'hello' }] }, ]; const tag = 'special(char)'; - await logger.saveCheckpoint(taggedConversation, tag); + const taggedFilePath = path.join(testGeminiDir, `checkpoint-${tag}.json`); + await fs.writeFile( + taggedFilePath, + JSON.stringify(taggedConversation, null, 2), + ); const loaded = await logger.loadCheckpoint(tag); expect(loaded).toEqual(taggedConversation); @@ -866,7 +916,7 @@ describe('Logger', () => { await logger.logMessage(MessageSenderType.USER, 'kept'); vi.advanceTimersByTime(1000); - vi.spyOn(fs, 'writeFile').mockRejectedValueOnce(new Error('Disk full')); + vi.mocked(atomicWriteFile).mockRejectedValueOnce(new Error('Disk full')); await logger.logMessage(MessageSenderType.USER, 'failed write'); expect(logger['lastLoggedUserEntry']).toBeNull(); @@ -912,7 +962,7 @@ describe('Logger', () => { 'cancelled prompt', ]); - vi.spyOn(fs, 'writeFile').mockRejectedValueOnce(new Error('Disk full')); + vi.mocked(atomicWriteFile).mockRejectedValueOnce(new Error('Disk full')); const removed = await logger.removeLastUserMessage(); expect(removed).toBe(false); @@ -961,7 +1011,7 @@ describe('Logger', () => { const trackedAfterUser = logger['lastLoggedUserEntry']; expect(trackedAfterUser).not.toBeNull(); - vi.spyOn(fs, 'writeFile').mockRejectedValueOnce(new Error('Disk full')); + vi.mocked(atomicWriteFile).mockRejectedValueOnce(new Error('Disk full')); await logger.logMessage(MessageSenderType.MODEL_SWITCH, 'qwen→qwen-max'); // Tracker is unchanged — the non-USER failure didn't shift which diff --git a/packages/core/src/core/logger.ts b/packages/core/src/core/logger.ts index a3c12bb3afd..4cea0b28757 100644 --- a/packages/core/src/core/logger.ts +++ b/packages/core/src/core/logger.ts @@ -8,6 +8,7 @@ import path from 'node:path'; import { promises as fs } from 'node:fs'; import type { Content } from '@google/genai'; import type { Storage } from '../config/storage.js'; +import { atomicWriteFile } from '../utils/atomicFileWrite.js'; import { createDebugLogger, type DebugLogger } from '../utils/debugLogger.js'; const LOG_FILE_NAME = 'logs.json'; @@ -187,7 +188,7 @@ export class Logger { } this.logs = await this._readLogFile(); if (!fileExisted && this.logs.length === 0) { - await fs.writeFile(this.logFilePath, '[]', 'utf-8'); + await atomicWriteFile(this.logFilePath, '[]', { encoding: 'utf-8' }); } const sessionLogs = this.logs.filter( (entry) => entry.sessionId === this.sessionId, @@ -258,10 +259,10 @@ export class Logger { currentLogsOnDisk.push(entryToAppend); try { - await fs.writeFile( + await atomicWriteFile( this.logFilePath, JSON.stringify(currentLogsOnDisk, null, 2), - 'utf-8', + { encoding: 'utf-8' }, ); this.logs = currentLogsOnDisk; return entryToAppend; // Return the successfully appended entry @@ -461,10 +462,10 @@ export class Logger { currentLogsOnDisk.splice(idx, 1); try { - await fs.writeFile( + await atomicWriteFile( logFilePath, JSON.stringify(currentLogsOnDisk, null, 2), - 'utf-8', + { encoding: 'utf-8' }, ); this.logs = currentLogsOnDisk; // Roll back this instance's nextMessageId so a subsequent log doesn't @@ -539,7 +540,9 @@ export class Logger { // Always save with the new encoded path. const path = this._checkpointPath(tag); try { - await fs.writeFile(path, JSON.stringify(conversation, null, 2), 'utf-8'); + await atomicWriteFile(path, JSON.stringify(conversation, null, 2), { + encoding: 'utf-8', + }); } catch (error) { this.debugLogger.error('Error writing to checkpoint file:', error); } diff --git a/packages/core/src/core/permissionFlow.ts b/packages/core/src/core/permissionFlow.ts index dafcb26dad6..b44e5a6d37f 100644 --- a/packages/core/src/core/permissionFlow.ts +++ b/packages/core/src/core/permissionFlow.ts @@ -115,11 +115,8 @@ export function needsConfirmation( ): boolean { const isAskUserQuestionTool = toolName === ToolNames.ASK_USER_QUESTION; - // IZN and YOLO modes auto-approve everything except ask_user_question - if ( - (approvalMode === ApprovalMode.IZN || approvalMode === ApprovalMode.YOLO) && - !isAskUserQuestionTool - ) { + // IZN mode auto-approves everything except ask_user_question + if (approvalMode === ApprovalMode.IZN && !isAskUserQuestionTool) { return false; } diff --git a/packages/core/src/extension/claude-converter.test.ts b/packages/core/src/extension/claude-converter.test.ts index 2e8e5085424..7dfd6088c4f 100644 --- a/packages/core/src/extension/claude-converter.test.ts +++ b/packages/core/src/extension/claude-converter.test.ts @@ -434,7 +434,7 @@ describe('convertClaudePluginPackage', () => { 'crlf-agents-plugin', ); - // Verify: agent file was properly parsed and converted into .qwen/agents folder structure + // Verify: agent file was properly parsed and converted into .hopcode/agents folder structure const convertedAgentsDir = path.join(result.convertedDir, 'agents'); expect(fs.existsSync(convertedAgentsDir)).toBe(true); @@ -682,7 +682,7 @@ describe('performVariableReplacement for Claude extensions', () => { } }); - it('should replace .claude with .qwen in shell scripts', () => { + it('should replace .claude with .hopcode in shell scripts', () => { const extDir = path.join(testDir, 'ext-sh'); fs.mkdirSync(extDir, { recursive: true }); diff --git a/packages/core/src/extension/extensionManager.ts b/packages/core/src/extension/extensionManager.ts index 4fe0c6e36c7..85e4a40069f 100644 --- a/packages/core/src/extension/extensionManager.ts +++ b/packages/core/src/extension/extensionManager.ts @@ -24,6 +24,10 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import * as os from 'node:os'; +import { + atomicWriteFile, + atomicWriteFileSync, +} from '../utils/atomicFileWrite.js'; import { getErrorMessage } from '../utils/errors.js'; import { EXTENSIONS_CONFIG_FILENAME, @@ -531,7 +535,7 @@ export class ExtensionManager { private writeEnablementConfig(config: AllExtensionsEnablementConfig): void { fs.mkdirSync(this.configDir, { recursive: true }); - fs.writeFileSync(this.configFilePath, JSON.stringify(config, null, 2)); + atomicWriteFileSync(this.configFilePath, JSON.stringify(config, null, 2)); } /** @@ -1072,7 +1076,7 @@ export class ExtensionManager { destinationPath, INSTALL_METADATA_FILENAME, ); - await fs.promises.writeFile(metadataPath, metadataString); + await atomicWriteFile(metadataPath, metadataString); extension = await this.loadExtension({ extensionDir: destinationPath }); if (!extension) { diff --git a/packages/core/src/hooks/hookRunner.ts b/packages/core/src/hooks/hookRunner.ts index 8bf2156681a..0217a206d4e 100644 --- a/packages/core/src/hooks/hookRunner.ts +++ b/packages/core/src/hooks/hookRunner.ts @@ -99,7 +99,7 @@ export class HookRunner { const signal = contextOrSignal && 'aborted' in contextOrSignal ? contextOrSignal - : (contextOrSignal as FunctionHookContext | undefined)?.signal; + : contextOrSignal?.signal; // Check if already aborted before starting if (signal?.aborted) { @@ -573,7 +573,7 @@ export class HookRunner { ...process.env, GEMINI_PROJECT_DIR: input.cwd, CLAUDE_PROJECT_DIR: input.cwd, // For compatibility - HOPCODE_PROJECT_DIR: input.cwd, + HOPCODE_PROJECT_DIR: input.cwd, // For HopCode compatibility ...getShellContextEnvVars(), ...hookConfig.env, }; diff --git a/packages/core/src/hooks/trustedHooks.test.ts b/packages/core/src/hooks/trustedHooks.test.ts new file mode 100644 index 00000000000..e9f7f746ce2 --- /dev/null +++ b/packages/core/src/hooks/trustedHooks.test.ts @@ -0,0 +1,129 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as path from 'node:path'; +import { atomicWriteFileSync } from '../utils/atomicFileWrite.js'; +import { TrustedHooksManager } from './trustedHooks.js'; +import { HookType, type HookConfig } from './types.js'; + +vi.mock('../utils/atomicFileWrite.js', () => ({ + atomicWriteFileSync: vi.fn(), +})); + +vi.mock('../config/storage.js', () => ({ + Storage: { + getGlobalHopCodeDir: vi.fn(() => '/mock/home/.hopcode'), + }, +})); + +vi.mock('node:fs', () => ({ + existsSync: vi.fn(() => true), + readFileSync: vi.fn(() => '{}'), + mkdirSync: vi.fn(), +})); + +describe('TrustedHooksManager', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('trustHooks writes via atomicWriteFileSync with credentials-grade options', () => { + const manager = new TrustedHooksManager(); + const hook: HookConfig = { + type: HookType.Command, + command: 'echo trusted', + }; + + manager.trustHooks('/project/a', { PreToolUse: [{ hooks: [hook] }] }); + + expect(atomicWriteFileSync).toHaveBeenCalledTimes(1); + const [, , options] = vi.mocked(atomicWriteFileSync).mock.calls[0]; + // mode 0o600 + forceMode: + noFollow:true — mirrors the credential + // write sites (sharedTokenManager / oauth-token-storage / + // file-token-storage). noFollow prevents a pre-placed symlink at + // the config path from redirecting the executable-trust list. + expect(options).toEqual({ + mode: 0o600, + forceMode: true, + noFollow: true, + }); + }); + + it('trustHooks writes the configPath under the global hopcode dir', () => { + const manager = new TrustedHooksManager(); + manager.trustHooks('/project/a', { + PreToolUse: [ + { hooks: [{ type: HookType.Command, command: 'echo trusted' }] }, + ], + }); + + const [configPath] = vi.mocked(atomicWriteFileSync).mock.calls[0]; + expect(configPath).toBe( + path.join('/mock/home/.hopcode', 'trusted_hooks.json'), + ); + }); + + it('trustHooks persists the hook key derived from the hook config', () => { + const manager = new TrustedHooksManager(); + manager.trustHooks('/project/a', { + PreToolUse: [ + { hooks: [{ type: HookType.Command, command: 'echo trusted' }] }, + ], + }); + + const [, content] = vi.mocked(atomicWriteFileSync).mock.calls[0]; + const saved = JSON.parse(content as string); + expect(saved['/project/a']).toEqual(['echo trusted']); + }); + + it('getUntrustedHooks returns the hook identifier when not previously trusted', () => { + const manager = new TrustedHooksManager(); + const untrusted = manager.getUntrustedHooks('/project/a', { + PreToolUse: [ + { + hooks: [ + { type: HookType.Command, command: 'rm -rf /' }, + { type: HookType.Command, command: 'echo safe' }, + ], + }, + ], + }); + + expect(untrusted).toEqual(['rm -rf /', 'echo safe']); + }); + + it('getUntrustedHooks returns empty after the hooks are trusted', () => { + const manager = new TrustedHooksManager(); + manager.trustHooks('/project/a', { + PreToolUse: [ + { + hooks: [ + { type: HookType.Command, command: 'rm -rf /' }, + { type: HookType.Command, command: 'echo safe' }, + ], + }, + ], + }); + + const untrusted = manager.getUntrustedHooks('/project/a', { + PreToolUse: [ + { + hooks: [ + { type: HookType.Command, command: 'rm -rf /' }, + { type: HookType.Command, command: 'echo safe' }, + ], + }, + ], + }); + + expect(untrusted).toEqual([]); + }); +}); diff --git a/packages/core/src/hooks/trustedHooks.ts b/packages/core/src/hooks/trustedHooks.ts index a39f5bef8c4..059faf9c0c6 100644 --- a/packages/core/src/hooks/trustedHooks.ts +++ b/packages/core/src/hooks/trustedHooks.ts @@ -12,6 +12,7 @@ import { type HookDefinition, type HookEventName, } from './types.js'; +import { atomicWriteFileSync } from '../utils/atomicFileWrite.js'; import { createDebugLogger } from '../utils/debugLogger.js'; const debugLogger = createDebugLogger('TRUSTED_HOOKS'); @@ -50,9 +51,16 @@ export class TrustedHooksManager { if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } - fs.writeFileSync( + // 0o600 + forceMode + noFollow: this file lists user-approved + // executable hook commands and is strictly more sensitive than + // trustedFolders.json / tipHistory.json. forceMode heals + // over-permissive perms restored from a backup; noFollow refuses + // to write through a pre-placed symlink (matches the credential + // write sites' security posture). + atomicWriteFileSync( this.configPath, JSON.stringify(this.trustedHooks, null, 2), + { mode: 0o600, forceMode: true, noFollow: true }, ); } catch (error) { debugLogger.warn('Failed to save trusted hooks config', error); diff --git a/packages/core/src/hopcode/sharedTokenManager.test.ts b/packages/core/src/hopcode/sharedTokenManager.test.ts index 0f30b64388d..7dd69e8cdc5 100644 --- a/packages/core/src/hopcode/sharedTokenManager.test.ts +++ b/packages/core/src/hopcode/sharedTokenManager.test.ts @@ -15,6 +15,7 @@ import { TokenManagerError, TokenError, } from './sharedTokenManager.js'; +import { atomicWriteFile } from '../utils/atomicFileWrite.js'; import type { IHopCodeOAuth2Client, HopCodeCredentials, @@ -35,6 +36,10 @@ vi.mock('node:fs', () => ({ unlinkSync: vi.fn(), })); +vi.mock('../utils/atomicFileWrite.js', () => ({ + atomicWriteFile: vi.fn().mockResolvedValue(undefined), +})); + vi.mock('node:os', () => ({ homedir: vi.fn(), })); @@ -254,10 +259,10 @@ describe('SharedTokenManager', () => { .fn() .mockResolvedValue(refreshResponse); - // Mock file operations + // Mock file operations (writeFile still needed for the wx lock path; + // credential save now routes through the mocked atomicWriteFile). mockFs.stat.mockResolvedValue({ mtimeMs: 1000 } as Stats); mockFs.writeFile.mockResolvedValue(undefined); - mockFs.rename.mockResolvedValue(undefined); mockFs.mkdir.mockResolvedValue(undefined); const result = await tokenManager.getValidCredentials(mockClient); @@ -267,6 +272,40 @@ describe('SharedTokenManager', () => { expect(mockClient.setCredentials).toHaveBeenCalled(); }); + it('wraps atomicWriteFile failure in TokenManagerError(FILE_ACCESS_ERROR)', async () => { + // PR #4333 review fold-in: the catch block in saveCredentialsToFile + // that maps disk-full / permission-denied to TokenManagerError was + // never exercised — atomicWriteFile is mocked as always-successful. + // Verify the error path so a regression that swallowed the failure + // (or skipped the cache-mtime update on failure) would be caught. + const mockClient = createMockHopCodeClient(createExpiredCredentials()); + const refreshResponse = createSuccessfulRefreshResponse(); + mockClient.refreshAccessToken = vi + .fn() + .mockResolvedValue(refreshResponse); + + mockFs.stat.mockResolvedValue({ mtimeMs: 1000 } as Stats); + mockFs.writeFile.mockResolvedValue(undefined); // wx lock path still needed + mockFs.mkdir.mockResolvedValue(undefined); + vi.mocked(atomicWriteFile).mockRejectedValueOnce( + Object.assign(new Error('ENOSPC: no space left on device'), { + code: 'ENOSPC', + }), + ); + + let caught: unknown; + try { + await tokenManager.getValidCredentials(mockClient); + } catch (e) { + caught = e; + } + expect(caught).toBeInstanceOf(TokenManagerError); + expect((caught as TokenManagerError).type).toBe( + TokenError.FILE_ACCESS_ERROR, + ); + expect((caught as Error).message).toContain('ENOSPC'); + }); + it('should force refresh when forceRefresh is true', async () => { const mockClient = createMockHopCodeClient(createValidCredentials()); const refreshResponse = createSuccessfulRefreshResponse(); @@ -278,7 +317,6 @@ describe('SharedTokenManager', () => { // Mock file operations mockFs.stat.mockResolvedValue({ mtimeMs: 1000 } as Stats); mockFs.writeFile.mockResolvedValue(undefined); - mockFs.rename.mockResolvedValue(undefined); mockFs.mkdir.mockResolvedValue(undefined); const result = await tokenManager.getValidCredentials(mockClient, true); @@ -448,9 +486,9 @@ describe('SharedTokenManager', () => { mockClient.refreshAccessToken = vi.fn().mockReturnValue(refreshPromise); - // Mock file operations for lock and save + // Mock file operations for lock and save (credential save now goes + // through atomicWriteFile mock; writeFile mock kept for the wx lock). mockFs.writeFile.mockResolvedValue(undefined); - mockFs.rename.mockResolvedValue(undefined); mockFs.mkdir.mockResolvedValue(undefined); // Start refresh diff --git a/packages/core/src/hopcode/sharedTokenManager.ts b/packages/core/src/hopcode/sharedTokenManager.ts index 694b1079711..a47810013e5 100644 --- a/packages/core/src/hopcode/sharedTokenManager.ts +++ b/packages/core/src/hopcode/sharedTokenManager.ts @@ -17,6 +17,7 @@ import { CredentialsClearRequiredError, } from './hopCodeOAuth2.js'; import { createDebugLogger } from '../utils/debugLogger.js'; +import { atomicWriteFile } from '../utils/atomicFileWrite.js'; import { Storage } from '../config/storage.js'; const debugLogger = createDebugLogger('HOPCODE_OAUTH'); @@ -616,7 +617,6 @@ export class SharedTokenManager { ): Promise { const filePath = this.getCredentialFilePath(); const dirPath = path.dirname(filePath); - const tempPath = `${filePath}.tmp.${randomUUID()}`; // Create directory with restricted permissions try { @@ -636,19 +636,16 @@ export class SharedTokenManager { const credString = JSON.stringify(credentials, null, 2); try { - // Write to temporary file first with restricted permissions - await this.withTimeout( - fs.writeFile(tempPath, credString, { mode: 0o600 }), - 5000, - 'File operation', - ); - - // Atomic move to final location - await this.withTimeout( - fs.rename(tempPath, filePath), - 5000, - 'File operation', - ); + // Don't wrap atomicWriteFile in withTimeout: a timeout would reject + // our caller while the rename can still complete after the lock is + // released, potentially overwriting another process's newer + // credentials. Atomic write is durable by design — accept whatever + // latency the I/O takes. (See PR #4095 Phase 2 Codex review round 3.) + await atomicWriteFile(filePath, credString, { + mode: 0o600, + forceMode: true, + noFollow: true, + }); // Update cached file modification time atomically after successful write const stats = await this.withTimeout( @@ -658,13 +655,6 @@ export class SharedTokenManager { ); this.memoryCache.fileModTime = stats.mtimeMs; } catch (error) { - // Clean up temp file if it exists - try { - await this.withTimeout(fs.unlink(tempPath), 1000, 'File operation'); - } catch (_cleanupError) { - // Ignore cleanup errors - temp file might not exist - } - throw new TokenManagerError( TokenError.FILE_ACCESS_ERROR, `Failed to write credentials file: ${error instanceof Error ? error.message : String(error)}`, diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 64356b367ad..daae4a33193 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -325,6 +325,7 @@ export * from './followup/index.js'; // Utilities // ============================================================================ +export * from './utils/atomicFileWrite.js'; export * from './utils/browser.js'; export * from './utils/bundlePaths.js'; export * from './utils/configResolver.js'; diff --git a/packages/core/src/lsp/NativeLspService.test.ts b/packages/core/src/lsp/NativeLspService.test.ts index 8c65038940b..cbf0eaaa1ca 100644 --- a/packages/core/src/lsp/NativeLspService.test.ts +++ b/packages/core/src/lsp/NativeLspService.test.ts @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { describe, beforeEach, expect, test, vi } from 'vitest'; +import { describe, beforeEach, afterEach, expect, test, vi } from 'vitest'; import { NativeLspService } from './NativeLspService.js'; import { EventEmitter } from 'events'; import type { Config as CoreConfig } from '../config/config.js'; @@ -1189,4 +1189,140 @@ describe('NativeLspService', () => { fs.rmSync(tempDir, { recursive: true, force: true }); } }); + + // PR #4333 review fold-in: cover the two error branches added in + // applyTextEdits — only-ENOENT read guard and the W_OK access check. + // The branches are reached via the private applyTextEdits, accessed + // through a typed cast since making them public-for-test would inflate + // the API surface for one verification. + describe('applyTextEdits — error branches', () => { + let tmpDir: string; + + beforeEach(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lsp-edits-error-')); + // Override the workspace mock so any path inside tmpDir is in-scope. + ( + mockWorkspace as unknown as { + isPathWithinWorkspace: (p: string) => boolean; + } + ).isPathWithinWorkspace = (p: string) => p.startsWith(tmpDir); + }); + + afterEach(() => { + try { + // Restore perms before rm so cleanup can traverse 0o000 / 0o444 files. + for (const f of fs.readdirSync(tmpDir)) { + try { + fs.chmodSync(path.join(tmpDir, f), 0o644); + } catch { + /* ignore */ + } + } + } catch { + /* ignore */ + } + fs.rmSync(tmpDir, { recursive: true, force: true }); + }); + + test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)( + 'read failure on chmod 0000 file propagates EACCES (does not silently become empty content)', + async () => { + const filePath = path.join(tmpDir, 'unreadable.txt'); + fs.writeFileSync(filePath, 'original content'); + fs.chmodSync(filePath, 0o000); + + const uri = pathToFileURL(filePath).toString(); + const edit = { + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }, + newText: 'INJECTED ', + }; + const applyTextEdits = ( + lspService as unknown as { + applyTextEdits: ( + uri: string, + edits: Array, + ) => Promise; + } + ).applyTextEdits.bind(lspService); + + let caught: NodeJS.ErrnoException | undefined; + try { + await applyTextEdits(uri, [edit]); + } catch (err) { + caught = err as NodeJS.ErrnoException; + } + expect(caught?.code).toBe('EACCES'); + + // File is unchanged — read fail should NOT have triggered the + // pre-fix "treat as empty, overwrite with edits" path. + fs.chmodSync(filePath, 0o644); + expect(fs.readFileSync(filePath, 'utf-8')).toBe('original content'); + }, + ); + + test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)( + 'chmod 0444 read-only file is rejected before write (W_OK check)', + async () => { + const filePath = path.join(tmpDir, 'readonly.txt'); + fs.writeFileSync(filePath, 'do not modify me'); + fs.chmodSync(filePath, 0o444); + + const uri = pathToFileURL(filePath).toString(); + const edit = { + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }, + newText: 'BAD ', + }; + const applyTextEdits = ( + lspService as unknown as { + applyTextEdits: ( + uri: string, + edits: Array, + ) => Promise; + } + ).applyTextEdits.bind(lspService); + + let caught: NodeJS.ErrnoException | undefined; + try { + await applyTextEdits(uri, [edit]); + } catch (err) { + caught = err as NodeJS.ErrnoException; + } + expect(caught?.code).toMatch(/^E(ACCES|PERM)$/); + + // Original content untouched — atomic rename did NOT bypass perms. + fs.chmodSync(filePath, 0o644); + expect(fs.readFileSync(filePath, 'utf-8')).toBe('do not modify me'); + }, + ); + + test('nonexistent file is accepted (LSP can create via edits)', async () => { + const filePath = path.join(tmpDir, 'new-file.txt'); + const uri = pathToFileURL(filePath).toString(); + const edit = { + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }, + newText: 'created via edit', + }; + const applyTextEdits = ( + lspService as unknown as { + applyTextEdits: ( + uri: string, + edits: Array, + ) => Promise; + } + ).applyTextEdits.bind(lspService); + + await applyTextEdits(uri, [edit]); + expect(fs.existsSync(filePath)).toBe(true); + expect(fs.readFileSync(filePath, 'utf-8')).toBe('created via edit'); + }); + }); }); diff --git a/packages/core/src/lsp/NativeLspService.ts b/packages/core/src/lsp/NativeLspService.ts index 2e5f1595b9b..ed1d708e4e1 100644 --- a/packages/core/src/lsp/NativeLspService.ts +++ b/packages/core/src/lsp/NativeLspService.ts @@ -45,6 +45,8 @@ import type { import * as path from 'path'; import { fileURLToPath, pathToFileURL } from 'url'; import * as fs from 'node:fs'; +import { promises as fsp } from 'node:fs'; +import { atomicWriteFile } from '../utils/atomicFileWrite.js'; import { createDebugLogger } from '../utils/debugLogger.js'; import { globSync } from 'glob'; @@ -1306,12 +1308,26 @@ export class NativeLspService { throw new Error(`Refusing to apply edits outside workspace: ${filePath}`); } - // Read the current file content + // Concurrency: this is an async read-modify-write (readFile → splice → + // access(W_OK) → atomicWriteFile) with await points between read and + // write. atomicWriteFile keeps the file from being torn, but does NOT + // serialize writers — two overlapping applyTextEdits calls for the SAME + // path can both read the same base content and the second rename clobbers + // the first (lost update). Latent today: applyWorkspaceEdit has no + // production caller and no workspace/applyEdit handler is wired. Before + // wiring one, serialize per resolved filePath (see jsonl-utils getFileLock). + + // Read the current file content. Only treat ENOENT as "new file"; any + // other read failure (EACCES on a read-protected file, EISDIR, etc.) + // must propagate — otherwise the atomic rename below would silently + // replace the unreadable target with edits applied to an empty buffer. let content: string; try { - content = fs.readFileSync(filePath, 'utf-8'); - } catch { - // File doesn't exist, treat as empty + content = await fsp.readFile(filePath, 'utf-8'); + } catch (err) { + if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') { + throw err; + } content = ''; } @@ -1347,8 +1363,22 @@ export class NativeLspService { lines.splice(startLine, endLine - startLine + 1, ...newLines); } - // Write back to file - fs.writeFileSync(filePath, lines.join('\n'), 'utf-8'); + // Honor file-level write permissions. Atomic rename (tmp + rename) + // would otherwise bypass a chmod 0444 lock because rename only needs + // parent-directory write access. ENOENT is fine — LSP may be creating + // the file via edits. + try { + await fsp.access(filePath, fs.constants.W_OK); + } catch (err) { + if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') { + throw err; + } + } + + // Atomic write so a crash mid-edit can't leave the user file half-written. + // Async variant avoids blocking the event loop on the LSP edit hot path + // (sync renameWithRetry can stall up to 350ms under Atomics.wait backoff). + await atomicWriteFile(filePath, lines.join('\n'), { encoding: 'utf-8' }); } /** diff --git a/packages/core/src/mcp/oauth-token-storage.test.ts b/packages/core/src/mcp/oauth-token-storage.test.ts index 0111fde2d45..253eda4e866 100644 --- a/packages/core/src/mcp/oauth-token-storage.test.ts +++ b/packages/core/src/mcp/oauth-token-storage.test.ts @@ -11,6 +11,7 @@ import { MCPOAuthTokenStorage } from './oauth-token-storage.js'; import { FORCE_ENCRYPTED_FILE_ENV_VAR } from './token-storage/index.js'; import type { OAuthCredentials, OAuthToken } from './token-storage/types.js'; import { HOPCODE_DIR } from '../utils/paths.js'; +import { atomicWriteFile } from '../utils/atomicFileWrite.js'; // Mock debugLogger const mockDebugLogger = vi.hoisted(() => ({ @@ -33,6 +34,10 @@ vi.mock('node:fs', () => ({ }, })); +vi.mock('../utils/atomicFileWrite.js', () => ({ + atomicWriteFile: vi.fn(), +})); + vi.mock('node:path', () => ({ dirname: vi.fn(), join: vi.fn(), @@ -142,7 +147,7 @@ describe('MCPOAuthTokenStorage', () => { it('should save token with restricted permissions', async () => { vi.mocked(fs.readFile).mockRejectedValue({ code: 'ENOENT' }); vi.mocked(fs.mkdir).mockResolvedValue(undefined); - vi.mocked(fs.writeFile).mockResolvedValue(undefined); + vi.mocked(atomicWriteFile).mockResolvedValue(undefined); await tokenStorage.saveToken( 'test-server', @@ -155,10 +160,10 @@ describe('MCPOAuthTokenStorage', () => { path.join('/mock/home', HOPCODE_DIR), { recursive: true }, ); - expect(fs.writeFile).toHaveBeenCalledWith( + expect(atomicWriteFile).toHaveBeenCalledWith( path.join('/mock/home', HOPCODE_DIR, 'mcp-oauth-tokens.json'), expect.stringContaining('test-server'), - { mode: 0o600 }, + { mode: 0o600, forceMode: true, noFollow: true }, ); }); @@ -170,7 +175,7 @@ describe('MCPOAuthTokenStorage', () => { vi.mocked(fs.readFile).mockResolvedValue( JSON.stringify([existingCredentials]), ); - vi.mocked(fs.writeFile).mockResolvedValue(undefined); + vi.mocked(atomicWriteFile).mockResolvedValue(undefined); const newToken: OAuthToken = { ...mockToken, @@ -178,7 +183,7 @@ describe('MCPOAuthTokenStorage', () => { }; await tokenStorage.saveToken('existing-server', newToken); - const writeCall = vi.mocked(fs.writeFile).mock.calls[0]; + const writeCall = vi.mocked(atomicWriteFile).mock.calls[0]; const savedData = JSON.parse( writeCall[1] as string, ) as OAuthCredentials[]; @@ -192,7 +197,7 @@ describe('MCPOAuthTokenStorage', () => { vi.mocked(fs.readFile).mockRejectedValue({ code: 'ENOENT' }); vi.mocked(fs.mkdir).mockResolvedValue(undefined); const writeError = new Error('Disk full'); - vi.mocked(fs.writeFile).mockRejectedValue(writeError); + vi.mocked(atomicWriteFile).mockRejectedValue(writeError); await expect( tokenStorage.saveToken('test-server', mockToken), @@ -247,11 +252,11 @@ describe('MCPOAuthTokenStorage', () => { vi.mocked(fs.readFile).mockResolvedValue( JSON.stringify([credentials1, credentials2]), ); - vi.mocked(fs.writeFile).mockResolvedValue(undefined); + vi.mocked(atomicWriteFile).mockResolvedValue(undefined); await tokenStorage.deleteCredentials('server1'); - const writeCall = vi.mocked(fs.writeFile).mock.calls[0]; + const writeCall = vi.mocked(atomicWriteFile).mock.calls[0]; const savedData = JSON.parse(writeCall[1] as string); expect(savedData).toHaveLength(1); @@ -269,7 +274,7 @@ describe('MCPOAuthTokenStorage', () => { expect(fs.unlink).toHaveBeenCalledWith( path.join('/mock/home', HOPCODE_DIR, 'mcp-oauth-tokens.json'), ); - expect(fs.writeFile).not.toHaveBeenCalled(); + expect(atomicWriteFile).not.toHaveBeenCalled(); }); it('should handle removal of non-existent token gracefully', async () => { @@ -279,7 +284,7 @@ describe('MCPOAuthTokenStorage', () => { await tokenStorage.deleteCredentials('non-existent'); - expect(fs.writeFile).not.toHaveBeenCalled(); + expect(atomicWriteFile).not.toHaveBeenCalled(); expect(fs.unlink).not.toHaveBeenCalled(); }); diff --git a/packages/core/src/mcp/oauth-token-storage.ts b/packages/core/src/mcp/oauth-token-storage.ts index 1b251566b6c..7283849191f 100644 --- a/packages/core/src/mcp/oauth-token-storage.ts +++ b/packages/core/src/mcp/oauth-token-storage.ts @@ -7,6 +7,7 @@ import { promises as fs } from 'node:fs'; import * as path from 'node:path'; import { Storage } from '../config/storage.js'; +import { atomicWriteFile } from '../utils/atomicFileWrite.js'; import { getErrorMessage } from '../utils/errors.js'; import { createDebugLogger } from '../utils/debugLogger.js'; import type { @@ -99,11 +100,11 @@ export class MCPOAuthTokenStorage implements TokenStorage { const tokenFile = this.getTokenFilePath(); try { - await fs.writeFile( - tokenFile, - JSON.stringify(tokenArray, null, 2), - { mode: 0o600 }, // Restrict file permissions - ); + await atomicWriteFile(tokenFile, JSON.stringify(tokenArray, null, 2), { + mode: 0o600, + forceMode: true, + noFollow: true, + }); } catch (error) { debugLogger.error( `Failed to save MCP OAuth token: ${getErrorMessage(error)}`, @@ -179,9 +180,11 @@ export class MCPOAuthTokenStorage implements TokenStorage { // Remove file if no tokens left await fs.unlink(tokenFile); } else { - await fs.writeFile(tokenFile, JSON.stringify(tokenArray, null, 2), { - mode: 0o600, - }); + await atomicWriteFile( + tokenFile, + JSON.stringify(tokenArray, null, 2), + { mode: 0o600, forceMode: true, noFollow: true }, + ); } } catch (error) { debugLogger.error( diff --git a/packages/core/src/mcp/token-storage/file-token-storage.test.ts b/packages/core/src/mcp/token-storage/file-token-storage.test.ts index 00e25aa0b92..d4300907678 100644 --- a/packages/core/src/mcp/token-storage/file-token-storage.test.ts +++ b/packages/core/src/mcp/token-storage/file-token-storage.test.ts @@ -9,6 +9,7 @@ import { promises as fs } from 'node:fs'; import * as path from 'node:path'; import { FileTokenStorage } from './file-token-storage.js'; import type { OAuthCredentials } from './types.js'; +import { atomicWriteFile } from '../../utils/atomicFileWrite.js'; vi.mock('node:fs', () => ({ promises: { @@ -19,6 +20,10 @@ vi.mock('node:fs', () => ({ }, })); +vi.mock('../../utils/atomicFileWrite.js', () => ({ + atomicWriteFile: vi.fn(), +})); + vi.mock('node:os', () => ({ default: { homedir: vi.fn(() => '/home/test'), @@ -121,7 +126,7 @@ describe('FileTokenStorage', () => { ); mockFs.readFile.mockResolvedValue(encryptedData); mockFs.mkdir.mockResolvedValue(undefined); - mockFs.writeFile.mockResolvedValue(undefined); + vi.mocked(atomicWriteFile).mockResolvedValue(undefined); const credentials: OAuthCredentials = { serverName: 'test-server', @@ -138,11 +143,15 @@ describe('FileTokenStorage', () => { path.join('/home/test', '.hopcode'), { recursive: true, mode: 0o700 }, ); - expect(mockFs.writeFile).toHaveBeenCalled(); + expect(atomicWriteFile).toHaveBeenCalled(); - const writeCall = mockFs.writeFile.mock.calls[0]; + const writeCall = vi.mocked(atomicWriteFile).mock.calls[0]; expect(writeCall[1]).toMatch(/^[0-9a-f]+:[0-9a-f]+:[0-9a-f]+$/); - expect(writeCall[2]).toEqual({ mode: 0o600 }); + expect(writeCall[2]).toEqual({ + mode: 0o600, + forceMode: true, + noFollow: true, + }); }); it('should update existing credentials', async () => { @@ -150,7 +159,7 @@ describe('FileTokenStorage', () => { JSON.stringify({ 'existing-server': existingCredentials }), ); mockFs.readFile.mockResolvedValue(encryptedData); - mockFs.writeFile.mockResolvedValue(undefined); + vi.mocked(atomicWriteFile).mockResolvedValue(undefined); const newCredentials: OAuthCredentials = { serverName: 'test-server', @@ -163,14 +172,41 @@ describe('FileTokenStorage', () => { await storage.setCredentials(newCredentials); - expect(mockFs.writeFile).toHaveBeenCalled(); - const writeCall = mockFs.writeFile.mock.calls[0]; - const decrypted = storage['decrypt'](writeCall[1]); + expect(atomicWriteFile).toHaveBeenCalled(); + const writeCall = vi.mocked(atomicWriteFile).mock.calls[0]; + const decrypted = storage['decrypt'](writeCall[1] as string); const saved = JSON.parse(decrypted); expect(saved['existing-server']).toEqual(existingCredentials); expect(saved['test-server'].token.accessToken).toBe('new-token'); }); + + // saveTokens has no try/catch around atomicWriteFile, so disk + // failures (ENOSPC, EROFS, EPERM) propagate to setCredentials + // callers. A regression that silently swallowed the failure or + // left the in-memory token map out of sync with disk would have + // gone undetected — sibling sharedTokenManager.test.ts got the + // same regression test in round 1. + it('should propagate atomicWriteFile failures', async () => { + const encryptedData = storage['encrypt']( + JSON.stringify({ 'existing-server': existingCredentials }), + ); + mockFs.readFile.mockResolvedValue(encryptedData); + mockFs.mkdir.mockResolvedValue(undefined); + vi.mocked(atomicWriteFile).mockRejectedValueOnce( + Object.assign(new Error('ENOSPC: no space left on device'), { + code: 'ENOSPC', + }) as NodeJS.ErrnoException, + ); + + await expect( + storage.setCredentials({ + serverName: 'test-server', + token: { accessToken: 'tok', tokenType: 'Bearer' }, + updatedAt: Date.now(), + }), + ).rejects.toThrow(/ENOSPC/); + }); }); describe('deleteCredentials', () => { @@ -228,20 +264,46 @@ describe('FileTokenStorage', () => { JSON.stringify({ server1: credentials1, server2: credentials2 }), ); mockFs.readFile.mockResolvedValue(encryptedData); - mockFs.writeFile.mockResolvedValue(undefined); + vi.mocked(atomicWriteFile).mockResolvedValue(undefined); await storage.deleteCredentials('server1'); - expect(mockFs.writeFile).toHaveBeenCalled(); + expect(atomicWriteFile).toHaveBeenCalled(); expect(mockFs.unlink).not.toHaveBeenCalled(); - const writeCall = mockFs.writeFile.mock.calls[0]; - const decrypted = storage['decrypt'](writeCall[1]); + const writeCall = vi.mocked(atomicWriteFile).mock.calls[0]; + const decrypted = storage['decrypt'](writeCall[1] as string); const saved = JSON.parse(decrypted); expect(saved['server1']).toBeUndefined(); expect(saved['server2']).toEqual(credentials2); }); + + it('should propagate atomicWriteFile failures', async () => { + const credentials1: OAuthCredentials = { + serverName: 'server1', + token: { accessToken: 'token1', tokenType: 'Bearer' }, + updatedAt: Date.now(), + }; + const credentials2: OAuthCredentials = { + serverName: 'server2', + token: { accessToken: 'token2', tokenType: 'Bearer' }, + updatedAt: Date.now(), + }; + const encryptedData = storage['encrypt']( + JSON.stringify({ server1: credentials1, server2: credentials2 }), + ); + mockFs.readFile.mockResolvedValue(encryptedData); + vi.mocked(atomicWriteFile).mockRejectedValueOnce( + Object.assign(new Error('EROFS: read-only file system'), { + code: 'EROFS', + }) as NodeJS.ErrnoException, + ); + + await expect(storage.deleteCredentials('server1')).rejects.toThrow( + /EROFS/, + ); + }); }); describe('listServers', () => { diff --git a/packages/core/src/mcp/token-storage/file-token-storage.ts b/packages/core/src/mcp/token-storage/file-token-storage.ts index 6483f73e1b9..3c69d9d7470 100644 --- a/packages/core/src/mcp/token-storage/file-token-storage.ts +++ b/packages/core/src/mcp/token-storage/file-token-storage.ts @@ -11,6 +11,7 @@ import * as crypto from 'node:crypto'; import { BaseTokenStorage } from './base-token-storage.js'; import type { OAuthCredentials } from './types.js'; import { Storage } from '../../config/storage.js'; +import { atomicWriteFile } from '../../utils/atomicFileWrite.js'; export class FileTokenStorage extends BaseTokenStorage { private readonly tokenFilePath: string; @@ -100,7 +101,11 @@ export class FileTokenStorage extends BaseTokenStorage { const json = JSON.stringify(data, null, 2); const encrypted = this.encrypt(json); - await fs.writeFile(this.tokenFilePath, encrypted, { mode: 0o600 }); + await atomicWriteFile(this.tokenFilePath, encrypted, { + mode: 0o600, + forceMode: true, + noFollow: true, + }); } async getCredentials(serverName: string): Promise { diff --git a/packages/core/src/memory/dream.ts b/packages/core/src/memory/dream.ts index 3c923cf3a5e..4750236a9d0 100644 --- a/packages/core/src/memory/dream.ts +++ b/packages/core/src/memory/dream.ts @@ -6,6 +6,7 @@ import * as fs from 'node:fs/promises'; import type { Config } from '../config/config.js'; +import { atomicWriteFile } from '../utils/atomicFileWrite.js'; import { getAutoMemoryMetadataPath } from './paths.js'; import { planManagedAutoMemoryDreamByAgent } from './dreamAgentPlanner.js'; import { rebuildManagedAutoMemoryIndex } from './indexer.js'; @@ -122,10 +123,10 @@ async function updateDreamMetadataResult( metadata.lastDreamSessionId = sessionId; metadata.recentSessionIdsSinceDream = []; } - await fs.writeFile( + await atomicWriteFile( metadataPath, `${JSON.stringify(metadata, null, 2)}\n`, - 'utf-8', + { encoding: 'utf-8' }, ); } catch { // Best-effort metadata bump. diff --git a/packages/core/src/memory/extract.ts b/packages/core/src/memory/extract.ts index bc5de399ab0..10aea83afc8 100644 --- a/packages/core/src/memory/extract.ts +++ b/packages/core/src/memory/extract.ts @@ -7,6 +7,7 @@ import * as fs from 'node:fs/promises'; import type { Content } from '@google/genai'; import type { Config } from '../config/config.js'; +import { atomicWriteFile } from '../utils/atomicFileWrite.js'; import { createDebugLogger } from '../utils/debugLogger.js'; import { partToString } from '../utils/partUtils.js'; import { @@ -90,10 +91,10 @@ async function writeExtractCursor( projectRoot: string, cursor: AutoMemoryExtractCursor, ): Promise { - await fs.writeFile( + await atomicWriteFile( getAutoMemoryExtractCursorPath(projectRoot), `${JSON.stringify(cursor, null, 2)}\n`, - 'utf-8', + { encoding: 'utf-8' }, ); } @@ -115,10 +116,10 @@ async function bumpMetadata( metadata.lastExtractionTouchedTopics = touchedTopics; metadata.lastExtractionStatus = touchedTopics.length > 0 ? 'updated' : 'noop'; - await fs.writeFile( + await atomicWriteFile( getAutoMemoryMetadataPath(projectRoot), `${JSON.stringify(metadata, null, 2)}\n`, - 'utf-8', + { encoding: 'utf-8' }, ); } catch { // Scaffold creation already writes metadata; ignore non-critical update errors. diff --git a/packages/core/src/memory/forget.ts b/packages/core/src/memory/forget.ts index 09135a5646a..a95233d4a8f 100644 --- a/packages/core/src/memory/forget.ts +++ b/packages/core/src/memory/forget.ts @@ -7,6 +7,7 @@ import * as fs from 'node:fs/promises'; import type { Content } from '@google/genai'; import type { Config } from '../config/config.js'; +import { atomicWriteFile } from '../utils/atomicFileWrite.js'; import { runSideQuery } from '../utils/sideQuery.js'; import { buildAutoMemoryEntrySearchText, @@ -222,10 +223,10 @@ async function bumpMetadata(projectRoot: string, now: Date): Promise { ); const metadata = JSON.parse(content) as AutoMemoryMetadata; metadata.updatedAt = now.toISOString(); - await fs.writeFile( + await atomicWriteFile( getAutoMemoryMetadataPath(projectRoot), `${JSON.stringify(metadata, null, 2)}\n`, - 'utf-8', + { encoding: 'utf-8' }, ); } catch { // Best-effort metadata bump. @@ -287,10 +288,10 @@ export async function forgetManagedAutoMemoryMatches( } else { const heading = getAutoMemoryBodyHeading(rawBody); const newBody = renderAutoMemoryBody(heading, kept); - await fs.writeFile( + await atomicWriteFile( filePath, `---\n${frontmatter}\n---\n\n${newBody}\n`, - 'utf-8', + { encoding: 'utf-8' }, ); } diff --git a/packages/core/src/memory/indexer.ts b/packages/core/src/memory/indexer.ts index d085523d1b2..45fb21cdea3 100644 --- a/packages/core/src/memory/indexer.ts +++ b/packages/core/src/memory/indexer.ts @@ -5,6 +5,7 @@ */ import * as fs from 'node:fs/promises'; +import { atomicWriteFile } from '../utils/atomicFileWrite.js'; import { getAutoMemoryIndexPath, getAutoMemoryMetadataPath } from './paths.js'; import { scanAutoMemoryTopicDocuments, @@ -78,6 +79,8 @@ export async function rebuildManagedAutoMemoryIndex( readAutoMemoryMetadata(projectRoot), ]); const content = buildManagedAutoMemoryIndex(docs, metadata); - await fs.writeFile(getAutoMemoryIndexPath(projectRoot), content, 'utf-8'); + await atomicWriteFile(getAutoMemoryIndexPath(projectRoot), content, { + encoding: 'utf-8', + }); return content; } diff --git a/packages/core/src/memory/manager.ts b/packages/core/src/memory/manager.ts index c405c954c8f..84beff67040 100644 --- a/packages/core/src/memory/manager.ts +++ b/packages/core/src/memory/manager.ts @@ -39,6 +39,7 @@ import { randomUUID } from 'node:crypto'; import type { Content, Part } from '@google/genai'; import type { Config } from '../config/config.js'; import { Storage } from '../config/storage.js'; +import { atomicWriteFile } from '../utils/atomicFileWrite.js'; import { createDebugLogger } from '../utils/debugLogger.js'; import { logMemoryDream, @@ -288,10 +289,10 @@ async function writeDreamMetadata( projectRoot: string, metadata: AutoMemoryMetadata, ): Promise { - await fs.writeFile( + await atomicWriteFile( getAutoMemoryMetadataPath(projectRoot), `${JSON.stringify(metadata, null, 2)}\n`, - 'utf-8', + { encoding: 'utf-8' }, ); } diff --git a/packages/core/src/memory/skillReviewAgentPlanner.ts b/packages/core/src/memory/skillReviewAgentPlanner.ts index 5a3c2b564e5..aec89f8ff65 100644 --- a/packages/core/src/memory/skillReviewAgentPlanner.ts +++ b/packages/core/src/memory/skillReviewAgentPlanner.ts @@ -147,7 +147,7 @@ async function evaluateScopedDecision( } // Restrict to the canonical `/SKILL.md` slot. Without this, // the agent could write auxiliary files (notes, README, attachments) - // anywhere under `.qwen/skills/**` — SkillManager would ignore them + // anywhere under `.hopcode/skills/**` — SkillManager would ignore them // but they still pollute the directory. if (path.basename(ctx.filePath) !== SKILL_FILE_NAME) { return 'deny'; @@ -270,7 +270,7 @@ function buildAgentHistory(history: Content[]): Content[] { /** * Enumerate directories under the project skills root that contain a * SKILL.md. Returned names are the directory basenames (the same identifier - * the agent uses when picking `.qwen/skills//SKILL.md`). + * the agent uses when picking `.hopcode/skills//SKILL.md`). * * Best-effort: any read error (ENOENT, EACCES, ...) returns `[]` so a * temporarily-unreadable skills dir downgrades to "no enumeration" rather diff --git a/packages/core/src/permissions/permission-manager.test.ts b/packages/core/src/permissions/permission-manager.test.ts index 472c08f7d92..21dc7862338 100644 --- a/packages/core/src/permissions/permission-manager.test.ts +++ b/packages/core/src/permissions/permission-manager.test.ts @@ -1002,7 +1002,7 @@ describe('PermissionManager', () => { // produce a hard 'deny' from resolveDefaultPermission. Before the fix // the L4 default branch returned 'deny' for any command containing // $(), backticks, <(), or >(), which: - // 1. could not be overridden by YOLO mode, and + // 1. could not be overridden by IZN mode, and // 2. fired inconsistently — only when hasRelevantRules() happened to // be true (e.g. a compound command where another sub-command // matched an unrelated allow rule). Standalone substitution diff --git a/packages/core/src/permissions/permission-manager.ts b/packages/core/src/permissions/permission-manager.ts index a18cd45ff51..a0e59ea1b26 100644 --- a/packages/core/src/permissions/permission-manager.ts +++ b/packages/core/src/permissions/permission-manager.ts @@ -400,10 +400,10 @@ export class PermissionManager { * * Command substitution ($(), ``, <(), >()) is NOT a hard deny here — it * falls through to 'ask' along with every other non-read-only command, so - * the user (or YOLO mode) can decide. The user-facing warning is surfaced + * the user (or IZN mode) can decide. The user-facing warning is surfaced * by ShellToolInvocation.getConfirmationDetails so the confirmation prompt * still flags the substitution clearly. See issue #4093 for why a hard - * deny here is wrong: it (a) cannot be overridden by YOLO mode and (b) + * deny here is wrong: it (a) cannot be overridden by IZN mode and (b) * fires inconsistently based on whether the PermissionManager has * "relevant" rules for the surrounding compound command. * diff --git a/packages/core/src/services/gitWorktreeService.symlinks.integ.test.ts b/packages/core/src/services/gitWorktreeService.symlinks.integ.test.ts index b7caa3c938c..78bc801aabc 100644 --- a/packages/core/src/services/gitWorktreeService.symlinks.integ.test.ts +++ b/packages/core/src/services/gitWorktreeService.symlinks.integ.test.ts @@ -220,24 +220,24 @@ describe('GitWorktreeService.createUserWorktree() — symlinkDirectories', () => expect(wrote).toBe(false); }); - it('rejects paths inside .qwen (security guard)', async () => { - // `.qwen` is CLI metadata: symlinking `.qwen/worktrees` would create - // a worktrees-inside-worktrees loop; symlinking `.qwen/projects` or - // `.qwen/tmp` would alias session metadata users have no legitimate + it('rejects paths inside .hopcode (security guard)', async () => { + // `.hopcode` is CLI metadata: symlinking `.hopcode/worktrees` would create + // a worktrees-inside-worktrees loop; symlinking `.hopcode/projects` or + // `.hopcode/tmp` would alias session metadata users have no legitimate // reason to share across worktrees. Guard rejects the whole subtree. - await fs.mkdir(path.join(repoRoot, '.qwen'), { recursive: true }); - await fs.writeFile(path.join(repoRoot, '.qwen', 'projects'), 'data'); + await fs.mkdir(path.join(repoRoot, '.hopcode'), { recursive: true }); + await fs.writeFile(path.join(repoRoot, '.hopcode', 'projects'), 'data'); const service = new GitWorktreeService(repoRoot); - const result = await service.createUserWorktree('reject-qwen', 'main', { - symlinkDirectories: ['.qwen/projects'], + const result = await service.createUserWorktree('reject-hopcode', 'main', { + symlinkDirectories: ['.hopcode/projects'], }); expect(result.success).toBe(true); const wt = result.worktree!.path; - // No symlink at /.qwen/projects. + // No symlink at /.hopcode/projects. const wrote = await fs - .lstat(path.join(wt, '.qwen', 'projects')) + .lstat(path.join(wt, '.hopcode', 'projects')) .then((s) => s.isSymbolicLink()) .catch(() => false); expect(wrote).toBe(false); @@ -320,9 +320,9 @@ describe('GitWorktreeService.createUserWorktree() — symlinkDirectories', () => } }); - it('refuses sources whose realpath escapes the repo root or lands in .git/.qwen (committed-symlink bypass)', async () => { + it('refuses sources whose realpath escapes the repo root or lands in .git/.hopcode (committed-symlink bypass)', async () => { // Round-7 security fix: the lexical `isWithinRoot(sourceAbs, …)` and - // `.git`/`.qwen` blocklist checks DON'T resolve symlinks, so a symlink + // `.git`/`.hopcode` blocklist checks DON'T resolve symlinks, so a symlink // committed into the source repo HEAD (or set up out-of-band by a // malicious post-install script / repo tarball) can chain through to // arbitrary targets. Two flavours covered here: diff --git a/packages/core/src/services/gitWorktreeService.ts b/packages/core/src/services/gitWorktreeService.ts index f0612813173..9f5835d15d9 100644 --- a/packages/core/src/services/gitWorktreeService.ts +++ b/packages/core/src/services/gitWorktreeService.ts @@ -1102,8 +1102,8 @@ export class GitWorktreeService { * repo. * * Used by Phase D-1's re-attach path: when `--worktree foo` is passed - * and `/.qwen/worktrees/foo` already exists on disk, we - * verify it really IS a Qwen-managed worktree of the current repo (not + * and `/.hopcode/worktrees/foo` already exists on disk, we + * verify it really IS a HopCode-managed worktree of the current repo (not * a standalone `git init` someone dropped at that path) before * assuming it's safe to chdir into. Returning the HEAD SHA in the * same call avoids a second subprocess to recapture it after chdir. @@ -1123,7 +1123,7 @@ export class GitWorktreeService { * 4. `--show-toplevel` → git's idea of the worktree top. For a real * linked worktree this equals `worktreePath`; for a plain * directory living UNDER the main repo (e.g. `mkdir - * /.qwen/worktrees/foo`) git walks up to the outer `.git` + * /.hopcode/worktrees/foo`) git walks up to the outer `.git` * and returns the OUTER repo's root — which would otherwise pass * the common-dir check and let us "re-attach" to a non-worktree * directory. Compare paths to reject this. @@ -1642,7 +1642,7 @@ export class GitWorktreeService { return; } const gitDirAbs = path.join(repoRootAbs, '.git'); - const qwenDirAbs = path.join(repoRootAbs, '.qwen'); + const hopcodeDirAbs = path.join(repoRootAbs, '.hopcode'); // Same canonical-vs-canonical requirement for the dest side. The // worktree was just created by `git worktree add`, so the path // should exist; fall back to the input path on realpath error so a @@ -1699,14 +1699,14 @@ export class GitWorktreeService { // Refuse to symlink git-internal paths into the worktree. `.git` // would silently break commits / status / diff inside the // worktree (the worktree's own gitlink file points at the parent - // common-dir, and a symlink would shadow it). The whole `.qwen` - // tree is also off-limits: linking `.qwen` (parent) would - // recursively pull `.qwen/worktrees` into the new worktree, - // recreating the loop; linking `.qwen/worktrees` directly - // creates the same loop more obviously; and `.qwen/projects` - // / `.qwen/tmp` are CLI metadata users have no legitimate + // common-dir, and a symlink would shadow it). The whole `.hopcode` + // tree is also off-limits: linking `.hopcode` (parent) would + // recursively pull `.hopcode/worktrees` into the new worktree, + // recreating the loop; linking `.hopcode/worktrees` directly + // creates the same loop more obviously; and `.hopcode/projects` + // / `.hopcode/tmp` are CLI metadata users have no legitimate // reason to share across worktrees. - // `gitDirAbs` / `qwenDirAbs` are canonical (derived from the + // `gitDirAbs` / `hopcodeDirAbs` are canonical (derived from the // realpath'd `repoRootAbs` hoisted above the loop), so these // comparisons stay consistent with the post-stat realpath check. if (isWithinRoot(sourceAbs, gitDirAbs)) { @@ -1715,10 +1715,10 @@ export class GitWorktreeService { ); continue; } - if (isWithinRoot(sourceAbs, qwenDirAbs)) { + if (isWithinRoot(sourceAbs, hopcodeDirAbs)) { debugLogger.warn( `symlinkConfiguredDirectories: refusing path "${raw}" — ` + - `the .qwen tree is CLI-managed; symlinking any of it could ` + + `the .hopcode tree is CLI-managed; symlinking any of it could ` + `create a worktrees-inside-worktrees loop or alias CLI metadata.`, ); continue; @@ -1748,7 +1748,7 @@ export class GitWorktreeService { // containment + blocklist checks against the realpath. The lexical // checks above only see `path.resolve(repoRoot, raw)` — they can't // tell that `/node_modules` is actually a symlink chaining - // into `.git`, an outside dir, or `.qwen`. Without this step a + // into `.git`, an outside dir, or `.hopcode`. Without this step a // committed-or-out-of-band source symlink bypasses every guard the // lexical loop set up. Use the realpath as the symlink target so // the new link points canonically rather than preserving the chain. @@ -1773,9 +1773,9 @@ export class GitWorktreeService { ); continue; } - if (isWithinRoot(realSource, qwenDirAbs)) { + if (isWithinRoot(realSource, hopcodeDirAbs)) { debugLogger.warn( - `symlinkConfiguredDirectories: refusing path "${raw}" — real source ${realSource} resolves inside .qwen`, + `symlinkConfiguredDirectories: refusing path "${raw}" — real source ${realSource} resolves inside .hopcode`, ); continue; } diff --git a/packages/core/src/services/memoryDiagnosticsDumper.ts b/packages/core/src/services/memoryDiagnosticsDumper.ts index 2ce8f3a6934..55490f8356b 100644 --- a/packages/core/src/services/memoryDiagnosticsDumper.ts +++ b/packages/core/src/services/memoryDiagnosticsDumper.ts @@ -1,6 +1,6 @@ /** * @license - * Copyright 2026 Qwen Team + * Copyright 2026 HopCode Team * SPDX-License-Identifier: Apache-2.0 */ diff --git a/packages/core/src/skills/skill-manager.test.ts b/packages/core/src/skills/skill-manager.test.ts index 73620664354..06f4a1da896 100644 --- a/packages/core/src/skills/skill-manager.test.ts +++ b/packages/core/src/skills/skill-manager.test.ts @@ -164,8 +164,8 @@ describe('SkillManager', () => { if (yamlString.includes('name: shared-skill')) { const desc = yamlString.includes('From hopcode dir') ? 'From hopcode dir' - : yamlString.includes('From agent dir') - ? 'From agent dir' + : yamlString.includes('From agents dir') + ? 'From agents dir' : 'A shared skill'; return { name: 'shared-skill', description: desc }; } @@ -626,21 +626,17 @@ You are a helpful assistant. beforeEach(() => { // Mock directory listing based on path to handle multiple base dirs per level. // Use path.join to construct expected paths so separators match on all platforms. - const projectHopcodeSkillsDir = path.join( + const projectQwenSkillsDir = path.join( '/test/project', '.hopcode', 'skills', ); - const userHopcodeSkillsDir = path.join( - '/home/user', - '.hopcode', - 'skills', - ); + const userQwenSkillsDir = path.join('/home/user', '.hopcode', 'skills'); // eslint-disable-next-line @typescript-eslint/no-explicit-any vi.mocked(fs.readdir).mockImplementation((dirPath: any) => { const pathStr = String(dirPath); - if (pathStr === projectHopcodeSkillsDir) { + if (pathStr === projectQwenSkillsDir) { return Promise.resolve([ { name: 'skill1', @@ -662,7 +658,7 @@ You are a helpful assistant. }, ] as unknown as Awaited>); } - if (pathStr === userHopcodeSkillsDir) { + if (pathStr === userQwenSkillsDir) { return Promise.resolve([ { name: 'skill3', @@ -744,13 +740,13 @@ Skill 3 content`); mockParseYaml.mockImplementation((yamlString: string) => yaml.parse(yamlString), ); - const projectHopcodeSkillsDir = path.join( + const projectQwenSkillsDir = path.join( '/test/project', '.hopcode', 'skills', ); vi.mocked(fs.readdir).mockImplementation((dirPath) => { - if (String(dirPath) === projectHopcodeSkillsDir) { + if (String(dirPath) === projectQwenSkillsDir) { return Promise.resolve( ['high', 'unset-beta', 'unset-alpha', 'negative'].map((name) => ({ name, @@ -842,7 +838,7 @@ Body`); it('should deduplicate same-name skills across provider dirs within a level', async () => { // Override readdir to return the same skill name from both .hopcode and .agents dirs vi.mocked(fs.readdir).mockReset(); - const projectHopcodeDir = path.join( + const projectHopCodeDir = path.join( '/test/project', '.hopcode', 'skills', @@ -852,7 +848,7 @@ Body`); // eslint-disable-next-line @typescript-eslint/no-explicit-any vi.mocked(fs.readdir).mockImplementation((dirPath: any) => { const pathStr = String(dirPath); - if (pathStr === projectHopcodeDir) { + if (pathStr === projectHopCodeDir) { return Promise.resolve([ { name: 'shared-skill', @@ -984,8 +980,7 @@ Body`); function mockReaddirForLevels(levels: Set) { vi.mocked(fs.readdir).mockImplementation((dirPath) => { const pathStr = String(dirPath); - const isBundled = - pathStr.endsWith(bundledDirSegment) && !pathStr.includes('.hopcode'); + const isBundled = pathStr.endsWith(bundledDirSegment); const isProject = pathStr.includes(projectDirSegment) && pathStr.startsWith(projectPrefix); @@ -1430,23 +1425,16 @@ Body. // otherwise the user copy's globs activate the visible (project) // skill, even when the touched file is outside the project skill's // declared paths. - const projectHopcodeSkillsDir = path.join( + const projectQwenSkillsDir = path.join( '/test/project', '.hopcode', 'skills', ); - const userHopcodeSkillsDir = path.join( - '/home/user', - '.hopcode', - 'skills', - ); + const userQwenSkillsDir = path.join('/home/user', '.hopcode', 'skills'); // eslint-disable-next-line @typescript-eslint/no-explicit-any vi.mocked(fs.readdir).mockImplementation((dirPath: any) => { const pathStr = String(dirPath); - if ( - pathStr === projectHopcodeSkillsDir || - pathStr === userHopcodeSkillsDir - ) { + if (pathStr === projectQwenSkillsDir || pathStr === userQwenSkillsDir) { return Promise.resolve([ { name: 'foo', @@ -1463,7 +1451,7 @@ Body. vi.mocked(fs.access).mockResolvedValue(undefined); vi.mocked(fs.readFile).mockImplementation((filePath) => { const pathStr = String(filePath); - if (pathStr.startsWith(projectHopcodeSkillsDir)) { + if (pathStr.startsWith(projectQwenSkillsDir)) { return Promise.resolve(`--- name: foo description: A test skill @@ -1474,7 +1462,7 @@ paths: Project body. `); } - if (pathStr.startsWith(userHopcodeSkillsDir)) { + if (pathStr.startsWith(userQwenSkillsDir)) { return Promise.resolve(`--- name: foo description: A test skill diff --git a/packages/core/src/tools/computer-use/install-state.test.ts b/packages/core/src/tools/computer-use/install-state.test.ts index fb9a16900eb..18889e0b8fd 100644 --- a/packages/core/src/tools/computer-use/install-state.test.ts +++ b/packages/core/src/tools/computer-use/install-state.test.ts @@ -65,7 +65,7 @@ describe('install-state', () => { it('installStatePathFor returns correct path', () => { const path = installStatePathFor(tmpHome); expect(path).toBe( - pathJoin(tmpHome, '.qwen', 'computer-use', 'installed.json'), + pathJoin(tmpHome, '.hopcode', 'computer-use', 'installed.json'), ); }); }); diff --git a/packages/core/src/tools/computer-use/install-state.ts b/packages/core/src/tools/computer-use/install-state.ts index a3cf552733b..faea12d4d94 100644 --- a/packages/core/src/tools/computer-use/install-state.ts +++ b/packages/core/src/tools/computer-use/install-state.ts @@ -20,7 +20,7 @@ export interface InstallState { * point at a temp directory. */ export function installStatePathFor(home: string = homedir()): string { - return join(home, '.qwen', 'computer-use', 'installed.json'); + return join(home, '.hopcode', 'computer-use', 'installed.json'); } export async function loadInstallState( diff --git a/packages/core/src/tools/monitor.test.ts b/packages/core/src/tools/monitor.test.ts index 93d3183eda3..c73cc824159 100644 --- a/packages/core/src/tools/monitor.test.ts +++ b/packages/core/src/tools/monitor.test.ts @@ -1,4 +1,4 @@ -/** +/** * @license * Copyright 2025 HopCode * SPDX-License-Identifier: Apache-2.0 @@ -419,7 +419,7 @@ describe('MonitorTool', () => { // Command substitution previously returned 'deny' here. Per #4093 it // now falls through to 'ask' (matching ShellToolInvocation and // PermissionManager.resolveDefaultPermission); the substitution - // warning is surfaced via getConfirmationDetails. YOLO mode can now + // warning is surfaced via getConfirmationDetails. IZN mode can now // override the prompt; before this change it could not. it('asks for command substitution before confirmation', async () => { const invocation = createInvocation({ diff --git a/packages/core/src/tools/monitor.ts b/packages/core/src/tools/monitor.ts index bec76a01f8a..b011c749111 100644 --- a/packages/core/src/tools/monitor.ts +++ b/packages/core/src/tools/monitor.ts @@ -1,4 +1,4 @@ -/** +/** * @license * Copyright 2025 HopCode * SPDX-License-Identifier: Apache-2.0 @@ -174,12 +174,12 @@ class MonitorToolInvocation extends BaseToolInvocation< // Command substitution ($(), ``, <(), >()) is NOT a hard deny here — // it falls through to 'ask' along with every other non-read-only - // command, so the user (or YOLO mode) can decide. The user-facing + // command, so the user (or IZN mode) can decide. The user-facing // warning is surfaced by getConfirmationDetails below so the // confirmation prompt still flags the substitution clearly. This // mirrors the same reasoning applied to ShellToolInvocation and // PermissionManager.resolveDefaultPermission in #4093: a hard deny - // here (a) cannot be overridden by YOLO and (b) was inconsistent + // here (a) cannot be overridden by IZN and (b) was inconsistent // with the shell-tool path. Monitor still maintains a separate // permission boundary (Monitor(...) rules don't share with // Bash(...) — see comment in getConfirmationDetails); only the diff --git a/packages/core/src/tools/notebook-edit.test.ts b/packages/core/src/tools/notebook-edit.test.ts index 0ceda528a03..dc727b94e13 100644 --- a/packages/core/src/tools/notebook-edit.test.ts +++ b/packages/core/src/tools/notebook-edit.test.ts @@ -691,7 +691,7 @@ describe('NotebookEditTool', () => { ).toThrow(/additional properties|modified_notebook_content/i); }); - it('rejects qwenignored notebooks during validation', () => { + it('rejects hopcodeignored notebooks during validation', () => { fs.writeFileSync( path.join(tempDir, '.hopcodeignore'), '*.ipynb\n', diff --git a/packages/core/src/tools/shell.ts b/packages/core/src/tools/shell.ts index ef1db4e48b6..2d8a85c99e1 100644 --- a/packages/core/src/tools/shell.ts +++ b/packages/core/src/tools/shell.ts @@ -1482,7 +1482,7 @@ export class ShellToolInvocation extends BaseToolInvocation< // Flag command substitution ($(), backticks, <(), >()) so the user // sees a visible warning in the confirmation dialog. We surface this // as an informational warning rather than denying outright; the deny - // path was inconsistent and could not be overridden by YOLO mode + // path was inconsistent and could not be overridden by IZN mode // (see issue #4093). Substitution is detected on both the stripped // and original command so wrappers like `bash -c "..."` are checked // along with their inner contents. diff --git a/packages/core/src/tools/todoWrite.test.ts b/packages/core/src/tools/todoWrite.test.ts index a7b5d174558..f34e4aa4396 100644 --- a/packages/core/src/tools/todoWrite.test.ts +++ b/packages/core/src/tools/todoWrite.test.ts @@ -14,13 +14,19 @@ import * as path from 'node:path'; import type { Config } from '../config/config.js'; import type { AggregatedHookResult } from '../hooks/hookAggregator.js'; import { Storage } from '../config/storage.js'; +import { atomicWriteFile } from '../utils/atomicFileWrite.js'; // Mock fs modules vi.mock('fs/promises'); vi.mock('fs'); +vi.mock('../utils/atomicFileWrite.js', () => ({ + atomicWriteFile: vi.fn(), +})); + const mockFs = vi.mocked(fs); const mockFsSync = vi.mocked(fsSync); +const mockAtomicWrite = vi.mocked(atomicWriteFile); describe('TodoWriteTool', () => { let tool: TodoWriteTool; @@ -143,7 +149,7 @@ describe('TodoWriteTool', () => { enoentError.code = 'ENOENT'; mockFs.readFile.mockRejectedValue(enoentError); mockFs.mkdir.mockResolvedValue(undefined); - mockFs.writeFile.mockResolvedValue(undefined); + mockAtomicWrite.mockResolvedValue(undefined); const invocation = tool.build(params); const result = await invocation.execute(mockAbortSignal); @@ -161,10 +167,10 @@ describe('TodoWriteTool', () => { { id: '2', content: 'Task 2', status: 'in_progress' }, ], }); - expect(mockFs.writeFile).toHaveBeenCalledWith( + expect(mockAtomicWrite).toHaveBeenCalledWith( expect.stringContaining('test-session-123.json'), expect.stringContaining('"todos"'), - 'utf-8', + { encoding: 'utf-8' }, ); }); @@ -185,7 +191,7 @@ describe('TodoWriteTool', () => { JSON.stringify({ todos: existingTodos }), ); mockFs.mkdir.mockResolvedValue(undefined); - mockFs.writeFile.mockResolvedValue(undefined); + mockAtomicWrite.mockResolvedValue(undefined); const invocation = tool.build(params); const result = await invocation.execute(mockAbortSignal); @@ -203,10 +209,10 @@ describe('TodoWriteTool', () => { { id: '2', content: 'New Task', status: 'pending' }, ], }); - expect(mockFs.writeFile).toHaveBeenCalledWith( + expect(mockAtomicWrite).toHaveBeenCalledWith( expect.stringContaining('test-session-123.json'), expect.stringMatching(/"Updated Task"/), - 'utf-8', + { encoding: 'utf-8' }, ); }); @@ -223,7 +229,7 @@ describe('TodoWriteTool', () => { enoentError.code = 'ENOENT'; mockFs.readFile.mockRejectedValue(enoentError); mockFs.mkdir.mockResolvedValue(undefined); - mockFs.writeFile.mockRejectedValue(new Error('Write failed')); + mockAtomicWrite.mockRejectedValue(new Error('Write failed')); const invocation = tool.build(params); const result = await invocation.execute(mockAbortSignal); @@ -241,7 +247,7 @@ describe('TodoWriteTool', () => { }; mockFs.mkdir.mockResolvedValue(undefined); - mockFs.writeFile.mockResolvedValue(undefined); + mockAtomicWrite.mockResolvedValue(undefined); // Mock readTodosFromFile returning existing todos mockFs.readFile.mockResolvedValue( JSON.stringify({ @@ -260,10 +266,10 @@ describe('TodoWriteTool', () => { type: 'todo_list', todos: [], }); - expect(mockFs.writeFile).toHaveBeenCalledWith( + expect(mockAtomicWrite).toHaveBeenCalledWith( expect.stringContaining('test-session-123.json'), expect.stringContaining('"todos"'), - 'utf-8', + { encoding: 'utf-8' }, ); }); @@ -312,7 +318,7 @@ describe('TodoWriteTool', () => { HookPhase.Validation, mockAbortSignal, ); - expect(mockFs.writeFile).not.toHaveBeenCalled(); + expect(mockAtomicWrite).not.toHaveBeenCalled(); expect(result.llmContent).toContain( 'Todo creation blocked: Creation denied', ); @@ -369,7 +375,7 @@ describe('TodoWriteTool', () => { HookPhase.Validation, mockAbortSignal, ); - expect(mockFs.writeFile).not.toHaveBeenCalled(); + expect(mockAtomicWrite).not.toHaveBeenCalled(); expect(result.llmContent).toContain( 'Todo completion blocked: Completion denied', ); @@ -421,12 +427,12 @@ describe('TodoWriteTool', () => { enoentError.code = 'ENOENT'; mockFs.readFile.mockRejectedValue(enoentError); mockFs.mkdir.mockResolvedValue(undefined); - mockFs.writeFile.mockResolvedValue(undefined); + mockAtomicWrite.mockResolvedValue(undefined); const invocation = tool.build(params); const result = await invocation.execute(mockAbortSignal); - expect(mockFs.writeFile).toHaveBeenCalled(); + expect(mockAtomicWrite).toHaveBeenCalled(); expect(mockHookSystem.fireTodoCreatedEvent).toHaveBeenNthCalledWith( 1, '1', @@ -511,7 +517,7 @@ describe('TodoWriteTool', () => { releaseSlowHook?.(); const result = await executionPromise; - expect(mockFs.writeFile).not.toHaveBeenCalled(); + expect(mockAtomicWrite).not.toHaveBeenCalled(); expect(result.llmContent).toContain( 'Todo creation blocked: Second todo denied', ); @@ -548,12 +554,12 @@ describe('TodoWriteTool', () => { enoentError.code = 'ENOENT'; mockFs.readFile.mockRejectedValue(enoentError); mockFs.mkdir.mockResolvedValue(undefined); - mockFs.writeFile.mockResolvedValue(undefined); + mockAtomicWrite.mockResolvedValue(undefined); const invocation = tool.build(params); const result = await invocation.execute(mockAbortSignal); - expect(mockFs.writeFile).toHaveBeenCalled(); + expect(mockAtomicWrite).toHaveBeenCalled(); expect(result.llmContent).toContain( 'Todos have been modified successfully', ); @@ -618,12 +624,12 @@ describe('TodoWriteTool', () => { enoentError.code = 'ENOENT'; mockFs.readFile.mockRejectedValue(enoentError); mockFs.mkdir.mockResolvedValue(undefined); - mockFs.writeFile.mockResolvedValue(undefined); + mockAtomicWrite.mockResolvedValue(undefined); const invocation = tool.build(params); const result = await invocation.execute(mockAbortSignal); - expect(mockFs.writeFile).toHaveBeenCalled(); + expect(mockAtomicWrite).toHaveBeenCalled(); expect(postWriteStarted).toEqual(['1', '2']); expect(postWriteReleaseCount).toBe(2); expect(result.llmContent).toContain( @@ -683,7 +689,7 @@ describe('TodoWriteTool', () => { }); }); -describe('TodoWriteTool ? runtime output directory', () => { +describe('TodoWriteTool – runtime output directory', () => { let tool: TodoWriteTool; let mockAbortSignal: AbortSignal; let mockConfig: Config; @@ -724,13 +730,13 @@ describe('TodoWriteTool ? runtime output directory', () => { enoentError.code = 'ENOENT'; mockFs.readFile.mockRejectedValue(enoentError); mockFs.mkdir.mockResolvedValue(undefined); - mockFs.writeFile.mockResolvedValue(undefined); + mockAtomicWrite.mockResolvedValue(undefined); const invocation = tool.build(params); await invocation.execute(mockAbortSignal); // Verify the file path starts with the custom runtime dir - const writePath = mockFs.writeFile.mock.calls[0]?.[0] as string; + const writePath = mockAtomicWrite.mock.calls[0]?.[0] as string; expect(writePath).toContain(path.join(customRuntimeDir, 'todos')); expect(writePath).toContain('runtime-session.json'); }); @@ -748,12 +754,12 @@ describe('TodoWriteTool ? runtime output directory', () => { enoentError.code = 'ENOENT'; mockFs.readFile.mockRejectedValue(enoentError); mockFs.mkdir.mockResolvedValue(undefined); - mockFs.writeFile.mockResolvedValue(undefined); + mockAtomicWrite.mockResolvedValue(undefined); const invocation = tool.build(params); await invocation.execute(mockAbortSignal); - const writePath = mockFs.writeFile.mock.calls[0]?.[0] as string; + const writePath = mockAtomicWrite.mock.calls[0]?.[0] as string; expect(writePath).toContain(path.join(envRuntimeDir, 'todos')); }); @@ -767,12 +773,12 @@ describe('TodoWriteTool ? runtime output directory', () => { enoentError.code = 'ENOENT'; mockFs.readFile.mockRejectedValue(enoentError); mockFs.mkdir.mockResolvedValue(undefined); - mockFs.writeFile.mockResolvedValue(undefined); + mockAtomicWrite.mockResolvedValue(undefined); const invocation = tool.build(params); await invocation.execute(mockAbortSignal); - const writePath = mockFs.writeFile.mock.calls[0]?.[0] as string; + const writePath = mockAtomicWrite.mock.calls[0]?.[0] as string; expect(writePath).toContain(path.join('.hopcode', 'todos')); }); diff --git a/packages/core/src/tools/todoWrite.ts b/packages/core/src/tools/todoWrite.ts index 83580ca618d..ee2168b1d98 100644 --- a/packages/core/src/tools/todoWrite.ts +++ b/packages/core/src/tools/todoWrite.ts @@ -14,6 +14,7 @@ import * as path from 'path'; import type { Config } from '../config/config.js'; import { Storage } from '../config/storage.js'; import { ToolDisplayNames, ToolNames } from './tool-names.js'; +import { atomicWriteFile } from '../utils/atomicFileWrite.js'; import { createDebugLogger } from '../utils/debugLogger.js'; import { detectTodoChanges, HookPhase, type TodoItem } from '../hooks/types.js'; export type { TodoItem } from '../hooks/types.js'; @@ -284,7 +285,9 @@ async function writeTodosToFile( sessionId: sessionId || 'default', }; - await fs.writeFile(todoFilePath, JSON.stringify(data, null, 2), 'utf-8'); + await atomicWriteFile(todoFilePath, JSON.stringify(data, null, 2), { + encoding: 'utf-8', + }); } function createBlockedTodoResult( diff --git a/packages/core/src/utils/atomicFileWrite.test.ts b/packages/core/src/utils/atomicFileWrite.test.ts index 596d510ceac..124b4694bf8 100644 --- a/packages/core/src/utils/atomicFileWrite.test.ts +++ b/packages/core/src/utils/atomicFileWrite.test.ts @@ -1,14 +1,21 @@ /** * @license - * Copyright 2026 HopCode Team Team + * Copyright 2025 HopCode Team * SPDX-License-Identifier: Apache-2.0 */ +import * as fsSync from 'node:fs'; import * as fs from 'node:fs/promises'; import * as path from 'node:path'; import * as os from 'node:os'; -import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import { atomicWriteFile, atomicWriteJSON } from './atomicFileWrite.js'; +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { + atomicWriteFile, + atomicWriteFileSync, + atomicWriteJSON, + renameWithRetry, + renameWithRetrySync, +} from './atomicFileWrite.js'; describe('atomicWriteJSON', () => { let tmpDir: string; @@ -426,3 +433,1193 @@ describe('atomicWriteFile', () => { }, ); }); + +describe('atomicWriteFileSync', () => { + let tmpDir: string; + + beforeEach(async () => { + tmpDir = await fs.mkdtemp( + path.join(os.tmpdir(), 'atomic-write-sync-test-'), + ); + }); + + afterEach(async () => { + await fs.rm(tmpDir, { recursive: true, force: true }); + }); + + it('should write string content to a new file', () => { + const filePath = path.join(tmpDir, 'test.txt'); + atomicWriteFileSync(filePath, 'hello sync'); + + expect(fsSync.readFileSync(filePath, 'utf-8')).toBe('hello sync'); + }); + + it('should write Buffer content to a new file', () => { + const filePath = path.join(tmpDir, 'test.bin'); + const buf = Buffer.from([0xca, 0xfe, 0xba, 0xbe]); + atomicWriteFileSync(filePath, buf); + + expect(fsSync.readFileSync(filePath)).toEqual(buf); + }); + + it.skipIf(process.platform === 'win32')( + 'should preserve existing file permissions', + () => { + const filePath = path.join(tmpDir, 'test.txt'); + fsSync.writeFileSync(filePath, 'original'); + fsSync.chmodSync(filePath, 0o600); + + atomicWriteFileSync(filePath, 'updated'); + + expect(fsSync.statSync(filePath).mode & 0o777).toBe(0o600); + expect(fsSync.readFileSync(filePath, 'utf-8')).toBe('updated'); + }, + ); + + it.skipIf(process.platform === 'win32')( + 'should apply explicit mode option for new files', + () => { + const filePath = path.join(tmpDir, 'secret.txt'); + atomicWriteFileSync(filePath, 'secret', { mode: 0o600 }); + + expect(fsSync.statSync(filePath).mode & 0o777).toBe(0o600); + }, + ); + + it('should not leave temp files on success', () => { + const filePath = path.join(tmpDir, 'test.txt'); + atomicWriteFileSync(filePath, 'content'); + + expect(fsSync.readdirSync(tmpDir)).toEqual(['test.txt']); + }); + + it('should clean up temp file when write fails', () => { + const filePath = path.join(tmpDir, 'nonexistent', 'test.txt'); + expect(() => atomicWriteFileSync(filePath, 'data')).toThrow(); + + expect(fsSync.readdirSync(tmpDir)).toEqual([]); + }); + + it('should overwrite existing file atomically', () => { + const filePath = path.join(tmpDir, 'test.txt'); + atomicWriteFileSync(filePath, 'v1'); + atomicWriteFileSync(filePath, 'v2'); + + expect(fsSync.readFileSync(filePath, 'utf-8')).toBe('v2'); + }); + + it('should respect encoding option', () => { + const filePath = path.join(tmpDir, 'test.txt'); + atomicWriteFileSync(filePath, 'café', { encoding: 'utf-8' }); + + expect(fsSync.readFileSync(filePath, 'utf-8')).toBe('café'); + }); + + it('should resolve symlinks and write to the real target', () => { + const realFile = path.join(tmpDir, 'real.txt'); + const linkFile = path.join(tmpDir, 'link.txt'); + + fsSync.writeFileSync(realFile, 'original'); + fsSync.symlinkSync(realFile, linkFile); + + atomicWriteFileSync(linkFile, 'updated via symlink'); + + expect(fsSync.readlinkSync(linkFile)).toBe(realFile); + expect(fsSync.readFileSync(realFile, 'utf-8')).toBe('updated via symlink'); + }); + + it('should write through a broken symlink without replacing it', () => { + const realFile = path.join(tmpDir, 'target.txt'); + const linkFile = path.join(tmpDir, 'broken-link.txt'); + + fsSync.symlinkSync(realFile, linkFile); + + atomicWriteFileSync(linkFile, 'created via broken symlink'); + + expect(fsSync.readlinkSync(linkFile)).toBe(realFile); + expect(fsSync.readFileSync(realFile, 'utf-8')).toBe( + 'created via broken symlink', + ); + }); + + it('should resolve multi-level symlink chains', () => { + const realFile = path.join(tmpDir, 'real.txt'); + const linkA = path.join(tmpDir, 'link-a.txt'); + const linkB = path.join(tmpDir, 'link-b.txt'); + + fsSync.writeFileSync(realFile, 'original'); + fsSync.symlinkSync(realFile, linkA); + fsSync.symlinkSync(linkA, linkB); + + atomicWriteFileSync(linkB, 'updated via chain'); + + expect(fsSync.readlinkSync(linkB)).toBe(linkA); + expect(fsSync.readlinkSync(linkA)).toBe(realFile); + expect(fsSync.readFileSync(realFile, 'utf-8')).toBe('updated via chain'); + }); + + it('should throw if parent directory does not exist', () => { + const filePath = path.join(tmpDir, 'no', 'such', 'dir', 'file.txt'); + expect(() => atomicWriteFileSync(filePath, 'data')).toThrow(); + }); +}); + +describe('forceMode option', () => { + let tmpDir: string; + + beforeEach(async () => { + tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'force-mode-test-')); + }); + + afterEach(async () => { + await fs.rm(tmpDir, { recursive: true, force: true }); + }); + + it.skipIf(process.platform === 'win32')( + 'atomicWriteFile: forceMode tightens an over-permissive existing file', + async () => { + const filePath = path.join(tmpDir, 'creds.json'); + await fs.writeFile(filePath, 'old'); + await fs.chmod(filePath, 0o644); // legacy bad perms + + await atomicWriteFile(filePath, 'new', { + mode: 0o600, + forceMode: true, + }); + + expect((await fs.stat(filePath)).mode & 0o777).toBe(0o600); + }, + ); + + it.skipIf(process.platform === 'win32')( + 'atomicWriteFile: without forceMode, existing 0o644 is preserved', + async () => { + const filePath = path.join(tmpDir, 'creds.json'); + await fs.writeFile(filePath, 'old'); + await fs.chmod(filePath, 0o644); + + await atomicWriteFile(filePath, 'new', { mode: 0o600 }); + + // Existing mode wins — documented default behavior. + expect((await fs.stat(filePath)).mode & 0o777).toBe(0o644); + }, + ); + + it.skipIf(process.platform === 'win32')( + 'atomicWriteFileSync: forceMode tightens an over-permissive existing file', + () => { + const filePath = path.join(tmpDir, 'creds.json'); + fsSync.writeFileSync(filePath, 'old'); + fsSync.chmodSync(filePath, 0o644); + + atomicWriteFileSync(filePath, 'new', { + mode: 0o600, + forceMode: true, + }); + + expect(fsSync.statSync(filePath).mode & 0o777).toBe(0o600); + }, + ); + + it.skipIf(process.platform === 'win32')( + 'forceMode without mode preserves existing permissions (does not drop to umask)', + async () => { + const filePath = path.join(tmpDir, 'file.txt'); + await fs.writeFile(filePath, 'old'); + await fs.chmod(filePath, 0o600); + + // forceMode:true without mode is meaningless (nothing to force) — must + // not silently downgrade to umask default. Regression: pre-fix this + // dropped the file to 0o644 because forceMode skipped the stat. + await atomicWriteFile(filePath, 'new', { forceMode: true }); + + expect(await fs.readFile(filePath, 'utf-8')).toBe('new'); + expect((await fs.stat(filePath)).mode & 0o777).toBe(0o600); + }, + ); + + it.skipIf(process.platform === 'win32')( + 'atomicWriteFileSync: forceMode without mode preserves existing permissions', + () => { + const filePath = path.join(tmpDir, 'file.txt'); + fsSync.writeFileSync(filePath, 'old'); + fsSync.chmodSync(filePath, 0o600); + + atomicWriteFileSync(filePath, 'new', { forceMode: true }); + + expect(fsSync.readFileSync(filePath, 'utf-8')).toBe('new'); + expect(fsSync.statSync(filePath).mode & 0o777).toBe(0o600); + }, + ); +}); + +// PR #4333 review fold-in: cover rename-retry + EXDEV-fallback paths the +// existing behavior tests can't exercise (vitest can't spy on ESM exports +// of node:fs). Uses the `_testFs` / `_renameImpl` seams added to the +// production helpers. +describe('renameWithRetry (async, dependency-injected rename)', () => { + let tmpDir: string; + beforeEach(async () => { + tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'rename-retry-async-')); + }); + afterEach(async () => { + await fs.rm(tmpDir, { recursive: true, force: true }); + }); + + it('retries on EPERM and eventually succeeds', async () => { + const src = path.join(tmpDir, 'src.txt'); + const dest = path.join(tmpDir, 'dest.txt'); + await fs.writeFile(src, 'data'); + + let attempts = 0; + const mockRename = async (s: string, d: string) => { + attempts++; + if (attempts < 3) { + const e: NodeJS.ErrnoException = new Error('EPERM'); + e.code = 'EPERM'; + throw e; + } + await fs.rename(s, d); + }; + + await renameWithRetry(src, dest, 3, 1, mockRename); + expect(attempts).toBe(3); + expect(fsSync.existsSync(dest)).toBe(true); + }); + + it('gives up after retries exhausted', async () => { + let attempts = 0; + const mockRename = async () => { + attempts++; + const e: NodeJS.ErrnoException = new Error('EPERM'); + e.code = 'EPERM'; + throw e; + }; + await expect(renameWithRetry('s', 'd', 2, 1, mockRename)).rejects.toThrow( + /EPERM/, + ); + expect(attempts).toBe(3); // initial attempt + 2 retries + }); + + it('does not retry on non-retryable errors (ENOSPC)', async () => { + let attempts = 0; + const mockRename = async () => { + attempts++; + const e: NodeJS.ErrnoException = new Error('ENOSPC'); + e.code = 'ENOSPC'; + throw e; + }; + await expect(renameWithRetry('s', 'd', 3, 1, mockRename)).rejects.toThrow( + /ENOSPC/, + ); + expect(attempts).toBe(1); + }); + + // The existing tests cover retry count + error propagation but not the + // backoff curve itself. A regression that swapped `delayMs * 2 ** attempt` + // for linear, constant, or — worst — regressive backoff (which intensifies + // under Windows AV-scan stress) would pass every other test. Fake timers + // make the assertion deterministic without burning real wall-clock time. + it('backs off exponentially: delayMs, 2*delayMs, 4*delayMs, ...', async () => { + vi.useFakeTimers(); + try { + const gaps: number[] = []; + let lastInvocation = Date.now(); + const mockRename = async () => { + const now = Date.now(); + gaps.push(now - lastInvocation); + lastInvocation = now; + const e: NodeJS.ErrnoException = new Error('EPERM'); + e.code = 'EPERM'; + throw e; + }; + + const promise = renameWithRetry('s', 'd', 3, 50, mockRename); + // Catch eventual rejection so unhandled-rejection doesn't fire. + promise.catch(() => {}); + + // 4 invocations total (initial + 3 retries), gaps after the + // first should be [50, 100, 200]. + await vi.advanceTimersByTimeAsync(50); + await vi.advanceTimersByTimeAsync(100); + await vi.advanceTimersByTimeAsync(200); + + await expect(promise).rejects.toThrow(/EPERM/); + // gaps[0] is the first invocation's offset from the timer start + // (effectively 0). gaps[1..] are the post-retry waits. + expect(gaps.slice(1)).toEqual([50, 100, 200]); + } finally { + vi.useRealTimers(); + } + }); +}); + +describe('renameWithRetrySync (dependency-injected rename)', () => { + let tmpDir: string; + beforeEach(async () => { + tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'rename-retry-sync-')); + }); + afterEach(async () => { + await fs.rm(tmpDir, { recursive: true, force: true }); + }); + + it('retries on EACCES and succeeds', () => { + const src = path.join(tmpDir, 'src.txt'); + const dest = path.join(tmpDir, 'dest.txt'); + fsSync.writeFileSync(src, 'data'); + + let attempts = 0; + const mockRename = (s: string, d: string) => { + attempts++; + if (attempts < 3) { + const e: NodeJS.ErrnoException = new Error('EACCES'); + e.code = 'EACCES'; + throw e; + } + fsSync.renameSync(s, d); + }; + + renameWithRetrySync(src, dest, 3, 1, mockRename); + expect(attempts).toBe(3); + expect(fsSync.existsSync(dest)).toBe(true); + }); + + it('gives up after retries exhausted', () => { + let attempts = 0; + const mockRename = () => { + attempts++; + const e: NodeJS.ErrnoException = new Error('EPERM'); + e.code = 'EPERM'; + throw e; + }; + expect(() => renameWithRetrySync('s', 'd', 2, 1, mockRename)).toThrow( + /EPERM/, + ); + expect(attempts).toBe(3); + }); + + it('does not retry on non-retryable errors (EINVAL)', () => { + let attempts = 0; + const mockRename = () => { + attempts++; + const e: NodeJS.ErrnoException = new Error('EINVAL'); + e.code = 'EINVAL'; + throw e; + }; + expect(() => renameWithRetrySync('s', 'd', 3, 1, mockRename)).toThrow( + /EINVAL/, + ); + expect(attempts).toBe(1); + }); +}); + +describe('EXDEV fallback (async + sync)', () => { + let tmpDir: string; + beforeEach(async () => { + tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'exdev-fallback-')); + }); + afterEach(async () => { + await fs.rm(tmpDir, { recursive: true, force: true }); + }); + + it('atomicWriteFile: falls back to direct write on EXDEV, cleans up tmp', async () => { + const filePath = path.join(tmpDir, 'exdev.txt'); + const exdevRename = async () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + + await atomicWriteFile(filePath, 'fallback-payload', undefined, { + rename: exdevRename, + }); + + expect(await fs.readFile(filePath, 'utf-8')).toBe('fallback-payload'); + // No tmp residue + expect(await fs.readdir(tmpDir)).toEqual(['exdev.txt']); + }); + + it('atomicWriteFileSync: falls back to direct write on EXDEV, cleans up tmp', () => { + const filePath = path.join(tmpDir, 'exdev-sync.txt'); + const exdevRename = () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + + atomicWriteFileSync(filePath, 'sync-fallback-payload', undefined, { + rename: exdevRename, + }); + + expect(fsSync.readFileSync(filePath, 'utf-8')).toBe( + 'sync-fallback-payload', + ); + expect(fsSync.readdirSync(tmpDir)).toEqual(['exdev-sync.txt']); + }); + + it('atomicWriteFile: non-EXDEV rename failure propagates (no fallback)', async () => { + const filePath = path.join(tmpDir, 'eio.txt'); + const eioRename = async () => { + const e: NodeJS.ErrnoException = new Error('EIO'); + e.code = 'EIO'; + throw e; + }; + + await expect( + atomicWriteFile(filePath, 'data', undefined, { rename: eioRename }), + ).rejects.toThrow(/atomicWriteFile\(.*eio\.txt.*\):.*EIO/); + // Tmp cleaned up even though rename failed + expect(await fs.readdir(tmpDir)).toEqual([]); + }); + + it('atomicWriteFileSync: non-EXDEV rename failure propagates and cleans up tmp', () => { + // Mirror of the async EIO test above — review fold-in: sync variant + // had the same `unlinkSync + re-throw` path but no test exercising + // it (the previous "should clean up temp file when write fails" + // test only covered writeFileSync failure before rename). + const filePath = path.join(tmpDir, 'eio-sync.txt'); + const eioRename = () => { + const e: NodeJS.ErrnoException = new Error('EIO'); + e.code = 'EIO'; + throw e; + }; + + expect(() => + atomicWriteFileSync(filePath, 'data', undefined, { rename: eioRename }), + ).toThrow(/atomicWriteFileSync\(.*eio-sync\.txt.*\):.*EIO/); + expect(fsSync.readdirSync(tmpDir)).toEqual([]); + }); + + it('atomicWriteFile: annotates errors whose message contains the target path (startsWith guard, not includes)', async () => { + // Guards the documented idempotency-guard bug: it once used + // `message.includes(targetPath)`, but real syscall errors embed the + // *tmp* path (which contains the target as a substring), so annotation + // was silently skipped on every real failure. Here the rename error + // message embeds a tmp-style path containing the target; with the + // correct `startsWith` guard the message is still annotated. Reverting + // to the `includes` guard would skip annotation and fail this test. + const filePath = path.join(tmpDir, 'pathinmsg.txt'); + const renameWithPathInMsg = async () => { + const e: NodeJS.ErrnoException = new Error( + `EIO: i/o error, rename '${filePath}.abc123.tmp'`, + ); + e.code = 'EIO'; + throw e; + }; + + await expect( + atomicWriteFile(filePath, 'data', undefined, { + rename: renameWithPathInMsg, + }), + ).rejects.toThrow(/^atomicWriteFile\(/); + }); + + // PR #4333 review fold-in: the EXDEV-then-fallback-write-fails path is + // the only place fnName='atomicWriteFileSync' is exercised, so without + // these tests a regression that dropped or misapplied the annotation + // would go undetected on sync. + it('atomicWriteFile: EXDEV fallback write failure is annotated with target + fn name', async () => { + const filePath = path.join(tmpDir, 'exdev-write-fail.txt'); + const exdevRename = async () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + // Selective failure: succeed on the first call (the tmp-file write) + // so the EXDEV branch is actually reached; fail on the second call + // (the direct write inside the EXDEV fallback). Without this + // distinction the tmp-file write would fail FIRST with ENOSPC, + // skipping the EXDEV branch entirely and leaving the inner + // annotateWriteError call dead-code untested. + let writeCalls = 0; + const failingWrite = async ( + p: string, + d: string | Buffer | NodeJS.ArrayBufferView, + opts: unknown, + ) => { + writeCalls++; + if (writeCalls === 1) { + // Actually write the tmp file so subsequent cleanup works. + await fs.writeFile( + p, + d as Buffer, + opts as Parameters[2], + ); + return; + } + const e: NodeJS.ErrnoException = new Error( + `ENOSPC: no space left on device, open '${filePath}'`, + ); + e.code = 'ENOSPC'; + throw e; + }; + + let caught: unknown; + try { + await atomicWriteFile(filePath, 'data', undefined, { + rename: exdevRename, + writeFile: failingWrite as unknown as typeof fs.writeFile, + }); + } catch (err) { + caught = err; + } + expect((caught as NodeJS.ErrnoException)?.code).toBe('ENOSPC'); + expect((caught as Error).message).toMatch( + /atomicWriteFile\(.*exdev-write-fail\.txt.*\):.*ENOSPC/, + ); + }); + + it('atomicWriteFileSync: EXDEV fallback write failure is annotated with sync fn name', () => { + const filePath = path.join(tmpDir, 'exdev-sync-write-fail.txt'); + const exdevRename = () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + // Same selective-failure pattern as the async test: first call (tmp + // write) succeeds so the EXDEV branch is genuinely reached; second + // call (fallback write) throws. + let writeCalls = 0; + const failingWrite = ( + p: string, + d: string | NodeJS.ArrayBufferView, + opts: unknown, + ) => { + writeCalls++; + if (writeCalls === 1) { + fsSync.writeFileSync( + p, + d, + opts as Parameters[2], + ); + return; + } + const e: NodeJS.ErrnoException = new Error( + `ENOSPC: no space left on device, open '${filePath}'`, + ); + e.code = 'ENOSPC'; + throw e; + }; + + let caught: unknown; + try { + atomicWriteFileSync(filePath, 'data', undefined, { + rename: exdevRename, + writeFile: failingWrite as unknown as typeof fsSync.writeFileSync, + }); + } catch (err) { + caught = err; + } + expect((caught as NodeJS.ErrnoException)?.code).toBe('ENOSPC'); + expect((caught as Error).message).toMatch( + /atomicWriteFileSync\(.*exdev-sync-write-fail\.txt.*\):.*ENOSPC/, + ); + }); +}); + +// PR #4333 review fold-in: noFollow is a security-critical option used +// by all credential write sites — these tests verify the actual +// symlink-skipping behavior (happy path AND EXDEV fallback path), +// not just that the option is passed through to a mock. +describe('noFollow option — symlink protection', () => { + let tmpDir: string; + beforeEach(async () => { + tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'no-follow-test-')); + }); + afterEach(async () => { + await fs.rm(tmpDir, { recursive: true, force: true }); + }); + + it('atomicWriteFile: noFollow replaces a pre-placed symlink instead of writing through it', async () => { + const real = path.join(tmpDir, 'real.txt'); + const link = path.join(tmpDir, 'link.txt'); + await fs.writeFile(real, 'ORIGINAL'); + await fs.symlink(real, link); + + await atomicWriteFile(link, 'NEW', { noFollow: true }); + + // link is now a regular file, not a symlink + expect(fsSync.lstatSync(link).isSymbolicLink()).toBe(false); + expect(await fs.readFile(link, 'utf-8')).toBe('NEW'); + // real file was NOT followed-through to + expect(await fs.readFile(real, 'utf-8')).toBe('ORIGINAL'); + }); + + it('atomicWriteFileSync: noFollow replaces a pre-placed symlink instead of writing through it', () => { + const real = path.join(tmpDir, 'real.txt'); + const link = path.join(tmpDir, 'link.txt'); + fsSync.writeFileSync(real, 'ORIGINAL'); + fsSync.symlinkSync(real, link); + + atomicWriteFileSync(link, 'NEW', { noFollow: true }); + + expect(fsSync.lstatSync(link).isSymbolicLink()).toBe(false); + expect(fsSync.readFileSync(link, 'utf-8')).toBe('NEW'); + expect(fsSync.readFileSync(real, 'utf-8')).toBe('ORIGINAL'); + }); + + it('atomicWriteFile: noFollow EXDEV fallback also refuses to follow symlinks', async () => { + const real = path.join(tmpDir, 'real.txt'); + const link = path.join(tmpDir, 'link.txt'); + await fs.writeFile(real, 'ORIGINAL'); + await fs.symlink(real, link); + + // Force the rename path to fail with EXDEV → exercise the + // noFollow-aware fallback (was the security regression Codex caught). + const exdevRename = async () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + + await atomicWriteFile( + link, + 'NEW', + { noFollow: true }, + { rename: exdevRename }, + ); + + expect(fsSync.lstatSync(link).isSymbolicLink()).toBe(false); + expect(await fs.readFile(link, 'utf-8')).toBe('NEW'); + // The real file MUST be untouched — pre-fix this is where the + // attacker's symlink would have redirected credentials to. + expect(await fs.readFile(real, 'utf-8')).toBe('ORIGINAL'); + }); + + it('atomicWriteFileSync: noFollow EXDEV fallback also refuses to follow symlinks', () => { + const real = path.join(tmpDir, 'real.txt'); + const link = path.join(tmpDir, 'link.txt'); + fsSync.writeFileSync(real, 'ORIGINAL'); + fsSync.symlinkSync(real, link); + + const exdevRename = () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + + atomicWriteFileSync( + link, + 'NEW', + { noFollow: true }, + { rename: exdevRename }, + ); + + expect(fsSync.lstatSync(link).isSymbolicLink()).toBe(false); + expect(fsSync.readFileSync(link, 'utf-8')).toBe('NEW'); + expect(fsSync.readFileSync(real, 'utf-8')).toBe('ORIGINAL'); + }); + + // Earlier noFollow EXDEV tests pre-place a symlink, so the + // `unlink(targetPath)` in the fallback always succeeds. These exercise + // the ENOENT-swallow branch — first-write scenarios (initial credential + // provisioning on a cross-device mount). + // Mode assertions are Linux/macOS only — Windows NTFS reports 0o666 + // for any non-read-only file regardless of chmod, matching the existing + // platform-guard pattern used elsewhere in this file. + // + // These tests also spy on path-based chmod to verify the *mechanism*, + // not just the outcome. Under typical umask 0o022, `open(O_EXCL, 0o600)` + // already creates the file at 0o600, so a regression that swapped + // `fd.chmod()` back to a path-based `tryChmod(targetPath)` (the + // pre-fix TOCTOU-vulnerable form) would leave the mode assertion + // passing. Asserting the path-based chmod was never called against + // `targetPath` catches that regression directly. + it.skipIf(process.platform === 'win32')( + 'atomicWriteFile: noFollow EXDEV fallback creates a new file when target does not exist', + async () => { + const target = path.join(tmpDir, 'never-created.txt'); + const exdevRename = async () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + const chmodSpy = vi.fn(fs.chmod); + + await atomicWriteFile( + target, + 'NEW', + { noFollow: true, mode: 0o600 }, + { rename: exdevRename, chmod: chmodSpy }, + ); + + expect(fsSync.lstatSync(target).isSymbolicLink()).toBe(false); + expect(await fs.readFile(target, 'utf-8')).toBe('NEW'); + expect(fsSync.statSync(target).mode & 0o777).toBe(0o600); + // Path-based chmod is permitted on the tmp file (pre-rename) but + // must never run against the credential target — that path is + // exclusively for the open-fd fchmod. + const targetCalls = chmodSpy.mock.calls.filter(([p]) => p === target); + expect(targetCalls).toEqual([]); + }, + ); + + it.skipIf(process.platform === 'win32')( + 'atomicWriteFileSync: noFollow EXDEV fallback creates a new file when target does not exist', + () => { + const target = path.join(tmpDir, 'never-created-sync.txt'); + const exdevRename = () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + const chmodSpy = vi.fn(fsSync.chmodSync); + + atomicWriteFileSync( + target, + 'NEW', + { noFollow: true, mode: 0o600 }, + { rename: exdevRename, chmod: chmodSpy }, + ); + + expect(fsSync.lstatSync(target).isSymbolicLink()).toBe(false); + expect(fsSync.readFileSync(target, 'utf-8')).toBe('NEW'); + expect(fsSync.statSync(target).mode & 0o777).toBe(0o600); + const targetCalls = chmodSpy.mock.calls.filter(([p]) => p === target); + expect(targetCalls).toEqual([]); + }, + ); + + // The narrowed fchmod catch (round-8 fix) silently swallows ENOSYS/ENOTSUP + // (FAT/exFAT — typical removable-storage credential mount) but propagates + // every other error. Without injection, neither side of the branch is + // exercised and a one-line revert of the catch narrowing would pass + // every test. The orphan-cleanup-on-fchmod-failure path also has no + // coverage without these injections. + // Both ENOSYS (Linux FAT) and ENOTSUP (macOS exFAT) must be swallowed + // — dropping either from the catch condition would silently leave a + // credential file at the umask-masked open() mode on one of the two + // common removable-media filesystems. + it.each(['ENOSYS', 'ENOTSUP'] as const)( + 'atomicWriteFile: noFollow EXDEV swallows fchmod %s (FAT/exFAT)', + async (chmodCode) => { + const target = path.join(tmpDir, `fat-target-${chmodCode}.txt`); + const exdevRename = async () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + const fchmod = async () => { + const e: NodeJS.ErrnoException = new Error(chmodCode); + e.code = chmodCode; + throw e; + }; + + await atomicWriteFile( + target, + 'NEW', + { noFollow: true, mode: 0o600 }, + { rename: exdevRename, fchmod }, + ); + + expect(await fs.readFile(target, 'utf-8')).toBe('NEW'); + }, + ); + + it('atomicWriteFile: noFollow EXDEV propagates fchmod EPERM and removes the orphan', async () => { + const target = path.join(tmpDir, 'eperm-target.txt'); + const exdevRename = async () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + const fchmod = async () => { + const e: NodeJS.ErrnoException = new Error('EPERM'); + e.code = 'EPERM'; + throw e; + }; + + await expect( + atomicWriteFile( + target, + 'NEW', + { noFollow: true, mode: 0o600 }, + { rename: exdevRename, fchmod }, + ), + ).rejects.toThrow(/EPERM/); + + // The O_EXCL-created file MUST be removed so the next retry doesn't + // deadlock. This is the credential-refresh-loop bug round-8 review + // surfaced. + expect(fsSync.existsSync(target)).toBe(false); + }); + + it.each(['ENOSYS', 'ENOTSUP'] as const)( + 'atomicWriteFileSync: noFollow EXDEV swallows fchmod %s (FAT/exFAT)', + (chmodCode) => { + const target = path.join(tmpDir, `fat-target-sync-${chmodCode}.txt`); + const exdevRename = () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + const fchmod = () => { + const e: NodeJS.ErrnoException = new Error(chmodCode); + e.code = chmodCode; + throw e; + }; + + atomicWriteFileSync( + target, + 'NEW', + { noFollow: true, mode: 0o600 }, + { rename: exdevRename, fchmod }, + ); + + expect(fsSync.readFileSync(target, 'utf-8')).toBe('NEW'); + }, + ); + + it('atomicWriteFileSync: noFollow EXDEV propagates fchmod EPERM and removes the orphan', () => { + const target = path.join(tmpDir, 'eperm-target-sync.txt'); + const exdevRename = () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + const fchmod = () => { + const e: NodeJS.ErrnoException = new Error('EPERM'); + e.code = 'EPERM'; + throw e; + }; + + expect(() => + atomicWriteFileSync( + target, + 'NEW', + { noFollow: true, mode: 0o600 }, + { rename: exdevRename, fchmod }, + ), + ).toThrow(/EPERM/); + + expect(fsSync.existsSync(target)).toBe(false); + }); + + // The pre-open unlink at `targetPath` swallows ENOENT (first-write + // case) but propagates anything else. Without injection, no test + // exercises the propagation path — a regression to a blanket catch + // would let a real error (EACCES on the parent directory, EROFS on + // a remount) hide behind the subsequent EEXIST from O_EXCL. + it('atomicWriteFile: noFollow EXDEV pre-open unlink propagates non-ENOENT errors', async () => { + const target = path.join(tmpDir, 'eacces-target.txt'); + const exdevRename = async () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + const unlink = async (p: fsSync.PathLike) => { + // Only the pre-open unlink at targetPath should fail; tmp-file + // cleanup goes through `fs.unlink` directly (not the seam). + if (p === target) { + const e: NodeJS.ErrnoException = new Error('EACCES'); + e.code = 'EACCES'; + throw e; + } + }; + + await expect( + atomicWriteFile( + target, + 'NEW', + { noFollow: true, mode: 0o600 }, + { rename: exdevRename, unlink: unlink as typeof fs.unlink }, + ), + ).rejects.toThrow(/EACCES/); + }); + + it('atomicWriteFileSync: noFollow EXDEV pre-open unlink propagates non-ENOENT errors', () => { + const target = path.join(tmpDir, 'eacces-target-sync.txt'); + const exdevRename = () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + const unlink = (p: fsSync.PathLike) => { + if (p === target) { + const e: NodeJS.ErrnoException = new Error('EACCES'); + e.code = 'EACCES'; + throw e; + } + }; + + expect(() => + atomicWriteFileSync( + target, + 'NEW', + { noFollow: true, mode: 0o600 }, + { rename: exdevRename, unlink: unlink as typeof fsSync.unlinkSync }, + ), + ).toThrow(/EACCES/); + }); + + // Symlink-resolution failures (EACCES on intermediate dir, ELOOP) + // must share the `atomicWriteFile("path"): ...` annotation prefix + // so logs reference the logical filePath instead of an internal + // intermediate component. + it.skipIf(process.platform === 'win32')( + 'atomicWriteFile: annotates resolveSymlinkChain ELOOP failures with the logical filePath', + async () => { + const linkA = path.join(tmpDir, 'loop-a'); + const linkB = path.join(tmpDir, 'loop-b'); + await fs.symlink(linkB, linkA); + await fs.symlink(linkA, linkB); + + await expect(atomicWriteFile(linkA, 'X')).rejects.toThrow( + new RegExp(`atomicWriteFile\\(.*${path.basename(linkA)}.*\\):`), + ); + }, + ); + + it.skipIf(process.platform === 'win32')( + 'atomicWriteFileSync: annotates resolveSymlinkChainSync ELOOP failures with the logical filePath', + () => { + const linkA = path.join(tmpDir, 'loop-a-sync'); + const linkB = path.join(tmpDir, 'loop-b-sync'); + fsSync.symlinkSync(linkB, linkA); + fsSync.symlinkSync(linkA, linkB); + + expect(() => atomicWriteFileSync(linkA, 'X')).toThrow( + new RegExp(`atomicWriteFileSync\\(.*${path.basename(linkA)}.*\\):`), + ); + }, + ); + + // Round-13 narrowed the path-level tryChmod / tryChmodSync catch to + // ENOSYS/ENOTSUP only — same shape as the round-8 fd-level fchmod + // narrowing — but unlike fchmod the tryChmod path had zero direct + // coverage. The existing EXDEV tests pass `options: undefined`, so + // `desiredMode === undefined` short-circuits before chmod is even + // attempted. Inject `_testFs.chmod` and exercise both sides of the + // narrowed catch. + it.each(['ENOSYS', 'ENOTSUP'] as const)( + 'atomicWriteFile: tryChmod swallows %s (FAT/exFAT — non-noFollow EXDEV path)', + async (chmodCode) => { + const target = path.join(tmpDir, `trychmod-${chmodCode}.txt`); + const exdevRename = async () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + const chmod = async () => { + const e: NodeJS.ErrnoException = new Error(chmodCode); + e.code = chmodCode; + throw e; + }; + + await atomicWriteFile( + target, + 'NEW', + { mode: 0o600 }, + { rename: exdevRename, chmod }, + ); + + expect(await fs.readFile(target, 'utf-8')).toBe('NEW'); + }, + ); + + it('atomicWriteFile: tryChmod propagates EPERM (non-noFollow EXDEV path)', async () => { + const target = path.join(tmpDir, 'trychmod-eperm.txt'); + const exdevRename = async () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + const chmod = async () => { + const e: NodeJS.ErrnoException = new Error('EPERM'); + e.code = 'EPERM'; + throw e; + }; + + await expect( + atomicWriteFile( + target, + 'NEW', + { mode: 0o600 }, + { rename: exdevRename, chmod }, + ), + ).rejects.toThrow(/EPERM/); + }); + + it.each(['ENOSYS', 'ENOTSUP'] as const)( + 'atomicWriteFileSync: tryChmodSync swallows %s (FAT/exFAT — non-noFollow EXDEV path)', + (chmodCode) => { + const target = path.join(tmpDir, `trychmod-sync-${chmodCode}.txt`); + const exdevRename = () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + const chmod = () => { + const e: NodeJS.ErrnoException = new Error(chmodCode); + e.code = chmodCode; + throw e; + }; + + atomicWriteFileSync( + target, + 'NEW', + { mode: 0o600 }, + { rename: exdevRename, chmod }, + ); + + expect(fsSync.readFileSync(target, 'utf-8')).toBe('NEW'); + }, + ); + + it('atomicWriteFileSync: tryChmodSync propagates EPERM (non-noFollow EXDEV path)', () => { + const target = path.join(tmpDir, 'trychmod-sync-eperm.txt'); + const exdevRename = () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + const chmod = () => { + const e: NodeJS.ErrnoException = new Error('EPERM'); + e.code = 'EPERM'; + throw e; + }; + + expect(() => + atomicWriteFileSync( + target, + 'NEW', + { mode: 0o600 }, + { rename: exdevRename, chmod }, + ), + ).toThrow(/EPERM/); + }); + + // Round-13's orphan-cleanup unlink (after a failed write/sync/fchmod + // on the noFollow EXDEV path) was using raw `fs.unlink` / + // `fsSync.unlinkSync` instead of the injected `unlinkImpl` seam + // every other fs op flows through. These tests inject a spy on + // unlinkImpl and assert it's invoked with targetPath on the + // failure path — guards against silently bypassing the seam in + // any future refactor. + it('atomicWriteFile: orphan cleanup on fchmod failure goes through unlinkImpl', async () => { + const target = path.join(tmpDir, 'orphan-via-seam.txt'); + const exdevRename = async () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + const fchmod = async () => { + const e: NodeJS.ErrnoException = new Error('EPERM'); + e.code = 'EPERM'; + throw e; + }; + const unlinkSpy = vi.fn(fs.unlink); + + await expect( + atomicWriteFile( + target, + 'NEW', + { noFollow: true, mode: 0o600 }, + { + rename: exdevRename, + fchmod, + unlink: unlinkSpy as typeof fs.unlink, + }, + ), + ).rejects.toThrow(/EPERM/); + + const orphanCleanupCalls = unlinkSpy.mock.calls.filter( + ([p]) => p === target, + ); + // Pre-open unlink + post-failure orphan cleanup: target appears twice. + expect(orphanCleanupCalls.length).toBeGreaterThanOrEqual(2); + expect(fsSync.existsSync(target)).toBe(false); + }); + + it('atomicWriteFileSync: orphan cleanup on fchmod failure goes through unlinkImpl', () => { + const target = path.join(tmpDir, 'orphan-via-seam-sync.txt'); + const exdevRename = () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + const fchmod = () => { + const e: NodeJS.ErrnoException = new Error('EPERM'); + e.code = 'EPERM'; + throw e; + }; + const unlinkSpy = vi.fn(fsSync.unlinkSync); + + expect(() => + atomicWriteFileSync( + target, + 'NEW', + { noFollow: true, mode: 0o600 }, + { + rename: exdevRename, + fchmod, + unlink: unlinkSpy as typeof fsSync.unlinkSync, + }, + ), + ).toThrow(/EPERM/); + + const orphanCleanupCalls = unlinkSpy.mock.calls.filter( + ([p]) => p === target, + ); + expect(orphanCleanupCalls.length).toBeGreaterThanOrEqual(2); + expect(fsSync.existsSync(target)).toBe(false); + }); + + // PR #4333 review fold-in: the noFollow EXDEV fallback must open the + // target with O_EXCL so a symlink racing back into existence between + // the pre-open unlink and the open cannot redirect the credential + // write (the TOCTOU the whole noFollow branch defends against). The + // open/openSync call is routed through the `_testFs` seam specifically + // so these tests can assert the no-clobber flag *directly* — dropping + // O_EXCL silently re-introduces the symlink-follow hole yet leaves + // every behavioral test green (they pre-place a static symlink, so the + // unlink-then-open window is never actually raced). The earlier tests + // only inject an EEXIST-style error; this asserts the create flags. + it('atomicWriteFile: noFollow EXDEV opens the target with O_EXCL (no-clobber create)', async () => { + const target = path.join(tmpDir, 'oexcl-async.txt'); + const exdevRename = async () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + const openSpy = vi.fn(fs.open); + + await atomicWriteFile( + target, + 'NEW', + { noFollow: true }, + { rename: exdevRename, open: openSpy }, + ); + + expect(openSpy).toHaveBeenCalledTimes(1); + const flags = openSpy.mock.calls[0][1] as number; + // The load-bearing assertion: O_EXCL must be set (no-clobber create). + expect(flags & fsSync.constants.O_EXCL).toBe(fsSync.constants.O_EXCL); + expect(flags & fsSync.constants.O_CREAT).toBe(fsSync.constants.O_CREAT); + // Sanity: the write genuinely went through the seam-routed open. + expect(await fs.readFile(target, 'utf-8')).toBe('NEW'); + }); + + it('atomicWriteFileSync: noFollow EXDEV opens the target with O_EXCL (no-clobber create)', () => { + const target = path.join(tmpDir, 'oexcl-sync.txt'); + const exdevRename = () => { + const e: NodeJS.ErrnoException = new Error('EXDEV'); + e.code = 'EXDEV'; + throw e; + }; + const openSpy = vi.fn(fsSync.openSync); + + atomicWriteFileSync( + target, + 'NEW', + { noFollow: true }, + { rename: exdevRename, open: openSpy }, + ); + + expect(openSpy).toHaveBeenCalledTimes(1); + const flags = openSpy.mock.calls[0][1] as number; + expect(flags & fsSync.constants.O_EXCL).toBe(fsSync.constants.O_EXCL); + expect(flags & fsSync.constants.O_CREAT).toBe(fsSync.constants.O_CREAT); + expect(fsSync.readFileSync(target, 'utf-8')).toBe('NEW'); + }); +}); diff --git a/packages/core/src/utils/atomicFileWrite.ts b/packages/core/src/utils/atomicFileWrite.ts index 037b0e4c540..a99d2845db7 100644 --- a/packages/core/src/utils/atomicFileWrite.ts +++ b/packages/core/src/utils/atomicFileWrite.ts @@ -1,15 +1,19 @@ /** * @license - * Copyright 2026 HopCode + * Copyright 2025 HopCode Team * SPDX-License-Identifier: Apache-2.0 */ import * as crypto from 'node:crypto'; +import * as fsSync from 'node:fs'; import type { Stats } from 'node:fs'; import * as fs from 'node:fs/promises'; import * as path from 'node:path'; +import { createDebugLogger } from './debugLogger.js'; import { isNodeError } from './errors.js'; +const debugLogger = createDebugLogger('ATOMIC_WRITE'); + export interface AtomicWriteOptions { /** Number of rename retries on EPERM/EACCES (default: 3). */ retries?: number; @@ -24,21 +28,47 @@ export interface AtomicWriteFileOptions extends AtomicWriteOptions { flush?: boolean; /** Encoding for string content. Default: 'utf-8'. */ encoding?: BufferEncoding; + /** + * Ignore the existing target's permission bits and apply `mode` + * regardless. Use for secrets that must heal historically over-permissive + * files (e.g. a credential file accidentally restored from backup at + * 0o644 must be forced back to 0o600). No effect when `mode` is unset. + * Default: false. + */ + forceMode?: boolean; + /** + * Do NOT follow symlinks at `filePath` — write to / replace the link + * itself rather than its target. Pre-`atomicWriteFile` migration code + * used `fs.rename(tmp, filePath)`, which atomically *replaces* a + * symlink with the new regular file. The default behavior resolves + * the chain and writes through, which is a security regression for + * credential files on shared hosts (a pre-placed symlink could + * redirect tokens to an attacker-controlled path). Credential write + * sites pass `noFollow: true` to match the old replace-the-symlink + * semantics. Default: false (follow symlinks). See PR #4333 review. + */ + noFollow?: boolean; } /** * Rename a file with retry on EPERM/EACCES (common on Windows under * concurrent access). Uses exponential backoff. + * + * @param _renameImpl Internal test seam — defaults to `fs.rename`. Tests + * inject a mock to exercise retry, give-up, and non-retryable paths + * that vitest cannot otherwise spy on (ESM exports of `node:fs` are + * non-configurable). */ export async function renameWithRetry( src: string, dest: string, retries: number, delayMs: number, + _renameImpl: (s: string, d: string) => Promise = fs.rename, ): Promise { for (let attempt = 0; attempt <= retries; attempt++) { try { - await fs.rename(src, dest); + await _renameImpl(src, dest); return; } catch (error: unknown) { const isRetryable = @@ -108,13 +138,45 @@ export async function atomicWriteFile( filePath: string, data: string | Buffer, options?: AtomicWriteFileOptions, + /** + * Internal test seam — defaults to real `fs.rename` / `fs.writeFile` / + * `fs.open`. Tests inject overrides to exercise EXDEV fallback and + * rename-retry paths that vitest cannot spy on (ESM exports of `node:fs` + * are non-configurable). The `open` seam additionally lets tests assert + * the O_EXCL no-clobber create flag on the noFollow EXDEV path. + * Production callers never pass this. + */ + _testFs?: { + rename?: (s: string, d: string) => Promise; + writeFile?: typeof fs.writeFile; + open?: typeof fs.open; + chmod?: typeof fs.chmod; + fchmod?: (fh: fs.FileHandle, mode: number) => Promise; + unlink?: typeof fs.unlink; + }, ): Promise { const retries = options?.retries ?? 3; const delayMs = options?.delayMs ?? 50; const flush = options?.flush ?? true; const encoding = options?.encoding ?? 'utf-8'; + const renameImpl = _testFs?.rename ?? fs.rename; + const writeFileImpl = _testFs?.writeFile ?? fs.writeFile; + const openImpl = _testFs?.open ?? fs.open; + const chmodImpl = _testFs?.chmod ?? fs.chmod; + const fchmodImpl = + _testFs?.fchmod ?? ((fh: fs.FileHandle, mode: number) => fh.chmod(mode)); + const unlinkImpl = _testFs?.unlink ?? fs.unlink; - const targetPath = await resolveSymlinkChain(filePath); + // Annotate symlink resolution failures (EACCES on intermediate dir, + // ELOOP on circular chain) with the logical filePath so they share + // the `atomicWriteFile("path"): ...` prefix the rest of the function + // applies — otherwise incident-response logs reference an + // intermediate path component that the caller never asked about. + const targetPath = options?.noFollow + ? filePath + : await resolveSymlinkChain(filePath).catch((err) => { + throw annotateWriteError(err, filePath); + }); // Stat the target to preserve existing permissions and detect // ownership-changing renames (see the ownership-preservation note in @@ -128,8 +190,14 @@ export async function atomicWriteFile( } } - const existingMode = - existingStat !== undefined ? existingStat.mode & 0o7777 : undefined; + // forceMode skips permission preservation only when an explicit mode is + // supplied — otherwise we'd silently downgrade an existing file's perms + // to the process umask. forceMode without mode falls back to preservation. + let existingMode: number | undefined; + if (!options?.forceMode || options?.mode === undefined) { + existingMode = + existingStat !== undefined ? existingStat.mode & 0o7777 : undefined; + } const desiredMode = existingMode ?? options?.mode; const writeOptions: { @@ -141,13 +209,25 @@ export async function atomicWriteFile( if (flush) writeOptions.flush = true; if (desiredMode !== undefined) writeOptions.mode = desiredMode; - // chmod fails on filesystems without POSIX permissions (FAT/exFAT). Best-effort. + // chmod fails on filesystems without POSIX permissions (FAT/exFAT) — + // narrow the catch to ENOSYS/ENOTSUP so security-relevant errors + // (sandbox EPERM, transient EIO, read-only EROFS) propagate. This + // matters specifically on the EXDEV non-noFollow fallback below, + // where tryChmod is the *sole* mode-setting mechanism for an + // existing target (writeFile ignores `mode` when the target exists). + // Non-credential callers don't pass `mode`, so `desiredMode === + // undefined` short-circuits before any chmod is attempted. const tryChmod = async (target: string): Promise => { if (desiredMode === undefined) return; try { - await fs.chmod(target, desiredMode); - } catch { - // Ignore — not all filesystems support chmod. + await chmodImpl(target, desiredMode); + } catch (chmodErr) { + if ( + !isNodeError(chmodErr) || + (chmodErr.code !== 'ENOSYS' && chmodErr.code !== 'ENOTSUP') + ) { + throw chmodErr; + } } }; @@ -179,36 +259,400 @@ export async function atomicWriteFile( const tmpPath = `${targetPath}.${crypto.randomBytes(6).toString('hex')}.tmp`; try { - await fs.writeFile(tmpPath, data, writeOptions); + await writeFileImpl(tmpPath, data, writeOptions); await tryChmod(tmpPath); - await renameWithRetry(tmpPath, targetPath, retries, delayMs); + await renameWithRetry(tmpPath, targetPath, retries, delayMs, renameImpl); } catch (error) { - // Clean up temp file. + // Clean up temp file. Routed through unlinkImpl so the test + // seam covers every fs.unlink call site in this function (pre-open, + // tmp cleanup, orphan cleanup) — keeps the seam abstraction + // consistent for future test authors even though this branch is + // best-effort. try { - await fs.unlink(tmpPath); + await unlinkImpl(tmpPath); } catch { // Ignore cleanup errors. } // EXDEV: cross-device rename not supported — fall back to direct write. if (isNodeError(error) && error.code === 'EXDEV') { - await fs.writeFile(targetPath, data, writeOptions); - await tryChmod(targetPath); - return; + try { + if (options?.noFollow) { + // Naive fallback `writeFile(targetPath)` follows symlinks, + // defeating the entire purpose of noFollow on credential + // paths. Unlink any existing entry (matches the rename + // happy path that atomically replaces a symlink), then + // open with O_EXCL to refuse writing through a symlink + // that races back into existence. Non-ENOENT errors + // (EACCES on parent dir, EROFS, etc.) propagate so the + // caller sees the real cause instead of a downstream + // EEXIST from O_EXCL. + try { + await unlinkImpl(targetPath); + } catch (unlinkErr) { + if (!isNodeError(unlinkErr) || unlinkErr.code !== 'ENOENT') { + throw unlinkErr; + } + } + const fd = await openImpl( + targetPath, + fsSync.constants.O_WRONLY | + fsSync.constants.O_CREAT | + fsSync.constants.O_EXCL, + desiredMode ?? 0o666, + ); + let writeOk = false; + try { + try { + await fd.writeFile( + typeof data === 'string' ? Buffer.from(data, encoding) : data, + ); + if (flush) await fd.sync(); + // fchmod via the open fd — immune to symlink swap between + // close and a path-based chmod, which would otherwise redirect + // the 0o600 onto an attacker-pointed target and silently + // defeat noFollow on the EXDEV fallback path. + // + // Narrow the catch to FAT/exFAT signatures (ENOSYS / ENOTSUP). + // Operations on credential files are security-sensitive enough + // that a sandbox EPERM, transient EIO, or read-only EROFS + // should fail loudly rather than leave the file at the + // umask-masked open() mode with no diagnostic trail. + if (desiredMode !== undefined) { + try { + await fchmodImpl(fd, desiredMode); + } catch (chmodErr) { + if ( + !isNodeError(chmodErr) || + (chmodErr.code !== 'ENOSYS' && chmodErr.code !== 'ENOTSUP') + ) { + throw chmodErr; + } + } + } + writeOk = true; + } finally { + await fd.close(); + } + } catch (writeErr) { + // O_EXCL created targetPath; if any of write/sync/fchmod + // threw, remove the orphan so the next retry doesn't + // deadlock on EEXIST (e.g. credential refresh loop after + // a transient seccomp EPERM on `fchmod`). + if (!writeOk) { + try { + await unlinkImpl(targetPath); + } catch (orphanErr) { + // Best-effort cleanup, but log so incident response + // can correlate the original write error with a + // subsequent EEXIST loop. + debugLogger.debug( + `orphan unlink failed for ${targetPath}:`, + orphanErr, + ); + } + } + throw writeErr; + } + } else { + await writeFileImpl(targetPath, data, writeOptions); + await tryChmod(targetPath); + } + return; + } catch (fallbackError) { + // Preserve the function's error-shape contract even on the + // non-atomic fallback path (e.g. ENOSPC writing directly). + throw annotateWriteError(fallbackError, targetPath); + } } - throw error; + throw annotateWriteError(error, targetPath); } } +function annotateWriteError( + error: unknown, + targetPath: string, + fnName: string = 'atomicWriteFile', +): unknown { + if (error instanceof Error && !error.message.startsWith(`${fnName}(`)) { + error.message = `${fnName}(${JSON.stringify(targetPath)}): ${error.message}`; + } + return error; +} + /** Atomically write a JSON value to a file. Delegates to {@link atomicWriteFile}. */ export async function atomicWriteJSON( filePath: string, data: unknown, - options?: AtomicWriteOptions, + options?: AtomicWriteFileOptions, ): Promise { await atomicWriteFile(filePath, JSON.stringify(data, null, 2), { encoding: 'utf-8', ...options, }); } + +// --- Synchronous variants ---------------------------------------------------- + +/** + * True blocking sleep without busy-wait. Backed by a tiny SharedArrayBuffer + * since Atomics.wait requires an Int32Array view of shared memory. + */ +function blockingSleep(ms: number): void { + if (ms <= 0) return; + const sab = new SharedArrayBuffer(4); + const i32 = new Int32Array(sab); + Atomics.wait(i32, 0, 0, ms); +} + +/** + * Sync mirror of {@link renameWithRetry}. Retries on EPERM/EACCES with + * exponential backoff (common on Windows under concurrent AV scans). + * + * @param _renameImpl Internal test seam — see {@link renameWithRetry}. + */ +export function renameWithRetrySync( + src: string, + dest: string, + retries: number, + delayMs: number, + _renameImpl: (s: string, d: string) => void = fsSync.renameSync, +): void { + for (let attempt = 0; attempt <= retries; attempt++) { + try { + _renameImpl(src, dest); + return; + } catch (error: unknown) { + const isRetryable = + isNodeError(error) && + (error.code === 'EPERM' || error.code === 'EACCES'); + if (!isRetryable || attempt === retries) { + throw error; + } + blockingSleep(delayMs * 2 ** attempt); + } + } +} + +/** + * Sync mirror of {@link resolveSymlinkChain}. Walks symlinks (including + * broken ones) up to POSIX SYMLOOP_MAX. Returns the original path for + * non-symlinks. + */ +function resolveSymlinkChainSync(filePath: string): string { + const maxHops = 40; + let current = filePath; + for (let i = 0; i < maxHops; i++) { + let lstats: fsSync.Stats; + try { + lstats = fsSync.lstatSync(current); + } catch (err) { + if (isNodeError(err) && err.code === 'ENOENT') { + return current; + } + throw err; + } + if (!lstats.isSymbolicLink()) { + return current; + } + const linkTarget = fsSync.readlinkSync(current); + if (path.isAbsolute(linkTarget)) { + current = linkTarget; + } else { + const parentDir = fsSync.realpathSync(path.dirname(current)); + current = path.resolve(parentDir, linkTarget); + } + } + const err = new Error( + `ELOOP: too many levels of symbolic links, resolve '${filePath}'`, + ); + (err as NodeJS.ErrnoException).code = 'ELOOP'; + throw err; +} + +/** + * Synchronous variant of {@link atomicWriteFile}. Same semantics: symlink + * resolution, permission preservation (or `forceMode` override), fsync via + * `flush: true`, EPERM/EACCES rename retry, EXDEV fallback to direct write. + * + * Use for code paths that cannot await (e.g. settings persistence on + * `process.exit`). Prefer the async variant when possible. + */ +export function atomicWriteFileSync( + filePath: string, + data: string | Buffer, + options?: AtomicWriteFileOptions, + /** Internal test seam — see {@link atomicWriteFile}. */ + _testFs?: { + rename?: (s: string, d: string) => void; + writeFile?: typeof fsSync.writeFileSync; + open?: typeof fsSync.openSync; + chmod?: typeof fsSync.chmodSync; + fchmod?: (fd: number, mode: number) => void; + unlink?: typeof fsSync.unlinkSync; + }, +): void { + const retries = options?.retries ?? 3; + const delayMs = options?.delayMs ?? 50; + const flush = options?.flush ?? true; + const encoding = options?.encoding ?? 'utf-8'; + const renameImpl = _testFs?.rename ?? fsSync.renameSync; + const writeFileImpl = _testFs?.writeFile ?? fsSync.writeFileSync; + const openImpl = _testFs?.open ?? fsSync.openSync; + const chmodImpl = _testFs?.chmod ?? fsSync.chmodSync; + const fchmodImpl = _testFs?.fchmod ?? fsSync.fchmodSync; + const unlinkImpl = _testFs?.unlink ?? fsSync.unlinkSync; + + // Annotate symlink-resolution failures with the logical filePath + // (see atomicWriteFile for rationale). + let targetPath: string; + if (options?.noFollow) { + targetPath = filePath; + } else { + try { + targetPath = resolveSymlinkChainSync(filePath); + } catch (err) { + throw annotateWriteError(err, filePath, 'atomicWriteFileSync'); + } + } + const tmpPath = `${targetPath}.${crypto.randomBytes(6).toString('hex')}.tmp`; + + // forceMode without mode falls back to permission preservation — otherwise + // we'd silently downgrade an existing file's perms to the process umask. + let existingMode: number | undefined; + if (!options?.forceMode || options?.mode === undefined) { + try { + const stat = fsSync.statSync(targetPath); + existingMode = stat.mode & 0o7777; + } catch (err) { + if (!isNodeError(err) || err.code !== 'ENOENT') { + throw err; + } + } + } + + const desiredMode = existingMode ?? options?.mode; + + const writeOptions: { + encoding?: BufferEncoding; + flush?: boolean; + mode?: number; + } = {}; + if (typeof data === 'string') writeOptions.encoding = encoding; + if (flush) writeOptions.flush = true; + if (desiredMode !== undefined) writeOptions.mode = desiredMode; + + // See tryChmod in atomicWriteFile for rationale on the narrowed catch. + const tryChmodSync = (target: string): void => { + if (desiredMode === undefined) return; + try { + chmodImpl(target, desiredMode); + } catch (chmodErr) { + if ( + !isNodeError(chmodErr) || + (chmodErr.code !== 'ENOSYS' && chmodErr.code !== 'ENOTSUP') + ) { + throw chmodErr; + } + } + }; + + try { + writeFileImpl(tmpPath, data, writeOptions); + tryChmodSync(tmpPath); + renameWithRetrySync(tmpPath, targetPath, retries, delayMs, renameImpl); + } catch (error) { + // See atomicWriteFile for the unlinkImpl-seam routing rationale. + try { + unlinkImpl(tmpPath); + } catch { + // Ignore cleanup errors. + } + + if (isNodeError(error) && error.code === 'EXDEV') { + try { + if (options?.noFollow) { + // See atomicWriteFile for the rationale — noFollow must not + // be silently dropped on the cross-device fallback path. + // Non-ENOENT errors propagate. + try { + unlinkImpl(targetPath); + } catch (unlinkErr) { + if (!isNodeError(unlinkErr) || unlinkErr.code !== 'ENOENT') { + throw unlinkErr; + } + } + const fd = openImpl( + targetPath, + fsSync.constants.O_WRONLY | + fsSync.constants.O_CREAT | + fsSync.constants.O_EXCL, + desiredMode ?? 0o666, + ); + let writeOk = false; + try { + try { + const buf = + typeof data === 'string' ? Buffer.from(data, encoding) : data; + // writeFileSync(fd, buf) loops until the full buffer is + // written. Plain `fsSync.writeSync(fd, buf)` returns the + // bytes-actually-written and can short-write, which would + // silently truncate the credential file while still + // reaching fsync + fchmod. The async sibling + // (`fd.writeFile`) handles short-writes internally; the + // sync path now matches. + fsSync.writeFileSync(fd, buf); + if (flush) fsSync.fsyncSync(fd); + // fchmod on the open fd (see atomicWriteFile for rationale). + // Narrow the catch to FAT/exFAT signatures so EPERM/EIO/EROFS + // surface instead of leaving a credential file at the + // umask-masked open() mode silently. + if (desiredMode !== undefined) { + try { + fchmodImpl(fd, desiredMode); + } catch (chmodErr) { + if ( + !isNodeError(chmodErr) || + (chmodErr.code !== 'ENOSYS' && chmodErr.code !== 'ENOTSUP') + ) { + throw chmodErr; + } + } + } + writeOk = true; + } finally { + fsSync.closeSync(fd); + } + } catch (writeErr) { + // O_EXCL created targetPath; remove the orphan on failure + // so subsequent retries don't deadlock on EEXIST. + if (!writeOk) { + try { + unlinkImpl(targetPath); + } catch (orphanErr) { + debugLogger.debug( + `orphan unlink failed for ${targetPath}:`, + orphanErr, + ); + } + } + throw writeErr; + } + } else { + writeFileImpl(targetPath, data, writeOptions); + tryChmodSync(targetPath); + } + return; + } catch (fallbackError) { + throw annotateWriteError( + fallbackError, + targetPath, + 'atomicWriteFileSync', + ); + } + } + + throw annotateWriteError(error, targetPath, 'atomicWriteFileSync'); + } +} diff --git a/packages/core/src/utils/debugLogger.ts b/packages/core/src/utils/debugLogger.ts index f95bc16cb34..ef4c3560a9e 100644 --- a/packages/core/src/utils/debugLogger.ts +++ b/packages/core/src/utils/debugLogger.ts @@ -148,6 +148,14 @@ function writeLog( const line = buildLogLine(level, message, tag, traceCtx); void ensureDebugDirExists() + // Debug logs are best-effort diagnostic output: 1050+ call sites, + // default-enabled, fire-and-forget. Per-line fsync would force + // continuous I/O pressure / SSD wear without user benefit — losing + // the last few hundred ms of debug output on crash is acceptable + // and the module already tracks `hasWriteFailure` for the + // degraded-mode UI. Kernel page-cache flush is sufficient here. + // (JSONL session writes via writeLine/writeLineSync DO use + // flush:true — those are the actual #3681 closure target.) .then(() => fs.appendFile(logFilePath, line, 'utf8')) .catch((error) => { hasWriteFailure = true; diff --git a/packages/core/src/utils/installationManager.ts b/packages/core/src/utils/installationManager.ts index e2bff2ff863..df84fce0f23 100644 --- a/packages/core/src/utils/installationManager.ts +++ b/packages/core/src/utils/installationManager.ts @@ -8,6 +8,7 @@ import * as fs from 'node:fs'; import { randomUUID } from 'node:crypto'; import * as path from 'node:path'; import { Storage } from '../config/storage.js'; +import { atomicWriteFileSync } from './atomicFileWrite.js'; import { createDebugLogger } from '../utils/debugLogger.js'; const debugLogger = createDebugLogger('INSTALLATION'); @@ -32,7 +33,9 @@ export class InstallationManager { const installationIdFile = this.getInstallationIdPath(); const dir = path.dirname(installationIdFile); fs.mkdirSync(dir, { recursive: true }); - fs.writeFileSync(installationIdFile, installationId, 'utf-8'); + atomicWriteFileSync(installationIdFile, installationId, { + encoding: 'utf-8', + }); } /** diff --git a/packages/core/src/utils/jsonl-utils.test.ts b/packages/core/src/utils/jsonl-utils.test.ts index a45dbb444cd..56e0b886c11 100644 --- a/packages/core/src/utils/jsonl-utils.test.ts +++ b/packages/core/src/utils/jsonl-utils.test.ts @@ -23,6 +23,9 @@ import { parseLineTolerant, read, readLines, + write, + writeLine, + writeLineSync, } from './jsonl-utils.js'; let tmpRoot: string; @@ -259,3 +262,75 @@ describe('reader resource cleanup', () => { expect(result).toBe(2); }); }); + +// PR #4333 review fold-in: smoke tests for the three write paths. Downstream +// callers (chatRecordingService, sessionService) mock these entirely, so a +// regression in flush:true or atomicWriteFileSync wiring would otherwise go +// undetected. Tests use real fs and assert roundtrip integrity. +describe('writeLine / writeLineSync / write', () => { + it('writeLine round-trips through read() with flush:true appended records', async () => { + const file = path.join( + tmpRoot, + `wl-${Math.random().toString(36).slice(2)}.jsonl`, + ); + await writeLine(file, { kind: 'a', n: 1 }); + await writeLine(file, { kind: 'b', n: 2 }); + await writeLine(file, { kind: 'c', n: 3 }); + + const records = await read(file); + expect(records).toEqual([ + { kind: 'a', n: 1 }, + { kind: 'b', n: 2 }, + { kind: 'c', n: 3 }, + ]); + // No `}{` glue: each line is its own well-formed record. + const raw = fs.readFileSync(file, 'utf8'); + expect(raw).toBe( + '{"kind":"a","n":1}\n{"kind":"b","n":2}\n{"kind":"c","n":3}\n', + ); + }); + + it('writeLineSync appends well-formed records with trailing newlines', () => { + const file = path.join( + tmpRoot, + `wls-${Math.random().toString(36).slice(2)}.jsonl`, + ); + writeLineSync(file, { sync: true, i: 0 }); + writeLineSync(file, { sync: true, i: 1 }); + + expect(fs.readFileSync(file, 'utf8')).toBe( + '{"sync":true,"i":0}\n{"sync":true,"i":1}\n', + ); + }); + + it('write() full-file replaces existing content via atomic write', async () => { + const file = path.join( + tmpRoot, + `wf-${Math.random().toString(36).slice(2)}.jsonl`, + ); + await writeLine(file, { v: 1 }); + await writeLine(file, { v: 2 }); + expect((await read(file)).length).toBe(2); + + // Replace the entire file via the sync write() helper. + write(file, [{ v: 10 }, { v: 20 }, { v: 30 }]); + + expect(await read(file)).toEqual([{ v: 10 }, { v: 20 }, { v: 30 }]); + // No tmp residue from atomicWriteFileSync. + const dirEntries = fs + .readdirSync(tmpRoot) + .filter((f) => f.startsWith(path.basename(file))); + expect(dirEntries).toEqual([path.basename(file)]); + }); + + // The other write() test targets a path inside the pre-created tmpRoot, + // so the `if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })` + // branch is never exercised. A regression that dropped that branch would + // make write() fail with ENOENT only when callers target a brand-new + // subdirectory. + it('write() creates parent dirs when missing', () => { + const nested = path.join(tmpRoot, 'a', 'b', 'c', 'file.jsonl'); + write(nested, [{ x: 1 }]); + expect(fs.readFileSync(nested, 'utf-8')).toBe('{"x":1}\n'); + }); +}); diff --git a/packages/core/src/utils/jsonl-utils.ts b/packages/core/src/utils/jsonl-utils.ts index b03f1e173aa..2644d70328f 100644 --- a/packages/core/src/utils/jsonl-utils.ts +++ b/packages/core/src/utils/jsonl-utils.ts @@ -23,6 +23,7 @@ import fs from 'node:fs'; import path from 'node:path'; +import { atomicWriteFileSync } from './atomicFileWrite.js'; import readline from 'node:readline'; import { finished } from 'node:stream/promises'; import { Mutex } from 'async-mutex'; @@ -267,13 +268,35 @@ export async function writeLine( await fs.promises.mkdir(dir, { recursive: true }); ensuredDirs.add(dir); } - await fs.promises.appendFile(filePath, line, 'utf8'); + // flush:true fsyncs after each line so a process killed mid-write + // doesn't leave a glued `}{` record on disk (closes #3681). On + // Node v22/v24 strace shows string + utf8 + flush:true does fsync + // correctly; passing a Buffer is forward-compat insurance against + // any future C++ fast path that might bypass JS-side flush logic + // for the string case, with no behavior delta on tested versions. + await fs.promises.appendFile(filePath, Buffer.from(line, 'utf8'), { + flush: true, + }); }); } /** * Synchronous version of writeLine for use in non-async contexts. - * Uses a simple flag-based locking mechanism (less robust than async version). + * + * NOTE: this function is unsynchronized — there is no locking. The + * `writeLine` async variant uses a per-file `Mutex` to serialize + * concurrent writers, but that lock is bypassed by `writeLineSync` + * and `write()`. Callers that share a JSONL file with concurrent + * `writeLine()` callers must serialize externally. + * + * `flush: true` fsyncs after each appended record so a `kill -9` + * mid-tool-call cannot leave a glued `}{` record on disk (closes + * #3681). The line is converted to a `Buffer` for forward-compat + * insurance — strace on Node v22/v24 confirms string + utf8 + + * flush:true does fsync correctly today, but Buffer is the + * unambiguous slow-path form and protects against any future C++ + * fast-path optimization that might bypass the flush hook for + * strings. */ export function writeLineSync(filePath: string, data: unknown): void { const line = `${JSON.stringify(data)}\n`; @@ -282,7 +305,7 @@ export function writeLineSync(filePath: string, data: unknown): void { if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } - fs.appendFileSync(filePath, line, 'utf8'); + fs.appendFileSync(filePath, Buffer.from(line, 'utf8'), { flush: true }); } /** @@ -296,7 +319,7 @@ export function write(filePath: string, data: unknown[]): void { if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } - fs.writeFileSync(filePath, `${lines}\n`, 'utf8'); + atomicWriteFileSync(filePath, `${lines}\n`, { encoding: 'utf8' }); } /** diff --git a/packages/core/src/utils/projectSummary.ts b/packages/core/src/utils/projectSummary.ts index 32367f3ed9a..02bc719c569 100644 --- a/packages/core/src/utils/projectSummary.ts +++ b/packages/core/src/utils/projectSummary.ts @@ -6,6 +6,7 @@ import * as fs from 'fs/promises'; import * as path from 'path'; +import { atomicWriteFile } from './atomicFileWrite.js'; export interface ProjectSummaryInfo { hasHistory: boolean; @@ -85,7 +86,9 @@ export async function saveWelcomeBackRestartChoice( summaryFingerprint, }; - await fs.writeFile(statePath, JSON.stringify(state, null, 2), 'utf-8'); + await atomicWriteFile(statePath, JSON.stringify(state, null, 2), { + encoding: 'utf-8', + }); } export async function clearWelcomeBackState(): Promise { diff --git a/packages/sdk-typescript/src/daemon/types.ts b/packages/sdk-typescript/src/daemon/types.ts index bf4a7b5e4ed..18419e079fa 100644 --- a/packages/sdk-typescript/src/daemon/types.ts +++ b/packages/sdk-typescript/src/daemon/types.ts @@ -709,7 +709,6 @@ export const DAEMON_APPROVAL_MODES = [ 'auto-edit', 'auto', 'izn', - 'yolo', ] as const; export type DaemonApprovalMode = (typeof DAEMON_APPROVAL_MODES)[number]; diff --git a/packages/vscode-ide-companion/schemas/settings.schema.json b/packages/vscode-ide-companion/schemas/settings.schema.json index 0e70e16e7b7..63924bb8b8b 100644 --- a/packages/vscode-ide-companion/schemas/settings.schema.json +++ b/packages/vscode-ide-companion/schemas/settings.schema.json @@ -19,7 +19,7 @@ "additionalProperties": true }, "plansDirectory": { - "description": "Custom directory for approved Plan Mode files. Relative paths are resolved from the project root, and the resolved path must stay within the project root. Defaults to ~/.qwen/plans.", + "description": "Custom directory for approved Plan Mode files. Relative paths are resolved from the project root, and the resolved path must stay within the project root. Defaults to ~/.hopcode/plans.", "type": "string" }, "env": { @@ -60,7 +60,7 @@ "default": 5 }, "cleanupPeriodDays": { - "description": "Number of days to retain ~/.qwen/file-history/ session backups used by /rewind. Backups older than this are removed by a background housekeeping pass that runs at most once per day. Set to 0 for minimum retention (~1 hour) — protects sessions touched in the last hour, plus the currently active session. Other persistent caches will honor the same setting in the future.", + "description": "Number of days to retain ~/.hopcode/file-history/ session backups used by /rewind. Backups older than this are removed by a background housekeeping pass that runs at most once per day. Set to 0 for minimum retention (~1 hour) — protects sessions touched in the last hour, plus the currently active session. Other persistent caches will honor the same setting in the future.", "type": "number", "default": 30 }, @@ -108,7 +108,7 @@ "default": false }, "language": { - "description": "The language for the user interface. Use \"auto\" to detect from system settings. You can also use custom language codes (e.g., \"es\", \"fr\") by placing JS language files in ~/.qwen/locales/ (e.g., ~/.qwen/locales/es.js). Options: auto, en, zh-TW, zh, ru, de, ja, pt, fr, ca", + "description": "The language for the user interface. Use \"auto\" to detect from system settings. You can also use custom language codes (e.g., \"es\", \"fr\") by placing JS language files in ~/.hopcode/locales/ (e.g., ~/.hopcode/locales/es.js). Options: auto, en, zh-TW, zh, ru, de, ja, pt, fr, ca", "enum": [ "auto", "en", @@ -803,14 +803,13 @@ } }, "approvalMode": { - "description": "Approval mode for tool usage. Controls how tools are approved before execution. Options: plan, default, auto-edit, auto, izn, yolo", + "description": "Approval mode for tool usage. Controls how tools are approved before execution. Options: plan, default, auto-edit, auto, izn", "enum": [ "plan", "default", "auto-edit", "auto", - "izn", - "yolo" + "izn" ], "default": "default" }, @@ -969,7 +968,7 @@ "additionalProperties": true }, "runtimeOutputDir": { - "description": "Custom directory for runtime output (temp files, debug logs, session data, todos, etc.). Config files remain at ~/.qwen (or QWEN_HOME if set). Env var QWEN_RUNTIME_DIR takes priority.", + "description": "Custom directory for runtime output (temp files, debug logs, session data, todos, etc.). Config files remain at ~/.hopcode (or QWEN_HOME if set). Env var QWEN_RUNTIME_DIR takes priority.", "type": "string" } } @@ -989,7 +988,7 @@ "type": "object", "properties": { "worktreeBaseDir": { - "description": "Custom base directory for Arena worktrees. Defaults to ~/.qwen/arena.", + "description": "Custom base directory for Arena worktrees. Defaults to ~/.hopcode/arena.", "type": "string" }, "preserveArtifacts": { diff --git a/packages/vscode-ide-companion/src/services/settingsWriter.ts b/packages/vscode-ide-companion/src/services/settingsWriter.ts index 6c2c6e4f4bb..6e02f36368f 100644 --- a/packages/vscode-ide-companion/src/services/settingsWriter.ts +++ b/packages/vscode-ide-companion/src/services/settingsWriter.ts @@ -227,7 +227,7 @@ function writeSettings(settings: Record): void { fs.renameSync(tmpPath, settingsPath); } catch (renameErr) { // renameSync can fail on Windows when a watcher / antivirus holds the - // target (EPERM/EBUSY). The temp file otherwise lingers in ~/.qwen + // target (EPERM/EBUSY). The temp file otherwise lingers in ~/.hopcode // containing API keys — clean it up so secrets don't accumulate on // disk across repeated failed writes. try { diff --git a/packages/vscode-ide-companion/src/types/approvalModeValueTypes.ts b/packages/vscode-ide-companion/src/types/approvalModeValueTypes.ts index 28c2a03083a..0c6eeb843c5 100644 --- a/packages/vscode-ide-companion/src/types/approvalModeValueTypes.ts +++ b/packages/vscode-ide-companion/src/types/approvalModeValueTypes.ts @@ -13,5 +13,4 @@ export type ApprovalModeValue = | 'default' | 'auto-edit' | 'auto' - | 'izn' | 'izn'; diff --git a/packages/web-templates/src/insight/src/App.tsx b/packages/web-templates/src/insight/src/App.tsx index d45286e41fd..1fd1b437dba 100644 --- a/packages/web-templates/src/insight/src/App.tsx +++ b/packages/web-templates/src/insight/src/App.tsx @@ -160,7 +160,7 @@ function InsightApp({ data }: { data: InsightData }) { hasRecordEntries(data.friction)); const showFeatures = !!data.qualitative && - (hasMeaningfulArray(data.qualitative.improvements?.Qwen_md_additions) || + (hasMeaningfulArray(data.qualitative.improvements?.Hopcode_md_additions) || hasMeaningfulArray(data.qualitative.improvements?.features_to_try)); const showPatterns = !!data.qualitative && diff --git a/packages/web-templates/src/insight/src/Qualitative.tsx b/packages/web-templates/src/insight/src/Qualitative.tsx index 6eb940f48fb..16245009286 100644 --- a/packages/web-templates/src/insight/src/Qualitative.tsx +++ b/packages/web-templates/src/insight/src/Qualitative.tsx @@ -567,13 +567,13 @@ function HopcodeMdAdditionsSection({ const checkedCount = checkedState.filter(Boolean).length; return ( -
+

Suggested HOPCODE.md Additions

Just copy this into HopCode to add it to your HOPCODE.md.

-
+