Skip to content

feat(run): add opt-in cleanup of the Claude Code session directory - #394

Merged
zpzjzj merged 4 commits into
alibaba:mainfrom
Walternater:fix/claude-projects-cleanup
Nov 12, 2026
Merged

zpzjzj merged 4 commits into
alibaba:mainfrom
Walternater:fix/claude-projects-cleanup

Conversation

@Walternater

@Walternater Walternater commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

An evaluation deletes its workspace, but Claude Code keeps a project directory outside it: ~/.claude/projects/<workspace-key>/ holds the session transcript and a memory/ folder, so repeated runs add up in the user's own session history.

This adds an explicit way to remove it, off by default:

  • --cleanup-sessions (default false) and environment.cleanup_sessions: true request it; the runner ORs the two so a suite can turn it on in YAML.
  • --no-delete takes precedence: the workspace and the sessions are both preserved, and the run reports that cleanup was skipped.
  • Only claude_code implements it today. With the flag set for another engine, the run reports that session cleanup is unsupported rather than doing nothing silently.
  • The rest of the project directory is removed as one unit — sessions and memory together.

Related issues

Fixes #366

Changes

  • agent.SessionDirCleaner: optional interface, implemented by ClaudeCodeAgent. It removes the project directory for this run's workspace key, using the same canonical-name match as the session lookup, so the directory the adapter read its transcript from is the one it deletes.
  • evaluator: calls the hook before closing the per-case runtime, and only when cleanup was requested and the workspace is deleted. It reports, once per run, every reason a requested cleanup did not run (no-delete, externally owned workspace, unsupported agent).
  • runtime.WorkspaceOwner: NoneRuntime reports whether it owns the workspace, so an externally owned --workspace keeps its sessions.
  • --cleanup-sessions in both CLI references; a "Session cleanup" section in writing-evals.md; CHANGELOG under Unreleased → Fixed.
  • Tests: default (no cleanup), explicit cleanup, --no-delete precedence with its message, externally owned workspace, unsupported agent with its message, YAML opt-in, and the adapter's own behaviour (matching directory removed, unrelated directory kept, shared directory kept, idempotent).

Test plan

  • make test
  • make verify
  • Manual, real CLI, macOS arm64, environment.type: none, Claude Code 2.1.317 — counting new directories under ~/.claude/projects:
default                                  -> 1 new directory (preserved, as before)
--cleanup-sessions                       -> 0 new directories (removed)
--cleanup-sessions --no-delete           -> 1 new directory, and the run printed
   level=WARNING msg="session cleanup requested but not run: --no-delete keeps both the workspace and its sessions"
environment.cleanup_sessions: true       -> 0 new directories

Negative controls: deleting rm -rf from the cleanup script makes the adapter test fail (project directory ... still exists); removing the cleanupSessions guard makes the "not requested" evaluator case fail (CleanupSessionDir calls = 1, want 0); removing the deleteWorkspace guard makes the --no-delete case fail.

Notes for reviewers

  • Follow-up for the other built-in engines and custom engines is feat(agent): add session cleanup lifecycle for built-in and custom agents #267, as you asked; the unsupported path is reported explicitly until then.
  • The directory is removed whole, which is what "the entire corresponding project directory, including sessions and memory" means here; I did not try to keep memory/ because the transcript and the memory entry are written by the CLI into the same directory and nothing in the adapter knows which files are which.
  • Safeguards kept: externally owned workspaces are preserved, and a directory is removed only when every *.jsonl in it records this workspace, so a directory shared by two workspaces that differ only in punctuation is left alone.

Disclosure

This PR was written with AI assistance: DeepSeek Harness (deepseek-v4.1-flash) drafted the change, the tests and this description.

I am wangchongfei. I reviewed every line of this diff and ran the checks above myself before opening it. I take full responsibility for the change.

I am stating this here, and on my profile, because a maintainer should know who — and what — they are reviewing.

@CLAassistant

CLAassistant commented Nov 12, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-12T06:05:57.034629Z d2e1a75 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d2e1a75e71

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/evaluator/evaluator.go Resolved
Comment thread internal/agent/session_lookup.go Resolved
@Walternater

Copy link
Copy Markdown
Contributor Author

Both findings are fixed in aec238e.

P1 (external workspace). DefaultEvaluator now cleans only when the runtime reports it owns the workspace: a new optional runtime.WorkspaceOwner is implemented by NoneRuntime from ownsWorkspaceDir, so --workspace <existing dir> keeps both the workspace and the project directory.

P2 (lossy name match). A canonical-name match is now only a candidate. The cleanup script removes a directory only when every *.jsonl in it records this workspace's working directory (the same encoded "cwd": markers the session lookup uses), so a directory shared with another workspace is left alone, and a directory with no identity markers is kept rather than guessed at.

Tests: keeps a directory shared with another workspace, keeps a directory whose sessions record no working directory, and externally owned workspace kept each fail when their guard is removed. make test and make verify pass.

@zpzjzj zpzjzj left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The cleanup makes sense, but enabling it by default changes existing behavior. Before merging, could we add an explicit opt-in flag?

  • Add --cleanup-sessions, defaulting to false, preserving the current behavior of deleting the workspace while retaining sessions.
  • If exposed in YAML, use cleanup_sessions.
  • Let --no-delete take precedence: when both flags are set, preserve both the workspace and sessions, and report that session cleanup was skipped.
  • Document that cleanup currently supports only claude_code and removes the entire corresponding project directory, including sessions and memory. Keep the safeguards for externally owned workspaces, uncertain ownership, and shared directories.
  • Follow up on other built-in agents and custom engines through #267. For unsupported agents, explicitly report that cleanup is unsupported when the flag is enabled.

Please add tests and documentation covering the default behavior, explicit cleanup, and interaction with --no-delete before merging.

Walternater added a commit to Walternater/skill-up that referenced this pull request Nov 12, 2026
Review feedback on alibaba#394: removing the Claude Code project directory by
default changes existing behaviour, and those sessions are user-visible
history that survives an evaluation today.

- --cleanup-sessions (default false) and environment.cleanup_sessions ask for
  it; the runner ORs the two, so YAML can enable it for a suite.
- --no-delete wins over the request, and the run says why cleanup was skipped.
- Only claude_code implements SessionDirCleaner. When the flag is set for any
  other engine the run reports that cleanup is unsupported instead of
  silently doing nothing.
- The existing safeguards stay: externally owned workspaces are preserved, and
  a directory is removed only when every session file in it records this
  workspace.
- Docs: the flag in both CLI references, a "Session cleanup" section in
  writing-evals, and the CHANGELOG entry now describes the opt-in.

Refs alibaba#366
@Walternater Walternater changed the title fix(agent): remove the Claude Code project directory with the workspace feat(run): add opt-in cleanup of the Claude Code session directory Nov 12, 2026
@Walternater

Copy link
Copy Markdown
Contributor Author

All five points are in 7b79191.

  • Opt-in: --cleanup-sessions, default false; environment.cleanup_sessions: true for YAML (the runner ORs them). The default run keeps today's behaviour: deleting the workspace and retaining the sessions.
  • --no-delete precedence: it wins, both are preserved, and the run says so — level=WARNING msg="session cleanup requested but not run: --no-delete keeps both the workspace and its sessions".
  • Documented scope: both CLI references and a new "Session cleanup" section in docs/guide/writing-evals.md say that only claude_code is supported and that the whole project directory goes, sessions and memory included. I did not try to keep memory/: the CLI writes the transcript and the memory entry into the same directory and nothing in the adapter knows which file is which.
  • Safeguards kept: externally owned workspaces (--workspace) are preserved, and a directory is removed only when every *.jsonl in it records this workspace — two workspaces differing only in punctuation share one directory, so it is left untouched.
  • Unsupported agents: with the flag set for any other engine the run reports that cleanup is unsupported instead of silently skipping (agent "qoder_cli" does not support it (supported today: claude_code)). Follow-up work for the other engines is feat(agent): add session cleanup lifecycle for built-in and custom agents #267.

Tests cover each of those: default, explicit cleanup, --no-delete with its message, externally owned workspace, unsupported agent with its message, the YAML opt-in, plus the adapter's own matching/idempotency. make test and make verify pass.

Real CLI, macOS, environment.type: none: default leaves one new ~/.claude/projects directory, --cleanup-sessions leaves none, --cleanup-sessions --no-delete leaves one and prints the warning, environment.cleanup_sessions: true leaves none.

With environment.type: none, every claude_code case left a directory under
~/.claude/projects/<workspace-key>/ after the run: the workspace was deleted
and the transcript directory was not. Repeated runs piled eval sessions into
the user's own Claude Code history, where session search and memory sync pick
them up as the user's own.

The evaluator now calls an optional agent.SessionDirCleaner hook before it
closes the per-case runtime, and only when the workspace is deleted too. The
Claude Code adapter implements it with the same canonical-name match the
session lookup uses, so the directory the adapter read the transcript from is
the directory it removes. --no-delete keeps both.

Tests: the adapter removes the matching directory and leaves an unrelated one
alone; the evaluator calls the hook once when the workspace is deleted and not
at all when it is kept. Each fails with its fix removed.

Refs alibaba#366
Review feedback on the first version of this change:

- The canonical name match is lossy: workspaces whose paths differ only in
  punctuation share one project directory. A directory is now removed only
  when every session file in it records this workspace, so a directory shared
  with another workspace survives.
- --workspace passes a directory the caller owns, and NoneRuntime preserves it
  even when deletion is requested. The project directory is now cleaned only
  when the runtime reports it owns the workspace (new runtime.WorkspaceOwner).

Both behaviours have a test that fails when its guard is removed.

Refs alibaba#366
Review feedback on alibaba#394: removing the Claude Code project directory by
default changes existing behaviour, and those sessions are user-visible
history that survives an evaluation today.

- --cleanup-sessions (default false) and environment.cleanup_sessions ask for
  it; the runner ORs the two, so YAML can enable it for a suite.
- --no-delete wins over the request, and the run says why cleanup was skipped.
- Only claude_code implements SessionDirCleaner. When the flag is set for any
  other engine the run reports that cleanup is unsupported instead of
  silently doing nothing.
- The existing safeguards stay: externally owned workspaces are preserved, and
  a directory is removed only when every session file in it records this
  workspace.
- Docs: the flag in both CLI references, a "Session cleanup" section in
  writing-evals, and the CHANGELOG entry now describes the opt-in.

Refs alibaba#366
@Walternater
Walternater force-pushed the fix/claude-projects-cleanup branch from 7b79191 to 8a3b567 Compare November 12, 2026 09:26

zpzjzj commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the update. I found a couple of issues that should be addressed before merging:

  1. CLI precedence: If cleanup_sessions: true is set in YAML, --cleanup-sessions=false still enables cleanup because the two values are combined with OR. Could we use the CLI value when the flag is explicitly set, and otherwise fall back to the YAML value? Please also add tests for both explicit true and false, including --no-delete.

  2. Session ownership: The current cwd string search can match a nested tool input or a session containing conflicting cwd values, so it may delete a directory belonging to another workspace. Could we parse the session identity fields and only delete when ownership is unambiguous? If parsing fails or ownership is unclear, the directory should be preserved.

  3. Directory discovery: The existing session lookup can find truncated or hashed directory names, while cleanup may silently skip them. Could we reuse the candidate discovery logic and apply the stricter ownership check before deletion?

For the cleanup tests, it would be helpful to cover mixed cwd values, nested tool input, and conflicting values beyond the current scan limit.

@Walternater

Copy link
Copy Markdown
Contributor Author

One correction on the follow-up: #267 is closed as not planned (2026-10-26). Your reasoning there was that a session id alone does not establish live resources and that local CLI history may be useful for debugging — which is also why this PR is opt-in rather than default. I therefore left the other engines on the "reported unsupported" path instead of reopening it.

If you want the follow-up tracked, say which you prefer and I will do it: reopen #267, or open a new issue scoped to the qoder/qwen session directories. Either way the shape is one agent.SessionDirCleaner per engine behind the same --cleanup-sessions; each engine needs its own answer about which files belong to the run (qodercli nests sub-agent transcripts one level deeper, qwen has an intermediate chats/ directory), so the identity check cannot simply be shared.

zpzjzj commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator

Reopening #267 sounds reasonable to me. For this PR, I’ll leave the scope up to you. A more complete solution is welcome, but keeping it Claude-only is also fine if Claude is the only engine you can validate in your current environment. Either way, please address the review findings above and clearly document the supported scope.

Review feedback on alibaba#394:

- An explicit --cleanup-sessions=false now overrides
  environment.cleanup_sessions: true; only an unset flag falls back to the
  config.
- Ownership is decided from each transcript's parsed cwd/directories fields,
  never a string search: a cwd inside a tool argument no longer counts, and a
  directory is removed only when every transcript records this workspace.
  Directories whose transcripts disagree, fail to parse, or record nothing are
  kept, as is one whose transcript is too large to read in full.
- Directory discovery matches the session lookup: canonical-name matches
  first, every directory when none matches, so a truncated or hashed name is
  not silently skipped.
- Tests cover mixed workspaces, a nested tool-input cwd, a conflict beyond the
  old 64 KiB scan limit, a malformed transcript, a transcript without
  identity, and a hashed directory name.

Refs alibaba#366
@Walternater

Copy link
Copy Markdown
Contributor Author

All three are in 8312e17.

1. CLI precedence. An explicit --cleanup-sessions=false now overrides environment.cleanup_sessions: true; only an unset flag falls back to the config (cmd.Flags().Changed is carried through as CleanupSessionsSet). Tests cover an unset flag with the config on, explicit true, explicit false against a config true, and the --no-delete interaction. Both CLI references and the writing-evals section say the flag wins.

2. Ownership. Cleanup no longer searches for the cwd string. Each transcript line is parsed and only its top-level cwd / directories fields are identity, so a path inside a tool argument cannot match. A directory is removed only when every transcript in it records this workspace; it is kept when transcripts disagree, a line fails to parse, no identity is recorded, or a transcript exceeds the 4 MiB read bound. Tests: mixed workspaces, nested tool input, a conflict that only appears after 70 KiB (past the old scan limit), a malformed line, no identity.

3. Discovery. Candidate discovery is now the lookup's two-phase shape: directories whose canonicalised name matches the workspace key first, and every directory at that depth when none does, so a truncated or hashed name is not silently skipped. There is a test for a hashed directory name holding this run's transcript: it is removed, and a sibling without identity is kept.

Re-ran the real CLI after the change (macOS, environment.type: none): default leaves one new ~/.claude/projects directory; --cleanup-sessions leaves none; --cleanup-sessions --no-delete leaves one and prints the skip warning; environment.cleanup_sessions: true leaves none; and environment.cleanup_sessions: true plus an explicit --cleanup-sessions=false leaves one, which is the precedence fix above.

On #267: I cannot reopen an issue I did not open (no triage rights here), so I left the scope Claude-only, as you said is fine, and documented that the other engines report "unsupported". If you want the follow-up tracked, reopen #267 or tell me to open a scoped issue and I will.

@zpzjzj
zpzjzj added this pull request to the merge queue Nov 12, 2026
Merged via the queue into alibaba:main with commit ecb2499 Nov 12, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

claude_code on the none runtime leaves a ~/.claude/projects folder for every case workspace

3 participants