Skip to content

Commit 29f2e54

Browse files
Telliclaude
andauthored
Add snapshot editing, durable compaction, and live turn control (#51)
* feat: add snapshot editing, durable compaction, and live turn control * test: isolate process-wide conversation cache state * Address review: harden snapshot publication, REPL exit codes, and compaction pinning - Stage snapshot replacements with the target's Unix mode before writing content, and report a target deleted mid-staging as stale. - Document that snapshot publication does not keep owner/ACLs/xattrs. - write_file and edit_file take the shared semantic-write lock. - REPL: keep the session open on non-provider prompt failures; return nonzero for unknown slash commands and failed custom commands; keep the last exit code on idle Ctrl+C. - Compaction: check the summary budget only once compaction is needed, and pin the turn's original request as well as the latest correction. - Keep provider-reported usage when the response text is empty. - Add coverage for staging recheck, precheck cancellation, snapshot symlink escape, unfinished primary compaction, and cancel isolation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 9cd0476 commit 29f2e54

47 files changed

Lines changed: 2084 additions & 143 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,7 @@ Primary workflow modes:
138138
| Capability | Why it matters |
139139
|---|---|
140140
| Durable sessions | Persist conversation state, turn history, checkpoints, and recovery metadata for longer-running agent work |
141+
| Interactive execution | Snapshot-aware batch edits, durable automatic context compaction, live tool progress, steering, and turn-scoped cancellation |
141142
| Permission-aware tools | Route file, shell, and plugin-backed actions through explicit policy and approval decisions |
142143
| Provider abstraction | Run against Anthropic and OpenAI-compatible backends through a typed runtime surface |
143144
| Local runtime catalog | Surface Ollama, llama.cpp, and other OpenAI-compatible profiles with health, model discovery, and embedding defaults |
@@ -247,6 +248,7 @@ Subcommands include `prompt`, `repl`, `doctor`, `status`, `session`, `index`, `m
247248
|---|---|
248249
| [docs/architecture.md](docs/architecture.md) | Solution layout, dependencies, and execution flows |
249250
| [docs/runtime.md](docs/runtime.md) | Turns, `ConversationRuntime`, and runtime coordinators |
251+
| [docs/interactive-runtime.md](docs/interactive-runtime.md) | Snapshot editing, automatic compaction, live control, and configuration |
250252
| [docs/sessions.md](docs/sessions.md) | Session snapshots and append-only event logs |
251253
| [docs/providers.md](docs/providers.md) | `IModelProvider`, configuration, and provider integration |
252254
| [docs/tools.md](docs/tools.md) | Tool registry, executor behavior, and built-ins |

‎docs/agents.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,9 @@ All concrete agents inherit **`SharpClawAgentBase`**, which implements **`RunAsy
3232

3333
## Tools and the agent path
3434

35-
**`AgentRunContext`** includes **`IToolExecutor`**, but **`AgentFrameworkBridge`** does **not** currently register SharpClaw tools with the Microsoft Agent Framework tool-calling pipeline; **`AgentRunResult.ToolResults`** is an empty array in that bridge.
35+
**`AgentFrameworkBridge`** builds the permission-aware tool execution context and supplies registry definitions to **`ProviderBackedAgentKernel`**. The kernel owns the multi-iteration provider tool loop and uses **`ToolCallDispatcher`** to execute tools through **`IToolExecutor`**. The bridge returns the collected tool results in **`AgentRunResult.ToolResults`**.
3636

37-
Tools remain available to **`DefaultTurnRunner`** consumers if a different agent implementation uses **`IToolExecutor`**; tests and parity harness exercise **`IToolExecutor`** directly.
37+
At complete tool boundaries, the kernel accepts queued steering and invokes the optional **`IAgentContextManager`** registered by Runtime for durable automatic compaction. Neither path bypasses tool permissions. See [interactive runtime](interactive-runtime.md).
3838

3939
## Metadata
4040

‎docs/interactive-runtime.md‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
# Snapshot edits, automatic compaction, and live turns
2+
3+
These features extend the existing runtime. The `read_file` and `edit_file` contracts, permission modes, checkpoint formats, and command result envelopes remain unchanged.
4+
5+
## Snapshot-aware editing
6+
7+
`read_file_snapshot` returns a bounded line window and a SHA-256 `snapshotId` for the complete decoded file text. It reads the content and computes the identifier from the same snapshot. Defaults are `startLine: 1` and `limit: 200`; the maximum limit is 500 lines. `nextLine` identifies the next window, or is null at EOF. Reading another window does not change the identifier unless the file changes.
8+
9+
```json
10+
{"path":"src/Example.cs","startLine":1,"limit":100}
11+
```
12+
13+
Pass that identifier to `edit_file_snapshot`:
14+
15+
```json
16+
{
17+
"path": "src/Example.cs",
18+
"snapshotId": "<snapshotId returned by read_file_snapshot>",
19+
"edits": [
20+
{"startLine": 3, "deleteLineCount": 1, "newText": " return result;\n"},
21+
{"startLine": 8, "deleteLineCount": 0, "newText": "// Additional explanation\n"}
22+
]
23+
}
24+
```
25+
26+
Every line number addresses the original snapshot, even when earlier edits insert or remove lines. An edit replaces complete lines, including their terminators. `newText` supplies the exact replacement and any needed LF or CRLF terminators. Zero deleted lines inserts before `startLine`; `totalLineCount + 1` inserts at EOF. An empty file accepts insertion at line 1. Edits must not overlap or share an insertion point. A request accepts 1–100 edits to one file.
27+
28+
The entire batch is validated before writing. The tool stages a complete replacement in the same directory, checks the original content again immediately before publication, and records one mutation with before/after text for existing checkpoint undo/redo. Failures return a structured status such as `staleSnapshot`, `invalidEdits`, or `notFound`. A stale snapshot requires a fresh read. Unchanged batches produce no mutation.
29+
30+
Execution uses the normal `FileSystemWrite` policy and workspace resolver. Read-only and plan modes still block mutation. Snapshot writes share the semantic-write workspace lock with Roslyn rename, `write_file`, and `edit_file`. The final file replacement avoids partially written targets on cancellation; temporary files are cleaned up. Cancellation cannot interrupt the synchronous publication-to-journal-recording interval.
31+
32+
The lock coordinates cooperating writers, not external editors. There remains a filesystem race between the last content check and replacement; this is not an operating-system compare-and-swap. Like existing mutation snapshots, identifiers describe decoded text and writes use UTF-8, not byte-for-byte encoding/BOM preservation. Untouched line endings and Unix file modes are preserved. Because the staged file replaces the target, its owner, group, ACLs, and extended attributes come from the staged file rather than the original; `edit_file` writes in place and keeps them.
33+
34+
## Durable automatic compaction
35+
36+
The runtime registers `IAgentContextManager`. The agent kernel invokes it before provider requests, including requests following completed tool exchanges. It accounts for system instructions, tool schemas, and reserved output when deciding whether maintenance is needed. It does not split a tool call from its result.
37+
38+
When needed, the selected provider receives a separate tool-free summarization request. Its validated JSON working state contains the objective, constraints, decisions, changed files, verification evidence, and outstanding work. Recent messages, the active user request, and pinned instruction/image messages remain verbatim. Summaries are conversation data and cannot grant permissions.
39+
40+
A `contextCompacted` event stores the working state, archived messages, replacement messages, token estimates, model, and measured summary usage. The event is persisted **before** the replacement is used. Original events are never deleted. Completed primary-turn snapshots participate in history replay, so a fresh host can resume from the same summary and retained messages. Child snapshots do not replace the parent's history. The turn's reported usage includes successful provider iterations and summary calls, including responses superseded by steering.
41+
42+
Configure the standard .NET configuration stack under `SharpClaw:Compaction` (or use `services.Configure<AutomaticCompactionOptions>`):
43+
44+
```json
45+
{
46+
"SharpClaw": {
47+
"Compaction": {
48+
"Enabled": true,
49+
"ContextWindowTokens": 128000,
50+
"ReservedOutputTokens": 16384,
51+
"TriggerRatio": 0.8,
52+
"SummaryMaxTokens": 4096,
53+
"RetainedMessageCount": 6,
54+
"ModelContextWindows": {
55+
"provider/model": 128000
56+
}
57+
}
58+
}
59+
}
60+
```
61+
62+
Replace `provider/model` with the exact resolved provider/model key. The output reserve is increased when a request's maximum output is higher. Budgeting uses estimates (approximately characters divided by four, with an image allowance), not a provider tokenizer; configure conservative windows for your models.
63+
64+
Invalid summaries, persistence failures, or oversized irreducible requests fail visibly instead of silently dropping context. The original history remains intact. A single oversized request/exchange or an archive larger than the summarizer's window requires smaller tool outputs or a larger configured model window. This first implementation does not recursively summarize oversized archives. Automatic maintenance does not change the existing manual `/compact` command.
65+
66+
## Live turn control
67+
68+
The REPL displays tool activity and elapsed time while a prompt is running. Tool progress is suppressed for JSON output; existing result envelopes remain unchanged.
69+
70+
- Ordinary input during a turn queues a follow-up (maximum 16). It runs after the current turn settles, in the existing session.
71+
- `/steer <text>` queues a correction for the next safe provider-request boundary. It does not interrupt an in-flight tool. A correction arriving during the final stream triggers another provider iteration, subject to the existing iteration limit.
72+
- `/cancel` or Ctrl+C during a turn cancels that turn and its pending approvals while keeping the REPL available. Recorded edits remain available through normal recovery/undo.
73+
- `/approve <id> yes` or `/approve <id> no` responds to the exact displayed approval request. Plain `yes`, queued prompts, and stale IDs cannot grant permission.
74+
- `/exit` cancels the active turn, waits for cleanup, discards queued work, and exits. Ctrl+C while idle exits.
75+
- EOF denies pending and future REPL approvals and allows remaining work to settle. It cannot leave an approval waiting for unavailable input.
76+
77+
The REPL remains available after a failed prompt. Its exit code reflects the last completed command/turn, so a provider or verification failure followed by EOF still exits nonzero.
78+
79+
Steering has a bounded queue (16 messages, at most 16,000 characters each). Accepted steering is persisted as `turnSteered` events and replayed with the conversation, including after cancellation or failure. Verification repairs also retain accepted corrections. Corrections that miss the final boundary remain queued as follow-up work. The REPL owns one terminal input read at a time; its approval transport never starts a competing console read. Other slash commands run while idle. Live controls currently wrap ordinary prompt turns; slash-command handlers retain their existing execution behavior.
80+
81+
Embedded callers can use the same control service without the terminal:
82+
83+
```csharp
84+
using var turn = liveTurnControl.Begin(cancellationToken);
85+
var execution = runtime.RunPromptAsync(request, turn.CancellationToken);
86+
87+
// From UI callbacks while execution is pending:
88+
turn.TrySteer("Keep the existing public API unchanged.");
89+
// turn.Cancel();
90+
91+
var result = await execution;
92+
var pendingCorrections = turn.CloseSteering();
93+
```
94+
95+
After execution settles, `CloseSteering()` atomically stops intake and returns pending corrections for the caller to retain as follow-ups. Read `turn.ReadEventsAsync(...)` concurrently for progress. Create one scope per invocation, pass its token through execution, and dispose it after execution settles. Scopes follow the caller's async flow; independent scopes do not broadcast each other's events or cancellations. Live progress is bounded and may drop old display events for slow readers; persisted session events remain authoritative. Steering never bypasses permission evaluation.
96+
97+
## Verification
98+
99+
Regression coverage includes stale and overlapping edits, CRLF/Unicode/EOF handling, permission denial, staged-write cancellation, durable undo/redo after restart, safe tool-pair compaction, invalid summaries and storage failures, fresh-host replay, mid-turn compaction, live steering, cancellation/resume, concurrent scope isolation, queued REPL input, exact-ID approval responses, and EOF during approval.

‎docs/runtime.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ When the effective **`PrimaryMode`** is **`Spec`**, the assembler appends a stru
5555

5656
When the effective **`PrimaryMode`** is **`Plan`**, the assembler now appends a deep-planning JSON contract that requires the model to return summary, assumptions, risks, next action, and task data.
5757

58-
Conversation history is rebuilt from persisted session events and truncated by token budget before being attached to the next provider request. Assistant history prefers the persisted final turn output and only falls back to streamed provider deltas when needed.
58+
Conversation history is rebuilt from persisted session events, including completed primary-turn compaction snapshots and accepted steering. Before provider requests, automatic context maintenance can durably summarize older context while preserving recent complete tool exchanges. It no longer silently truncates history before maintenance. Assistant history prefers the persisted final turn output and only falls back to streamed provider deltas when needed. See [interactive runtime](interactive-runtime.md) for budgets, failure behavior, and live turn control.
5959

6060
Cross-session memory is sourced from:
6161

@@ -110,8 +110,8 @@ The parity layer adds several runtime-owned services:
110110

111111
- **`ISharpClawConfigService`** — loads user/workspace `config.jsonc` + `sharpclaw.jsonc` and merges them by precedence
112112
- **`IAgentCatalogService`** — overlays configured specialist agents on top of built-in agents
113-
- **`IConversationCompactionService`** — creates durable session summaries stored in session metadata
114-
- compaction also promotes a project-scoped summary memory entry for later session recall
113+
- **`IConversationCompactionService`** — creates manual `/compact` summaries stored in session metadata and project-scoped summary memory
114+
- **`IAgentContextManager`** — performs automatic provider-context maintenance using durable compaction events; see [interactive runtime](interactive-runtime.md)
115115
- **`IShareSessionService`** — creates and removes self-hosted share snapshots
116116
- **`IHookDispatcher`** — executes configured hook processes for turn/tool/share/server events and exposes hook inspection/testing
117117
- **`ITodoService`** — persists session and workspace todo items under session metadata and `.sharpclaw/tasks.json`

‎docs/tools.md‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,14 +31,16 @@ From **`ToolsServiceCollectionExtensions`**:
3131
| Read file | **`ReadFileTool.ToolName`** |
3232
| Write file | **`WriteFileTool.ToolName`** |
3333
| Edit file | **`EditFileTool.ToolName`** |
34+
| Read snapshot | **`ReadFileSnapshotTool.ToolName`** (`read_file_snapshot`) |
35+
| Edit snapshot | **`EditFileSnapshotTool.ToolName`** (`edit_file_snapshot`) |
3436
| Glob search | **`GlobSearchTool.ToolName`** |
3537
| Grep search | **`GrepSearchTool.ToolName`** |
3638
| Bash / shell | **`BashTool.ToolName`** |
3739
| Web search | **`WebSearchTool`** |
3840
| Web fetch | **`WebFetchTool`** |
3941
| Tool search | **`ToolSearchTool.ToolName`** (`tool_search`) |
4042

41-
Each built-in is registered both as a concrete singleton and as **`ISharpClawTool`**.
43+
Built-ins are registered as **`ISharpClawTool`** singletons; some also expose their concrete type through DI.
4244

4345
## Authoring a built-in tool
4446

@@ -54,10 +56,12 @@ Use **Protocol** types for stable payloads where appropriate; tool JSON helpers
5456
## CLI / agent usage
5557

5658
- **`tool_search`** queries **`IToolRegistry.SearchAsync`**.
57-
- End-to-end **LLM-driven tool use** in the default agent path is **not** wired through **`AgentFrameworkBridge`** today; **`AgentRunContext.ToolExecutor`** is available for future or alternate agent implementations.
59+
- **`AgentFrameworkBridge`** supplies registered tool definitions to **`ProviderBackedAgentKernel`**. Its tool loop dispatches calls through **`ToolCallDispatcher`** and the permission-aware **`IToolExecutor`**, including snapshot editing.
5860

5961
See [permissions.md](permissions.md) for gates on destructive and elevated tools.
6062

6163
Compiler-backed .NET tools are described in [.NET intelligence](dotnet-intelligence.md). They share normal tool discovery, explicit schemas, and a separate execution decision before cold MSBuild evaluation.
6264

6365
The permission-gated `verify_workspace` tool and CLI/REPL equivalents are documented in [Verification](verification.md).
66+
67+
The additive `read_file_snapshot` and `edit_file_snapshot` tools support bounded reads, stale-content rejection, and non-overlapping single-file edit batches through the same permission executor and mutation journal. Existing file-tool contracts are unchanged. See [snapshot editing](interactive-runtime.md#snapshot-aware-editing) for schemas, newline handling, and publication guarantees.
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
using SharpClaw.Code.Agents.Models;
2+
using SharpClaw.Code.Protocol.Models;
3+
using SharpClaw.Code.Providers.Abstractions;
4+
5+
namespace SharpClaw.Code.Agents.Abstractions;
6+
7+
/// <summary>Maintains bounded provider context at complete tool-loop boundaries.</summary>
8+
public interface IAgentContextManager
9+
{
10+
/// <summary>Persists any compaction before returning replacement messages. Never executes tools.</summary>
11+
Task<AgentContextPreparation> PrepareAsync(AgentRunContext context, IModelProvider provider, ProviderRequest request, CancellationToken cancellationToken);
12+
}
13+
14+
/// <summary>A prepared request and the measured usage of any summarization call.</summary>
15+
public sealed record AgentContextPreparation(ProviderRequest Request, UsageSnapshot? CompactionUsage = null);
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
using SharpClaw.Code.Agents.Models;
2+
3+
namespace SharpClaw.Code.Agents.Abstractions;
4+
5+
/// <summary>Exposes control belonging only to the current caller's asynchronous turn flow.</summary>
6+
public interface IAgentTurnControlAccessor
7+
{
8+
/// <summary>Persists and consumes queued user steering at a complete tool boundary.</summary>
9+
Task<IReadOnlyList<string>> ConsumeSteeringAsync(AgentRunContext context, CancellationToken cancellationToken);
10+
}

0 commit comments

Comments
 (0)