This repository was archived by the owner on Sep 30, 2026. It is now read-only.
Repository navigation
feat(tools): add agent-callable compact_context tool - #1
Merged
Merged
Conversation
Give a running agent a first-class tool to trigger manual compaction of its own context mid-turn, instead of relying only on automatic compaction or a human pressing /compact. This is ordinary self-management, so the tool is registered by default and is not gated behind debug-control. The tool acts only on the caller's own session (from ToolContext.session_id) and reuses the existing compaction path end to end: it defers to Agent::request_manual_compaction, the same code /compact runs, and the background summary is applied at the turn boundary via the existing CompactionFinished path. Design: the real compaction entry point needs the caller's live session messages and a forked provider, both owned by the Agent, which is exclusively locked (Arc<Mutex<Agent>>) across its own turn while the tool runs. A socket self-call would re-subscribe a live session and risk a takeover, and ToolContext has 60+ construction sites so threading a handle through it is a wide change. Instead the tool records a per-session request in a process-global keyed by session id (mirroring SESSION_TOOL_POLICIES), and both agent turn loops drain it at the safe point after all tool results are in, where they hold &mut Agent. When the provider does not support compaction the tool returns a clear explanation rather than erroring, and queues nothing. Tests: the tool queues a request and reports on a compaction-capable provider, queues nothing and explains on an unsupported provider, and appears in the default tool listing.
yjuyjuy
added a commit
that referenced
this pull request
Aug 13, 2026
* Fix fork master CI rot: formatting, clippy, and stale TUI tests Fork master CI had been red since the fork was created. Three independent causes, all artifacts of the messy upstream sync that took new code but left old tests and dropped upstream lint gates: Format + Quality Guardrails (cargo fmt --all --check): - client_lifecycle_tests.rs landed unformatted. Reformatted. Quality Guardrails (cargo clippy --all-targets --all-features -D warnings, previously masked behind the earlier fmt failure): - turn_notify.rs: the macOS/test-only notification helpers (notification_text, osc_safe, kitty_notification_id, kitty_notification_sequence, iterm_notification_sequence) and the base64::Engine import were ungated, so non-macOS non-test builds saw them as dead code. Gated with #[cfg(any(target_os = "macos", test))], matching upstream. - onboarding_graph.rs: restored the upstream #![cfg_attr(not(test), allow(dead_code))] module attribute the sync dropped; the descriptive graph's invariant helpers are exercised only by tests. - ui_onboarding.rs: int_plus_one (`>= x + 1` -> `> x`). - remote/input_dispatch.rs: collapsed a collapsible_if into a let-chain, preserving the unconditional take() of the one-shot stash. - tests/e2e/test_support/mod.rs: a Request::Message constructor was missing the submission_nonce field added by the dedup change. Set None. Build & Test (jcode-tui lib tests, all three OS): - test_context_command_reports_session_context_snapshot: the todo confidence renders as a categorical label now, so assert "confidence plausible" (score 77 -> Plausible) instead of the old "confidence 77%". - unbiased_visual_prompt_retry_renders_complete_feedback_change: the live card (associated ToolCall) compacts verbose feedback while the restored card renders every section; assert section presence rather than the full untruncated strings the older renderer no longer emits at width 72. - test_prepare_messages_shows_live_batch_progress_in_chat_history: the empty-ish initial chat renders the "Updates" changelog banner, whose real entries carry PR references like (#16) that contain "#1" and tripped the batch-row numbering assertion. Pin the changelog to empty for the test and restore it afterwards. Validated: cargo fmt --all --check clean, cargo clippy --all-targets --all-features -D warnings clean, the three previously-failing tests plus the turn_notify suite pass. * Refresh oversized-file ratchet baseline for the post-sync fork tree The oversized-file ratchet (scripts/check_code_size_budget.py) compares production Rust file sizes against scripts/code_size_budget.json, which was last set before the large upstream sync pulled in hundreds of commits of file growth. The ratchet had never actually run on fork master because the earlier formatting failure short-circuited the Quality Guardrails job before it was reached; fixing formatting exposed ~28 stale entries. Refresh the baseline to the current tree with `--update`, the script's documented mechanism after an intentional large change, so the ratchet enforces "do not grow from here" against reality instead of a long-superseded snapshot. No production code changes; only the baseline JSON is updated. * Refresh remaining Quality Guardrails ratchet baselines for post-sync fork With formatting fixed, the Quality Guardrails job runs every ratchet step that was previously skipped after the oversized-file step failed. The remaining ratchet baselines were also set before the large upstream sync and are stale against the current tree, so they too must be refreshed to "do not regress from here": - scripts/test_size_budget.json: oversized test-file set (37 -> 41). - scripts/panic_budget.json: panic-prone usage (63 -> 74, inherited from synced upstream code, not this change). - scripts/swallowed_error_budget.json: swallowed-error-like patterns (3091 -> 3209, likewise inherited from the sync). - scripts/wildcard_reexport_budget.json: cross-crate wildcard re-exports (16 -> 17). These record the sizes/counts already present in the synced tree; this change adds no new production panic-prone or swallowed-error patterns of its own. Only baseline JSON is updated. Verified locally: cargo fmt --all --check, cargo clippy --all-targets --all-features -D warnings, every ratchet script, cargo test -p jcode-sdk parity, cargo test -p jcode-desktop2 profile::, and cargo machete all pass. * Use a non-triggering fake token in the secret-rejection test The Security preflight secret scan (scripts/security_preflight.sh) matches `gh[pousr]_[A-Za-z0-9]{36,}` across all tracked files, and a discover.rs test fixture used a 40-char `ghp_...` string to prove normalize_selection_name rejects GitHub-token-shaped input. That fixture tripped the scan, failing the Linux Build & Test job. Shorten the fake token to `ghp_exampletoken1234`. The app's own detector (contains_prefixed_secret) still flags it - it only needs the `ghp_` prefix plus at least 8 characters - so the test still verifies rejection, while the preflight regex (which requires 36+ trailing characters) no longer matches it. No production behavior change. Verified: the test still passes and scripts/security_preflight.sh --strict now passes (secret scan clean, script permissions clean, cargo-audit only reports the documented allowed advisories). --------- Co-authored-by: jeremy <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds a first-class
compact_contexttool so a running agent can trigger compaction of its own context mid-turn, instead of relying only on automatic compaction or a human pressing/compact. This is ordinary self-management, so the tool is registered by default and is not gated behind debug-control.The tool acts only on the caller's own session (from
ToolContext.session_id) and reuses the existing compaction path end to end: it defers toAgent::request_manual_compaction(the same code/compactruns), and the background summary is applied at the turn boundary via the existingCompactionFinishedpath. It deliberately offers no way to compact another session.Design (why the work is deferred)
The real compaction entry point needs the caller's live session messages and a forked provider, both owned by the
Agent, which is exclusively locked (Arc<Mutex<Agent>>) across its own turn while the tool runs. So the tool cannot borrow the agent synchronously:Subscribea live session and risk a takeover of the very session executing the tool.ToolContext(design B) touches 60+ construction sites.Instead the tool records a per-session request in a process-global keyed by session id, mirroring the existing
SESSION_TOOL_POLICIESpattern, and both agent turn loops (turn_loops.rsandturn_streaming_mpsc.rs) drain it at the safe point after all tool results are in, where they already hold&mut Agent. NoToolContextchange is needed.When the provider does not support compaction the tool returns a clear explanation rather than erroring, and queues nothing.
Behavior
compact_contexttakes no required parameters (just the sharedintent).Tests
crates/jcode-app-core/src/tool/compact.rsunit tests:compact_contextappears in the default tool listing (Registry::new().tool_names())Validation
cargo build -p jcode-app-corecleancargo build -p jcode --bin jcodeclean (whole workspace)cargo test -p jcode-app-core compactgreen (3 new tests pass)cargo clippy -p jcode-app-core --lib --testsclean for the touched code (remaining warnings are pre-existing intool/todo.rs, untouched here)Note: a full interactive TUI smoke needs a live provider session, which is not reproducible in this environment (the available Claude OAuth token fails to refresh). The registry test is the authoritative programmatic equivalent, asserting the tool is in the exact default set every live session builds.