From 875d376358839ce7fdad1045be96b1206692bdd6 Mon Sep 17 00:00:00 2001 From: telli Date: Tue, 10 Nov 2026 03:32:00 -0800 Subject: [PATCH 01/12] Address launch findings review (baseline) Security, correctness and durability fixes described in docs/launch-findings-review.md, committed as-is before the quality pass. Co-Authored-By: Claude Opus 5.5 --- README.md | 23 ++-- docs/launch-findings-review.md | 66 +++++++++++ docs/mcp.md | 2 + docs/permissions.md | 6 +- docs/plugins.md | 4 +- extensions/vscode/README.md | 4 +- extensions/vscode/package.json | 18 +-- extensions/vscode/src/extension.ts | 5 +- .../vscode/test/editorCommands.test.cjs | 3 +- src/SharpClaw.Code.Acp/AcpStdioHost.cs | 13 +- .../Internal/ProviderBackedAgentKernel.cs | 24 +--- src/SharpClaw.Code.Cli/CliHostBuilder.cs | 14 ++- src/SharpClaw.Code.Cli/Program.cs | 34 ++++-- .../Models/CommandExecutionContext.cs | 6 +- .../Options/GlobalCliOptions.cs | 13 +- src/SharpClaw.Code.Commands/Repl/ReplHost.cs | 14 ++- .../Models/ProcessRunRequest.cs | 4 +- .../Services/LocalFileSystem.cs | 35 +++++- .../Services/LocalPackagePath.cs | 36 ++++++ .../Services/PathService.cs | 14 ++- .../Services/ProcessRunner.cs | 39 +++++- .../Services/ProcessMcpServerHost.cs | 17 ++- .../Services/SdkMcpProcessSupervisor.cs | 2 +- .../Services/SqliteWorkspaceKnowledgeStore.cs | 7 +- .../Rules/DangerousShellPatternRule.cs | 6 +- .../Rules/PluginTrustRule.cs | 13 +- .../Services/PermissionPolicyEngine.cs | 49 ++++++-- .../Services/PluginManager.cs | 41 +++---- .../AnthropicProvider.cs | 15 ++- .../Configuration/AnthropicProviderOptions.cs | 2 +- .../Internal/AnthropicSdkStreamAdapter.cs | 36 +++++- .../Internal/OpenAiMeaiStreamAdapter.cs | 19 ++- .../Resilience/ResilientProviderDecorator.cs | 7 ++ .../Configuration/SharpClawConfigService.cs | 4 +- .../CheckpointMutationCoordinator.cs | 6 + .../Orchestration/ConversationRuntime.cs | 18 ++- .../Prompts/PromptReferenceResolver.cs | 10 +- .../Server/WorkspaceHttpServer.cs | 65 +++++----- .../Verification/VerificationService.cs | 4 +- .../Workflow/HookDispatcher.cs | 6 +- .../Services/SkillRegistry.cs | 4 +- .../BuiltIn/GlobSearchTool.cs | 2 +- .../BuiltIn/GrepSearchTool.cs | 14 ++- .../BuiltIn/ReadFileTool.cs | 2 + .../BuiltIn/WebFetchTool.cs | 2 +- .../Registry/ToolRegistry.cs | 1 + .../Utilities/GlobPatternMatcher.cs | 7 +- .../Utilities/WorkspaceSearchFiles.cs | 22 ++++ .../Services/PublicNetwork.cs | 51 ++++++++ .../Services/WebFetchService.cs | 17 ++- .../WebServiceCollectionExtensions.cs | 1 + .../Memory/CSharpRenameTests.cs | 2 +- .../Runtime/ApprovalAuthIntegrationTests.cs | 19 ++- .../Runtime/InteractiveMilestoneTests.cs | 2 +- .../Runtime/WorkspaceHttpServerAdminTests.cs | 18 ++- .../AutomaticVerificationTests.cs | 4 +- .../ParityScenarioTests.cs | 6 +- .../Commands/FeatureCommandHandlersTests.cs | 4 +- .../Commands/ModeAndCliOptionsTests.cs | 20 ++++ .../McpPlugins/McpAndPluginLifecycleTests.cs | 8 +- .../WorkspaceKnowledgeServicesTests.cs | 15 +++ .../PermissionPolicyEngineTests.cs | 50 +++++++- .../Providers/ProviderStreamAdapterTests.cs | 41 +++++++ .../Providers/ResilienceTests.cs | 21 ++++ .../Providers/ToolUseStreamAdapterTests.cs | 2 + .../ConfiguredApprovalIdentityServiceTests.cs | 12 +- .../Runtime/LaunchSecurityRegressionTests.cs | 111 ++++++++++++++++++ .../Runtime/PromptReferenceResolverTests.cs | 13 ++ .../Runtime/SharpClawConfigServiceTests.cs | 4 + .../Tools/SnapshotEditingTests.cs | 2 +- .../Web/WebServiceAndToolTests.cs | 2 +- 71 files changed, 958 insertions(+), 225 deletions(-) create mode 100644 docs/launch-findings-review.md create mode 100644 src/SharpClaw.Code.Infrastructure/Services/LocalPackagePath.cs create mode 100644 src/SharpClaw.Code.Tools/Utilities/WorkspaceSearchFiles.cs create mode 100644 src/SharpClaw.Code.Web/Services/PublicNetwork.cs create mode 100644 tests/SharpClaw.Code.UnitTests/Runtime/LaunchSecurityRegressionTests.cs diff --git a/README.md b/README.md index c37d68c..ba1c1a4 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ It is designed for: - teams that want a **C# coding agent** runtime instead of stitching together ad hoc scripts - developers building **AI-powered CLI tools** with strong machine-readable output -- products that need **MCP integration**, plugin discovery, and permission-aware tool execution +- products that need **MCP server hosting and outbound lifecycle management**, plugin discovery, and permission-aware tool execution - workflows that need **durable session state**, append-only history, and replayable runtime events - cross-platform environments, with deliberate attention to **Windows-safe behavior** @@ -142,8 +142,8 @@ Primary workflow modes: | Permission-aware tools | Route file, shell, and plugin-backed actions through explicit policy and approval decisions | | Provider abstraction | Run against Anthropic and OpenAI-compatible backends through a typed runtime surface | | Local runtime catalog | Surface Ollama, llama.cpp, and other OpenAI-compatible profiles with health, model discovery, and embedding defaults | -| MCP support | Register outbound servers and host permission-aware stdio or Streamable HTTP tools | -| Plugins and skills | Extend the runtime with trusted plugin manifests and discoverable workspace skills | +| MCP support | Manage outbound server lifecycle (agent tool invocation is not connected); host permission-aware stdio or Streamable HTTP tools | +| Plugins and skills | Discover plugin manifests and workspace skills; plugin process calls require explicit approval | | .NET intelligence | Resolve exact Roslyn symbols, find references and hierarchy, inspect compiler diagnostics, and rename with undo | | Verification | Explicit build/test reports and opt-in bounded repair, with permission checks and durable recovery | | Workspace knowledge | Build a durable local index for lexical, symbol, and semantic workspace search | @@ -153,7 +153,7 @@ Primary workflow modes: | JSON-friendly CLI | Use the same runtime through human-readable terminal flows or machine-readable command output | | Spec workflow mode | Turn prompts into structured requirements, technical design, and task documents for feature proposals | | Embedded SDK + server | Host the runtime via `SharpClaw.Code` or expose prompt, session, admin, and SSE endpoints for editor or automation clients | -| Config + agent catalog | Layer user/workspace JSONC config with typed agent defaults, tool allowlists, and runtime hooks | +| Config + agent catalog | Layer user/workspace JSONC config with typed agent defaults and tool allowlists; executable hooks are user-config only | | Session sharing | Create self-hosted share links and durable sanitized share snapshots under `.sharpclaw/` | | Diagnostics context | Surface configured diagnostics sources into prompt context, status, and machine-readable output | @@ -267,7 +267,7 @@ Subcommands include `prompt`, `repl`, `doctor`, `status`, `session`, `index`, `m ## Configuration -SharpClaw Code uses both the standard .NET configuration stack (`appsettings.json`, environment variables, CLI args) and layered SharpClaw JSONC config files: +The CLI reads provider/runtime settings from environment variables and binds command options explicitly. It never loads repository `appsettings*.json` or .NET command-line configuration overrides. Embedded .NET hosts may supply their own trusted `IConfiguration`. Layered SharpClaw JSONC config files are: - user config: `~/.config/sharpclaw/config.jsonc` on Unix-like systems - Windows user config: `%AppData%\\SharpClaw\\config.jsonc` @@ -275,7 +275,9 @@ SharpClaw Code uses both the standard .NET configuration stack (`appsettings.jso Precedence is: -`CLI args > workspace sharpclaw.jsonc > user config.jsonc > appsettings/environment defaults` +`explicit CLI options > workspace agent/content settings > user JSONC defaults` + +`server` and executable `hooks` settings come only from user JSONC or an explicit embedded-host configuration service. Workspace JSONC cannot override them. CLI invocations do not start the background scheduler; embedded hosts can opt into its hosted lifecycle. Key runtime configuration sections: @@ -290,11 +292,11 @@ Key runtime configuration sections: Key `sharpclaw.jsonc` capabilities: - `shareMode`: `manual`, `auto`, or `disabled` -- `server`: host, port, and optional public base URL for share links +- `server` (user config only): host, port, approval identity settings, and optional public base URL for share links - `defaultAgentId`: default prompt agent - `agents`: typed agent catalog entries with model defaults, tool allowlists, and instruction appendices - `lspServers`: configured diagnostics sources -- `hooks`: lifecycle hooks for turn/tool/share/server events +- `hooks` (user config only): explicitly configured executable lifecycle hooks for turn/tool/share/server events - `connectLinks`: browser entry points for provider or external auth flows All options are validated at startup via `IValidateOptions` implementations. @@ -310,7 +312,10 @@ All options are validated at startup via `IValidateOptions` implementations. - Embedded hosts can opt into trusted-header or OIDC-backed approval identity, tenant-aware usage metering, webhook/SSE event streaming, and admin APIs for provider catalog, index status, search, memory inspection, and tool package management. - The CLI mirrors those enterprise surfaces with `usage summary`, `usage detail`, and `tool-packages` commands while preserving the existing workspace-local `usage`, `cost`, and `stats` flows. - Operational commands support stable JSON output via `--output-format json`, which makes them suitable for scripts, editors, and automation. -- The embedded server exposes local JSON and SSE endpoints for prompts, sessions, admin control, metering, and event streaming. +- Every embedded HTTP endpoint requires a host secret: set `SHARPCLAW_SERVER_TOKEN` to at least 32 non-whitespace characters. Send it as `Authorization: Bearer `, or use `X-SharpClaw-Server-Token` when `Authorization` carries a separate OIDC approval identity. Browser Origin requests and unexpected Host values are rejected. Share links also require authentication. +- HTTP requests cannot raise the host permission mode or select tenant/storage roots. Hosts bind identity and storage through `RuntimeCommandContext.HostContext`. +- `/v1/events/stream` streams runtime envelopes. `/v1/prompt` SSE replays buffered turn events after completion; ACP currently sends final assistant text. Neither promises incremental model-token delivery. +- See [launch findings review](docs/launch-findings-review.md) for fixes, evidence, and remaining limitations. ## Contributing diff --git a/docs/launch-findings-review.md b/docs/launch-findings-review.md new file mode 100644 index 0000000..66186c5 --- /dev/null +++ b/docs/launch-findings-review.md @@ -0,0 +1,66 @@ +# Launch findings review + +Reviewed against the working tree on November 5, 2026. The supplied report identifies real defects, but its severity counts and some feature descriptions overstate what was established. Changes below address the confirmed execution boundaries and correctness failures. This review does not certify a launch or claim live-provider acceptance. + +## Security findings + +| Finding | Assessment and change | +| --- | --- | +| C1: unauthenticated HTTP and caller-selected permissions | Valid. Every endpoint now requires a host-supplied secret of at least 32 characters (`SHARPCLAW_SERVER_TOKEN`). Origin-bearing requests and unexpected Host values are rejected. Request permissions cannot exceed host permissions, and an explicitly read-only workflow cannot be raised by request JSON. Workspace configuration cannot set listener or approval-auth configuration. Share URLs also require authentication. | +| C2: repository `appsettings.json` changes credential destinations | Valid. CLI startup disables default .NET configuration sources and adds environment configuration explicitly. Repository appsettings and configuration command-line overrides are not loaded. Embedded hosts remain responsible for the configuration they explicitly supply. | +| C3: repository hooks execute automatically | Valid. Only user configuration supplies executable hooks; workspace hooks are ignored. User hooks are an explicit executable opt-in, including in read-only sessions. Hook failures now honor exit codes and propagate caller cancellation. | +| C4: self-trusted enabled plugin executes without approval | Valid. Manifest trust and stored workspace trust cannot waive plugin process approval. Calls require an explicit approval that cannot be remembered or scope-auto-approved; Plan, Research, and ReadOnly block plugin process tools. Explicit plugin-enable commands still run the requested health check. | +| Permission rules bypass the mode | Valid. Mode restrictions and all deny rules win before any approval. Invalid runtime mode enums are denied. Non-rememberable security rules cannot consume scope auto-approval. | +| `RequiresApproval` ignored | Valid. Enforced outside explicitly selected DangerFullAccess. Existing noninteractive write fixtures now supply file approval or a scripted approver. | +| Broad, opaque remembered approvals | Valid. Prompts include tool, working directory, and exact arguments. Memory keys include arguments, and expired approvals are ignored. Authenticated hosts revalidate each approval before any memory/auto-approval shortcut, closing an additional tenant-identity bypass found during testing. | +| `web_fetch` SSRF | Valid. Uses network approval scope. Production HTTP connections validate and pin public DNS answers, disable proxy routing, validate redirects, and block private/loopback/link-local destinations. Supported schemes are HTTP(S), without URL credentials. | +| Plugin/skill path traversal | Valid. Package IDs reject path syntax on all platforms, canonical package directories must remain in the catalog, and workspace-local catalogs cannot resolve outside the workspace through links. | +| Dangling link write escape | Valid. Canonicalization resolves link targets even when the destination does not exist, with a link-depth limit. | +| HTTP tenant/storage header injection and event leakage | Valid. Identity and storage routing come from the host context, not request headers or JSON. Event filtering always compares tenant IDs, including the absence of a tenant. | +| VS Code workspace executable settings | Valid. Launch settings are machine scoped, execution reads only user values, and untrusted workspaces are unsupported and checked before spawning. Default is the installed `sharpclaw acp` command. | + +## Functional findings + +| Finding | Assessment and change | +| --- | --- | +| H1: FTS operators crash prompts | Valid. User tokens are quoted before prefix matching. Regression cases execute real SQLite searches for AND, OR, and NOT. | +| H2: ordinary `@` text becomes missing files | Valid for the supplied examples. Email boundaries are respected; nonexistent ordinary mentions remain literal, while existing extensionless files/directories still expand and explicit relative/absolute missing references retain diagnostics. Text references have a 200 KiB limit. | +| H3: whitespace stream chunks dropped | Valid. Both agent output assembly and persisted provider delta events preserve whitespace-only chunks. | +| H4: retired Anthropic default | Valid. Default changed to `claude-sonnet-5-5`, an active model in the [Anthropic lifecycle documentation](https://platform.claude.com/docs/en/about-claude/model-deprecations). Custom model aliases remain under host control. | +| H5: Ctrl+C terminates REPL | Valid at CLI composition. The REPL already has turn controls, but starting ConsoleLifetime also canceled its lifetime. CLI commands now own their lifetime. A pseudo-terminal smoke test cancels a blocked local mock-provider request, verifies the REPL remains alive, then exits normally. | +| H6: stack traces, broken JSON errors, slash failures | Valid. CLI invocation disables the default exception printer and emits the selected error envelope, including parser/option errors. Slash-command exceptions are contained by the REPL. Five direct JSON error cases cover bad modes, auto-approval, session, and working directory. | +| H7: invalid modes become permissive defaults | Valid. Unknown permission, primary, output, and store modes raise explicit errors. | +| H8: OpenAI finish reason drops tool calls | Early termination is confirmed; the report's claim about every live tool call was not proven. Adapter now drains later tool and usage updates and rejects length/content-filter termination. A regression stream puts the function call and usage after the finish reason. No paid/live API request was made. | +| H9: main-agent outbound MCP calls absent | Valid for workspace registrations. Documentation now states lifecycle/discovery support only. Inbound MCP tool serving and the direct Parallel Search example do execute tools; they are separate paths. Main-agent outbound tool invocation remains unimplemented. | +| Extension launch requires this source repo | Valid. Default now launches the installed tool; documentation includes an absolute-project user-setting override for development. | + +## Business logic and durability + +| Finding | Assessment and change | +| --- | --- | +| Custom commands raise Research to Build | Valid. Research now survives command-mode clamping, alongside Plan and Spec. | +| CLI overrides agent/saved primary modes | Valid. Omitted primary mode remains unspecified at the runtime boundary; saved session mode wins over agent defaults on resume. | +| Anthropic token accounting absent | Valid. Message-start and cumulative delta usage are recorded, including cache-read and cache-creation input. Providers that omit usage still use the existing approximate fallback. | +| Provider stop reason ignored | Valid. Anthropic tool calls are buffered until a successful message stop; truncated, interrupted, or unsupported continuation responses fail without releasing tools. OpenAI length/content-filter responses also fail. | +| Empty responses create fake replies | Valid. Empty provider responses now fail explicitly; the unused placeholder helper was removed. | +| Circuit breaker reset by failed events | Valid. Failed events count as failures, with authentication classification retained. Regression verifies a 429 failed event opens the circuit. | +| Session saved before turn lock | Valid. Preference writes happen after the mutex, cross-process lock, and snapshot reload. | +| Undo/redo cancellation strands edits | Valid. Cancellation is accepted before mutation begins; once application starts, the operation finishes and saves its state despite caller cancellation. Filesystem failure or process death still requires the existing recovery mechanisms; this is not a filesystem transaction. | +| Nonatomic snapshots/torn NDJSON | Valid. Local text state uses same-directory temporary files and atomic replacement. Appends use an exclusive lock and discard an incomplete trailing record before writing the next event. Disk-loss/power-loss durability is not guaranteed by atomic rename alone. | +| One malformed plugin disables tools | Valid. Invalid manifests/states are logged and skipped, conflicting plugin tools are omitted, and built-in lookup is independent of plugin discovery. | +| MCP cancellation leaves Starting | Valid. Interrupted startup persists Faulted using a cleanup token and disposes a newly established session if needed. Stop checks cancellation before removing the tracked client. | +| ACP ignores cancel notifications | Valid for notifications without IDs. They are now accepted without emitting a JSON-RPC response. Existing live-control targeting and validation are retained. | +| Every CLI command starts scheduler | Valid. CLI bootstrap removes the scheduler hosted service and no longer starts the host implicitly. Embedded-host scheduling remains available; explicit schedule commands retain their own workspace context. | +| Bash lacks bounds and denylist misses variants | Valid. Shared process execution defaults to two minutes and one MiB characters per output stream, kills on failure/cancellation, and observes reader tasks. Verification explicitly retains its configured deadline. Recursive-rm flag permutations and find deletion/execution patterns receive a non-auto-approvable gate. These patterns are not a complete shell sandbox. | + +## Performance and feature limits + +- Fixed: Anthropic client reuse; Anthropic automatic cache control; private SQLite caches with WAL and busy timeout; generated/dependency-directory pruning and link avoidance in grep/glob; reusable bounded glob regexes; grep regex timeout, binary detection, and large-file exclusion; read-file and text-reference size limits. +- Still valid and open: webhook deliveries block their publishing call; hook configuration is reread for lifecycle events; event appends reopen the log; source traversal does not implement full `.gitignore` semantics. +- Prompt SSE currently replays events after execution, and ACP sends final assistant text. `/v1/events/stream` does stream runtime envelopes. Documentation now distinguishes these behaviors; incremental model-token delivery remains a larger provider/fallback orchestration change. +- No benchmark establishes the report's exact latency or cost multipliers. The existing fallback character-based token estimate is still approximate when a provider omits usage. +- Main-agent outbound MCP calls are deliberately not advertised as implemented. Adding them requires tool discovery, namespacing, permission-aware invocation, and lifecycle tests, rather than only exposing the SDK client. + +## Validation + +Validation results are recorded in the delivery message. Regression coverage includes actual SQLite FTS, dangling links, path IDs, private HTTP destinations and redirects, permission-mode precedence, exact approval arguments, post-finish tool calls, Anthropic usage/truncation, circuit-breaker failures, HTTP authentication/Origin/Host checks, tenant identity, snapshot replacement, torn log repair, and bounded process output. Direct CLI smoke checks use a temporary workspace and local mock provider with a fake API key. No production provider key was sent in those checks. diff --git a/docs/mcp.md b/docs/mcp.md index d40a991..81bcb26 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3,6 +3,8 @@ **Project:** `SharpClaw.Code.Mcp` **Registration:** `McpServiceCollectionExtensions.AddSharpClawMcp` (pulled in by **`AddSharpClawRuntime`**) +Outbound workspace registrations currently support connection, discovery counts, diagnostics, and start/stop/restart. Their tools are **not registered with the main coding agent**, so a successful handshake does not mean the agent can call them. Inbound MCP tool hosting is implemented separately in [MCP server](mcp-server.md). The Parallel Search example below has its own direct tool-call path; it does not fill this main-agent gap. + ## Official SDK MCP sessions use the **[ModelContextProtocol](https://www.nuget.org/packages/ModelContextProtocol)** NuGet package (official MCP C# SDK, version pinned in **`Directory.Packages.props`**). SharpClaw keeps **registry, CLI, Protocol DTOs, and diagnostics** as first-party code; **`SdkMcpProcessSupervisor`** drives: diff --git a/docs/permissions.md b/docs/permissions.md index 19abf33..8d4c0e3 100644 --- a/docs/permissions.md +++ b/docs/permissions.md @@ -47,7 +47,11 @@ The auto-approve budget is process-local and session-scoped, similar to remember Rules return **`PermissionRuleOutcome`**: Abstain, Allow, Deny, or **RequireApproval**. -If all rules abstain, **`EvaluateByModeAsync`** applies mode defaults (e.g. **ReadOnly** allows non-destructive **`ToolExecution`**; **WorkspaceWrite** auto-allows file/tool scope but may require approval for shell, network, session operations). +Mode restrictions and every denial take precedence over approvals or allowances. **ReadOnly** blocks mutations and elevated scopes; Plan/Research also deny mutating operations. `RequiresApproval` is enforced outside DangerFullAccess. Approval prompts include exact arguments and working directory, and remembered grants are scoped to those arguments. Authenticated hosts revalidate identity on every approval, before any memory or auto-approval shortcut. + +WorkspaceWrite allows file/tool scopes only when the tool does not explicitly require approval. Shell, network, and session operations require approval. Non-rememberable security gates (dangerous shell patterns and plugin processes) cannot use scope auto-approval. A plugin manifest or workspace session file cannot authorize its own executable code. Plugin process tools are blocked in read-only workflows. `web_fetch` uses network scope and restricts connections, DNS answers, and redirects to public HTTP(S) destinations. + +The dangerous-shell patterns are an additional approval gate, not an OS sandbox or a complete shell-language classifier. Approved shell commands still execute with the user's OS privileges. Subprocesses have a two-minute deadline and a one-MiB character output cap per stream. ## Approvals diff --git a/docs/plugins.md b/docs/plugins.md index a3c815e..1cc1281 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -20,7 +20,9 @@ Only plugins in **`PluginLifecycleState.Enabled`** surface tool descriptors to * ## Trust and permissions -Manifest trust flows into **Protocol** models and **`PermissionEvaluationContext`** (`ToolOriginatingPluginId`, **`PluginTrustRule`**, etc.). +Manifest trust is advisory metadata in **Protocol** and **`PermissionEvaluationContext`**. It does not grant execution authority. Plugin process tools require an explicit approval for each call; scope auto-approval and remembered workspace trust do not waive that gate. ReadOnly, Plan, and Research workflows block plugin processes. Explicit `plugins enable` runs the requested health check. + +Malformed manifests/states are skipped with diagnostics. Conflicting plugin tool names are omitted without disabling built-in tools. IDs and canonical catalog paths are validated before package filesystem operations. ## CLI diff --git a/extensions/vscode/README.md b/extensions/vscode/README.md index 3ec1664..de7e02e 100644 --- a/extensions/vscode/README.md +++ b/extensions/vscode/README.md @@ -25,9 +25,9 @@ What it currently does: By default the extension runs: ```bash -dotnet run --project src/SharpClaw.Code.Cli -- acp +sharpclaw acp ``` -Override that command through the `sharpClaw.cliCommand` and `sharpClaw.cliArgs` settings if you want to point the extension at an installed CLI or a different workspace layout. +Install the .NET tool first (`dotnet tool install --global SharpClaw.Code.Cli --prerelease`). Override `sharpClaw.cliCommand` and `sharpClaw.cliArgs` in user settings to select another installation. Workspace values are ignored, and the extension does not activate in untrusted workspaces. For source development, set the user command to `dotnet` and args to `["run", "--project", "/absolute/path/to/SharpClaw.Code.Cli", "--", "acp"]`. While a prompt runs, use **Steer Active Turn** to queue a correction or **Cancel Active Turn** to stop it. Commands target the active editor’s workspace folder. The output channel displays corrections that still need to be resubmitted when execution ends. Live controls require a host advertising `liveTurnControl`. Older hosts continue to support ordinary prompts. diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index f69777b..1913185 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -61,22 +61,20 @@ "properties": { "sharpClaw.cliCommand": { "type": "string", - "default": "dotnet", - "description": "Command used to launch the SharpClaw ACP host." + "default": "sharpclaw", + "description": "Command used to launch the SharpClaw ACP host.", + "scope": "machine" }, "sharpClaw.cliArgs": { "type": "array", "default": [ - "run", - "--project", - "src/SharpClaw.Code.Cli", - "--", "acp" ], "items": { "type": "string" }, - "description": "Arguments passed to the SharpClaw CLI command." + "description": "Arguments passed to the SharpClaw CLI command.", + "scope": "machine" } } } @@ -90,5 +88,11 @@ "@types/node": "^26.6.6", "@types/vscode": "^1.144.0", "typescript": "^7.0.2" + }, + "capabilities": { + "untrustedWorkspaces": { + "supported": false, + "description": "SharpClaw executes tools and requires a trusted workspace." + } } } diff --git a/extensions/vscode/src/extension.ts b/extensions/vscode/src/extension.ts index 82b75d1..0f98826 100644 --- a/extensions/vscode/src/extension.ts +++ b/extensions/vscode/src/extension.ts @@ -20,8 +20,9 @@ class AcpClient implements vscode.Disposable { context: vscode.ExtensionContext) { this.connection = new AcpConnection(() => { const config = vscode.workspace.getConfiguration("sharpClaw"); - const command = config.get("cliCommand", "dotnet"); - const args = config.get("cliArgs", ["run", "--project", "src/SharpClaw.Code.Cli", "--", "acp"]); + if (!vscode.workspace.isTrusted) throw new Error("SharpClaw requires a trusted workspace."); + const command = config.inspect("cliCommand")?.globalValue ?? "sharpclaw"; + const args = config.inspect("cliArgs")?.globalValue ?? ["acp"]; const cwd = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath ?? context.extensionPath; return spawn(command, args, { cwd, stdio: "pipe" }); }, (params, reply) => this.handleNotification(params, reply), text => this.output.append(text)); diff --git a/extensions/vscode/test/editorCommands.test.cjs b/extensions/vscode/test/editorCommands.test.cjs index 127c97f..72d493d 100644 --- a/extensions/vscode/test/editorCommands.test.cjs +++ b/extensions/vscode/test/editorCommands.test.cjs @@ -35,8 +35,9 @@ io.on("line", line => { const vscode = { commands: { registerCommand(id, callback) { commands.set(id, callback); return { dispose() {} }; } }, workspace: { + isTrusted: true, workspaceFolders: [folder], - getConfiguration() { return { get(key) { return key === "cliCommand" ? process.execPath : ["-e", fixture]; } }; } + getConfiguration() { return { inspect(key) { return { globalValue: key === "cliCommand" ? process.execPath : ["-e", fixture], workspaceValue: "untrusted-program" }; } }; } }, window: { createOutputChannel: () => output, diff --git a/src/SharpClaw.Code.Acp/AcpStdioHost.cs b/src/SharpClaw.Code.Acp/AcpStdioHost.cs index a782d22..6c43d1f 100644 --- a/src/SharpClaw.Code.Acp/AcpStdioHost.cs +++ b/src/SharpClaw.Code.Acp/AcpStdioHost.cs @@ -110,26 +110,31 @@ private async Task ProcessRequestAsync(JsonObject requestObject, AcpLiveTurns li var id = requestObject["id"]; if (requestObject["jsonrpc"] is not JsonValue version || !version.TryGetValue(out var protocol) || protocol != "2.0" || requestObject["method"] is not JsonValue name || !name.TryGetValue(out var method) || string.IsNullOrWhiteSpace(method) - || id is not JsonValue) + || (id is not null && id is not JsonValue)) { - await WriteErrorAsync(stdout, id, -32600, "Invalid request.", cancellationToken).ConfigureAwait(false); + if (id is not null) await WriteErrorAsync(stdout, id, -32600, "Invalid request.", cancellationToken).ConfigureAwait(false); return; } try { + if (id is null) + { + if (method == "session/cancel") live.Control(RequireWorkspace(requestObject["params"]), requestObject["params"], cancel: true); + return; + } var response = await DispatchAsync(method, id, requestObject["params"], live, stdout, cancellationToken).ConfigureAwait(false); await WriteResponseAsync(stdout, id, response, cancellationToken).ConfigureAwait(false); } catch (AcpRequestException ex) { logger.LogWarning(ex, "ACP request failed for method {Method} with JSON-RPC error {Code}.", method, ex.Code); - await WriteErrorAsync(stdout, id, ex.Code, ex.Message, cancellationToken, ex.Details).ConfigureAwait(false); + if (id is not null) await WriteErrorAsync(stdout, id, ex.Code, ex.Message, cancellationToken, ex.Details).ConfigureAwait(false); } catch (Exception ex) { logger.LogError(ex, "ACP request failed for method {Method}.", method); - await WriteErrorAsync(stdout, id, -32603, ex.Message, cancellationToken).ConfigureAwait(false); + if (id is not null) await WriteErrorAsync(stdout, id, -32603, ex.Message, cancellationToken).ConfigureAwait(false); } } diff --git a/src/SharpClaw.Code.Agents/Internal/ProviderBackedAgentKernel.cs b/src/SharpClaw.Code.Agents/Internal/ProviderBackedAgentKernel.cs index fc746f0..50aea10 100644 --- a/src/SharpClaw.Code.Agents/Internal/ProviderBackedAgentKernel.cs +++ b/src/SharpClaw.Code.Agents/Internal/ProviderBackedAgentKernel.cs @@ -252,7 +252,7 @@ internal async Task ExecuteAsync( CreateProviderFailedEventMessage(provider.ProviderName, providerEvent)); } - if (!providerEvent.IsTerminal && !string.IsNullOrWhiteSpace(providerEvent.Content)) + if (!providerEvent.IsTerminal && !string.IsNullOrEmpty(providerEvent.Content)) { candidateTextSegments.Add(providerEvent.Content); } @@ -408,13 +408,8 @@ internal async Task ExecuteAsync( var output = string.Concat(outputSegments); if (string.IsNullOrWhiteSpace(output)) { - logger.LogWarning( - "Provider {ProviderName} returned no stream content for session {SessionId}; returning placeholder response.", - activeProviderName, - request.Context.SessionId); - var placeholder = CreatePlaceholderResult(request, activeModel, $"Provider '{activeProviderName}' returned no content; using placeholder response."); - // Meter what the provider actually reported, not the synthetic placeholder estimate. - return placeholder with { Usage = AddUsage(totalUsage ?? placeholder.Usage, compactionUsage) }; + throw new ProviderExecutionException(activeProviderName, activeModel, ProviderFailureKind.StreamFailed, + $"Provider '{activeProviderName}' returned an empty response."); } var usage = totalUsage ?? new UsageSnapshot( @@ -482,19 +477,6 @@ async Task ApplySteeringAsync() internal Task ExecuteAsync(AgentFrameworkRequest request, CancellationToken cancellationToken) => ExecuteAsync(request, toolExecutionContext: null, availableTools: null, cancellationToken); - private static ProviderInvocationResult CreatePlaceholderResult(AgentFrameworkRequest request, string model, string summary) - { - var output = $"Session {request.Context.SessionId} turn {request.Context.TurnId}: placeholder response for '{request.Context.Prompt}' using model '{model}'."; - var usage = new UsageSnapshot( - InputTokens: request.Context.Prompt.Length, - OutputTokens: output.Length, - CachedInputTokens: 0, - TotalTokens: request.Context.Prompt.Length + output.Length, - EstimatedCostUsd: 0.0001m); - - return new ProviderInvocationResult(output, usage, summary, null, null); - } - private static ProviderExecutionException CreateMissingProviderException( string providerName, string model, diff --git a/src/SharpClaw.Code.Cli/CliHostBuilder.cs b/src/SharpClaw.Code.Cli/CliHostBuilder.cs index ae733ba..1df06bb 100644 --- a/src/SharpClaw.Code.Cli/CliHostBuilder.cs +++ b/src/SharpClaw.Code.Cli/CliHostBuilder.cs @@ -1,5 +1,8 @@ using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; +using SharpClaw.Code.Runtime.Workflow; using SharpClaw.Code.Cli.Composition; using SharpClaw.Code.Runtime; @@ -17,9 +20,18 @@ public static class CliHostBuilder /// A configured host instance. public static IHost BuildHost(string[]? args = null) { - var builder = Host.CreateApplicationBuilder(args ?? []); + // Repository appsettings files are untrusted and must never configure credential destinations. + var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings + { + DisableDefaults = true, + Args = args ?? [], + }); + builder.Configuration.AddEnvironmentVariables(); builder.Logging.ClearProviders(); builder.Services.AddSharpClawRuntime(builder.Configuration); + foreach (var descriptor in builder.Services.Where(d => d.ServiceType == typeof(IHostedService) + && d.ImplementationType == typeof(ScheduledPromptRunner)).ToArray()) + builder.Services.Remove(descriptor); builder.Services.AddSharpClawCli(); return builder.Build(); } diff --git a/src/SharpClaw.Code.Cli/Program.cs b/src/SharpClaw.Code.Cli/Program.cs index febb898..434c93e 100644 --- a/src/SharpClaw.Code.Cli/Program.cs +++ b/src/SharpClaw.Code.Cli/Program.cs @@ -1,16 +1,30 @@ using Microsoft.Extensions.DependencyInjection; using SharpClaw.Code.Cli; using SharpClaw.Code.Commands; +using SharpClaw.Code.Protocol.Commands; +using SharpClaw.Code.Protocol.Enums; using System.CommandLine; using var host = CliHostBuilder.BuildHost(args); -var commandFactory = host.Services.GetRequiredService(); -var rootCommand = await commandFactory.CreateRootCommandAsync(); -var parsed = rootCommand.Parse(args); -// MCP owns its transport lifetime. Starting Runtime would also start schedulers and outbound clients. -var isMcpServer = parsed.CommandResult.Command.Name == "serve" - && parsed.CommandResult.Parent is System.CommandLine.Parsing.CommandResult parent - && parent.Command.Name == "mcp"; -if (!isMcpServer) await host.StartAsync(); -try { return await parsed.InvokeAsync(); } -finally { if (!isMcpServer) await host.StopAsync(); } +var renderer = host.Services.GetRequiredService(); +var format = args.Where((value, index) => index > 0 && args[index - 1] == "--output-format").LastOrDefault() == "json" + || args.Contains("--output-format=json") ? OutputFormat.Json : OutputFormat.Text; +try +{ + var rootCommand = await host.Services.GetRequiredService().CreateRootCommandAsync(); + var parsed = rootCommand.Parse(args); + if (parsed.Errors.Count > 0) + throw new ArgumentException(string.Join(Environment.NewLine, parsed.Errors.Select(error => error.Message))); + // Commands own their runtime lifetime. ConsoleLifetime would cancel the REPL itself on Ctrl+C. + return await parsed.InvokeAsync(new InvocationConfiguration { EnableDefaultExceptionHandler = false }); +} +catch (OperationCanceledException) +{ + await renderer.RenderCommandResultAsync(new CommandResult(false, 130, format, "Operation cancelled.", null), format, CancellationToken.None); + return 130; +} +catch (Exception exception) +{ + await renderer.RenderCommandResultAsync(new CommandResult(false, 1, format, exception.Message, null), format, CancellationToken.None); + return 1; +} diff --git a/src/SharpClaw.Code.Commands/Models/CommandExecutionContext.cs b/src/SharpClaw.Code.Commands/Models/CommandExecutionContext.cs index 03b55c8..337bda7 100644 --- a/src/SharpClaw.Code.Commands/Models/CommandExecutionContext.cs +++ b/src/SharpClaw.Code.Commands/Models/CommandExecutionContext.cs @@ -15,6 +15,7 @@ namespace SharpClaw.Code.Commands.Models; /// Optional explicit session id for prompts and session-scoped commands. /// Optional explicit agent id for prompt execution. /// Optional embedded-host identity and tenant/storage context. +/// Whether a caller explicitly selected a workflow mode. /// Optional bounded auto-approval settings. public sealed record CommandExecutionContext( string WorkingDirectory, @@ -25,7 +26,8 @@ public sealed record CommandExecutionContext( string? SessionId = null, string? AgentId = null, RuntimeHostContext? HostContext = null, - ApprovalSettings? ApprovalSettings = null) + ApprovalSettings? ApprovalSettings = null, + bool PrimaryModeSpecified = true) { /// /// Converts the CLI command context into the runtime invocation context. @@ -47,7 +49,7 @@ public RuntimeCommandContext ToRuntimeCommandContext( Model, permissionModeOverride ?? PermissionMode, OutputFormat, - primaryModeOverride ?? PrimaryMode, + primaryModeOverride ?? (PrimaryModeSpecified ? PrimaryMode : null), SessionId, agentIdOverride ?? AgentId, isInteractive, diff --git a/src/SharpClaw.Code.Commands/Options/GlobalCliOptions.cs b/src/SharpClaw.Code.Commands/Options/GlobalCliOptions.cs index c624300..a7b0800 100644 --- a/src/SharpClaw.Code.Commands/Options/GlobalCliOptions.cs +++ b/src/SharpClaw.Code.Commands/Options/GlobalCliOptions.cs @@ -212,6 +212,8 @@ public CommandExecutionContext Resolve(ParseResult parseResult) var resolvedWorkingDirectory = string.IsNullOrWhiteSpace(cwd) ? Environment.CurrentDirectory : Path.GetFullPath(cwd); + if (!Directory.Exists(resolvedWorkingDirectory)) + throw new DirectoryNotFoundException($"Working directory does not exist: {resolvedWorkingDirectory}"); var primaryText = parseResult.GetValue(PrimaryModeOption) ?? "build"; var hostId = parseResult.GetValue(HostIdOption); var tenantId = parseResult.GetValue(TenantIdOption); @@ -226,6 +228,7 @@ public CommandExecutionContext Resolve(ParseResult parseResult) PermissionMode: yolo ? PermissionMode.DangerFullAccess : ParsePermissionMode(permissionModeText), OutputFormat: ParseOutputFormat(outputFormatText), PrimaryMode: ParsePrimaryMode(primaryText), + PrimaryModeSpecified: parseResult.GetResult(PrimaryModeOption) is { Implicit: false }, SessionId: parseResult.GetValue(SessionOption), AgentId: parseResult.GetValue(AgentOption), HostContext: hostContext, @@ -263,7 +266,8 @@ private static OutputFormat ParseOutputFormat(string value) => value.Trim().ToLowerInvariant() switch { "json" => OutputFormat.Json, - _ => OutputFormat.Text, + "text" => OutputFormat.Text, + _ => throw new ArgumentException($"Unknown output format: {value}."), }; private static PermissionMode ParsePermissionMode(string value) @@ -272,7 +276,7 @@ private static PermissionMode ParsePermissionMode(string value) "readonly" or "read-only" => PermissionMode.ReadOnly, "workspacewrite" or "workspace-write" or "prompt" or "autoapprovesafe" or "auto-approve-safe" => PermissionMode.WorkspaceWrite, "dangerfullaccess" or "danger-full-access" or "fulltrust" or "full-trust" => PermissionMode.DangerFullAccess, - _ => PermissionMode.WorkspaceWrite, + _ => throw new ArgumentException($"Unknown permission mode: {value}."), }; private static PrimaryMode ParsePrimaryMode(string value) @@ -281,7 +285,8 @@ private static PrimaryMode ParsePrimaryMode(string value) "plan" => PrimaryMode.Plan, "spec" => PrimaryMode.Spec, "research" => PrimaryMode.Research, - _ => PrimaryMode.Build, + "build" => PrimaryMode.Build, + _ => throw new ArgumentException($"Unknown primary mode: {value}."), }; private static SessionStoreKind? ParseSessionStoreKind(string? value) @@ -290,6 +295,6 @@ private static PrimaryMode ParsePrimaryMode(string value) null or "" => null, "filesystem" or "file-system" or "fileSystem" => SessionStoreKind.FileSystem, "sqlite" => SessionStoreKind.Sqlite, - _ => SessionStoreKind.FileSystem, + _ => throw new ArgumentException($"Unknown session store: {value}."), }; } diff --git a/src/SharpClaw.Code.Commands/Repl/ReplHost.cs b/src/SharpClaw.Code.Commands/Repl/ReplHost.cs index ee5db2f..15b9b37 100644 --- a/src/SharpClaw.Code.Commands/Repl/ReplHost.cs +++ b/src/SharpClaw.Code.Commands/Repl/ReplHost.cs @@ -101,7 +101,15 @@ void OnCancelKeyPress(object? sender, ConsoleCancelEventArgs args) else terminal.WriteError("The follow-up queue is full (16). Wait for a turn to finish."); continue; } - if (trimmed.StartsWith('/')) lastExitCode = await ExecuteSlashAsync(trimmed, context, lifetime.Token).ConfigureAwait(false); + if (trimmed.StartsWith('/')) + { + try { lastExitCode = await ExecuteSlashAsync(trimmed, context, lifetime.Token).ConfigureAwait(false); } + catch (Exception exception) when (exception is not OperationCanceledException) + { + terminal.WriteError($"Command failed: {exception.Message}"); + lastExitCode = 1; + } + } else queued.Enqueue(trimmed); } terminal.WriteInfo("Leaving interactive mode."); @@ -241,7 +249,7 @@ await outputRendererDispatcher.RenderCommandResultAsync( customDef.Name, argLine, context.ToRuntimeCommandContext( - primaryModeOverride: replInteractionState.PrimaryModeOverride ?? context.PrimaryMode, + primaryModeOverride: replInteractionState.PrimaryModeOverride ?? (context.PrimaryModeSpecified ? context.PrimaryMode : null), permissionModeOverride: replInteractionState.PermissionModeOverride ?? context.PermissionMode, agentIdOverride: replInteractionState.AgentIdOverride ?? context.AgentId, approvalSettingsOverride: replInteractionState.ApprovalSettingsOverride), @@ -297,7 +305,7 @@ private async Task ExecutePromptAsync(string prompt, CommandExecutionContex var result = await runtimeCommandService.ExecutePromptAsync( prompt, context.ToRuntimeCommandContext( - primaryModeOverride: replInteractionState.PrimaryModeOverride ?? context.PrimaryMode, + primaryModeOverride: replInteractionState.PrimaryModeOverride ?? (context.PrimaryModeSpecified ? context.PrimaryMode : null), permissionModeOverride: replInteractionState.PermissionModeOverride ?? context.PermissionMode, agentIdOverride: replInteractionState.AgentIdOverride ?? context.AgentId, approvalSettingsOverride: replInteractionState.ApprovalSettingsOverride), diff --git a/src/SharpClaw.Code.Infrastructure/Models/ProcessRunRequest.cs b/src/SharpClaw.Code.Infrastructure/Models/ProcessRunRequest.cs index 6f8902f..07e8f76 100644 --- a/src/SharpClaw.Code.Infrastructure/Models/ProcessRunRequest.cs +++ b/src/SharpClaw.Code.Infrastructure/Models/ProcessRunRequest.cs @@ -7,8 +7,10 @@ namespace SharpClaw.Code.Infrastructure.Models; /// The command-line arguments. /// The working directory, if any. /// Optional environment variable overrides. +/// Optional host-controlled deadline; defaults to two minutes. public sealed record ProcessRunRequest( string FileName, string[] Arguments, string? WorkingDirectory, - IReadOnlyDictionary? EnvironmentVariables); + IReadOnlyDictionary? EnvironmentVariables, + TimeSpan? ExecutionTimeout = null); diff --git a/src/SharpClaw.Code.Infrastructure/Services/LocalFileSystem.cs b/src/SharpClaw.Code.Infrastructure/Services/LocalFileSystem.cs index 07fa8e4..037d967 100644 --- a/src/SharpClaw.Code.Infrastructure/Services/LocalFileSystem.cs +++ b/src/SharpClaw.Code.Infrastructure/Services/LocalFileSystem.cs @@ -119,7 +119,7 @@ public async Task ReadAllLinesIfExistsAsync(string path, CancellationT } /// - public Task WriteAllTextAsync(string path, string content, CancellationToken cancellationToken) + public async Task WriteAllTextAsync(string path, string content, CancellationToken cancellationToken) { var directory = Path.GetDirectoryName(path); if (!string.IsNullOrWhiteSpace(directory)) @@ -127,7 +127,14 @@ public Task WriteAllTextAsync(string path, string content, CancellationToken can Directory.CreateDirectory(directory); } - return File.WriteAllTextAsync(path, content, cancellationToken); + var temporaryPath = path + $".{Guid.NewGuid():N}.tmp"; + try + { + await File.WriteAllTextAsync(temporaryPath, content, cancellationToken).ConfigureAwait(false); + cancellationToken.ThrowIfCancellationRequested(); + File.Move(temporaryPath, path, overwrite: true); + } + finally { TryDeleteFile(temporaryPath); } } /// @@ -157,9 +164,27 @@ public async Task AppendLineAsync(string path, string line, CancellationToken ca Directory.CreateDirectory(directory); } - await using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read, 4096, FileOptions.Asynchronous); - await using var writer = new StreamWriter(stream, Encoding.UTF8) { NewLine = "\n" }; - await writer.WriteLineAsync(line.AsMemory(), cancellationToken).ConfigureAwait(false); + await using var appendLock = await AcquireExclusiveFileLockAsync(path + ".append.lock", cancellationToken).ConfigureAwait(false); + await using var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.Asynchronous); + if (stream.Length > 0) + { + stream.Position = stream.Length - 1; + if (stream.ReadByte() != '\n') + { + var position = stream.Length - 1; + while (position >= 0) + { + stream.Position = position; + if (stream.ReadByte() == '\n') break; + position--; + } + stream.SetLength(position + 1); + } + } + stream.Position = stream.Length; + var bytes = Encoding.UTF8.GetBytes(line + "\n"); + await stream.WriteAsync(bytes, cancellationToken).ConfigureAwait(false); + await stream.FlushAsync(cancellationToken).ConfigureAwait(false); } /// diff --git a/src/SharpClaw.Code.Infrastructure/Services/LocalPackagePath.cs b/src/SharpClaw.Code.Infrastructure/Services/LocalPackagePath.cs new file mode 100644 index 0000000..88ea8af --- /dev/null +++ b/src/SharpClaw.Code.Infrastructure/Services/LocalPackagePath.cs @@ -0,0 +1,36 @@ +using SharpClaw.Code.Infrastructure.Abstractions; + +namespace SharpClaw.Code.Infrastructure.Services; + +/// Validates local package IDs and prevents package operations from escaping their catalog. +public static class LocalPackagePath +{ + /// Rejects IDs containing path syntax, including Windows path syntax on Unix. + public static void ValidateId(string id) + { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + if (id is "." or ".." || id.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not ('-' or '_' or '.'))) + throw new ArgumentException("Package IDs must contain only letters, digits, dots, hyphens, and underscores.", nameof(id)); + } + + /// Resolves a package directory and rejects links outside the catalog. + public static string Resolve(IPathService paths, string root, string id, string? workspaceRoot = null) + { + ValidateId(id); + var canonicalRoot = paths.GetCanonicalFullPath(root); + var directory = paths.GetCanonicalFullPath(paths.Combine(root, id)); + var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + if (workspaceRoot is not null) + { + var lexicalWorkspace = Path.TrimEndingDirectorySeparator(paths.GetFullPath(workspaceRoot)) + Path.DirectorySeparatorChar; + var canonicalWorkspace = Path.TrimEndingDirectorySeparator(paths.GetCanonicalFullPath(workspaceRoot)) + Path.DirectorySeparatorChar; + // External host storage is explicit; workspace-local catalogs must remain in their workspace. + if (paths.GetFullPath(root).StartsWith(lexicalWorkspace, comparison) + && !canonicalRoot.StartsWith(canonicalWorkspace, comparison)) + throw new ArgumentException("Package catalog escapes the workspace.", nameof(root)); + } + if (!directory.StartsWith(Path.TrimEndingDirectorySeparator(canonicalRoot) + Path.DirectorySeparatorChar, comparison)) + throw new ArgumentException("Package directory escapes the catalog.", nameof(id)); + return directory; + } +} diff --git a/src/SharpClaw.Code.Infrastructure/Services/PathService.cs b/src/SharpClaw.Code.Infrastructure/Services/PathService.cs index 9a0e12f..8922a07 100644 --- a/src/SharpClaw.Code.Infrastructure/Services/PathService.cs +++ b/src/SharpClaw.Code.Infrastructure/Services/PathService.cs @@ -16,8 +16,11 @@ public string GetFullPath(string path) => Path.GetFullPath(path); /// - public string GetCanonicalFullPath(string path) + public string GetCanonicalFullPath(string path) => GetCanonicalFullPath(path, 0); + + private static string GetCanonicalFullPath(string path, int linkDepth) { + if (linkDepth > 40) throw new IOException("Too many symbolic links in path."); ArgumentException.ThrowIfNullOrWhiteSpace(path); var fullPath = Path.GetFullPath(path); @@ -38,7 +41,7 @@ public string GetCanonicalFullPath(string path) { current = string.Equals(resolved, current, StringComparison.Ordinal) ? resolved - : GetCanonicalFullPath(resolved); + : GetCanonicalFullPath(resolved, linkDepth + 1); } } @@ -59,7 +62,12 @@ public string GetTempPath() private static string? TryResolveExistingLink(string path) { - FileSystemInfo? info = null; + FileSystemInfo? info = new FileInfo(path); + if (info.LinkTarget is { } linkTarget) + { + return Path.GetFullPath(Path.IsPathRooted(linkTarget) ? linkTarget : Path.Combine(Path.GetDirectoryName(path)!, linkTarget)); + } + info = null; if (Directory.Exists(path)) { info = new DirectoryInfo(path); diff --git a/src/SharpClaw.Code.Infrastructure/Services/ProcessRunner.cs b/src/SharpClaw.Code.Infrastructure/Services/ProcessRunner.cs index fec363a..a2c8b83 100644 --- a/src/SharpClaw.Code.Infrastructure/Services/ProcessRunner.cs +++ b/src/SharpClaw.Code.Infrastructure/Services/ProcessRunner.cs @@ -13,6 +13,9 @@ public sealed class ProcessRunner(ISystemClock systemClock) : IProcessRunner public async Task RunAsync(ProcessRunRequest request, CancellationToken cancellationToken) { ArgumentException.ThrowIfNullOrWhiteSpace(request.FileName); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(request.ExecutionTimeout ?? TimeSpan.FromMinutes(2)); + var processToken = timeout.Token; var startInfo = new ProcessStartInfo { @@ -44,24 +47,52 @@ public async Task RunAsync(ProcessRunRequest request, Cancella var startedAtUtc = systemClock.UtcNow; process.Start(); + var standardOutputTask = ReadBoundedAsync(process.StandardOutput, timeout, processToken); + var standardErrorTask = ReadBoundedAsync(process.StandardError, timeout, processToken); try { - var standardOutputTask = process.StandardOutput.ReadToEndAsync(cancellationToken); - var standardErrorTask = process.StandardError.ReadToEndAsync(cancellationToken); - await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false); + await process.WaitForExitAsync(processToken).ConfigureAwait(false); var standardOutput = await standardOutputTask.ConfigureAwait(false); var standardError = await standardErrorTask.ConfigureAwait(false); var completedAtUtc = systemClock.UtcNow; return new ProcessRunResult(process.ExitCode, standardOutput, standardError, startedAtUtc, completedAtUtc); } - catch (OperationCanceledException) + catch (Exception exception) { + timeout.Cancel(); TryKillProcessTree(process); + try { await Task.WhenAll(standardOutputTask, standardErrorTask).ConfigureAwait(false); } + catch (Exception) { /* Observe both reader failures before disposing the process. */ } + if (!cancellationToken.IsCancellationRequested && exception is OperationCanceledException) + { + var outputFailure = (standardOutputTask.Exception?.InnerExceptions.AsEnumerable() ?? []) + .Concat(standardErrorTask.Exception?.InnerExceptions.AsEnumerable() ?? []).OfType().FirstOrDefault(); + if (outputFailure is not null) throw outputFailure; + throw new TimeoutException("Process exceeded its execution deadline.", exception); + } throw; } } + private static async Task ReadBoundedAsync(StreamReader reader, CancellationTokenSource timeout, CancellationToken cancellationToken) + { + const int maxCharacters = 1024 * 1024; + var builder = new System.Text.StringBuilder(); + var buffer = new char[4096]; + while (true) + { + var count = await reader.ReadAsync(buffer.AsMemory(), cancellationToken).ConfigureAwait(false); + if (count == 0) return builder.ToString(); + if (builder.Length + count > maxCharacters) + { + timeout.Cancel(); + throw new IOException("Process output exceeded the 1 MiB character limit."); + } + builder.Append(buffer, 0, count); + } + } + private static void TryKillProcessTree(Process process) { try diff --git a/src/SharpClaw.Code.Mcp/Services/ProcessMcpServerHost.cs b/src/SharpClaw.Code.Mcp/Services/ProcessMcpServerHost.cs index 642ef7b..08df63c 100644 --- a/src/SharpClaw.Code.Mcp/Services/ProcessMcpServerHost.cs +++ b/src/SharpClaw.Code.Mcp/Services/ProcessMcpServerHost.cs @@ -71,7 +71,22 @@ private async Task StartCoreAsync(string workspaceRoot, string ResourceCount: server.Status.ResourceCount); await PersistAndEmitAsync(workspaceRoot, server.Status, startingStatus, cancellationToken).ConfigureAwait(false); - var processResult = await processSupervisor.StartAsync(server.Definition, workspaceRoot, cancellationToken).ConfigureAwait(false); + McpProcessStartResult? processResult = null; + try + { + processResult = await processSupervisor.StartAsync(server.Definition, workspaceRoot, cancellationToken).ConfigureAwait(false); + cancellationToken.ThrowIfCancellationRequested(); + } + catch (Exception exception) + { + if (processResult is { Started: true }) + await processSupervisor.StopAsync(new McpProcessStopRequest(processResult.Pid, processResult.SessionHandle), CancellationToken.None).ConfigureAwait(false); + var faulted = startingStatus with { State = McpLifecycleState.Faulted, IsHealthy = false, + StatusMessage = exception is OperationCanceledException ? "MCP startup cancelled." : exception.Message, + UpdatedAtUtc = systemClock.UtcNow, FailureKind = McpFailureKind.Startup }; + await PersistAndEmitAsync(workspaceRoot, startingStatus, faulted, CancellationToken.None).ConfigureAwait(false); + throw; + } var finalStatus = processResult.Started ? processResult.HandshakeSucceeded diff --git a/src/SharpClaw.Code.Mcp/Services/SdkMcpProcessSupervisor.cs b/src/SharpClaw.Code.Mcp/Services/SdkMcpProcessSupervisor.cs index 52ae65d..dcd77ba 100644 --- a/src/SharpClaw.Code.Mcp/Services/SdkMcpProcessSupervisor.cs +++ b/src/SharpClaw.Code.Mcp/Services/SdkMcpProcessSupervisor.cs @@ -165,9 +165,9 @@ public async Task StartAsync( /// public async Task StopAsync(McpProcessStopRequest request, CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); if (request.SessionHandle > 0 && Sessions.TryRemove(request.SessionHandle, out var tracked)) { - cancellationToken.ThrowIfCancellationRequested(); await tracked.DisposeAsync().ConfigureAwait(false); } diff --git a/src/SharpClaw.Code.Memory/Services/SqliteWorkspaceKnowledgeStore.cs b/src/SharpClaw.Code.Memory/Services/SqliteWorkspaceKnowledgeStore.cs index 06cbc26..55f8d2c 100644 --- a/src/SharpClaw.Code.Memory/Services/SqliteWorkspaceKnowledgeStore.cs +++ b/src/SharpClaw.Code.Memory/Services/SqliteWorkspaceKnowledgeStore.cs @@ -470,13 +470,16 @@ private async Task OpenConnectionAsync(string dbPath, Cancella { DataSource = dbPath, Mode = SqliteOpenMode.ReadWriteCreate, - Cache = SqliteCacheMode.Shared, + Cache = SqliteCacheMode.Private, }.ToString(); connectionPools.TryAdd(connectionString, 0); var connection = new SqliteConnection(connectionString); try { await connection.OpenAsync(cancellationToken).ConfigureAwait(false); + await using var pragma = connection.CreateCommand(); + pragma.CommandText = "PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;"; + await pragma.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); await EnsureSchemaAsync(connection, cancellationToken).ConfigureAwait(false); return connection; } @@ -677,7 +680,7 @@ private static string NormalizeFtsQuery(string query) .Split([' ', '\r', '\n', '\t'], StringSplitOptions.RemoveEmptyEntries) .Select(static token => new string(token.Where(static character => char.IsLetterOrDigit(character) || character == '_').ToArray())) .Where(static token => !string.IsNullOrWhiteSpace(token)) - .Select(static token => token.EndsWith('*') ? token : $"{token}*"); + .Select(static token => $"\"{token}\"*"); return string.Join(" ", tokens); } diff --git a/src/SharpClaw.Code.Permissions/Rules/DangerousShellPatternRule.cs b/src/SharpClaw.Code.Permissions/Rules/DangerousShellPatternRule.cs index d6f6485..226a2fd 100644 --- a/src/SharpClaw.Code.Permissions/Rules/DangerousShellPatternRule.cs +++ b/src/SharpClaw.Code.Permissions/Rules/DangerousShellPatternRule.cs @@ -36,7 +36,8 @@ private static bool IsDangerous(string command) { // Collapse whitespace runs so extra spaces don't bypass detection. var normalized = CollapseWhitespace().Replace(command.Trim(), " ").ToLowerInvariant(); - return normalized.Contains("rm -rf /", StringComparison.Ordinal) + return DangerousDeletionRegex().IsMatch(normalized) + || normalized.Contains("rm -rf /", StringComparison.Ordinal) || normalized.Contains("rm -rf .", StringComparison.Ordinal) || normalized.Contains("rm -rf ..", StringComparison.Ordinal) || normalized.Contains("sudo ", StringComparison.Ordinal) @@ -53,6 +54,9 @@ private static bool ContainsDangerousSubstitution(string normalized) return DangerousSubstitutionRegex().IsMatch(normalized); } + [GeneratedRegex(@"\b(?:rm\s+[^;|\r\n]*-[a-z]*r|find\s+[^;|\r\n]*-(?:delete|exec))\b", RegexOptions.IgnoreCase, matchTimeoutMilliseconds: 250)] + private static partial Regex DangerousDeletionRegex(); + [GeneratedRegex(@"\$\(.*(?:rm\s+-rf|mkfs|dd\s+if=|shutdown|reboot)", RegexOptions.Singleline)] private static partial Regex DangerousSubstitutionRegex(); diff --git a/src/SharpClaw.Code.Permissions/Rules/PluginTrustRule.cs b/src/SharpClaw.Code.Permissions/Rules/PluginTrustRule.cs index 95f8549..e5da516 100644 --- a/src/SharpClaw.Code.Permissions/Rules/PluginTrustRule.cs +++ b/src/SharpClaw.Code.Permissions/Rules/PluginTrustRule.cs @@ -30,15 +30,14 @@ public Task EvaluateAsync( return Task.FromResult(PermissionRuleResult.Abstain()); } - if (manifestTrust is PluginTrustLevel.DeveloperTrusted or PluginTrustLevel.WorkspaceTrusted) + if (context.PermissionMode == PermissionMode.ReadOnly || context.PrimaryMode is PrimaryMode.Plan or PrimaryMode.Research) { - return Task.FromResult(PermissionRuleResult.Abstain()); + return Task.FromResult(PermissionRuleResult.Deny("Plugin processes are unavailable in read-only workflows.")); } - return PermissionRuleHelpers.IsTrusted(context.TrustedPluginNames, context.ToolOriginatingPluginId) - ? Task.FromResult(PermissionRuleResult.Abstain()) - : Task.FromResult(PermissionRuleResult.RequireApproval( - $"Plugin tool '{request.ToolName}' from '{context.ToolOriginatingPluginId}' (manifest trust: Untrusted) requires approval or session trust.", - canRememberApproval: true)); + // Workspace session files, like manifests, are not an authority for executing arbitrary processes. + return Task.FromResult(PermissionRuleResult.RequireApproval( + $"Plugin tool '{request.ToolName}' from '{context.ToolOriginatingPluginId}' (manifest trust: {manifestTrust}) requires explicit approval.", + canRememberApproval: false)); } } diff --git a/src/SharpClaw.Code.Permissions/Services/PermissionPolicyEngine.cs b/src/SharpClaw.Code.Permissions/Services/PermissionPolicyEngine.cs index 9b8d86d..a547c88 100644 --- a/src/SharpClaw.Code.Permissions/Services/PermissionPolicyEngine.cs +++ b/src/SharpClaw.Code.Permissions/Services/PermissionPolicyEngine.cs @@ -13,7 +13,8 @@ public sealed class PermissionPolicyEngine( IEnumerable rules, IApprovalService approvalService, ISessionApprovalMemory sessionApprovalMemory, - IAutoApprovalBudgetTracker autoApprovalBudgetTracker) : IPermissionPolicyEngine + IAutoApprovalBudgetTracker autoApprovalBudgetTracker, + IApprovalPrincipalAccessor? approvalPrincipalAccessor = null) : IPermissionPolicyEngine { private readonly IPermissionRule[] orderedRules = rules.ToArray(); @@ -26,6 +27,17 @@ public async Task EvaluateAsync( ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(context); + if (!Enum.IsDefined(context.PermissionMode) || !Enum.IsDefined(context.PrimaryMode)) + return CreateDecision(request.ApprovalScope, context.PermissionMode, false, "Unknown runtime permission or workflow mode."); + + // A rule may tighten policy, but cannot bypass a mode or a later denial. + if (context.PermissionMode == PermissionMode.ReadOnly + && (request.IsDestructive || request.ApprovalScope is not (ApprovalScope.ToolExecution or ApprovalScope.PromptOutsideWorkspaceRead))) + { + return CreateDecision(request.ApprovalScope, context.PermissionMode, false, "Read-only mode blocks destructive or elevated tools."); + } + + PermissionRuleResult? approval = null; foreach (var rule in orderedRules) { var result = await rule.EvaluateAsync(request, context, cancellationToken).ConfigureAwait(false); @@ -34,16 +46,31 @@ public async Task EvaluateAsync( case PermissionRuleOutcome.Abstain: continue; case PermissionRuleOutcome.Allow: - return CreateDecision(request.ApprovalScope, context.PermissionMode, true, result.Reason); + continue; case PermissionRuleOutcome.Deny: return CreateDecision(request.ApprovalScope, context.PermissionMode, false, result.Reason); case PermissionRuleOutcome.RequireApproval: - return await ResolveApprovalAsync(request, context, result, cancellationToken).ConfigureAwait(false); + approval = approval is null ? result : PermissionRuleResult.RequireApproval( + CombineReasons(approval.Reason, result.Reason) ?? "Approval required.", + approval.CanRememberApproval && result.CanRememberApproval); + break; default: throw new InvalidOperationException($"Unhandled permission rule outcome '{result.Outcome}'."); } } + if (approval is not null) + { + return await ResolveApprovalAsync(request, context, approval, cancellationToken).ConfigureAwait(false); + } + + if (request.RequiresApproval && context.PermissionMode != PermissionMode.DangerFullAccess) + { + return await ResolveApprovalAsync(request, context, + PermissionRuleResult.RequireApproval(request.ApprovalScope == ApprovalScope.PromptOutsideWorkspaceRead + ? "Reading a file outside the workspace for prompt context requires approval." : "The tool requires approval.", canRememberApproval: true), cancellationToken).ConfigureAwait(false); + } + return await EvaluateByModeAsync(request, context, cancellationToken).ConfigureAwait(false); } @@ -73,7 +100,7 @@ ApprovalScope.ShellExecution or ApprovalScope.NetworkAccess or ApprovalScope.Ses => await ResolveApprovalAsync( request, context, - PermissionRuleResult.RequireApproval("Workspace-write mode requires approval for elevated operations."), + PermissionRuleResult.RequireApproval("Workspace-write mode requires approval for elevated operations.", canRememberApproval: true), cancellationToken).ConfigureAwait(false), _ => CreateDecision(request.ApprovalScope, context.PermissionMode, false, "The requested approval scope is not supported.") }, @@ -120,7 +147,10 @@ private async Task ResolveApprovalAsync( { var approvalKey = CreateApprovalKey(request, context); var approvalMemorySessionId = GetApprovalMemorySessionId(context); - if (ruleResult.CanRememberApproval && sessionApprovalMemory.TryGet(approvalMemorySessionId, approvalKey) is { } rememberedEntry && rememberedEntry.Decision.Approved) + var authenticatedHost = approvalPrincipalAccessor?.CurrentStatus is { Mode: not ApprovalAuthMode.Disabled }; + if (!authenticatedHost && !string.IsNullOrWhiteSpace(approvalMemorySessionId) + && ruleResult.CanRememberApproval && sessionApprovalMemory.TryGet(approvalMemorySessionId, approvalKey) is { } rememberedEntry && rememberedEntry.Decision.Approved + && (rememberedEntry.Decision.ExpiresAtUtc is null || rememberedEntry.Decision.ExpiresAtUtc > DateTimeOffset.UtcNow)) { return CreateDecision( request.ApprovalScope, @@ -129,7 +159,7 @@ private async Task ResolveApprovalAsync( $"Reused remembered approval for '{request.ToolName}'."); } - if (TryResolveAutoApproval(request, context, out var autoApprovedDecision)) + if (!authenticatedHost && ruleResult.CanRememberApproval && TryResolveAutoApproval(request, context, out var autoApprovedDecision)) { return autoApprovedDecision; } @@ -137,12 +167,12 @@ private async Task ResolveApprovalAsync( var approvalRequest = new ApprovalRequest( Scope: request.ApprovalScope, ToolName: request.ToolName, - Prompt: ruleResult.Reason ?? $"Approval is required for '{request.ToolName}'.", + Prompt: $"{ruleResult.Reason ?? $"Approval is required for '{request.ToolName}'."}\nTool: {request.ToolName}\nDirectory: {request.WorkingDirectory ?? context.WorkingDirectory}\nArguments: {request.ArgumentsJson}", RequestedBy: "permission-policy-engine", CanRememberDecision: ruleResult.CanRememberApproval); var approvalDecision = await approvalService.RequestApprovalAsync(approvalRequest, context, cancellationToken).ConfigureAwait(false); - if (approvalDecision.Approved && ruleResult.CanRememberApproval && approvalDecision.RememberForSession) + if (!authenticatedHost && !string.IsNullOrWhiteSpace(approvalMemorySessionId) && approvalDecision.Approved && ruleResult.CanRememberApproval && approvalDecision.RememberForSession) { sessionApprovalMemory.Store(approvalMemorySessionId, approvalKey, new ApprovalMemoryEntry(approvalDecision)); } @@ -229,7 +259,8 @@ private static string CreateApprovalKey(ToolExecutionRequest request, Permission request.WorkingDirectory ?? string.Empty, context.ToolOriginatingPluginId ?? string.Empty, trustSegment, - pathSegment); + pathSegment, + request.ArgumentsJson); } private static string GetApprovalMemorySessionId(PermissionEvaluationContext context) diff --git a/src/SharpClaw.Code.Plugins/Services/PluginManager.cs b/src/SharpClaw.Code.Plugins/Services/PluginManager.cs index f171574..bfa95b5 100644 --- a/src/SharpClaw.Code.Plugins/Services/PluginManager.cs +++ b/src/SharpClaw.Code.Plugins/Services/PluginManager.cs @@ -15,7 +15,7 @@ namespace SharpClaw.Code.Plugins.Services; /// /// Manages manifest-based plugins under . /// Tool descriptors are surfaced only for plugins in the state; execution goes through (out-of-process by default). -/// Trust on the manifest flows to permission evaluation via tool metadata. +/// Manifest trust is advisory metadata; workspace files cannot grant execution approval. /// public sealed class PluginManager( IPluginLoader pluginLoader, @@ -46,13 +46,17 @@ public async Task> ListAsync(string workspaceRoot, C var plugins = new List(); foreach (var pluginDirectory in fileSystem.EnumerateDirectories(pluginRoot)) { - var manifest = await LoadManifestAsync(pluginDirectory, cancellationToken).ConfigureAwait(false); - if (manifest is null) + try { - continue; + var manifest = await LoadManifestAsync(pluginDirectory, cancellationToken).ConfigureAwait(false); + if (manifest is null) continue; + manifestValidator.Validate(manifest); + plugins.Add(await LoadPluginStateAsync(pluginDirectory, manifest, cancellationToken).ConfigureAwait(false)); + } + catch (Exception exception) when (exception is JsonException or ArgumentException or InvalidOperationException or IOException) + { + logger.LogWarning(exception, "Ignoring invalid plugin at {Directory}.", pluginDirectory); } - - plugins.Add(await LoadPluginStateAsync(pluginDirectory, manifest, cancellationToken).ConfigureAwait(false)); } return plugins @@ -186,8 +190,10 @@ public async Task> ListToolDescriptorsAsync( var ordered = descriptors .OrderBy(tool => tool.Name, StringComparer.OrdinalIgnoreCase) .ToArray(); - ThrowIfDuplicateToolNames(ordered); - return ordered; + var conflicts = ordered.GroupBy(tool => tool.Name, StringComparer.OrdinalIgnoreCase) + .Where(group => group.Count() > 1).Select(group => group.Key).ToHashSet(StringComparer.OrdinalIgnoreCase); + foreach (var name in conflicts) logger.LogWarning("Ignoring conflicting plugin tool {ToolName}.", name); + return ordered.Where(tool => !conflicts.Contains(tool.Name)).ToArray(); } /// @@ -255,7 +261,10 @@ private string GetPluginsRoot(string workspaceRoot) PluginLocalStore.PluginsRelativeDirectoryName); private string GetPluginDirectory(string workspaceRoot, string pluginId) - => pathService.Combine(GetPluginsRoot(workspaceRoot), pluginId); + { + SharpClaw.Code.Infrastructure.Services.LocalPackagePath.ValidateId(pluginId); + return SharpClaw.Code.Infrastructure.Services.LocalPackagePath.Resolve(pathService, GetPluginsRoot(workspaceRoot), pluginId, workspaceRoot); + } private string EnsurePluginDirectory(string workspaceRoot, string pluginId) { @@ -398,18 +407,4 @@ await runtimeEventPublisher } } - private static void ThrowIfDuplicateToolNames(PluginToolDescriptor[] descriptors) - { - var duplicate = descriptors - .GroupBy(tool => tool.Name, StringComparer.OrdinalIgnoreCase) - .FirstOrDefault(group => group.Count() > 1); - if (duplicate is null) - { - return; - } - - var owners = string.Join(", ", duplicate.Select(tool => tool.SourcePluginId ?? "?").Distinct(StringComparer.OrdinalIgnoreCase)); - throw new InvalidOperationException( - $"Multiple enabled plugins expose the tool '{duplicate.Key}' (plugins: {owners}). Rename a tool or disable one plugin."); - } } diff --git a/src/SharpClaw.Code.Providers/AnthropicProvider.cs b/src/SharpClaw.Code.Providers/AnthropicProvider.cs index abee896..3e51e1f 100644 --- a/src/SharpClaw.Code.Providers/AnthropicProvider.cs +++ b/src/SharpClaw.Code.Providers/AnthropicProvider.cs @@ -22,6 +22,9 @@ public sealed class AnthropicProvider( ILogger logger) : IModelProvider { private readonly AnthropicProviderOptions _options = options.Value; + private readonly object clientLock = new(); + private AnthropicClient? cachedClient; + private string? cachedApiKey; /// public string ProviderName => _options.ProviderName; @@ -125,7 +128,7 @@ internal static MessageCreateParams CreateMessageParameters(ProviderRequest requ parameters = parameters with { System = systemPrompt }; } - return parameters; + return parameters with { CacheControl = new CacheControlEphemeral() }; } private AnthropicClient CreateClient(string? resolvedApiKey) @@ -142,7 +145,15 @@ private AnthropicClient CreateClient(string? resolvedApiKey) clientOptions.BaseUrl = normalized; } - return new AnthropicClient(clientOptions); + lock (clientLock) + { + if (cachedClient is null || !string.Equals(cachedApiKey, apiKey, StringComparison.Ordinal)) + { + cachedClient = new AnthropicClient(clientOptions); + cachedApiKey = apiKey; + } + return cachedClient; + } } private async Task ResolveCredentialAsync(CancellationToken cancellationToken) diff --git a/src/SharpClaw.Code.Providers/Configuration/AnthropicProviderOptions.cs b/src/SharpClaw.Code.Providers/Configuration/AnthropicProviderOptions.cs index 2f8490c..cb3159a 100644 --- a/src/SharpClaw.Code.Providers/Configuration/AnthropicProviderOptions.cs +++ b/src/SharpClaw.Code.Providers/Configuration/AnthropicProviderOptions.cs @@ -28,7 +28,7 @@ public sealed class AnthropicProviderOptions /// /// Gets or sets the default model id. /// - public string DefaultModel { get; set; } = "claude-3-7-sonnet-latest"; + public string DefaultModel { get; set; } = "claude-sonnet-5-5"; /// /// Gets or sets whether the provider supports structured image input. diff --git a/src/SharpClaw.Code.Providers/Internal/AnthropicSdkStreamAdapter.cs b/src/SharpClaw.Code.Providers/Internal/AnthropicSdkStreamAdapter.cs index 94b6f12..3ce913c 100644 --- a/src/SharpClaw.Code.Providers/Internal/AnthropicSdkStreamAdapter.cs +++ b/src/SharpClaw.Code.Providers/Internal/AnthropicSdkStreamAdapter.cs @@ -25,6 +25,9 @@ public static async IAsyncEnumerable AdaptAsync( string? pendingToolName = null; System.Text.StringBuilder? pendingToolInputBuilder = null; + long inputTokens = 0, outputTokens = 0, cachedTokens = 0, createdCacheTokens = 0; + var tools = new List(); + string? stopReason = null; IAsyncEnumerator? enumerator = null; try { @@ -61,7 +64,25 @@ public static async IAsyncEnumerable AdaptAsync( var ev = enumerator.Current; - if (ev.TryPickContentBlockStart(out var blockStart)) + if (ev.TryPickStart(out var start)) + { + inputTokens = start.Message.Usage.InputTokens; + createdCacheTokens = start.Message.Usage.CacheCreationInputTokens ?? 0; + outputTokens = start.Message.Usage.OutputTokens; + cachedTokens = start.Message.Usage.CacheReadInputTokens ?? 0; + } + else if (ev.TryPickDelta(out var delta)) + { + inputTokens = delta.Usage.InputTokens ?? inputTokens; + createdCacheTokens = delta.Usage.CacheCreationInputTokens ?? createdCacheTokens; + outputTokens = delta.Usage.OutputTokens; + cachedTokens = delta.Usage.CacheReadInputTokens ?? cachedTokens; + // Read the wire value of the SDK's extensible enum. + var json = System.Text.Json.JsonSerializer.SerializeToElement(delta.Delta); + if (json.TryGetProperty("stop_reason", out var reason) && reason.ValueKind == System.Text.Json.JsonValueKind.String) + stopReason = reason.GetString(); + } + else if (ev.TryPickContentBlockStart(out var blockStart)) { if (blockStart.ContentBlock.TryPickToolUse(out var toolUse)) { @@ -87,7 +108,7 @@ public static async IAsyncEnumerable AdaptAsync( if (pendingToolUseId is not null && pendingToolName is not null && pendingToolInputBuilder is not null) { var toolInputJson = pendingToolInputBuilder.ToString(); - yield return ProviderStreamEventFactory.ToolUse(requestId, clock, pendingToolUseId, pendingToolName, toolInputJson); + tools.Add(ProviderStreamEventFactory.ToolUse(requestId, clock, pendingToolUseId, pendingToolName, string.IsNullOrEmpty(toolInputJson) ? "{}" : toolInputJson)); pendingToolUseId = null; pendingToolName = null; pendingToolInputBuilder = null; @@ -95,7 +116,14 @@ public static async IAsyncEnumerable AdaptAsync( } else if (ev.TryPickStop(out _)) { - yield return ProviderStreamEventFactory.Completed(requestId, clock, null); + if (stopReason is not ("end_turn" or "tool_use" or "stop_sequence") || pendingToolUseId is not null) + { + yield return ProviderStreamEventFactory.Failed(requestId, clock, $"Anthropic response is incomplete (stop reason: {stopReason ?? "missing"}); tool calls were discarded."); + yield break; + } + foreach (var tool in tools) yield return tool; + yield return ProviderStreamEventFactory.Completed(requestId, clock, + new UsageSnapshot(inputTokens + createdCacheTokens + cachedTokens, outputTokens, cachedTokens, inputTokens + createdCacheTokens + cachedTokens + outputTokens, null)); yield break; } } @@ -108,7 +136,7 @@ public static async IAsyncEnumerable AdaptAsync( } } - yield return ProviderStreamEventFactory.Completed(requestId, clock, null); + yield return ProviderStreamEventFactory.Failed(requestId, clock, "Anthropic stream ended before message_stop."); } private static (string? Text, string? PartialJson) ExtractDeltas(RawContentBlockDelta delta) diff --git a/src/SharpClaw.Code.Providers/Internal/OpenAiMeaiStreamAdapter.cs b/src/SharpClaw.Code.Providers/Internal/OpenAiMeaiStreamAdapter.cs index 313862b..ee36732 100644 --- a/src/SharpClaw.Code.Providers/Internal/OpenAiMeaiStreamAdapter.cs +++ b/src/SharpClaw.Code.Providers/Internal/OpenAiMeaiStreamAdapter.cs @@ -20,7 +20,8 @@ public static async IAsyncEnumerable AdaptAsync( ISystemClock clock, [EnumeratorCancellation] CancellationToken cancellationToken) { - var completed = false; + UsageSnapshot? usage = null; + string? finishReason = null; IAsyncEnumerator? enumerator = null; try { @@ -80,13 +81,8 @@ public static async IAsyncEnumerable AdaptAsync( } } - if (update.FinishReason is { } finish && !string.IsNullOrEmpty(finish.Value)) - { - var usage = ProviderStreamEventFactory.TryUsageFromUpdate(update); - yield return ProviderStreamEventFactory.Completed(requestId, clock, usage); - completed = true; - yield break; - } + usage = ProviderStreamEventFactory.TryUsageFromUpdate(update) ?? usage; + finishReason = update.FinishReason?.Value ?? finishReason; } } finally @@ -97,9 +93,8 @@ public static async IAsyncEnumerable AdaptAsync( } } - if (!completed) - { - yield return ProviderStreamEventFactory.Completed(requestId, clock, null); - } + yield return finishReason is "length" or "content_filter" + ? ProviderStreamEventFactory.Failed(requestId, clock, $"Provider response stopped with {finishReason}; incomplete tool calls were discarded.") + : ProviderStreamEventFactory.Completed(requestId, clock, usage); } } diff --git a/src/SharpClaw.Code.Providers/Resilience/ResilientProviderDecorator.cs b/src/SharpClaw.Code.Providers/Resilience/ResilientProviderDecorator.cs index 99dfbf3..a2504b0 100644 --- a/src/SharpClaw.Code.Providers/Resilience/ResilientProviderDecorator.cs +++ b/src/SharpClaw.Code.Providers/Resilience/ResilientProviderDecorator.cs @@ -96,6 +96,13 @@ private async IAsyncEnumerable ExecuteWithResilienceAsync( break; } + if (enumerator.Current.IsTerminal && string.Equals(enumerator.Current.Kind, "failed", StringComparison.OrdinalIgnoreCase)) + { + attemptException = ProviderStreamFailureClassifier.ClassifyFailedEvent(enumerator.Current) is ProviderFailureKind.AuthenticationUnavailable + ? new ProviderExecutionException(ProviderName, request.Model, ProviderFailureKind.AuthenticationUnavailable, enumerator.Current.Content ?? "Provider authentication failed.") + : new HttpRequestException(enumerator.Current.Content ?? "Provider stream failed."); + break; + } emittedEvent = true; yield return enumerator.Current; } diff --git a/src/SharpClaw.Code.Runtime/Configuration/SharpClawConfigService.cs b/src/SharpClaw.Code.Runtime/Configuration/SharpClawConfigService.cs index c8c3493..3057855 100644 --- a/src/SharpClaw.Code.Runtime/Configuration/SharpClawConfigService.cs +++ b/src/SharpClaw.Code.Runtime/Configuration/SharpClawConfigService.cs @@ -83,7 +83,7 @@ private static SharpClawConfigDocument Merge(SharpClawConfigDocument? user, Shar var defaultAgentId = workspace?.DefaultAgentId ?? user?.DefaultAgentId; var shareMode = workspace?.ShareMode ?? user?.ShareMode ?? Protocol.Models.ShareMode.Manual; - var server = workspace?.Server ?? user?.Server ?? new SharpClawServerOptions("127.0.0.1", 7345, null); + var server = user?.Server ?? new SharpClawServerOptions("127.0.0.1", 7345, null); return new SharpClawConfigDocument( shareMode, @@ -91,7 +91,7 @@ private static SharpClawConfigDocument Merge(SharpClawConfigDocument? user, Shar defaultAgentId, MergeByKey(user?.Agents, workspace?.Agents, static item => item.Id), MergeByKey(user?.LspServers, workspace?.LspServers, static item => item.Id), - MergeByKey(user?.Hooks, workspace?.Hooks, static item => item.Name), + user?.Hooks, // Workspace files cannot authorize process execution. MergeByKey(user?.ConnectLinks, workspace?.ConnectLinks, static item => item.Target), MergeExternalAgents(user?.ExternalAgents, workspace?.ExternalAgents), workspace?.SkillPacks ?? user?.SkillPacks ?? new SkillPacksConfig(), diff --git a/src/SharpClaw.Code.Runtime/Mutations/CheckpointMutationCoordinator.cs b/src/SharpClaw.Code.Runtime/Mutations/CheckpointMutationCoordinator.cs index 46d1ffb..d9b887d 100644 --- a/src/SharpClaw.Code.Runtime/Mutations/CheckpointMutationCoordinator.cs +++ b/src/SharpClaw.Code.Runtime/Mutations/CheckpointMutationCoordinator.cs @@ -159,6 +159,9 @@ await eventPublisher.PublishAsync( ThrowIfPersistenceFails: true), cancellationToken).ConfigureAwait(false); + cancellationToken.ThrowIfCancellationRequested(); + // After the first mutation, finish and persist the transaction despite caller cancellation. + cancellationToken = CancellationToken.None; var appliedInverseCount = 0; try { @@ -294,6 +297,9 @@ await eventPublisher.PublishAsync( ThrowIfPersistenceFails: true), cancellationToken).ConfigureAwait(false); + cancellationToken.ThrowIfCancellationRequested(); + // After the first mutation, finish and persist the transaction despite caller cancellation. + cancellationToken = CancellationToken.None; var appliedForwardCount = 0; try { diff --git a/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs b/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs index d64eb2d..ffa0834 100644 --- a/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs +++ b/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs @@ -114,6 +114,7 @@ public async Task RunPromptAsync(RunPromptRequest request, var workspacePath = NormalizeWorkspacePath(request.WorkingDirectory); request = EnrichRequestWithEditorIngress(workspacePath, request); + var explicitPrimaryMode = request.PrimaryMode; request = await ApplyAgentAndConfigDefaultsAsync(workspacePath, request, cancellationToken).ConfigureAwait(false); var runtimeEvents = new List(); var session = await ResolveSessionAsync(workspacePath, request, cancellationToken).ConfigureAwait(false); @@ -130,9 +131,6 @@ public async Task RunPromptAsync(RunPromptRequest request, throw new InvalidOperationException($"Unable to resume session '{request.SessionId}'."); } - session = await EnsurePrimaryModePersistedAsync(workspacePath, session, request.PrimaryMode, cancellationToken).ConfigureAwait(false); - session = await EnsureApprovalSettingsPersistedAsync(workspacePath, session, request.ApprovalSettings, cancellationToken).ConfigureAwait(false); - var sessionMutex = GetSessionMutex(workspacePath, session.Id); await sessionMutex.WaitAsync(cancellationToken).ConfigureAwait(false); try @@ -149,6 +147,13 @@ public async Task RunPromptAsync(RunPromptRequest request, session = refreshed; } + if (explicitPrimaryMode is null && session.Metadata is not null + && session.Metadata.TryGetValue(SharpClawWorkflowMetadataKeys.PrimaryMode, out var savedMode) + && Enum.TryParse(savedMode, true, out var persistedMode) && Enum.IsDefined(persistedMode)) + request = request with { PrimaryMode = persistedMode }; + session = await EnsurePrimaryModePersistedAsync(workspacePath, session, request.PrimaryMode, cancellationToken).ConfigureAwait(false); + session = await EnsureApprovalSettingsPersistedAsync(workspacePath, session, request.ApprovalSettings, cancellationToken).ConfigureAwait(false); + session = await EnsureRecoverableFromFailedForPromptAsync( workspacePath, session, @@ -1326,7 +1331,7 @@ await AppendEventAsync( foreach (var providerEvent in turnRunResult.ProviderEvents ?? []) { - if (!providerEvent.IsTerminal && !string.IsNullOrWhiteSpace(providerEvent.Content)) + if (!providerEvent.IsTerminal && !string.IsNullOrEmpty(providerEvent.Content)) { await AppendEventAsync( workspacePath, @@ -1674,6 +1679,11 @@ private static PrimaryMode ClampPrimaryModeForCustomCommand(PrimaryMode context, return PrimaryMode.Plan; } + if (context == PrimaryMode.Research || effective == PrimaryMode.Research) + { + return PrimaryMode.Research; + } + if (context == PrimaryMode.Spec || effective == PrimaryMode.Spec) { return PrimaryMode.Spec; diff --git a/src/SharpClaw.Code.Runtime/Prompts/PromptReferenceResolver.cs b/src/SharpClaw.Code.Runtime/Prompts/PromptReferenceResolver.cs index 1728c07..a7fcd20 100644 --- a/src/SharpClaw.Code.Runtime/Prompts/PromptReferenceResolver.cs +++ b/src/SharpClaw.Code.Runtime/Prompts/PromptReferenceResolver.cs @@ -72,6 +72,12 @@ public async Task ResolveAsync( ? pathService.GetCanonicalFullPath(pathPart) : pathService.GetCanonicalFullPath(pathService.Combine(workDirFull, pathPart)); + if (!fileSystem.FileExists(resolvedFull) && !fileSystem.DirectoryExists(resolvedFull) + && !pathPart.StartsWith('.') && !Path.IsPathRooted(pathPart)) + { + continue; // Email, annotations, and package mentions are ordinary prompt text. + } + var outside = !IsWithinWorkspace(workspaceFull, resolvedFull); if (outside) { @@ -287,6 +293,8 @@ private static string ToDisplayPath(string workspaceRootFull, string workingDire Uri: resolvedFull)); } + if (File.Exists(resolvedFull) && new FileInfo(resolvedFull).Length > MaxDirectoryReferenceBytes) + throw new InvalidOperationException($"Referenced file exceeds {FormatBytes(MaxDirectoryReferenceBytes)}: '{display}'."); var text = await fileSystem.ReadAllTextIfExistsAsync(resolvedFull, cancellationToken).ConfigureAwait(false); if (text is null) { @@ -471,6 +479,6 @@ private static string ResolveMediaType(string path) _ => "image/jpeg", }; - [GeneratedRegex(@"@([^\s<>""|*?]+)", RegexOptions.CultureInvariant)] + [GeneratedRegex(@"(?""|*?]+)", RegexOptions.CultureInvariant)] private static partial Regex AtPathRegex(); } diff --git a/src/SharpClaw.Code.Runtime/Server/WorkspaceHttpServer.cs b/src/SharpClaw.Code.Runtime/Server/WorkspaceHttpServer.cs index 533c1ae..eeb2300 100644 --- a/src/SharpClaw.Code.Runtime/Server/WorkspaceHttpServer.cs +++ b/src/SharpClaw.Code.Runtime/Server/WorkspaceHttpServer.cs @@ -47,6 +47,9 @@ public async Task RunAsync( RuntimeCommandContext context, CancellationToken cancellationToken) { + var serverToken = Environment.GetEnvironmentVariable("SHARPCLAW_SERVER_TOKEN"); + if (string.IsNullOrWhiteSpace(serverToken) || serverToken.Length < 32 || serverToken.Any(char.IsWhiteSpace)) + throw new InvalidOperationException("Set SHARPCLAW_SERVER_TOKEN to a secret of at least 32 characters before starting the HTTP server."); var config = await sharpClawConfigService.GetConfigAsync(workspaceRoot, cancellationToken).ConfigureAwait(false); var effectiveHost = string.IsNullOrWhiteSpace(host) ? config.Document.Server?.Host ?? "127.0.0.1" : host!; var effectivePort = port is > 0 ? port.Value : config.Document.Server?.Port ?? 7345; @@ -76,7 +79,7 @@ public async Task RunAsync( } _ = Task.Run( - () => HandleRequestAsync(httpContext, workspaceRoot, context, cancellationToken), + () => HandleRequestAsync(httpContext, workspaceRoot, context, serverToken, effectiveHost, cancellationToken), CancellationToken.None); } } @@ -104,9 +107,28 @@ private async Task HandleRequestAsync( HttpListenerContext httpContext, string workspaceRoot, RuntimeCommandContext defaultContext, + string serverToken, + string listeningHost, CancellationToken cancellationToken) { var request = httpContext.Request; + // All endpoints share the host credential. Browser origins and DNS-rebinding hosts are rejected. + var expectedHost = httpContext.Request.LocalEndPoint.Address; + var hostName = request.Url?.Host.Trim('[', ']'); + var validHost = string.Equals(hostName, listeningHost, StringComparison.OrdinalIgnoreCase) + || string.Equals(hostName, "localhost", StringComparison.OrdinalIgnoreCase) + || (IPAddress.TryParse(hostName, out var address) && (IPAddress.IsLoopback(address) || address.Equals(expectedHost))); + var supplied = request.Headers["X-SharpClaw-Server-Token"] is { } hostToken + ? "Bearer " + hostToken : request.Headers["Authorization"]; + var expected = "Bearer " + serverToken; + if (!validHost || request.Headers["Origin"] is not null + || supplied is null || !System.Security.Cryptography.CryptographicOperations.FixedTimeEquals( + Encoding.UTF8.GetBytes(supplied), Encoding.UTF8.GetBytes(expected))) + { + await WriteJsonAsync(httpContext.Response, 401, new ErrorEnvelope("A valid server bearer token and host are required; browser origins are not accepted."), cancellationToken).ConfigureAwait(false); + httpContext.Response.Close(); + return; + } var response = httpContext.Response; var requestSucceeded = false; var statusCode = 500; @@ -289,9 +311,10 @@ private async Task HandlePromptAsync( var commandContext = new RuntimeCommandContext( WorkingDirectory: workspaceRoot, Model: payload.Model ?? defaultContext.Model, - PermissionMode: payload.PermissionMode ?? defaultContext.PermissionMode, + PermissionMode: (PermissionMode)Math.Min((int)(payload.PermissionMode ?? defaultContext.PermissionMode), (int)defaultContext.PermissionMode), OutputFormat: payload.OutputFormat ?? OutputFormat.Json, - PrimaryMode: payload.PrimaryMode ?? defaultContext.PrimaryMode, + PrimaryMode: defaultContext.PrimaryMode is PrimaryMode.Plan or PrimaryMode.Research + ? defaultContext.PrimaryMode : payload.PrimaryMode ?? defaultContext.PrimaryMode, SessionId: payload.SessionId ?? defaultContext.SessionId, AgentId: payload.AgentId ?? defaultContext.AgentId, IsInteractive: false, @@ -351,7 +374,7 @@ private async Task HandleAdminCreateSessionAsync( var session = await conversationRuntime .CreateSessionAsync( workspaceRoot, - payload?.PermissionMode ?? context.PermissionMode, + (PermissionMode)Math.Min((int)(payload?.PermissionMode ?? context.PermissionMode), (int)context.PermissionMode), payload?.OutputFormat ?? context.OutputFormat, cancellationToken) .ConfigureAwait(false); @@ -589,28 +612,8 @@ private static UsageMeteringQuery ParseUsageQuery(HttpListenerRequest request, s RuntimeHostContext? fallback, string? tenantOverride) { - var hostId = HeaderOrDefault(request, "X-SharpClaw-Host-Id", fallback?.HostId); - var tenantId = string.IsNullOrWhiteSpace(tenantOverride) - ? HeaderOrDefault(request, "X-SharpClaw-Tenant-Id", fallback?.TenantId) - : tenantOverride; - var storageRoot = HeaderOrDefault(request, "X-SharpClaw-Storage-Root", fallback?.StorageRoot); - var sessionStoreKind = TryParseEnum(request.Headers["X-SharpClaw-Session-Store"]) ?? fallback?.SessionStoreKind ?? SessionStoreKind.FileSystem; - var isEmbeddedHost = fallback?.IsEmbeddedHost ?? false; - - if (string.IsNullOrWhiteSpace(hostId) - && string.IsNullOrWhiteSpace(tenantId) - && string.IsNullOrWhiteSpace(storageRoot) - && fallback is null) - { - return null; - } - - return new RuntimeHostContext( - HostId: string.IsNullOrWhiteSpace(hostId) ? "workspace-http-server" : hostId!, - TenantId: string.IsNullOrWhiteSpace(tenantId) ? null : tenantId, - StorageRoot: string.IsNullOrWhiteSpace(storageRoot) ? null : storageRoot, - SessionStoreKind: sessionStoreKind, - IsEmbeddedHost: isEmbeddedHost || !string.IsNullOrWhiteSpace(storageRoot) || !string.IsNullOrWhiteSpace(tenantId)); + // Identity and storage routing belong to the authenticated host, never request headers or JSON. + return fallback; } private static bool IsAdminPath(string path) @@ -634,17 +637,9 @@ private static bool ShouldIncludeEnvelope( return false; } - if (string.IsNullOrWhiteSpace(hostContext?.TenantId)) - { - return true; - } - - return string.Equals(envelope.TenantId, hostContext.TenantId, StringComparison.Ordinal); + return string.Equals(envelope.TenantId, hostContext?.TenantId, StringComparison.Ordinal); } - private static string? HeaderOrDefault(HttpListenerRequest request, string headerName, string? fallback) - => string.IsNullOrWhiteSpace(request.Headers[headerName]) ? fallback : request.Headers[headerName]; - private static TEnum? TryParseEnum(string? value) where TEnum : struct, Enum => Enum.TryParse(value, ignoreCase: true, out var parsed) ? parsed : null; diff --git a/src/SharpClaw.Code.Runtime/Verification/VerificationService.cs b/src/SharpClaw.Code.Runtime/Verification/VerificationService.cs index 8b1500b..766c954 100644 --- a/src/SharpClaw.Code.Runtime/Verification/VerificationService.cs +++ b/src/SharpClaw.Code.Runtime/Verification/VerificationService.cs @@ -164,12 +164,12 @@ private async Task RunAsync(string kind, string target, timeout.CancelAfter(TimeSpan.FromSeconds(timeoutSeconds)); try { - var result = await processes.RunAsync(new ProcessRunRequest("dotnet", arguments.ToArray(), root, new Dictionary { ["DOTNET_NOLOGO"] = "1", ["DOTNET_CLI_TELEMETRY_OPTOUT"] = "1" }), timeout.Token).ConfigureAwait(false); + var result = await processes.RunAsync(new ProcessRunRequest("dotnet", arguments.ToArray(), root, new Dictionary { ["DOTNET_NOLOGO"] = "1", ["DOTNET_CLI_TELEMETRY_OPTOUT"] = "1" }, ExecutionTimeout: TimeSpan.FromSeconds(timeoutSeconds)), timeout.Token).ConfigureAwait(false); var parsed = diagnostics.Parse(result.StandardOutput, result.StandardError, root); var reason = result.ExitCode == 0 ? VerificationFailureReason.None : Classify(parsed, result.StandardOutput + "\n" + result.StandardError, kind); return new(kind, target, result.ExitCode == 0 ? VerificationStatus.Passed : VerificationStatus.Failed, reason, result.ExitCode, started, clock.UtcNow, (long)(clock.UtcNow - started).TotalMilliseconds, DotNetDiagnosticParser.Bound(result.StandardOutput, 16000), DotNetDiagnosticParser.Bound(result.StandardError, 16000), parsed); } - catch (OperationCanceledException) when (!caller.IsCancellationRequested) + catch (Exception error) when (!caller.IsCancellationRequested && error is OperationCanceledException or TimeoutException) { return Failure(VerificationFailureReason.Timeout, "Verification step timed out."); } diff --git a/src/SharpClaw.Code.Runtime/Workflow/HookDispatcher.cs b/src/SharpClaw.Code.Runtime/Workflow/HookDispatcher.cs index 785232a..8e6654a 100644 --- a/src/SharpClaw.Code.Runtime/Workflow/HookDispatcher.cs +++ b/src/SharpClaw.Code.Runtime/Workflow/HookDispatcher.cs @@ -14,7 +14,7 @@ public sealed class HookDispatcher( IProcessRunner processRunner, ILogger logger) : IHookDispatcher { - private readonly Dictionary lastResults = new(StringComparer.OrdinalIgnoreCase); + private readonly System.Collections.Concurrent.ConcurrentDictionary lastResults = new(StringComparer.OrdinalIgnoreCase); /// public async Task DispatchAsync(string workspaceRoot, HookTriggerKind trigger, string payloadJson, CancellationToken cancellationToken) @@ -78,7 +78,7 @@ private async Task ExecuteHookAsync( { try { - await processRunner.RunAsync( + var process = await processRunner.RunAsync( new ProcessRunRequest( hook.Command, hook.Arguments, @@ -90,6 +90,7 @@ await processRunner.RunAsync( }), cancellationToken).ConfigureAwait(false); + if (process.ExitCode != 0) throw new InvalidOperationException($"Hook exited with code {process.ExitCode}: {process.StandardError}"); var success = new HookTestResult(hook.Name, hook.Trigger, true, "Hook executed successfully.", DateTimeOffset.UtcNow); if (recordResult) { @@ -98,6 +99,7 @@ await processRunner.RunAsync( return success; } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } catch (Exception ex) { logger.LogWarning(ex, "Hook '{HookName}' failed for trigger {Trigger}.", hook.Name, hook.Trigger); diff --git a/src/SharpClaw.Code.Skills/Services/SkillRegistry.cs b/src/SharpClaw.Code.Skills/Services/SkillRegistry.cs index 4bfa056..da97269 100644 --- a/src/SharpClaw.Code.Skills/Services/SkillRegistry.cs +++ b/src/SharpClaw.Code.Skills/Services/SkillRegistry.cs @@ -84,7 +84,7 @@ public async Task InstallAsync(string workspaceRoot, SkillInstall var skillsRoot = EnsureSkillsRoot(workspaceRoot); fileSystem.CreateDirectory(skillsRoot); - var skillDirectory = pathService.Combine(skillsRoot, request.Id); + var skillDirectory = SharpClaw.Code.Infrastructure.Services.LocalPackagePath.Resolve(pathService, skillsRoot, request.Id, workspaceRoot); fileSystem.CreateDirectory(skillDirectory); var metadata = new Dictionary(request.Metadata ?? new Dictionary(), StringComparer.Ordinal) @@ -125,7 +125,7 @@ public Task UninstallAsync(string workspaceRoot, string skillId, Cancellat { ArgumentException.ThrowIfNullOrWhiteSpace(skillId); - var skillDirectory = pathService.Combine(EnsureSkillsRoot(workspaceRoot), skillId); + var skillDirectory = SharpClaw.Code.Infrastructure.Services.LocalPackagePath.Resolve(pathService, EnsureSkillsRoot(workspaceRoot), skillId, workspaceRoot); if (!fileSystem.DirectoryExists(skillDirectory)) { return Task.FromResult(false); diff --git a/src/SharpClaw.Code.Tools/BuiltIn/GlobSearchTool.cs b/src/SharpClaw.Code.Tools/BuiltIn/GlobSearchTool.cs index c5ed700..287b626 100644 --- a/src/SharpClaw.Code.Tools/BuiltIn/GlobSearchTool.cs +++ b/src/SharpClaw.Code.Tools/BuiltIn/GlobSearchTool.cs @@ -37,7 +37,7 @@ public override Task ExecuteAsync( var pathResolver = new WorkspacePathResolver(pathService); var workspaceRoot = pathResolver.ResolveWorkspaceRoot(context); cancellationToken.ThrowIfCancellationRequested(); - var matches = Directory.EnumerateFiles(workspaceRoot, "*", SearchOption.AllDirectories) + var matches = WorkspaceSearchFiles.Enumerate(workspaceRoot) .TakeWhile(_ => !cancellationToken.IsCancellationRequested) .Select(path => pathResolver.ToRelativePath(context, path)) .Where(path => GlobPatternMatcher.IsMatch(arguments.Pattern, path)) diff --git a/src/SharpClaw.Code.Tools/BuiltIn/GrepSearchTool.cs b/src/SharpClaw.Code.Tools/BuiltIn/GrepSearchTool.cs index cf3f274..df323a3 100644 --- a/src/SharpClaw.Code.Tools/BuiltIn/GrepSearchTool.cs +++ b/src/SharpClaw.Code.Tools/BuiltIn/GrepSearchTool.cs @@ -42,7 +42,7 @@ public override async Task ExecuteAsync( Regex regex; try { - regex = new Regex(arguments.Pattern, regexOptions); + regex = new Regex(arguments.Pattern, regexOptions, TimeSpan.FromMilliseconds(250)); } catch (ArgumentException ex) { @@ -52,7 +52,7 @@ public override async Task ExecuteAsync( var pathResolver = new WorkspacePathResolver(pathService); var workspaceRoot = pathResolver.ResolveWorkspaceRoot(context); var matches = new List(); - foreach (var file in Directory.EnumerateFiles(workspaceRoot, "*", SearchOption.AllDirectories)) + foreach (var file in WorkspaceSearchFiles.Enumerate(workspaceRoot)) { cancellationToken.ThrowIfCancellationRequested(); var relativePath = pathResolver.ToRelativePath(context, file); @@ -61,10 +61,16 @@ public override async Task ExecuteAsync( continue; } - var lines = await File.ReadAllLinesAsync(file, cancellationToken).ConfigureAwait(false); + if (new FileInfo(file).Length > 2 * 1024 * 1024) continue; + var text = await File.ReadAllTextAsync(file, cancellationToken).ConfigureAwait(false); + if (text.Contains('\0')) continue; + var lines = text.Split('\n'); for (var index = 0; index < lines.Length; index++) { - if (!regex.IsMatch(lines[index])) + bool matched; + try { matched = regex.IsMatch(lines[index]); } + catch (RegexMatchTimeoutException) { return CreateFailureResult(context, request, "Regex search exceeded its time limit."); } + if (!matched) { continue; } diff --git a/src/SharpClaw.Code.Tools/BuiltIn/ReadFileTool.cs b/src/SharpClaw.Code.Tools/BuiltIn/ReadFileTool.cs index 3069bd8..45cb0b8 100644 --- a/src/SharpClaw.Code.Tools/BuiltIn/ReadFileTool.cs +++ b/src/SharpClaw.Code.Tools/BuiltIn/ReadFileTool.cs @@ -36,6 +36,8 @@ public override async Task ExecuteAsync( var arguments = DeserializeArguments(request); var pathResolver = new WorkspacePathResolver(pathService); var fullPath = pathResolver.ResolvePath(context, arguments.Path); + if (File.Exists(fullPath) && new FileInfo(fullPath).Length > 2 * 1024 * 1024) + return CreateFailureResult(context, request, "File exceeds the 2 MiB read limit."); var lines = await fileSystem.ReadAllLinesIfExistsAsync(fullPath, cancellationToken).ConfigureAwait(false); if (lines.Length == 0 && !fileSystem.FileExists(fullPath)) { diff --git a/src/SharpClaw.Code.Tools/BuiltIn/WebFetchTool.cs b/src/SharpClaw.Code.Tools/BuiltIn/WebFetchTool.cs index 01babe7..fdb7bfb 100644 --- a/src/SharpClaw.Code.Tools/BuiltIn/WebFetchTool.cs +++ b/src/SharpClaw.Code.Tools/BuiltIn/WebFetchTool.cs @@ -19,7 +19,7 @@ public sealed class WebFetchTool(IWebFetchService webFetchService) : SharpClawTo public override ToolDefinition Definition { get; } = new( Name: ToolName, Description: "Fetch a web page and return structured text content.", - ApprovalScope: ApprovalScope.ToolExecution, + ApprovalScope: ApprovalScope.NetworkAccess, IsDestructive: false, RequiresApproval: false, InputTypeName: nameof(WebFetchToolArguments), diff --git a/src/SharpClaw.Code.Tools/Registry/ToolRegistry.cs b/src/SharpClaw.Code.Tools/Registry/ToolRegistry.cs index 597a19d..e2e2ce3 100644 --- a/src/SharpClaw.Code.Tools/Registry/ToolRegistry.cs +++ b/src/SharpClaw.Code.Tools/Registry/ToolRegistry.cs @@ -73,6 +73,7 @@ public async Task GetRequiredAsync( CancellationToken cancellationToken = default) { ArgumentException.ThrowIfNullOrWhiteSpace(toolName); + if (tools.TryGetValue(toolName, out var builtIn)) return builtIn; var allTools = await GetAllToolsAsync(workspaceRootForPluginTools, cancellationToken).ConfigureAwait(false); return allTools.TryGetValue(toolName, out var tool) ? tool diff --git a/src/SharpClaw.Code.Tools/Utilities/GlobPatternMatcher.cs b/src/SharpClaw.Code.Tools/Utilities/GlobPatternMatcher.cs index fcc90cf..c185769 100644 --- a/src/SharpClaw.Code.Tools/Utilities/GlobPatternMatcher.cs +++ b/src/SharpClaw.Code.Tools/Utilities/GlobPatternMatcher.cs @@ -4,6 +4,8 @@ namespace SharpClaw.Code.Tools.Utilities; internal static partial class GlobPatternMatcher { + private static readonly System.Collections.Concurrent.ConcurrentDictionary Patterns = new(StringComparer.Ordinal); + public static bool IsMatch(string pattern, string relativePath) { ArgumentException.ThrowIfNullOrWhiteSpace(pattern); @@ -11,7 +13,8 @@ public static bool IsMatch(string pattern, string relativePath) var normalizedPattern = NormalizePattern(pattern); var normalizedPath = relativePath.Replace('\\', '/'); - return CreateRegex(normalizedPattern).IsMatch(normalizedPath); + if (Patterns.Count > 128) Patterns.Clear(); + return Patterns.GetOrAdd(normalizedPattern, CreateRegex).IsMatch(normalizedPath); } private static string NormalizePattern(string pattern) @@ -33,6 +36,6 @@ private static Regex CreateRegex(string pattern) .Replace(@"\*", @"[^/]*") .Replace(@"\?", @"[^/]"); - return new Regex($"^{regexPattern}$", RegexOptions.Compiled | RegexOptions.CultureInvariant); + return new Regex($"^{regexPattern}$", RegexOptions.Compiled | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(250)); } } diff --git a/src/SharpClaw.Code.Tools/Utilities/WorkspaceSearchFiles.cs b/src/SharpClaw.Code.Tools/Utilities/WorkspaceSearchFiles.cs new file mode 100644 index 0000000..2245357 --- /dev/null +++ b/src/SharpClaw.Code.Tools/Utilities/WorkspaceSearchFiles.cs @@ -0,0 +1,22 @@ +namespace SharpClaw.Code.Tools.Utilities; + +/// Enumerates source files without following links or descending into generated dependency trees. +internal static class WorkspaceSearchFiles +{ + private static readonly HashSet IgnoredDirectories = new(StringComparer.OrdinalIgnoreCase) + { ".git", ".sharpclaw", "node_modules", "bin", "obj", ".vs", ".idea", "dist", "coverage", ".venv" }; + + internal static IEnumerable Enumerate(string root) + { + var pending = new Stack(); + pending.Push(root); + while (pending.TryPop(out var directory)) + { + foreach (var child in Directory.EnumerateDirectories(directory)) + if (!IgnoredDirectories.Contains(Path.GetFileName(child)) && (File.GetAttributes(child) & FileAttributes.ReparsePoint) == 0) + pending.Push(child); + foreach (var file in Directory.EnumerateFiles(directory)) + if ((File.GetAttributes(file) & FileAttributes.ReparsePoint) == 0) yield return file; + } + } +} diff --git a/src/SharpClaw.Code.Web/Services/PublicNetwork.cs b/src/SharpClaw.Code.Web/Services/PublicNetwork.cs new file mode 100644 index 0000000..02c9444 --- /dev/null +++ b/src/SharpClaw.Code.Web/Services/PublicNetwork.cs @@ -0,0 +1,51 @@ +using System.Net; +using System.Net.Sockets; + +namespace SharpClaw.Code.Web.Services; + +/// Restricts web fetch connections to public HTTP destinations, including after DNS resolution. +internal static class PublicNetwork +{ + internal static void ValidateUri(Uri uri) + { + if (uri.Scheme is not ("http" or "https") || uri.UserInfo.Length > 0 + || uri.IsLoopback || uri.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase) + || (IPAddress.TryParse(uri.DnsSafeHost, out var address) && !IsPublic(address))) + throw new HttpRequestException("Web fetch requires a public HTTP(S) destination."); + } + + internal static bool IsPublic(IPAddress address) + { + if (address.IsIPv4MappedToIPv6) address = address.MapToIPv4(); + if (IPAddress.IsLoopback(address)) return false; + var bytes = address.GetAddressBytes(); + if (address.AddressFamily == AddressFamily.InterNetworkV6) + return (bytes[0] & 0xe0) == 0x20 && !(bytes[0] == 0x20 && bytes[1] == 0x01 && bytes[2] == 0x0d && bytes[3] == 0xb8); + return bytes[0] is not (0 or 10 or 127) && bytes[0] < 224 + && !(bytes[0] == 169 && bytes[1] == 254) + && !(bytes[0] == 172 && bytes[1] is >= 16 and <= 31) + && !(bytes[0] == 192 && (bytes[1] == 168 || bytes[1] == 0)) + && !(bytes[0] == 100 && bytes[1] is >= 64 and <= 127) + && !(bytes[0] == 198 && bytes[1] is 18 or 19); + } + + internal static SocketsHttpHandler CreateHandler() => new() + { + AllowAutoRedirect = false, + UseProxy = false, + ConnectCallback = async (context, cancellationToken) => + { + var addresses = await Dns.GetHostAddressesAsync(context.DnsEndPoint.Host, cancellationToken).ConfigureAwait(false); + if (addresses.Length == 0 || addresses.Any(address => !IsPublic(address))) + throw new HttpRequestException("Web fetch cannot connect to private or reserved addresses."); + // Connect to the validated address itself so DNS rebinding cannot change the destination. + var socket = new Socket(SocketType.Stream, ProtocolType.Tcp); + try + { + await socket.ConnectAsync(addresses, context.DnsEndPoint.Port, cancellationToken).ConfigureAwait(false); + return new NetworkStream(socket, ownsSocket: true); + } + catch { socket.Dispose(); throw; } + }, + }; +} diff --git a/src/SharpClaw.Code.Web/Services/WebFetchService.cs b/src/SharpClaw.Code.Web/Services/WebFetchService.cs index 037a1d9..5747115 100644 --- a/src/SharpClaw.Code.Web/Services/WebFetchService.cs +++ b/src/SharpClaw.Code.Web/Services/WebFetchService.cs @@ -18,7 +18,7 @@ public async Task FetchAsync(string url, CancellationToken can { ArgumentException.ThrowIfNullOrWhiteSpace(url); - using var response = await ResilientHttpGet.GetAsync(httpClient, url, cancellationToken).ConfigureAwait(false); + using var response = await FetchPublicAsync(new Uri(url, UriKind.Absolute), cancellationToken).ConfigureAwait(false); var contentType = response.Content.Headers.ContentType?.MediaType; var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); @@ -53,6 +53,21 @@ public async Task FetchAsync(string url, CancellationToken can /// Uses declared media type when present; otherwise sniffs common markup so plain-text responses /// that are actually HTML still parse correctly (typical for minimal in tests/tools). /// + private async Task FetchPublicAsync(Uri uri, CancellationToken cancellationToken) + { + for (var redirects = 0; redirects <= 5; redirects++) + { + PublicNetwork.ValidateUri(uri); + var response = await ResilientHttpGet.GetAsync(httpClient, uri.AbsoluteUri, cancellationToken).ConfigureAwait(false); + if ((int)response.StatusCode is not (301 or 302 or 303 or 307 or 308)) return response; + var location = response.Headers.Location; + response.Dispose(); + if (location is null) throw new HttpRequestException("Redirect has no destination."); + uri = new Uri(uri, location); + } + throw new HttpRequestException("Too many redirects."); + } + private static bool ShouldTreatBodyAsHtml(string? mediaType, string body) { if (LooksLikeHtmlMediaType(mediaType)) diff --git a/src/SharpClaw.Code.Web/WebServiceCollectionExtensions.cs b/src/SharpClaw.Code.Web/WebServiceCollectionExtensions.cs index 3a204be..523c0c2 100644 --- a/src/SharpClaw.Code.Web/WebServiceCollectionExtensions.cs +++ b/src/SharpClaw.Code.Web/WebServiceCollectionExtensions.cs @@ -45,6 +45,7 @@ private static IServiceCollection AddSharpClawWebCore(IServiceCollection service services.AddHttpClient() .ConfigureHttpClient(client => client.Timeout = TimeSpan.FromSeconds(60)); services.AddHttpClient() + .ConfigurePrimaryHttpMessageHandler(PublicNetwork.CreateHandler) .ConfigureHttpClient(client => client.Timeout = TimeSpan.FromSeconds(60)); return services; } diff --git a/tests/SharpClaw.Code.IntegrationTests/Memory/CSharpRenameTests.cs b/tests/SharpClaw.Code.IntegrationTests/Memory/CSharpRenameTests.cs index 193a8ae..1e948b2 100644 --- a/tests/SharpClaw.Code.IntegrationTests/Memory/CSharpRenameTests.cs +++ b/tests/SharpClaw.Code.IntegrationTests/Memory/CSharpRenameTests.cs @@ -68,7 +68,7 @@ public async Task Permissions_and_conflicts_write_nothing_on_denial() var conflict = await tools.ExecuteAsync("csharp_rename_symbol", Arguments("IInvoiceService", "InvoiceService"), context, CancellationToken.None); conflict.Result.Succeeded.Should().BeFalse(); File.ReadAllText(Path.Combine(fixture.Root, "Library/Invoice.cs")).Should().Contain("interface IInvoiceService"); - var success = await tools.ExecuteAsync("csharp_rename_symbol", Arguments("IInvoiceService", "IBillingService"), context with { PermissionMode = PermissionMode.WorkspaceWrite }, CancellationToken.None); + var success = await tools.ExecuteAsync("csharp_rename_symbol", Arguments("IInvoiceService", "IBillingService"), context with { PermissionMode = PermissionMode.WorkspaceWrite, ApprovalSettings = new ApprovalSettings([ApprovalScope.FileSystemWrite], null) }, CancellationToken.None); success.Result.Succeeded.Should().BeTrue(success.Result.ErrorMessage); } diff --git a/tests/SharpClaw.Code.IntegrationTests/Runtime/ApprovalAuthIntegrationTests.cs b/tests/SharpClaw.Code.IntegrationTests/Runtime/ApprovalAuthIntegrationTests.cs index f99aaf3..84233e9 100644 --- a/tests/SharpClaw.Code.IntegrationTests/Runtime/ApprovalAuthIntegrationTests.cs +++ b/tests/SharpClaw.Code.IntegrationTests/Runtime/ApprovalAuthIntegrationTests.cs @@ -31,6 +31,7 @@ public sealed class ApprovalAuthIntegrationTests public async Task Embedded_http_server_should_enforce_oidc_admin_and_prompt_approval_auth() { await using var authority = new TestOidcAuthority(); + Environment.SetEnvironmentVariable("SHARPCLAW_SERVER_TOKEN", "integration-test-server-token-32-characters"); var workspaceRoot = CreateTemporaryWorkspace(); var outsideFile = Path.Combine(Path.GetTempPath(), "sharpclaw-approval-auth-targets", Guid.NewGuid().ToString("N"), "secret.txt"); Directory.CreateDirectory(Path.GetDirectoryName(outsideFile)!); @@ -54,6 +55,8 @@ await File.WriteAllTextAsync( var services = new ServiceCollection(); services.AddSharpClawRuntime(); + // This embedded host explicitly supplies its OIDC configuration; workspace files cannot do so. + services.AddSingleton(new HostConfig(workspaceRoot)); services.AddDeterministicMockModelProvider(); using var serviceProvider = services.BuildServiceProvider(); @@ -69,6 +72,8 @@ await File.WriteAllTextAsync( Timeout = TimeSpan.FromSeconds(10), }; + httpClient.DefaultRequestHeaders.Add("X-SharpClaw-Server-Token", "integration-test-server-token-32-characters"); + using var unauthenticatedAdminResponse = await httpClient.GetAsync("v1/admin/providers", CancellationToken.None); unauthenticatedAdminResponse.StatusCode.Should().Be(HttpStatusCode.Unauthorized); @@ -88,7 +93,7 @@ await File.WriteAllTextAsync( approvedPromptResponse.EnsureSuccessStatusCode(); using var wrongTenantPromptRequest = BuildPromptRequest(outsideFile, tenantId: "tenant-b"); - wrongTenantPromptRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authority.CreateToken("alice", "tenant-a")); + wrongTenantPromptRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authority.CreateToken("alice", "tenant-b")); using var wrongTenantPromptResponse = await httpClient.SendAsync(wrongTenantPromptRequest, CancellationToken.None); wrongTenantPromptResponse.StatusCode.Should().Be(HttpStatusCode.InternalServerError); (await ReadErrorAsync(wrongTenantPromptResponse)).Should().Contain("does not match runtime tenant"); @@ -100,6 +105,15 @@ await File.WriteAllTextAsync( } } + private sealed class HostConfig(string workspaceRoot) : ISharpClawConfigService + { + public async Task GetConfigAsync(string workspace, CancellationToken cancellationToken) + { + var json = await File.ReadAllTextAsync(Path.Combine(workspaceRoot, "sharpclaw.jsonc"), cancellationToken); + return new SharpClawConfigSnapshot(workspace, null, null, JsonSerializer.Deserialize(json, ProtocolJsonContext.Default.SharpClawConfigDocument)!); + } + } + private static HttpRequestMessage BuildPromptRequest(string outsideFile, string tenantId) { var payload = new ServerPromptRequest( @@ -184,7 +198,7 @@ private static async Task WaitForServerAsync(HttpClient httpClient, Task serverT WorkingDirectory: workspaceRoot, Model: "default", PermissionMode: PermissionMode.WorkspaceWrite, - OutputFormat: OutputFormat.Json), + OutputFormat: OutputFormat.Json, HostContext: new RuntimeHostContext("test-host", "tenant-a")), cancellationToken); try @@ -194,6 +208,7 @@ private static async Task WaitForServerAsync(HttpClient httpClient, Task serverT BaseAddress = new Uri($"http://127.0.0.1:{port}/"), Timeout = TimeSpan.FromMilliseconds(500), }; + httpClient.DefaultRequestHeaders.Add("X-SharpClaw-Server-Token", "integration-test-server-token-32-characters"); await WaitForServerAsync(httpClient, serverTask, TimeSpan.FromSeconds(10), cancellationToken).ConfigureAwait(false); return (port, serverTask); } diff --git a/tests/SharpClaw.Code.IntegrationTests/Runtime/InteractiveMilestoneTests.cs b/tests/SharpClaw.Code.IntegrationTests/Runtime/InteractiveMilestoneTests.cs index f945a41..865a76d 100644 --- a/tests/SharpClaw.Code.IntegrationTests/Runtime/InteractiveMilestoneTests.cs +++ b/tests/SharpClaw.Code.IntegrationTests/Runtime/InteractiveMilestoneTests.cs @@ -42,7 +42,7 @@ public async Task Snapshot_edit_survives_restart_and_uses_existing_undo_redo(boo var provider = new ScenarioProvider { SnapshotEdit = true, PreviewFirst = previewFirst }; using (var services = Services(provider)) { - var result = await services.GetRequiredService().RunPromptAsync(Request("Edit the file.") with { PermissionMode = PermissionMode.WorkspaceWrite }, CancellationToken.None); + var result = await services.GetRequiredService().RunPromptAsync(Request("Edit the file.") with { PermissionMode = PermissionMode.WorkspaceWrite, ApprovalSettings = new ApprovalSettings([ApprovalScope.FileSystemWrite], null) }, CancellationToken.None); result.ToolResults.Should().Contain(item => item.ToolName == "edit_file_snapshot" && item.Succeeded); if (previewFirst) { diff --git a/tests/SharpClaw.Code.IntegrationTests/Runtime/WorkspaceHttpServerAdminTests.cs b/tests/SharpClaw.Code.IntegrationTests/Runtime/WorkspaceHttpServerAdminTests.cs index cc20030..823880a 100644 --- a/tests/SharpClaw.Code.IntegrationTests/Runtime/WorkspaceHttpServerAdminTests.cs +++ b/tests/SharpClaw.Code.IntegrationTests/Runtime/WorkspaceHttpServerAdminTests.cs @@ -25,6 +25,7 @@ public sealed class WorkspaceHttpServerAdminTests [Fact] public async Task Admin_endpoints_should_expose_provider_session_usage_package_and_event_data() { + Environment.SetEnvironmentVariable("SHARPCLAW_SERVER_TOKEN", "integration-test-server-token-32-characters"); var workspaceRoot = CreateTemporaryWorkspace(); await File.WriteAllTextAsync(Path.Combine(workspaceRoot, "README.md"), "Workspace admin search content."); @@ -54,8 +55,22 @@ public async Task Admin_endpoints_should_expose_provider_session_usage_package_a BaseAddress = new Uri($"http://127.0.0.1:{port}/"), Timeout = TimeSpan.FromSeconds(10), }; + httpClient.DefaultRequestHeaders.Add("X-SharpClaw-Server-Token", "integration-test-server-token-32-characters"); await WaitForServerAsync(httpClient, CancellationToken.None); + using (var unauthenticated = new HttpClient { BaseAddress = httpClient.BaseAddress }) + (await unauthenticated.GetAsync("v1/status")).StatusCode.Should().Be(System.Net.HttpStatusCode.Unauthorized); + using (var browserRequest = new HttpRequestMessage(HttpMethod.Get, "v1/status")) + { + browserRequest.Headers.Add("Origin", "https://attacker.example"); + (await httpClient.SendAsync(browserRequest)).StatusCode.Should().Be(System.Net.HttpStatusCode.Unauthorized); + } + using (var rebound = new HttpRequestMessage(HttpMethod.Get, "v1/status")) + { + rebound.Headers.Host = "attacker.example"; + ((int)(await httpClient.SendAsync(rebound)).StatusCode).Should().BeGreaterThanOrEqualTo(400); + } + var providersJson = await httpClient.GetStringAsync("v1/admin/providers"); providersJson.Should().Contain("mock"); @@ -66,13 +81,14 @@ await httpClient.GetStringAsync("v1/admin/auth/status"), using var createSessionResponse = await httpClient.PostAsync( "v1/admin/sessions", - new StringContent("""{"permissionMode":"workspaceWrite","outputFormat":"json"}""", Encoding.UTF8, "application/json"), + new StringContent("""{"permissionMode":"dangerFullAccess","outputFormat":"json"}""", Encoding.UTF8, "application/json"), CancellationToken.None); createSessionResponse.EnsureSuccessStatusCode(); var createdSession = JsonSerializer.Deserialize( await createSessionResponse.Content.ReadAsStringAsync(), ProtocolJsonContext.Default.ConversationSession); createdSession.Should().NotBeNull(); + createdSession!.PermissionMode.Should().Be(PermissionMode.WorkspaceWrite); using var forkSessionResponse = await httpClient.PostAsync( $"v1/admin/sessions/{createdSession!.Id}/fork", diff --git a/tests/SharpClaw.Code.IntegrationTests/Verification/AutomaticVerificationTests.cs b/tests/SharpClaw.Code.IntegrationTests/Verification/AutomaticVerificationTests.cs index 978bde8..ad94a34 100644 --- a/tests/SharpClaw.Code.IntegrationTests/Verification/AutomaticVerificationTests.cs +++ b/tests/SharpClaw.Code.IntegrationTests/Verification/AutomaticVerificationTests.cs @@ -71,7 +71,7 @@ public async Task Successful_repair_disabled_path_and_permission_denial_are_dist var disabled = Request(fixture.Root, 2) with { Metadata = new() { [SharpClawWorkflowMetadataKeys.VerificationEnabled] = "false" } }; (await runtime.RunPromptAsync(disabled, CancellationToken.None)).Verification.Should().BeNull(); verification.Calls.Should().Be(2); - var denied = await runtime.RunPromptAsync(Request(fixture.Root, 2) with { PermissionMode = PermissionMode.WorkspaceWrite }, CancellationToken.None); + var denied = await runtime.RunPromptAsync(Request(fixture.Root, 2) with { PermissionMode = PermissionMode.WorkspaceWrite, ApprovalSettings = new ApprovalSettings([ApprovalScope.FileSystemWrite], null) }, CancellationToken.None); denied.Verification!.Reason.Should().Be(VerificationFailureReason.PermissionDenied); agent.Calls.Should().Be(4); verification.Calls.Should().Be(2); @@ -188,7 +188,7 @@ public async Task RunAsync(AgentRunContext context, Cancellation { Calls++; Contexts.Add(context); - var toolContext = new ToolExecutionContext(context.SessionId, context.TurnId, context.WorkingDirectory, context.WorkingDirectory, context.PermissionMode, context.OutputFormat, null, IsInteractive: context.IsInteractive, MutationRecorder: context.ToolMutationRecorder); + var toolContext = new ToolExecutionContext(context.SessionId, context.TurnId, context.WorkingDirectory, context.WorkingDirectory, context.PermissionMode, context.OutputFormat, null, IsInteractive: context.IsInteractive, MutationRecorder: context.ToolMutationRecorder, ApprovalSettings: context.ApprovalSettings); var result = await context.ToolExecutor.ExecuteAsync("write_file", JsonSerializer.Serialize(new { path = "Source.cs", content = "state" + Calls }), toolContext, cancellationToken); result.Result.Succeeded.Should().BeTrue(result.Result.ErrorMessage); AfterWrite?.Invoke(); diff --git a/tests/SharpClaw.Code.ParityHarness/ParityScenarioTests.cs b/tests/SharpClaw.Code.ParityHarness/ParityScenarioTests.cs index 3c9a7fc..0ee88a6 100644 --- a/tests/SharpClaw.Code.ParityHarness/ParityScenarioTests.cs +++ b/tests/SharpClaw.Code.ParityHarness/ParityScenarioTests.cs @@ -140,7 +140,8 @@ public async Task Read_file_roundtrip_returns_workspace_content() [Fact] public async Task Write_file_allowed_under_workspace_write_mode() { - var tools = ParityTestHost.GetToolExecutor(_provider); + using var approvedProvider = ParityTestHost.Create(replaceApprovals: true); + var tools = ParityTestHost.GetToolExecutor(approvedProvider); var json = JsonSerializer.Serialize(new { path = "out.txt", content = "wrote" }); var envelope = await tools.ExecuteAsync( WriteFileTool.ToolName, @@ -245,7 +246,8 @@ public async Task Permission_prompt_denied_blocks_shell_in_workspace_write() [Fact] public async Task Plugin_tool_roundtrip_executes_fixture_plugin_echo() { - var tools = ParityTestHost.GetToolExecutor(_provider); + using var approvedProvider = ParityTestHost.Create(replaceApprovals: true); + var tools = ParityTestHost.GetToolExecutor(approvedProvider); var json = JsonSerializer.Serialize(new { message = "parity-plugin" }); var envelope = await tools.ExecuteAsync( ParityFixturePluginTool.ToolName, diff --git a/tests/SharpClaw.Code.UnitTests/Commands/FeatureCommandHandlersTests.cs b/tests/SharpClaw.Code.UnitTests/Commands/FeatureCommandHandlersTests.cs index 63c66fb..d567fe1 100644 --- a/tests/SharpClaw.Code.UnitTests/Commands/FeatureCommandHandlersTests.cs +++ b/tests/SharpClaw.Code.UnitTests/Commands/FeatureCommandHandlersTests.cs @@ -149,7 +149,7 @@ public async Task Tool_packages_list_command_should_render_installed_package_pay var toolPackages = new StubToolPackageService(); var globalOptions = new GlobalCliOptions(); var handler = new ToolPackagesCommandHandler(toolPackages, new OutputRendererDispatcher([renderer])); - var exitCode = await InvokeCommandAsync(handler.BuildCommand(globalOptions), globalOptions, "tool-packages list --cwd /workspace --output-format json"); + var exitCode = await InvokeCommandAsync(handler.BuildCommand(globalOptions), globalOptions, "tool-packages list --cwd . --output-format json"); exitCode.Should().Be(0); var payload = JsonSerializer.Deserialize(renderer.LastResult!.DataJson!, ProtocolJsonContext.Default.ListInstalledToolPackage); @@ -180,7 +180,7 @@ await File.WriteAllTextAsync( var exitCode = await InvokeCommandAsync( handler.BuildCommand(globalOptions), globalOptions, - $"tool-packages install --manifest \"{manifestPath}\" --install-source cli --disable --cwd /workspace --output-format json"); + $"tool-packages install --manifest \"{manifestPath}\" --install-source cli --disable --cwd . --output-format json"); exitCode.Should().Be(0); toolPackages.LastInstallRequest.Should().NotBeNull(); diff --git a/tests/SharpClaw.Code.UnitTests/Commands/ModeAndCliOptionsTests.cs b/tests/SharpClaw.Code.UnitTests/Commands/ModeAndCliOptionsTests.cs index 77bc891..318b7a5 100644 --- a/tests/SharpClaw.Code.UnitTests/Commands/ModeAndCliOptionsTests.cs +++ b/tests/SharpClaw.Code.UnitTests/Commands/ModeAndCliOptionsTests.cs @@ -15,6 +15,26 @@ namespace SharpClaw.Code.UnitTests.Commands; /// public sealed class ModeAndCliOptionsTests { + [Theory] + [InlineData("--permission-mode bogus")] + [InlineData("--primary-mode plna")] + public void Invalid_modes_are_rejected(string arguments) + { + var options = new GlobalCliOptions(); + var command = new RootCommand(); + foreach (var option in options.All) command.Options.Add(option); + FluentActions.Invoking(() => options.Resolve(command.Parse(arguments))).Should().Throw(); + } + + [Fact] + public void Unspecified_primary_mode_is_left_to_agent_or_session_defaults() + { + var options = new GlobalCliOptions(); + var command = new RootCommand(); + foreach (var option in options.All) command.Options.Add(option); + options.Resolve(command.Parse("")).ToRuntimeCommandContext().PrimaryMode.Should().BeNull(); + } + [Fact] public void Global_cli_options_should_parse_spec_primary_mode() { diff --git a/tests/SharpClaw.Code.UnitTests/McpPlugins/McpAndPluginLifecycleTests.cs b/tests/SharpClaw.Code.UnitTests/McpPlugins/McpAndPluginLifecycleTests.cs index 8f6b471..85228d1 100644 --- a/tests/SharpClaw.Code.UnitTests/McpPlugins/McpAndPluginLifecycleTests.cs +++ b/tests/SharpClaw.Code.UnitTests/McpPlugins/McpAndPluginLifecycleTests.cs @@ -218,7 +218,7 @@ public async Task Plugin_manager_update_should_reset_enabled_state_to_discovered /// Ensures conflicting tool names across enabled plugins are rejected at descriptor list time. /// [Fact] - public async Task Plugin_manager_should_reject_duplicate_tool_names_across_enabled_plugins() + public async Task Plugin_manager_should_quarantine_duplicate_tool_names_across_enabled_plugins() { var workspacePath = CreateTemporaryWorkspace(); var manager = CreatePluginManager(); @@ -242,10 +242,8 @@ await manager.InstallAsync( await manager.EnableAsync(workspacePath, "p.one", CancellationToken.None); await manager.EnableAsync(workspacePath, "p.two", CancellationToken.None); - var act = async () => await manager.ListToolDescriptorsAsync(workspacePath, CancellationToken.None); - - await act.Should().ThrowAsync() - .Where(exception => exception.Message.Contains("shared_tool", StringComparison.Ordinal)); + var tools = await manager.ListToolDescriptorsAsync(workspacePath, CancellationToken.None); + tools.Should().NotContain(tool => tool.Name == "shared_tool"); } private static string CreateTemporaryWorkspace() diff --git a/tests/SharpClaw.Code.UnitTests/MemorySkillsGit/WorkspaceKnowledgeServicesTests.cs b/tests/SharpClaw.Code.UnitTests/MemorySkillsGit/WorkspaceKnowledgeServicesTests.cs index 1304d06..ff10821 100644 --- a/tests/SharpClaw.Code.UnitTests/MemorySkillsGit/WorkspaceKnowledgeServicesTests.cs +++ b/tests/SharpClaw.Code.UnitTests/MemorySkillsGit/WorkspaceKnowledgeServicesTests.cs @@ -99,6 +99,21 @@ await memoryStore.SaveAsync( recalled.Should().Contain(entry => entry.Id == "user-memory-1"); } + [Theory] + [InlineData("NOT")] + [InlineData("OR")] + [InlineData("AND")] + [InlineData("this AND that OR NOT")] + public async Task Fts_operators_in_user_text_are_literal_search_terms(string query) + { + Directory.CreateDirectory(workspaceRoot); + await File.WriteAllTextAsync(Path.Combine(workspaceRoot, "README.md"), "NOT OR AND this that"); + var store = CreateStore(); + await new WorkspaceIndexService(fileSystem, pathService, store).RefreshAsync(workspaceRoot, CancellationToken.None); + var result = await new WorkspaceSearchService(store).SearchAsync(workspaceRoot, new WorkspaceSearchRequest(query, 10), CancellationToken.None); + result.Hits.Should().NotBeEmpty(); + } + public void Dispose() { TestDirectoryCleanup.DeleteIfExists(workspaceRoot, clearSqlitePools: true); diff --git a/tests/SharpClaw.Code.UnitTests/Permissions/PermissionPolicyEngineTests.cs b/tests/SharpClaw.Code.UnitTests/Permissions/PermissionPolicyEngineTests.cs index a6e59ae..12d8844 100644 --- a/tests/SharpClaw.Code.UnitTests/Permissions/PermissionPolicyEngineTests.cs +++ b/tests/SharpClaw.Code.UnitTests/Permissions/PermissionPolicyEngineTests.cs @@ -112,7 +112,7 @@ public async Task EvaluateAsync_should_not_reuse_remembered_approval_across_dist firstFromA.IsAllowed.Should().BeTrue(); secondFromA.IsAllowed.Should().BeTrue(); firstFromB.IsAllowed.Should().BeTrue(); - approvalService.RequestCount.Should().Be(2); + approvalService.RequestCount.Should().Be(3); } /// @@ -172,7 +172,7 @@ public async Task EvaluateAsync_should_deny_untrusted_plugin_surfaced_tool_when_ [Theory] [InlineData(PluginTrustLevel.WorkspaceTrusted)] [InlineData(PluginTrustLevel.DeveloperTrusted)] - public async Task EvaluateAsync_should_allow_manifest_trusted_plugin_surfaced_tool_without_approval(PluginTrustLevel manifestTrust) + public async Task EvaluateAsync_should_deny_self_trusted_plugin_without_approval(PluginTrustLevel manifestTrust) { var engine = CreateEngine(new NonInteractiveApprovalService()); var context = CreateContext( @@ -190,14 +190,14 @@ public async Task EvaluateAsync_should_allow_manifest_trusted_plugin_surfaced_to var decision = await engine.EvaluateAsync(request, context, CancellationToken.None); - decision.IsAllowed.Should().BeTrue(); + decision.IsAllowed.Should().BeFalse(); } /// /// Ensures an untrusted manifest tier is waived when the originating plugin id is session-trusted. /// [Fact] - public async Task EvaluateAsync_should_allow_untrusted_manifest_plugin_tool_when_plugin_is_session_trusted() + public async Task EvaluateAsync_should_deny_workspace_session_trust_without_process_approval() { var engine = CreateEngine(new NonInteractiveApprovalService()); var context = CreateContext( @@ -215,7 +215,7 @@ public async Task EvaluateAsync_should_allow_untrusted_manifest_plugin_tool_when var decision = await engine.EvaluateAsync(request, context, CancellationToken.None); - decision.IsAllowed.Should().BeTrue(); + decision.IsAllowed.Should().BeFalse(); } /// @@ -332,6 +332,44 @@ public async Task EvaluateAsync_should_fall_back_to_prompt_when_auto_approve_bud approvalService.RequestCount.Should().Be(1); } + [Theory] + [InlineData("sudo ls")] + [InlineData("rm -fr /")] + [InlineData("find / -delete")] + public async Task Read_only_mode_cannot_be_overridden_by_approval_or_auto_approval(string command) + { + var approvals = new StubApprovalService(); + var engine = CreateEngine(approvals); + var request = CreateRequest("bash", System.Text.Json.JsonSerializer.Serialize(new { command }), ApprovalScope.ShellExecution, true, true); + var context = CreateContext(PermissionMode.ReadOnly, approvalSettings: new ApprovalSettings([ApprovalScope.ShellExecution], null)); + (await engine.EvaluateAsync(request, context, CancellationToken.None)).IsAllowed.Should().BeFalse(); + approvals.RequestCount.Should().Be(0); + } + + [Fact] + public async Task Explicit_approval_includes_arguments_and_is_not_reused_for_different_arguments() + { + var approvals = new StubApprovalService(); + var engine = CreateEngine(approvals); + var context = CreateContext(PermissionMode.WorkspaceWrite); + var request = CreateRequest("custom", "{\"path\":\"first.txt\"}", ApprovalScope.ToolExecution, true, false); + (await engine.EvaluateAsync(request, context, CancellationToken.None)).IsAllowed.Should().BeTrue(); + (await engine.EvaluateAsync(request with { ArgumentsJson = "{\"path\":\"second.txt\"}" }, context, CancellationToken.None)).IsAllowed.Should().BeTrue(); + approvals.RequestCount.Should().Be(2); + approvals.LastRequest!.Prompt.Should().Contain("second.txt").And.Contain("/workspace"); + } + + [Fact] + public async Task Dangerous_commands_cannot_use_auto_approval() + { + var approvals = new StubApprovalService(); + var engine = CreateEngine(approvals); + var request = CreateRequest("bash", "{\"command\":\"sudo ls\"}", ApprovalScope.ShellExecution, true, true); + var context = CreateContext(PermissionMode.WorkspaceWrite, approvalSettings: new ApprovalSettings([ApprovalScope.ShellExecution], null)); + (await engine.EvaluateAsync(request, context, CancellationToken.None)).IsAllowed.Should().BeTrue(); + approvals.RequestCount.Should().Be(1); + } + private static IPermissionPolicyEngine CreateEngine(IApprovalService approvalService) => new PermissionPolicyEngine( [ @@ -396,6 +434,7 @@ private static ToolExecutionRequest CreateRequest( private sealed class StubApprovalService : IApprovalService { public int RequestCount { get; private set; } + public ApprovalRequest? LastRequest { get; private set; } public Task RequestApprovalAsync( ApprovalRequest request, @@ -403,6 +442,7 @@ public Task RequestApprovalAsync( CancellationToken cancellationToken) { RequestCount++; + LastRequest = request; return Task.FromResult(new ApprovalDecision( Scope: request.Scope, Approved: true, diff --git a/tests/SharpClaw.Code.UnitTests/Providers/ProviderStreamAdapterTests.cs b/tests/SharpClaw.Code.UnitTests/Providers/ProviderStreamAdapterTests.cs index 8908053..d350301 100644 --- a/tests/SharpClaw.Code.UnitTests/Providers/ProviderStreamAdapterTests.cs +++ b/tests/SharpClaw.Code.UnitTests/Providers/ProviderStreamAdapterTests.cs @@ -15,6 +15,44 @@ namespace SharpClaw.Code.UnitTests.Providers; /// public sealed class ProviderStreamAdapterTests { + [Fact] + public async Task OpenAi_drains_tool_calls_and_usage_after_finish_reason() + { + async IAsyncEnumerable Stream() + { + yield return new ChatResponseUpdate(ChatRole.Assistant, []) { FinishReason = ChatFinishReason.ToolCalls }; + yield return new ChatResponseUpdate(ChatRole.Assistant, [new FunctionCallContent("call-1", "read_file", new Dictionary { ["path"] = "file.cs" })]); + yield return new ChatResponseUpdate(ChatRole.Assistant, [new UsageContent(new UsageDetails { InputTokenCount = 10, OutputTokenCount = 2 })]); + } + var events = new List(); + await foreach (var item in OpenAiMeaiStreamAdapter.AdaptAsync(Stream(), "req", new FixedSystemClock(), CancellationToken.None)) events.Add(item); + events.Should().ContainSingle(item => item.ToolName == "read_file"); + events[^1].Usage!.TotalTokens.Should().Be(12); + events[^1].Kind.Should().Be("completed"); + } + + [Fact] + public async Task Anthropic_preserves_usage_and_rejects_truncated_tool_calls() + { + async IAsyncEnumerable Stream(string reason) + { + yield return JsonSerializer.Deserialize("""{"type":"message_start","message":{"id":"msg","type":"message","role":"assistant","model":"test","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":0,"cache_read_input_tokens":5,"cache_creation_input_tokens":2}}}""")!; + yield return JsonSerializer.Deserialize("""{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"call","name":"bash","input":{}}}""")!; + yield return JsonSerializer.Deserialize("""{"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{}"}}""")!; + yield return JsonSerializer.Deserialize("""{"type":"content_block_stop","index":0}""")!; + yield return JsonSerializer.Deserialize("""{"type":"message_delta","delta":{"stop_reason":"STOP","stop_sequence":null},"usage":{"output_tokens":3}}""".Replace("STOP", reason))!; + yield return new RawMessageStreamEvent(new RawMessageStopEvent(), default); + } + var complete = new List(); + await foreach (var item in AnthropicSdkStreamAdapter.AdaptAsync(Stream("tool_use"), "req", new FixedSystemClock(), CancellationToken.None)) complete.Add(item); + complete[^1].Usage!.InputTokens.Should().Be(17); + complete[^1].Usage!.TotalTokens.Should().Be(20); + var truncated = new List(); + await foreach (var item in AnthropicSdkStreamAdapter.AdaptAsync(Stream("max_tokens"), "req", new FixedSystemClock(), CancellationToken.None)) truncated.Add(item); + truncated.Should().ContainSingle(item => item.Kind == "failed"); + truncated.Should().NotContain(item => item.ToolName != null); + } + [Fact] public async Task OpenAi_meai_adapter_emits_text_deltas_then_completed() { @@ -170,6 +208,7 @@ async IAsyncEnumerable Stream() }, default); + yield return System.Text.Json.JsonSerializer.Deserialize("""{"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":2}}""")!; yield return new RawMessageStreamEvent(new RawMessageStopEvent(), default); } @@ -196,6 +235,7 @@ async IAsyncEnumerable Stream() await Task.Yield(); throw new JsonException("Malformed Anthropic SSE data payload."); #pragma warning disable CS0162 + yield return System.Text.Json.JsonSerializer.Deserialize("""{"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":2}}""")!; yield return new RawMessageStreamEvent(new RawMessageStopEvent(), default); #pragma warning restore CS0162 } @@ -224,6 +264,7 @@ async IAsyncEnumerable Stream() await Task.Yield(); throw new IOException("socket closed while reading Anthropic SSE data."); #pragma warning disable CS0162 + yield return System.Text.Json.JsonSerializer.Deserialize("""{"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":2}}""")!; yield return new RawMessageStreamEvent(new RawMessageStopEvent(), default); #pragma warning restore CS0162 } diff --git a/tests/SharpClaw.Code.UnitTests/Providers/ResilienceTests.cs b/tests/SharpClaw.Code.UnitTests/Providers/ResilienceTests.cs index 99ad2a2..a7b0788 100644 --- a/tests/SharpClaw.Code.UnitTests/Providers/ResilienceTests.cs +++ b/tests/SharpClaw.Code.UnitTests/Providers/ResilienceTests.cs @@ -269,6 +269,27 @@ public async Task Circuit_breaker_stops_retries_in_current_request() mock.CallCount.Should().Be(2); } + [Fact] + public async Task Failed_events_open_the_circuit_instead_of_resetting_it() + { + async IAsyncEnumerable Failure() + { + await Task.Yield(); + yield return CreateEvent("failed") with { IsTerminal = true, Content = "HTTP 429 TooManyRequests" }; + } + var mock = new CountingMockProvider(); + mock.Behaviors.Enqueue(() => Task.FromResult(new ProviderStreamHandle(FakeRequest, Failure()))); + var decorator = BuildDecorator(mock, new ProviderResilienceOptions + { + MaxRetries = 0, CircuitBreakerFailureThreshold = 1, + CircuitBreakerBreakDuration = TimeSpan.FromMinutes(1), RequestTimeout = TimeSpan.FromSeconds(5), + }); + var handle = await decorator.StartStreamAsync(FakeRequest, CancellationToken.None); + await FluentActions.Awaiting(() => DrainAsync(handle.Events)).Should().ThrowAsync(); + await FluentActions.Awaiting(() => decorator.StartStreamAsync(FakeRequest, CancellationToken.None)).Should().ThrowAsync().WithMessage("*Circuit breaker*"); + mock.CallCount.Should().Be(1); + } + private static async Task DrainAsync(IAsyncEnumerable events) => _ = await CollectAsync(events); diff --git a/tests/SharpClaw.Code.UnitTests/Providers/ToolUseStreamAdapterTests.cs b/tests/SharpClaw.Code.UnitTests/Providers/ToolUseStreamAdapterTests.cs index a36f99e..a0a9214 100644 --- a/tests/SharpClaw.Code.UnitTests/Providers/ToolUseStreamAdapterTests.cs +++ b/tests/SharpClaw.Code.UnitTests/Providers/ToolUseStreamAdapterTests.cs @@ -63,6 +63,7 @@ async IAsyncEnumerable Stream() default); yield return new RawMessageStreamEvent(new RawContentBlockStopEvent { Index = 0 }, default); + yield return System.Text.Json.JsonSerializer.Deserialize("""{"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":2}}""")!; yield return new RawMessageStreamEvent(new RawMessageStopEvent(), default); } @@ -120,6 +121,7 @@ async IAsyncEnumerable Stream() default); yield return new RawMessageStreamEvent(new RawContentBlockStopEvent { Index = 1 }, default); + yield return System.Text.Json.JsonSerializer.Deserialize("""{"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":2}}""")!; yield return new RawMessageStreamEvent(new RawMessageStopEvent(), default); } diff --git a/tests/SharpClaw.Code.UnitTests/Runtime/ConfiguredApprovalIdentityServiceTests.cs b/tests/SharpClaw.Code.UnitTests/Runtime/ConfiguredApprovalIdentityServiceTests.cs index 45daaf7..82703f1 100644 --- a/tests/SharpClaw.Code.UnitTests/Runtime/ConfiguredApprovalIdentityServiceTests.cs +++ b/tests/SharpClaw.Code.UnitTests/Runtime/ConfiguredApprovalIdentityServiceTests.cs @@ -32,7 +32,7 @@ await File.WriteAllTextAsync( } """); - var service = new ConfiguredApprovalIdentityService(new SharpClawConfigService(new SharpClaw.Code.Infrastructure.Services.LocalFileSystem(), new SharpClaw.Code.Infrastructure.Services.PathService())); + var service = new ConfiguredApprovalIdentityService(new HostConfig()); var status = await service.GetStatusAsync(workspaceRoot, CancellationToken.None); var principal = await service.ResolveAsync( workspaceRoot, @@ -61,6 +61,16 @@ await File.WriteAllTextAsync( principal.AuthenticationType.Should().Be("trusted-header"); } + private sealed class HostConfig : SharpClaw.Code.Runtime.Abstractions.ISharpClawConfigService + { + public async Task GetConfigAsync(string workspace, CancellationToken cancellationToken) + { + var json = await File.ReadAllTextAsync(Path.Combine(workspace, "sharpclaw.jsonc"), cancellationToken); + return new SharpClawConfigSnapshot(workspace, null, null, + System.Text.Json.JsonSerializer.Deserialize(json, SharpClaw.Code.Protocol.Serialization.ProtocolJsonContext.Default.SharpClawConfigDocument)!); + } + } + public void Dispose() { if (Directory.Exists(workspaceRoot)) diff --git a/tests/SharpClaw.Code.UnitTests/Runtime/LaunchSecurityRegressionTests.cs b/tests/SharpClaw.Code.UnitTests/Runtime/LaunchSecurityRegressionTests.cs new file mode 100644 index 0000000..4a49c2e --- /dev/null +++ b/tests/SharpClaw.Code.UnitTests/Runtime/LaunchSecurityRegressionTests.cs @@ -0,0 +1,111 @@ +using FluentAssertions; +using SharpClaw.Code.Infrastructure.Services; +using SharpClaw.Code.Web.Services; + +namespace SharpClaw.Code.UnitTests.Runtime; + +/// Exercises malicious paths, network destinations, and interrupted durable writes. +public sealed class LaunchSecurityRegressionTests +{ + [Theory] + [InlineData("../..")] + [InlineData("..\\..")] + [InlineData("/tmp")] + [InlineData("C:\\users")] + [InlineData(".")] + public void Package_ids_cannot_be_paths(string id) + => FluentActions.Invoking(() => LocalPackagePath.ValidateId(id)).Should().Throw(); + + [Fact] + public void Dangling_symlink_cannot_hide_an_outside_write() + { + var root = Path.Combine(Path.GetTempPath(), $"sharpclaw-links-{Guid.NewGuid():N}"); + Directory.CreateDirectory(root); + try + { + var outside = Path.Combine(Path.GetTempPath(), $"outside-{Guid.NewGuid():N}.txt"); + var link = Path.Combine(root, "new.txt"); + try { File.CreateSymbolicLink(link, outside); } + catch (UnauthorizedAccessException) { return; } + catch (PlatformNotSupportedException) { return; } + var paths = new PathService(); + paths.GetCanonicalFullPath(link).Should().Be(paths.GetCanonicalFullPath(outside)); + FluentActions.Invoking(() => LocalPackagePath.Resolve(paths, root, "new.txt")).Should().Throw(); + File.Exists(outside).Should().BeFalse(); + } + finally { Directory.Delete(root, true); } + } + + [Theory] + [InlineData("http://127.0.0.1/secret")] + [InlineData("http://169.254.169.254/latest/meta-data")] + [InlineData("http://10.0.0.1/")] + [InlineData("http://[::1]/")] + [InlineData("http://[::ffff:127.0.0.1]/")] + [InlineData("file:///etc/passwd")] + public async Task Web_fetch_rejects_private_destinations_before_sending(string url) + { + using var client = new HttpClient(new RejectNetwork()); + var service = new WebFetchService(client); + await FluentActions.Awaiting(() => service.FetchAsync(url, CancellationToken.None)).Should().ThrowAsync(); + } + + [Fact] + public async Task Web_fetch_revalidates_redirect_targets() + { + using var client = new HttpClient(new RedirectToMetadata()); + var service = new WebFetchService(client); + await FluentActions.Awaiting(() => service.FetchAsync("https://example.com/", CancellationToken.None)).Should().ThrowAsync(); + } + + [Fact] + public async Task Cancelled_snapshot_replacement_keeps_previous_content_and_append_repairs_torn_record() + { + var directory = Path.Combine(Path.GetTempPath(), $"sharpclaw-durability-{Guid.NewGuid():N}"); + Directory.CreateDirectory(directory); + try + { + var path = Path.Combine(directory, "session.json"); + var files = new LocalFileSystem(); + await files.WriteAllTextAsync(path, "previous", CancellationToken.None); + using var cancelled = new CancellationTokenSource(); + cancelled.Cancel(); + await FluentActions.Awaiting(() => files.WriteAllTextAsync(path, "replacement", cancelled.Token)).Should().ThrowAsync(); + (await File.ReadAllTextAsync(path)).Should().Be("previous"); + Directory.GetFiles(directory, "*.tmp").Should().BeEmpty(); + var log = Path.Combine(directory, "events.ndjson"); + await File.WriteAllTextAsync(log, "{\"event\":1}\n{\"torn\""); + await files.AppendLineAsync(log, "{\"event\":2}", CancellationToken.None); + (await File.ReadAllLinesAsync(log)).Should().Equal("{\"event\":1}", "{\"event\":2}"); + } + finally { Directory.Delete(directory, true); } + } + + [Fact] + public async Task Excessive_subprocess_output_is_stopped_and_reported() + { + if (OperatingSystem.IsWindows()) return; + var runner = new ProcessRunner(new SystemClock()); + var request = new SharpClaw.Code.Infrastructure.Models.ProcessRunRequest("/bin/sh", + ["-c", "yes x | head -c 1200000"], Path.GetTempPath(), null); + using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + await FluentActions.Awaiting(() => runner.RunAsync(request, deadline.Token)).Should().ThrowAsync().WithMessage("*output exceeded*"); + } + + private sealed class RejectNetwork : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + => throw new InvalidOperationException("Private destinations must be rejected before HTTP."); + } + + private sealed class RedirectToMetadata : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + request.RequestUri!.Host.Should().Be("example.com"); + var response = new HttpResponseMessage(System.Net.HttpStatusCode.Redirect); + response.Headers.Location = new Uri("http://169.254.169.254/latest/meta-data"); + return Task.FromResult(response); + } + } +} diff --git a/tests/SharpClaw.Code.UnitTests/Runtime/PromptReferenceResolverTests.cs b/tests/SharpClaw.Code.UnitTests/Runtime/PromptReferenceResolverTests.cs index 9b232b5..18e1f1a 100644 --- a/tests/SharpClaw.Code.UnitTests/Runtime/PromptReferenceResolverTests.cs +++ b/tests/SharpClaw.Code.UnitTests/Runtime/PromptReferenceResolverTests.cs @@ -178,6 +178,19 @@ public async Task ResolveAsync_should_limit_directory_reference_file_count() resolution.ExpandedPrompt.Should().NotContain("file-20.txt"); } + [Theory] + [InlineData("email user@example.com")] + [InlineData("Java @Override and @types/node")] + public async Task Ordinary_at_mentions_remain_literal(string prompt) + { + var workspace = Path.GetTempPath(); + var session = CreateSession(workspace); + var resolution = await CreateResolver().ResolveAsync(workspace, workspace, session, + CreateTurn(session, prompt), CreateRequest(session, workspace, prompt), PrimaryMode.Build, false, CancellationToken.None); + resolution.ExpandedPrompt.Should().Be(prompt); + resolution.References.Should().BeEmpty(); + } + private static PromptReferenceResolver CreateResolver() { var pathService = new PathService(); diff --git a/tests/SharpClaw.Code.UnitTests/Runtime/SharpClawConfigServiceTests.cs b/tests/SharpClaw.Code.UnitTests/Runtime/SharpClawConfigServiceTests.cs index 8a01ce3..6f9f091 100644 --- a/tests/SharpClaw.Code.UnitTests/Runtime/SharpClawConfigServiceTests.cs +++ b/tests/SharpClaw.Code.UnitTests/Runtime/SharpClawConfigServiceTests.cs @@ -58,6 +58,8 @@ await File.WriteAllTextAsync( """ { "shareMode": "Disabled", + "server": { "host": "0.0.0.0", "port": 9999 }, + "hooks": [{ "name": "hostile", "trigger": "TurnCompleted", "command": "touch", "arguments": ["PWNED"] }], "verification": { "maxRepairIterations": 2 }, "defaultAgentId": "workspace-agent", "agents": [ @@ -83,6 +85,8 @@ await File.WriteAllTextAsync( var snapshot = await service.GetConfigAsync(workspace, CancellationToken.None); snapshot.Document.ShareMode.Should().Be(ShareMode.Disabled); + snapshot.Document.Server!.Host.Should().Be("127.0.0.1"); + snapshot.Document.Hooks.Should().BeNullOrEmpty(); snapshot.Document.Verification.Should().BeEquivalentTo(new VerificationOptions(true, VerificationScope.All, true, 2, false, 600)); snapshot.Document.DefaultAgentId.Should().Be("workspace-agent"); snapshot.Document.ConnectLinks.Should().ContainSingle(link => link.Target == "anthropic"); diff --git a/tests/SharpClaw.Code.UnitTests/Tools/SnapshotEditingTests.cs b/tests/SharpClaw.Code.UnitTests/Tools/SnapshotEditingTests.cs index 668658e..9b7f1b5 100644 --- a/tests/SharpClaw.Code.UnitTests/Tools/SnapshotEditingTests.cs +++ b/tests/SharpClaw.Code.UnitTests/Tools/SnapshotEditingTests.cs @@ -269,7 +269,7 @@ private async Task ReadAsync(int start = 1, int limit = 200) private Task EditAsync(string id, SnapshotLineEdit[] edits, ToolExecutionContext? context = null) => services.GetRequiredService().ExecuteAsync(EditFileSnapshotTool.ToolName, JsonSerializer.Serialize(new EditFileSnapshotArguments("file.txt", id, edits), Json), context ?? Context(), CancellationToken.None); - private ToolExecutionContext Context() => new("snapshot-session", "snapshot-turn", workspace, workspace, PermissionMode.WorkspaceWrite, OutputFormat.Json, null, IsInteractive: false, MutationRecorder: recorder); + private ToolExecutionContext Context() => new("snapshot-session", "snapshot-turn", workspace, workspace, PermissionMode.DangerFullAccess, OutputFormat.Json, null, IsInteractive: false, MutationRecorder: recorder); private sealed class Recorder : IToolMutationRecorder { public List Mutations { get; } = []; diff --git a/tests/SharpClaw.Code.UnitTests/Web/WebServiceAndToolTests.cs b/tests/SharpClaw.Code.UnitTests/Web/WebServiceAndToolTests.cs index 891421f..f9496d7 100644 --- a/tests/SharpClaw.Code.UnitTests/Web/WebServiceAndToolTests.cs +++ b/tests/SharpClaw.Code.UnitTests/Web/WebServiceAndToolTests.cs @@ -96,7 +96,7 @@ public async Task AddSharpClawTools_should_register_and_execute_web_tools() TurnId: "turn-001", WorkspaceRoot: "/workspace", WorkingDirectory: "/workspace", - PermissionMode: PermissionMode.WorkspaceWrite, + PermissionMode: PermissionMode.DangerFullAccess, OutputFormat: OutputFormat.Json, EnvironmentVariables: null, AllowedTools: null, From 1d57ff62617b9c5094d068874dd1a41bcbb1d267 Mon Sep 17 00:00:00 2001 From: telli Date: Tue, 10 Nov 2026 03:43:29 -0800 Subject: [PATCH 02/12] Fix permission, mode, process, SSRF, ACP, grep, and storage bugs - Dangerous-delete gate now catches rm -rf/-Rf/--recursive and flag permutations. - Custom commands no longer force Build over a saved session mode. - Process output keeps head and tail instead of throwing past 1 MiB; a background child holding the pipe no longer blocks completion; bash and external agents get 10- and 30-minute deadlines. - Web fetch allows public 192.0.x hosts, blocks 6to4/Teredo/TEST-NET, and caps response bodies at 5 MiB. - Spec-shaped ACP session/cancel notifications cancel live prompts. - Grep handles CRLF files; atomic rewrites keep Unix file modes. - Session and checkpoint IDs are validated before becoming paths. Co-Authored-By: Claude Opus 5.5 --- docs/launch-findings-review.md | 2 +- src/SharpClaw.Code.Acp/AcpLiveTurns.cs | 22 ++++ src/SharpClaw.Code.Acp/AcpStdioHost.cs | 9 +- .../Adapters/ExternalAgentAdapterBase.cs | 6 +- .../Services/LocalFileSystem.cs | 12 ++ .../Services/ProcessRunner.cs | 121 ++++++++++++++---- .../Services/RuntimeStoragePathResolver.cs | 19 ++- .../Services/ShellExecutor.cs | 7 +- .../Rules/DangerousShellPatternRule.cs | 3 +- .../Orchestration/ConversationRuntime.cs | 32 ++++- .../BuiltIn/GrepSearchTool.cs | 17 ++- .../Services/PublicNetwork.cs | 15 ++- .../Services/ResilientHttpGet.cs | 2 +- .../Services/WebFetchService.cs | 37 +++++- .../Runtime/SpecModeWorkflowTests.cs | 51 ++++++++ .../Acp/AcpStdioHostTests.cs | 46 +++++++ .../PermissionPolicyEngineTests.cs | 22 ++++ .../Runtime/LaunchSecurityRegressionTests.cs | 101 ++++++++++++++- .../Tools/ToolRegistryAndExecutionTests.cs | 22 ++++ 19 files changed, 495 insertions(+), 51 deletions(-) diff --git a/docs/launch-findings-review.md b/docs/launch-findings-review.md index 66186c5..b5ee2b3 100644 --- a/docs/launch-findings-review.md +++ b/docs/launch-findings-review.md @@ -49,7 +49,7 @@ Reviewed against the working tree on November 5, 2026. The supplied report ident | Nonatomic snapshots/torn NDJSON | Valid. Local text state uses same-directory temporary files and atomic replacement. Appends use an exclusive lock and discard an incomplete trailing record before writing the next event. Disk-loss/power-loss durability is not guaranteed by atomic rename alone. | | One malformed plugin disables tools | Valid. Invalid manifests/states are logged and skipped, conflicting plugin tools are omitted, and built-in lookup is independent of plugin discovery. | | MCP cancellation leaves Starting | Valid. Interrupted startup persists Faulted using a cleanup token and disposes a newly established session if needed. Stop checks cancellation before removing the tracked client. | -| ACP ignores cancel notifications | Valid for notifications without IDs. They are now accepted without emitting a JSON-RPC response. Existing live-control targeting and validation are retained. | +| ACP ignores cancel notifications | Valid for notifications without IDs. A spec-shaped `session/cancel` notification (only `sessionId`, optional `cwd`) cancels that session's live-controlled prompts on the connection, without a JSON-RPC response. Prompts that did not opt into `liveTurnControl` are not tracked and cannot yet be cancelled this way. Request-form cancels keep their `promptRequestId` targeting. | | Every CLI command starts scheduler | Valid. CLI bootstrap removes the scheduler hosted service and no longer starts the host implicitly. Embedded-host scheduling remains available; explicit schedule commands retain their own workspace context. | | Bash lacks bounds and denylist misses variants | Valid. Shared process execution defaults to two minutes and one MiB characters per output stream, kills on failure/cancellation, and observes reader tasks. Verification explicitly retains its configured deadline. Recursive-rm flag permutations and find deletion/execution patterns receive a non-auto-approvable gate. These patterns are not a complete shell sandbox. | diff --git a/src/SharpClaw.Code.Acp/AcpLiveTurns.cs b/src/SharpClaw.Code.Acp/AcpLiveTurns.cs index b6aa66a..78a6356 100644 --- a/src/SharpClaw.Code.Acp/AcpLiveTurns.cs +++ b/src/SharpClaw.Code.Acp/AcpLiveTurns.cs @@ -67,6 +67,28 @@ internal JsonObject Control(string workspace, JsonNode? parameters, bool cancel) return new JsonObject { ["accepted"] = cancel || target.Handle.TrySteer(text!) }; } + /// + /// Handles a spec-shaped session/cancel notification, which carries only sessionId: + /// cancels every live-controlled prompt for that session on this connection, optionally narrowed by cwd. + /// + internal int CancelSession(JsonNode? parameters, string? workspace) + { + var sessionId = parameters?["sessionId"] is JsonValue value && value.TryGetValue(out var text) ? text : null; + if (string.IsNullOrEmpty(sessionId)) return 0; + workspace = workspace is null ? null : Path.TrimEndingDirectorySeparator(workspace); + var cancelled = 0; + foreach (var prompt in active.Values) + { + if (prompt.SessionId != sessionId) continue; + if (workspace is not null && !string.Equals(prompt.Workspace, workspace, + OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) continue; + prompt.Handle.Cancel(); + cancelled++; + } + + return cancelled; + } + private static void AddPending(JsonObject result, IReadOnlyList pending) { if (pending.Count == 0) return; diff --git a/src/SharpClaw.Code.Acp/AcpStdioHost.cs b/src/SharpClaw.Code.Acp/AcpStdioHost.cs index 6c43d1f..8ba8405 100644 --- a/src/SharpClaw.Code.Acp/AcpStdioHost.cs +++ b/src/SharpClaw.Code.Acp/AcpStdioHost.cs @@ -120,7 +120,14 @@ private async Task ProcessRequestAsync(JsonObject requestObject, AcpLiveTurns li { if (id is null) { - if (method == "session/cancel") live.Control(RequireWorkspace(requestObject["params"]), requestObject["params"], cancel: true); + if (method == "session/cancel") + { + var parameters = requestObject["params"]; + if (parameters?["promptRequestId"] is not null) + live.Control(RequireWorkspace(parameters), parameters, cancel: true); + else if (live.CancelSession(parameters, parameters?["cwd"] is null ? null : RequireWorkspace(parameters)) == 0) + logger.LogDebug("ACP session/cancel notification matched no live-controlled prompt."); + } return; } var response = await DispatchAsync(method, id, requestObject["params"], live, stdout, cancellationToken).ConfigureAwait(false); diff --git a/src/SharpClaw.Code.ExternalAgents/Adapters/ExternalAgentAdapterBase.cs b/src/SharpClaw.Code.ExternalAgents/Adapters/ExternalAgentAdapterBase.cs index cbb2de9..33f0ce7 100644 --- a/src/SharpClaw.Code.ExternalAgents/Adapters/ExternalAgentAdapterBase.cs +++ b/src/SharpClaw.Code.ExternalAgents/Adapters/ExternalAgentAdapterBase.cs @@ -13,6 +13,9 @@ public abstract class ExternalAgentAdapterBase( IProcessRunner processRunner, IExternalAgentConfigProvider configProvider) : IExternalAgentAdapter { + /// Deadline for one external agent run; delegated agents routinely run far longer than a shell command. + protected static readonly TimeSpan ExternalAgentTimeout = TimeSpan.FromMinutes(30); + /// public abstract ExternalAgentDescriptor Descriptor { get; } @@ -72,7 +75,8 @@ public async Task RunAsync(ExternalAgentRunRequest reque executable, MergeArguments(adapterConfig, request), request.WorkspacePath, - request.Environment), + request.Environment, + ExternalAgentTimeout), cancellationToken) .ConfigureAwait(false); var output = string.IsNullOrWhiteSpace(result.StandardOutput) diff --git a/src/SharpClaw.Code.Infrastructure/Services/LocalFileSystem.cs b/src/SharpClaw.Code.Infrastructure/Services/LocalFileSystem.cs index 037d967..c957163 100644 --- a/src/SharpClaw.Code.Infrastructure/Services/LocalFileSystem.cs +++ b/src/SharpClaw.Code.Infrastructure/Services/LocalFileSystem.cs @@ -132,11 +132,23 @@ public async Task WriteAllTextAsync(string path, string content, CancellationTok { await File.WriteAllTextAsync(temporaryPath, content, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); + PreserveUnixFileMode(path, temporaryPath); File.Move(temporaryPath, path, overwrite: true); } finally { TryDeleteFile(temporaryPath); } } + /// Carries an existing file's permission bits (for example the executable bit) onto its replacement. + private static void PreserveUnixFileMode(string existingPath, string replacementPath) + { + if (OperatingSystem.IsWindows() || !File.Exists(existingPath)) + { + return; + } + + File.SetUnixFileMode(replacementPath, File.GetUnixFileMode(existingPath)); + } + /// public async Task CopyFileAsync(string sourcePath, string destinationPath, CancellationToken cancellationToken) { diff --git a/src/SharpClaw.Code.Infrastructure/Services/ProcessRunner.cs b/src/SharpClaw.Code.Infrastructure/Services/ProcessRunner.cs index a2c8b83..eb9c482 100644 --- a/src/SharpClaw.Code.Infrastructure/Services/ProcessRunner.cs +++ b/src/SharpClaw.Code.Infrastructure/Services/ProcessRunner.cs @@ -47,49 +47,126 @@ public async Task RunAsync(ProcessRunRequest request, Cancella var startedAtUtc = systemClock.UtcNow; process.Start(); - var standardOutputTask = ReadBoundedAsync(process.StandardOutput, timeout, processToken); - var standardErrorTask = ReadBoundedAsync(process.StandardError, timeout, processToken); + var standardOutput = new BoundedOutputReader(process.StandardOutput); + var standardError = new BoundedOutputReader(process.StandardError); + using var readerCancellation = CancellationTokenSource.CreateLinkedTokenSource(processToken); + var standardOutputTask = standardOutput.ReadToEndAsync(readerCancellation.Token); + var standardErrorTask = standardError.ReadToEndAsync(readerCancellation.Token); try { await process.WaitForExitAsync(processToken).ConfigureAwait(false); - var standardOutput = await standardOutputTask.ConfigureAwait(false); - var standardError = await standardErrorTask.ConfigureAwait(false); - var completedAtUtc = systemClock.UtcNow; + try + { + // A background grandchild can inherit the pipes and keep them open after the shell exits. + await Task.WhenAll(standardOutputTask, standardErrorTask) + .WaitAsync(PostExitDrainGrace, processToken) + .ConfigureAwait(false); + } + catch (TimeoutException) + { + readerCancellation.Cancel(); + await ObserveAsync(standardOutputTask, standardErrorTask).ConfigureAwait(false); + } - return new ProcessRunResult(process.ExitCode, standardOutput, standardError, startedAtUtc, completedAtUtc); + var completedAtUtc = systemClock.UtcNow; + return new ProcessRunResult(process.ExitCode, standardOutput.GetText(), standardError.GetText(), startedAtUtc, completedAtUtc); } catch (Exception exception) { timeout.Cancel(); TryKillProcessTree(process); - try { await Task.WhenAll(standardOutputTask, standardErrorTask).ConfigureAwait(false); } - catch (Exception) { /* Observe both reader failures before disposing the process. */ } + await ObserveAsync(standardOutputTask, standardErrorTask).ConfigureAwait(false); if (!cancellationToken.IsCancellationRequested && exception is OperationCanceledException) { - var outputFailure = (standardOutputTask.Exception?.InnerExceptions.AsEnumerable() ?? []) - .Concat(standardErrorTask.Exception?.InnerExceptions.AsEnumerable() ?? []).OfType().FirstOrDefault(); - if (outputFailure is not null) throw outputFailure; throw new TimeoutException("Process exceeded its execution deadline.", exception); } throw; } } - private static async Task ReadBoundedAsync(StreamReader reader, CancellationTokenSource timeout, CancellationToken cancellationToken) + /// Characters retained per output stream; output beyond this keeps its head and tail. + public const int MaxRetainedCharacters = 1024 * 1024; + + private static readonly TimeSpan PostExitDrainGrace = TimeSpan.FromSeconds(2); + + private static async Task ObserveAsync(Task first, Task second) + { + try { await Task.WhenAll(first, second).ConfigureAwait(false); } + catch (Exception) { /* Observe both reader failures before disposing the process. */ } + } + + /// + /// Drains a process stream with bounded memory, keeping the first and last halves of the retained budget. + /// + private sealed class BoundedOutputReader(StreamReader reader) { - const int maxCharacters = 1024 * 1024; - var builder = new System.Text.StringBuilder(); - var buffer = new char[4096]; - while (true) + private const int HalfBudget = MaxRetainedCharacters / 2; + private readonly System.Text.StringBuilder head = new(); + private readonly char[] tail = new char[HalfBudget]; + private int tailStart; + private int tailLength; + private long droppedCharacters; + private readonly object gate = new(); + + public async Task ReadToEndAsync(CancellationToken cancellationToken) { - var count = await reader.ReadAsync(buffer.AsMemory(), cancellationToken).ConfigureAwait(false); - if (count == 0) return builder.ToString(); - if (builder.Length + count > maxCharacters) + var buffer = new char[4096]; + while (true) { - timeout.Cancel(); - throw new IOException("Process output exceeded the 1 MiB character limit."); + var count = await reader.ReadAsync(buffer.AsMemory(), cancellationToken).ConfigureAwait(false); + if (count == 0) return; + lock (gate) Append(buffer.AsSpan(0, count)); } - builder.Append(buffer, 0, count); + } + + public string GetText() + { + lock (gate) + { + if (tailLength == 0) return head.ToString(); + var builder = new System.Text.StringBuilder(head.Length + tailLength + 96); + builder.Append(head); + if (droppedCharacters > 0) + { + builder.Append($"\n[... {droppedCharacters} characters of output omitted ...]\n"); + } + + var firstSegment = Math.Min(tailLength, tail.Length - tailStart); + builder.Append(tail, tailStart, firstSegment); + builder.Append(tail, 0, tailLength - firstSegment); + return builder.ToString(); + } + } + + private void Append(ReadOnlySpan chunk) + { + var headRoom = HalfBudget - head.Length; + if (headRoom > 0) + { + var taken = Math.Min(headRoom, chunk.Length); + head.Append(chunk[..taken]); + chunk = chunk[taken..]; + } + + if (chunk.IsEmpty) return; + if (chunk.Length >= tail.Length) + { + droppedCharacters += tailLength + (chunk.Length - tail.Length); + chunk[^tail.Length..].CopyTo(tail); + tailStart = 0; + tailLength = tail.Length; + return; + } + + var overflow = Math.Max(0, tailLength + chunk.Length - tail.Length); + droppedCharacters += overflow; + tailStart = (tailStart + overflow) % tail.Length; + tailLength -= overflow; + var writeAt = (tailStart + tailLength) % tail.Length; + var firstSegment = Math.Min(chunk.Length, tail.Length - writeAt); + chunk[..firstSegment].CopyTo(tail.AsSpan(writeAt)); + chunk[firstSegment..].CopyTo(tail); + tailLength += chunk.Length; } } diff --git a/src/SharpClaw.Code.Infrastructure/Services/RuntimeStoragePathResolver.cs b/src/SharpClaw.Code.Infrastructure/Services/RuntimeStoragePathResolver.cs index 98a0510..b986d98 100644 --- a/src/SharpClaw.Code.Infrastructure/Services/RuntimeStoragePathResolver.cs +++ b/src/SharpClaw.Code.Infrastructure/Services/RuntimeStoragePathResolver.cs @@ -35,7 +35,7 @@ public string GetSessionsRoot(string workspacePath) /// public string GetSessionRoot(string workspacePath, string sessionId) - => pathService.Combine(GetSessionsRoot(workspacePath), sessionId); + => pathService.Combine(GetSessionsRoot(workspacePath), RequireSingleSegment(sessionId, nameof(sessionId))); /// public string GetSessionSnapshotPath(string workspacePath, string sessionId) @@ -55,7 +55,7 @@ public string GetCheckpointsRoot(string workspacePath, string sessionId) /// public string GetCheckpointPath(string workspacePath, string sessionId, string checkpointId) - => pathService.Combine(GetCheckpointsRoot(workspacePath, sessionId), $"{checkpointId}.json"); + => pathService.Combine(GetCheckpointsRoot(workspacePath, sessionId), $"{RequireSingleSegment(checkpointId, nameof(checkpointId))}.json"); /// public string GetMutationsRoot(string workspacePath, string sessionId) @@ -151,6 +151,21 @@ private string BuildWorkspaceKey(string workspacePath) return $"{slug}-{hash}"; } + /// + /// Rejects identifiers that would leave their storage directory (separators, rooted paths, dot segments). + /// Session and checkpoint IDs reach this from HTTP routes, ACP parameters, and imported bundles. + /// + private static string RequireSingleSegment(string value, string parameterName) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value, parameterName); + if (value is "." or ".." || value.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not ('-' or '_' or '.'))) + { + throw new ArgumentException($"'{value}' is not a valid identifier; use letters, digits, dots, hyphens, and underscores.", parameterName); + } + + return value; + } + private static string SanitizeSegment(string value) { var builder = new StringBuilder(value.Length); diff --git a/src/SharpClaw.Code.Infrastructure/Services/ShellExecutor.cs b/src/SharpClaw.Code.Infrastructure/Services/ShellExecutor.cs index b50f980..41b1c8c 100644 --- a/src/SharpClaw.Code.Infrastructure/Services/ShellExecutor.cs +++ b/src/SharpClaw.Code.Infrastructure/Services/ShellExecutor.cs @@ -8,6 +8,9 @@ namespace SharpClaw.Code.Infrastructure.Services; /// public sealed class ShellExecutor(IProcessRunner processRunner) : IShellExecutor { + /// Deadline for agent shell commands; long enough for typical builds and test runs. + public static readonly TimeSpan ShellCommandTimeout = TimeSpan.FromMinutes(10); + /// public Task ExecuteAsync( string command, @@ -18,8 +21,8 @@ public Task ExecuteAsync( ArgumentException.ThrowIfNullOrWhiteSpace(command); var request = OperatingSystem.IsWindows() - ? new ProcessRunRequest("cmd.exe", ["/c", command], workingDirectory, environmentVariables) - : new ProcessRunRequest("/bin/sh", ["-lc", command], workingDirectory, environmentVariables); + ? new ProcessRunRequest("cmd.exe", ["/c", command], workingDirectory, environmentVariables, ShellCommandTimeout) + : new ProcessRunRequest("/bin/sh", ["-lc", command], workingDirectory, environmentVariables, ShellCommandTimeout); return processRunner.RunAsync(request, cancellationToken); } diff --git a/src/SharpClaw.Code.Permissions/Rules/DangerousShellPatternRule.cs b/src/SharpClaw.Code.Permissions/Rules/DangerousShellPatternRule.cs index 226a2fd..3bf83ea 100644 --- a/src/SharpClaw.Code.Permissions/Rules/DangerousShellPatternRule.cs +++ b/src/SharpClaw.Code.Permissions/Rules/DangerousShellPatternRule.cs @@ -54,7 +54,8 @@ private static bool ContainsDangerousSubstitution(string normalized) return DangerousSubstitutionRegex().IsMatch(normalized); } - [GeneratedRegex(@"\b(?:rm\s+[^;|\r\n]*-[a-z]*r|find\s+[^;|\r\n]*-(?:delete|exec))\b", RegexOptions.IgnoreCase, matchTimeoutMilliseconds: 250)] + // Matches rm with any recursive flag token (-r, -rf, -fR, -f -r, --recursive) and find with delete/exec actions. + [GeneratedRegex(@"\brm\s(?:[^;|&\r\n]*\s)?(?:-[a-z]*r[a-z]*|--recursive)(?=[\s;|&]|$)|\bfind\s[^;|&\r\n]*\s-(?:delete|exec|execdir|ok|okdir)\b", RegexOptions.IgnoreCase, matchTimeoutMilliseconds: 250)] private static partial Regex DangerousDeletionRegex(); [GeneratedRegex(@"\$\(.*(?:rm\s+-rf|mkfs|dd\s+if=|shutdown|reboot)", RegexOptions.Singleline)] diff --git a/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs b/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs index ffa0834..59e98b6 100644 --- a/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs +++ b/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs @@ -117,7 +117,7 @@ public async Task RunPromptAsync(RunPromptRequest request, var explicitPrimaryMode = request.PrimaryMode; request = await ApplyAgentAndConfigDefaultsAsync(workspacePath, request, cancellationToken).ConfigureAwait(false); var runtimeEvents = new List(); - var session = await ResolveSessionAsync(workspacePath, request, cancellationToken).ConfigureAwait(false); + var session = await ResolveSessionAsync(workspacePath, request.SessionId, cancellationToken).ConfigureAwait(false); var isNewSession = false; if (session is null) @@ -556,8 +556,16 @@ public async Task ExecuteCustomCommandAsync( metadata[SharpClawWorkflowMetadataKeys.CustomCommandName] = definition.Name; var permission = ClampPermissionModeForCustomCommand(context.PermissionMode, definition.PermissionMode); - var contextPrimary = context.PrimaryMode ?? PrimaryMode.Build; - var primary = ClampPrimaryModeForCustomCommand(contextPrimary, definition.PrimaryModeOverride); + // With no caller-selected mode and no command override, leave the mode unspecified so the session's saved mode applies. + // Otherwise clamp against the caller's mode, falling back to the saved session mode, so markdown cannot leave Plan/Research/Spec. + PrimaryMode? primary = null; + if (context.PrimaryMode is not null || definition.PrimaryModeOverride is not null) + { + var baseline = context.PrimaryMode + ?? await ResolveSavedPrimaryModeAsync(workspace, context.SessionId, cancellationToken).ConfigureAwait(false) + ?? PrimaryMode.Build; + primary = ClampPrimaryModeForCustomCommand(baseline, definition.PrimaryModeOverride); + } return await RunPromptAsync( new RunPromptRequest( @@ -1182,14 +1190,24 @@ private static string FormatStatusMessage(RuntimeStatusReport report) private static string FormatProviderFailureReason(ProviderExecutionException exception) => $"Provider failure ({exception.Kind}): {exception.Message}"; - private async Task ResolveSessionAsync(string workspacePath, RunPromptRequest request, CancellationToken cancellationToken) + private async Task ResolveSavedPrimaryModeAsync(string workspacePath, string? sessionId, CancellationToken cancellationToken) + { + var session = await ResolveSessionAsync(workspacePath, sessionId, cancellationToken).ConfigureAwait(false); + return session?.Metadata is not null + && session.Metadata.TryGetValue(SharpClawWorkflowMetadataKeys.PrimaryMode, out var savedMode) + && Enum.TryParse(savedMode, true, out var persistedMode) && Enum.IsDefined(persistedMode) + ? persistedMode + : null; + } + + private async Task ResolveSessionAsync(string workspacePath, string? sessionId, CancellationToken cancellationToken) { - if (!string.IsNullOrWhiteSpace(request.SessionId)) + if (!string.IsNullOrWhiteSpace(sessionId)) { - var resolvedSession = await sessionStore.GetByIdAsync(workspacePath, request.SessionId, cancellationToken).ConfigureAwait(false); + var resolvedSession = await sessionStore.GetByIdAsync(workspacePath, sessionId, cancellationToken).ConfigureAwait(false); if (resolvedSession is null) { - throw new InvalidOperationException($"Session '{request.SessionId}' was not found in workspace '{workspacePath}'."); + throw new InvalidOperationException($"Session '{sessionId}' was not found in workspace '{workspacePath}'."); } return resolvedSession; diff --git a/src/SharpClaw.Code.Tools/BuiltIn/GrepSearchTool.cs b/src/SharpClaw.Code.Tools/BuiltIn/GrepSearchTool.cs index df323a3..18ebed2 100644 --- a/src/SharpClaw.Code.Tools/BuiltIn/GrepSearchTool.cs +++ b/src/SharpClaw.Code.Tools/BuiltIn/GrepSearchTool.cs @@ -64,8 +64,8 @@ public override async Task ExecuteAsync( if (new FileInfo(file).Length > 2 * 1024 * 1024) continue; var text = await File.ReadAllTextAsync(file, cancellationToken).ConfigureAwait(false); if (text.Contains('\0')) continue; - var lines = text.Split('\n'); - for (var index = 0; index < lines.Length; index++) + var lines = SplitLines(text); + for (var index = 0; index < lines.Count; index++) { bool matched; try { matched = regex.IsMatch(lines[index]); } @@ -91,4 +91,17 @@ public override async Task ExecuteAsync( return CreateSuccessResult(context, request, textOutput, payload); } + + /// Splits like : CR, LF, and CRLF terminate lines; no trailing empty line. + private static List SplitLines(string text) + { + var lines = new List(); + using var reader = new StringReader(text); + while (reader.ReadLine() is { } line) + { + lines.Add(line); + } + + return lines; + } } diff --git a/src/SharpClaw.Code.Web/Services/PublicNetwork.cs b/src/SharpClaw.Code.Web/Services/PublicNetwork.cs index 02c9444..facbb88 100644 --- a/src/SharpClaw.Code.Web/Services/PublicNetwork.cs +++ b/src/SharpClaw.Code.Web/Services/PublicNetwork.cs @@ -20,11 +20,22 @@ internal static bool IsPublic(IPAddress address) if (IPAddress.IsLoopback(address)) return false; var bytes = address.GetAddressBytes(); if (address.AddressFamily == AddressFamily.InterNetworkV6) - return (bytes[0] & 0xe0) == 0x20 && !(bytes[0] == 0x20 && bytes[1] == 0x01 && bytes[2] == 0x0d && bytes[3] == 0xb8); + { + // Global unicast only, excluding documentation (2001:db8::/32) and the IPv4-embedding + // transition ranges Teredo (2001::/32) and 6to4 (2002::/16). + return (bytes[0] & 0xe0) == 0x20 + && !(bytes[0] == 0x20 && bytes[1] == 0x01 && bytes[2] == 0x0d && bytes[3] == 0xb8) + && !(bytes[0] == 0x20 && bytes[1] == 0x01 && bytes[2] == 0x00 && bytes[3] == 0x00) + && !(bytes[0] == 0x20 && bytes[1] == 0x02); + } + return bytes[0] is not (0 or 10 or 127) && bytes[0] < 224 && !(bytes[0] == 169 && bytes[1] == 254) && !(bytes[0] == 172 && bytes[1] is >= 16 and <= 31) - && !(bytes[0] == 192 && (bytes[1] == 168 || bytes[1] == 0)) + && !(bytes[0] == 192 && bytes[1] == 168) + && !(bytes[0] == 192 && bytes[1] == 0 && bytes[2] is 0 or 2) + && !(bytes[0] == 198 && bytes[1] == 51 && bytes[2] == 100) + && !(bytes[0] == 203 && bytes[1] == 0 && bytes[2] == 113) && !(bytes[0] == 100 && bytes[1] is >= 64 and <= 127) && !(bytes[0] == 198 && bytes[1] is 18 or 19); } diff --git a/src/SharpClaw.Code.Web/Services/ResilientHttpGet.cs b/src/SharpClaw.Code.Web/Services/ResilientHttpGet.cs index 8824216..ce8bac5 100644 --- a/src/SharpClaw.Code.Web/Services/ResilientHttpGet.cs +++ b/src/SharpClaw.Code.Web/Services/ResilientHttpGet.cs @@ -21,7 +21,7 @@ public static async Task GetAsync( HttpResponseMessage response; try { - response = await httpClient.GetAsync(requestUri, cancellationToken).ConfigureAwait(false); + response = await httpClient.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); } catch (HttpRequestException) when (attempt < MaxAttempts) { diff --git a/src/SharpClaw.Code.Web/Services/WebFetchService.cs b/src/SharpClaw.Code.Web/Services/WebFetchService.cs index 5747115..9022638 100644 --- a/src/SharpClaw.Code.Web/Services/WebFetchService.cs +++ b/src/SharpClaw.Code.Web/Services/WebFetchService.cs @@ -20,7 +20,7 @@ public async Task FetchAsync(string url, CancellationToken can using var response = await FetchPublicAsync(new Uri(url, UriKind.Absolute), cancellationToken).ConfigureAwait(false); var contentType = response.Content.Headers.ContentType?.MediaType; - var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + var body = await ReadBoundedBodyAsync(response.Content, cancellationToken).ConfigureAwait(false); if (!ShouldTreatBodyAsHtml(contentType, body)) { @@ -49,10 +49,33 @@ public async Task FetchAsync(string url, CancellationToken can Content: DecodeAndNormalize(text)); } - /// - /// Uses declared media type when present; otherwise sniffs common markup so plain-text responses - /// that are actually HTML still parse correctly (typical for minimal in tests/tools). - /// + /// Maximum response bytes read from one fetch; larger bodies are truncated. + public const int MaxBodyBytes = 5 * 1024 * 1024; + + private static async Task ReadBoundedBodyAsync(HttpContent content, CancellationToken cancellationToken) + { + await using var stream = await content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + using var bounded = new MemoryStream(); + var chunk = new byte[81920]; + while (bounded.Length < MaxBodyBytes) + { + var wanted = (int)Math.Min(chunk.Length, MaxBodyBytes - bounded.Length); + var read = await stream.ReadAsync(chunk.AsMemory(0, wanted), cancellationToken).ConfigureAwait(false); + if (read == 0) break; + bounded.Write(chunk, 0, read); + } + + var encoding = System.Text.Encoding.UTF8; + var charset = content.Headers.ContentType?.CharSet?.Trim('"'); + if (!string.IsNullOrWhiteSpace(charset)) + { + try { encoding = System.Text.Encoding.GetEncoding(charset); } + catch (ArgumentException) { /* Unknown charset: fall back to UTF-8. */ } + } + + return encoding.GetString(bounded.GetBuffer(), 0, (int)bounded.Length).TrimStart('\uFEFF'); + } + private async Task FetchPublicAsync(Uri uri, CancellationToken cancellationToken) { for (var redirects = 0; redirects <= 5; redirects++) @@ -68,6 +91,10 @@ private async Task FetchPublicAsync(Uri uri, CancellationTo throw new HttpRequestException("Too many redirects."); } + /// + /// Uses declared media type when present; otherwise sniffs common markup so plain-text responses + /// that are actually HTML still parse correctly (typical for minimal in tests/tools). + /// private static bool ShouldTreatBodyAsHtml(string? mediaType, string body) { if (LooksLikeHtmlMediaType(mediaType)) diff --git a/tests/SharpClaw.Code.IntegrationTests/Runtime/SpecModeWorkflowTests.cs b/tests/SharpClaw.Code.IntegrationTests/Runtime/SpecModeWorkflowTests.cs index 7e47733..6d69033 100644 --- a/tests/SharpClaw.Code.IntegrationTests/Runtime/SpecModeWorkflowTests.cs +++ b/tests/SharpClaw.Code.IntegrationTests/Runtime/SpecModeWorkflowTests.cs @@ -143,6 +143,57 @@ await File.WriteAllTextAsync( File.Exists(result.SpecArtifacts!.RequirementsPath).Should().BeTrue(); } + /// + /// Ensures a custom command without a caller-selected mode cannot switch a saved research session to build. + /// + [Theory] + [InlineData(null)] + [InlineData("build")] + public async Task ExecuteCustomCommand_without_caller_mode_should_keep_saved_research_mode(string? commandMode) + { + var workspacePath = CreateTemporaryWorkspace(); + Directory.CreateDirectory(Path.Combine(workspacePath, ".sharpclaw", "commands")); + var frontmatter = commandMode is null ? "" : $"primaryMode: {commandMode}\n"; + await File.WriteAllTextAsync( + Path.Combine(workspacePath, ".sharpclaw", "commands", "summarize.md"), + $"---\ndescription: Summarize\n{frontmatter}---\nSummarize $ARGUMENTS\n"); + + using var serviceProvider = CreateRuntimeServices(services => + { + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + }); + var conversation = serviceProvider.GetRequiredService(); + var commands = serviceProvider.GetRequiredService(); + + var researched = await conversation.RunPromptAsync( + new RunPromptRequest( + Prompt: "Research the change", + SessionId: null, + WorkingDirectory: workspacePath, + PermissionMode: PermissionMode.WorkspaceWrite, + OutputFormat: OutputFormat.Text, + Metadata: new Dictionary { ["provider"] = "spec-provider", ["model"] = "spec-model" }, + PrimaryMode: PrimaryMode.Research), + CancellationToken.None); + + var result = await commands.ExecuteCustomCommandAsync( + "summarize", + "the plan", + new RuntimeCommandContext( + WorkingDirectory: workspacePath, + Model: "spec-model", + PermissionMode: PermissionMode.WorkspaceWrite, + OutputFormat: OutputFormat.Text, + PrimaryMode: null, + SessionId: researched.Session.Id), + CancellationToken.None); + + result.Session.Metadata![SharpClawWorkflowMetadataKeys.PrimaryMode] + .Should().BeEquivalentTo(nameof(PrimaryMode.Research)); + } + private static string CreateTemporaryWorkspace() { var workspacePath = Path.Combine(Path.GetTempPath(), "sharpclaw-spec-mode-tests", Guid.NewGuid().ToString("N")); diff --git a/tests/SharpClaw.Code.UnitTests/Acp/AcpStdioHostTests.cs b/tests/SharpClaw.Code.UnitTests/Acp/AcpStdioHostTests.cs index 4b6130d..5adea73 100644 --- a/tests/SharpClaw.Code.UnitTests/Acp/AcpStdioHostTests.cs +++ b/tests/SharpClaw.Code.UnitTests/Acp/AcpStdioHostTests.cs @@ -249,6 +249,52 @@ public async Task Live_controls_match_prompt_session_and_workspace_and_return_un output.ToString().Should().NotContain("private correction"); } + [Theory] + [InlineData("""{"sessionId":"one"}""")] + [InlineData("""{"sessionId":"one","cwd":"."}""")] + public async Task Spec_shaped_cancel_notification_cancels_the_sessions_live_prompt(string cancelParams) + { + var cancelledBeforeEof = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var runtime = new StubConversationRuntime + { + DuringPrompt = async (request, token) => + { + try { await Task.Delay(Timeout.Infinite, token); } + catch (OperationCanceledException) { cancelledBeforeEof.TrySetResult(); throw; } + } + }; + var host = CreateHost(runtime, controls: new LiveTurnControlService()); + var input = new GatedLineReader( + """{"jsonrpc":"2.0","id":"a","method":"session/prompt","params":{"cwd":".","sessionId":"one","prompt":"work","liveTurnControl":true}}""", + $$"""{"jsonrpc":"2.0","method":"session/cancel","params":{{cancelParams}}}"""); + using var output = new StringWriter(); + + var run = host.RunAsync(input, output, CancellationToken.None); + var completed = await Task.WhenAny(cancelledBeforeEof.Task, Task.Delay(TimeSpan.FromSeconds(5))); + input.Release(); + await run.WaitAsync(TimeSpan.FromSeconds(10)); + + completed.Should().BeSameAs(cancelledBeforeEof.Task, "the notification, not EOF, must cancel the prompt"); + ReadResponseResult(output, "a")["stopReason"]!.GetValue().Should().Be("cancelled"); + output.ToString().Should().NotContain("\"error\""); + } + + /// Serves fixed lines, then blocks reads until released so EOF cannot be what cancels a prompt. + private sealed class GatedLineReader(params string[] lines) : TextReader + { + private readonly Queue pending = new(lines); + private readonly TaskCompletionSource gate = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public void Release() => gate.TrySetResult(); + + public override async ValueTask ReadLineAsync(CancellationToken cancellationToken) + { + if (pending.TryDequeue(out var line)) return line; + await gate.Task.WaitAsync(cancellationToken); + return null; + } + } + [Theory] [InlineData(true)] [InlineData(false)] diff --git a/tests/SharpClaw.Code.UnitTests/Permissions/PermissionPolicyEngineTests.cs b/tests/SharpClaw.Code.UnitTests/Permissions/PermissionPolicyEngineTests.cs index 12d8844..72a7d34 100644 --- a/tests/SharpClaw.Code.UnitTests/Permissions/PermissionPolicyEngineTests.cs +++ b/tests/SharpClaw.Code.UnitTests/Permissions/PermissionPolicyEngineTests.cs @@ -346,6 +346,28 @@ public async Task Read_only_mode_cannot_be_overridden_by_approval_or_auto_approv approvals.RequestCount.Should().Be(0); } + [Theory] + [InlineData("rm -rf src", true)] + [InlineData("rm -Rf ~/projects", true)] + [InlineData("rm -fr build", true)] + [InlineData("rm -r build", true)] + [InlineData("rm --recursive build", true)] + [InlineData("rm -f -r build", true)] + [InlineData("find . -name '*.tmp' -delete", true)] + [InlineData("rm notes.txt", false)] + [InlineData("rm -f notes.txt", false)] + [InlineData("rm --force notes.txt", false)] + public async Task Recursive_deletions_require_a_fresh_prompt_despite_shell_auto_approval(string command, bool expectPrompt) + { + var approvals = new StubApprovalService(); + var engine = CreateEngine(approvals); + var request = CreateRequest("bash", System.Text.Json.JsonSerializer.Serialize(new { command }), ApprovalScope.ShellExecution, true, true); + var context = CreateContext(PermissionMode.WorkspaceWrite, approvalSettings: new ApprovalSettings([ApprovalScope.ShellExecution], null)); + + (await engine.EvaluateAsync(request, context, CancellationToken.None)).IsAllowed.Should().BeTrue(); + approvals.RequestCount.Should().Be(expectPrompt ? 1 : 0); + } + [Fact] public async Task Explicit_approval_includes_arguments_and_is_not_reused_for_different_arguments() { diff --git a/tests/SharpClaw.Code.UnitTests/Runtime/LaunchSecurityRegressionTests.cs b/tests/SharpClaw.Code.UnitTests/Runtime/LaunchSecurityRegressionTests.cs index 4a49c2e..ff18813 100644 --- a/tests/SharpClaw.Code.UnitTests/Runtime/LaunchSecurityRegressionTests.cs +++ b/tests/SharpClaw.Code.UnitTests/Runtime/LaunchSecurityRegressionTests.cs @@ -16,6 +16,29 @@ public sealed class LaunchSecurityRegressionTests public void Package_ids_cannot_be_paths(string id) => FluentActions.Invoking(() => LocalPackagePath.ValidateId(id)).Should().Throw(); + [Theory] + [InlineData("../other-workspace")] + [InlineData("/tmp/elsewhere")] + [InlineData("..")] + [InlineData("a/b")] + [InlineData("a\\b")] + [InlineData("C:\\users")] + public void Session_ids_cannot_be_paths(string sessionId) + { + var resolver = SharpClaw.Code.UnitTests.Support.TestRuntimeStorageResolver.Create(Path.GetTempPath()); + FluentActions.Invoking(() => resolver.GetSessionSnapshotPath(Path.GetTempPath(), sessionId)).Should().Throw(); + FluentActions.Invoking(() => resolver.GetCheckpointPath(Path.GetTempPath(), "session-1", sessionId)).Should().Throw(); + } + + [Fact] + public void Generated_session_ids_resolve_inside_the_sessions_root() + { + var resolver = SharpClaw.Code.UnitTests.Support.TestRuntimeStorageResolver.Create(Path.GetTempPath()); + var workspace = Path.GetTempPath(); + resolver.GetSessionSnapshotPath(workspace, $"session-{Guid.NewGuid():N}") + .Should().StartWith(resolver.GetSessionsRoot(workspace) + Path.DirectorySeparatorChar); + } + [Fact] public void Dangling_symlink_cannot_hide_an_outside_write() { @@ -42,6 +65,10 @@ public void Dangling_symlink_cannot_hide_an_outside_write() [InlineData("http://10.0.0.1/")] [InlineData("http://[::1]/")] [InlineData("http://[::ffff:127.0.0.1]/")] + [InlineData("http://192.0.2.10/")] + [InlineData("http://192.0.0.8/")] + [InlineData("http://[2002:c0a8:101::1]/")] + [InlineData("http://[2001:0:4136:e378::1]/")] [InlineData("file:///etc/passwd")] public async Task Web_fetch_rejects_private_destinations_before_sending(string url) { @@ -50,6 +77,25 @@ public async Task Web_fetch_rejects_private_destinations_before_sending(string u await FluentActions.Awaiting(() => service.FetchAsync(url, CancellationToken.None)).Should().ThrowAsync(); } + [Theory] + [InlineData("http://192.0.78.9/")] + [InlineData("http://93.184.215.14/")] + [InlineData("http://[2606:4700::1111]/")] + public async Task Web_fetch_allows_public_literal_destinations(string url) + { + using var client = new HttpClient(new AcceptNetwork()); + var service = new WebFetchService(client); + (await service.FetchAsync(url, CancellationToken.None)).Content.Should().Contain("ok"); + } + + [Fact] + public async Task Web_fetch_truncates_oversized_bodies() + { + using var client = new HttpClient(new AcceptNetwork(new string('a', WebFetchService.MaxBodyBytes + 4096))); + var service = new WebFetchService(client); + (await service.FetchAsync("http://192.0.78.9/", CancellationToken.None)).Content.Length.Should().BeLessThanOrEqualTo(WebFetchService.MaxBodyBytes); + } + [Fact] public async Task Web_fetch_revalidates_redirect_targets() { @@ -82,14 +128,55 @@ public async Task Cancelled_snapshot_replacement_keeps_previous_content_and_appe } [Fact] - public async Task Excessive_subprocess_output_is_stopped_and_reported() + public async Task Excessive_subprocess_output_is_bounded_and_keeps_head_and_tail() + { + if (OperatingSystem.IsWindows()) return; + var runner = new ProcessRunner(new SystemClock()); + var request = new SharpClaw.Code.Infrastructure.Models.ProcessRunRequest("/bin/sh", + ["-c", "echo FIRST; yes x | head -c 3000000; echo; echo LAST"], Path.GetTempPath(), null); + using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(20)); + + var result = await runner.RunAsync(request, deadline.Token); + + result.ExitCode.Should().Be(0); + result.StandardOutput.Length.Should().BeLessThan(ProcessRunner.MaxRetainedCharacters + 200); + result.StandardOutput.Should().StartWith("FIRST").And.Contain("characters of output omitted"); + result.StandardOutput.TrimEnd().Should().EndWith("LAST"); + } + + [Fact] + public async Task Atomic_rewrite_keeps_the_executable_bit() + { + if (OperatingSystem.IsWindows()) return; + var path = Path.Combine(Path.GetTempPath(), $"sharpclaw-mode-{Guid.NewGuid():N}.sh"); + try + { + await File.WriteAllTextAsync(path, "#!/bin/sh\necho one\n"); + var mode = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute | UnixFileMode.GroupRead | UnixFileMode.GroupExecute; + File.SetUnixFileMode(path, mode); + + await new LocalFileSystem().WriteAllTextAsync(path, "#!/bin/sh\necho two\n", CancellationToken.None); + + File.GetUnixFileMode(path).Should().Be(mode); + (await File.ReadAllTextAsync(path)).Should().Contain("two"); + } + finally { File.Delete(path); } + } + + [Fact] + public async Task Background_child_holding_the_pipe_does_not_block_completion() { if (OperatingSystem.IsWindows()) return; var runner = new ProcessRunner(new SystemClock()); var request = new SharpClaw.Code.Infrastructure.Models.ProcessRunRequest("/bin/sh", - ["-c", "yes x | head -c 1200000"], Path.GetTempPath(), null); - using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(10)); - await FluentActions.Awaiting(() => runner.RunAsync(request, deadline.Token)).Should().ThrowAsync().WithMessage("*output exceeded*"); + ["-c", "echo started; sleep 30 &"], Path.GetTempPath(), null, TimeSpan.FromSeconds(20)); + var stopwatch = System.Diagnostics.Stopwatch.StartNew(); + + var result = await runner.RunAsync(request, CancellationToken.None); + + stopwatch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(10)); + result.ExitCode.Should().Be(0); + result.StandardOutput.Should().Contain("started"); } private sealed class RejectNetwork : HttpMessageHandler @@ -98,6 +185,12 @@ protected override Task SendAsync(HttpRequestMessage reques => throw new InvalidOperationException("Private destinations must be rejected before HTTP."); } + private sealed class AcceptNetwork(string body = "ok") : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + => Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK) { Content = new StringContent(body) }); + } + private sealed class RedirectToMetadata : HttpMessageHandler { protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) diff --git a/tests/SharpClaw.Code.UnitTests/Tools/ToolRegistryAndExecutionTests.cs b/tests/SharpClaw.Code.UnitTests/Tools/ToolRegistryAndExecutionTests.cs index 3d1346a..137de34 100644 --- a/tests/SharpClaw.Code.UnitTests/Tools/ToolRegistryAndExecutionTests.cs +++ b/tests/SharpClaw.Code.UnitTests/Tools/ToolRegistryAndExecutionTests.cs @@ -123,6 +123,28 @@ await executor.ExecuteAsync( grepPayload!.Matches.Should().ContainSingle(match => match.Path == "docs/readme.md"); } + /// + /// Ensures grep treats CRLF line endings like LF: end anchors match and returned lines carry no carriage return. + /// + [Fact] + public async Task GrepSearch_should_match_line_end_anchors_in_crlf_files() + { + var workspacePath = CreateTemporaryWorkspace(); + await File.WriteAllTextAsync(Path.Combine(workspacePath, "windows.txt"), "alpha needle\r\nbeta\r\nneedle gamma\r\n"); + var executor = CreateExecutor(CreateRegistryWithStubShell()); + var context = CreateContext(workspacePath, PermissionMode.WorkspaceWrite); + + var grepResult = await executor.ExecuteAsync( + GrepSearchTool.ToolName, + JsonSerializer.Serialize(new GrepSearchToolArguments("needle$", null, 20, false)), + context, + CancellationToken.None); + + grepResult.Result.Succeeded.Should().BeTrue(); + var payload = JsonSerializer.Deserialize(grepResult.Result.StructuredOutputJson!, JsonOptions); + payload!.Matches.Should().ContainSingle().Which.Should().Be(new GrepSearchMatch("windows.txt", 1, "alpha needle")); + } + /// /// Ensures the executor rejects attempts to access files outside the workspace. /// From 700e6210547f52a87783eef6e4b898599e5db0a8 Mon Sep 17 00:00:00 2001 From: telli Date: Tue, 10 Nov 2026 03:46:49 -0800 Subject: [PATCH 03/12] Complete tool-only turns and align plugin ID validation - A turn that ran tools but ended without closing text no longer fails as an empty provider response (new tool_call_silent_finish parity scenario). - Plugin manifests must use the same ID rule as the package catalog, so an installed plugin can always be enabled, disabled, and removed. Co-Authored-By: Claude Opus 5.5 --- .../Internal/ProviderBackedAgentKernel.cs | 3 ++- .../Services/PluginManifestValidator.cs | 12 ++++++---- .../DeterministicMockModelProvider.cs | 8 +++++++ .../ParityProviderScenario.cs | 3 +++ .../ParityScenarioTests.cs | 23 +++++++++++++++++++ .../PluginManifestValidatorTests.cs | 17 ++++++++++++++ 6 files changed, 61 insertions(+), 5 deletions(-) diff --git a/src/SharpClaw.Code.Agents/Internal/ProviderBackedAgentKernel.cs b/src/SharpClaw.Code.Agents/Internal/ProviderBackedAgentKernel.cs index 50aea10..23d1dcb 100644 --- a/src/SharpClaw.Code.Agents/Internal/ProviderBackedAgentKernel.cs +++ b/src/SharpClaw.Code.Agents/Internal/ProviderBackedAgentKernel.cs @@ -406,7 +406,8 @@ internal async Task ExecuteAsync( } var output = string.Concat(outputSegments); - if (string.IsNullOrWhiteSpace(output)) + // A turn that ran tools may legitimately end without closing text; only a turn that produced nothing is a failure. + if (string.IsNullOrWhiteSpace(output) && allToolResults.Count == 0) { throw new ProviderExecutionException(activeProviderName, activeModel, ProviderFailureKind.StreamFailed, $"Provider '{activeProviderName}' returned an empty response."); diff --git a/src/SharpClaw.Code.Plugins/Services/PluginManifestValidator.cs b/src/SharpClaw.Code.Plugins/Services/PluginManifestValidator.cs index 801e622..8c16be7 100644 --- a/src/SharpClaw.Code.Plugins/Services/PluginManifestValidator.cs +++ b/src/SharpClaw.Code.Plugins/Services/PluginManifestValidator.cs @@ -1,4 +1,5 @@ using System.Text.Json; +using SharpClaw.Code.Infrastructure.Services; using SharpClaw.Code.Plugins.Models; using SharpClaw.Code.Protocol.Enums; @@ -29,12 +30,15 @@ public void Validate(PluginManifest manifest) throw new InvalidOperationException($"Plugin id length cannot exceed {MaxPluginIdLength} characters."); } - if (manifest.Id.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 - || manifest.Id.Contains('/', StringComparison.Ordinal) - || manifest.Id.Contains('\\', StringComparison.Ordinal)) + // Same rule the package catalog enforces on enable/disable/remove, so an installable plugin is always manageable. + try + { + LocalPackagePath.ValidateId(manifest.Id); + } + catch (ArgumentException) { throw new InvalidOperationException( - $"Plugin id '{manifest.Id}' contains characters that cannot be used as a local directory name."); + $"Plugin id '{manifest.Id}' must contain only letters, digits, dots, hyphens, and underscores."); } ArgumentException.ThrowIfNullOrWhiteSpace(manifest.Name); diff --git a/tests/SharpClaw.Code.MockProvider/DeterministicMockModelProvider.cs b/tests/SharpClaw.Code.MockProvider/DeterministicMockModelProvider.cs index 37c5fff..ea7dc06 100644 --- a/tests/SharpClaw.Code.MockProvider/DeterministicMockModelProvider.cs +++ b/tests/SharpClaw.Code.MockProvider/DeterministicMockModelProvider.cs @@ -89,6 +89,14 @@ private async IAsyncEnumerable StreamEventsAsync( yield return CreateTerminal(request, sequence: 2); } yield break; + case ParityProviderScenario.ToolCallSilentFinish: + if (!HasToolResultInMessages(request)) + { + yield return CreateToolUse(request, sequence: 1, "toolu_mock_002", "read_file", """{"path":"test.txt"}"""); + } + + yield return CreateTerminal(request, sequence: 2); + yield break; case ParityProviderScenario.StreamingText: default: yield return CreateDelta(request, sequence: 1, "Hello "); diff --git a/tests/SharpClaw.Code.MockProvider/ParityProviderScenario.cs b/tests/SharpClaw.Code.MockProvider/ParityProviderScenario.cs index 9b8d0d9..62420d6 100644 --- a/tests/SharpClaw.Code.MockProvider/ParityProviderScenario.cs +++ b/tests/SharpClaw.Code.MockProvider/ParityProviderScenario.cs @@ -25,4 +25,7 @@ public static class ParityProviderScenario /// second call (with tool results in messages) emits a text response. /// public const string ToolCallRoundtrip = "tool_call_roundtrip"; + + /// Calls a tool, then finishes the turn with no text after receiving its result. + public const string ToolCallSilentFinish = "tool_call_silent_finish"; } diff --git a/tests/SharpClaw.Code.ParityHarness/ParityScenarioTests.cs b/tests/SharpClaw.Code.ParityHarness/ParityScenarioTests.cs index 0ee88a6..15fd1c6 100644 --- a/tests/SharpClaw.Code.ParityHarness/ParityScenarioTests.cs +++ b/tests/SharpClaw.Code.ParityHarness/ParityScenarioTests.cs @@ -392,6 +392,29 @@ public async Task Tool_call_roundtrip_executes_loop_and_returns_final_text() turn.FinalOutput.Should().Contain("Tool result received"); } + [Fact] + public async Task Tool_call_followed_by_an_empty_final_message_completes_the_turn() + { + await File.WriteAllTextAsync(Path.Combine(_workspace, "test.txt"), "fixture-content"); + + using var provider = ParityTestHost.Create(replaceApprovals: null); + var runtime = ParityTestHost.GetConversation(provider); + var turn = await runtime.RunPromptAsync( + new RunPromptRequest( + Prompt: "tool then silence", + SessionId: null, + WorkingDirectory: _workspace, + PermissionMode.WorkspaceWrite, + OutputFormat.Text, + Metadata: new Dictionary + { + [ParityMetadataKeys.Scenario] = ParityProviderScenario.ToolCallSilentFinish, + }), + CancellationToken.None); + + turn.ToolResults.Should().ContainSingle(result => result.Succeeded); + } + /// /// Documents parity catalog entries for discoverability in test runners. /// diff --git a/tests/SharpClaw.Code.UnitTests/McpPlugins/PluginManifestValidatorTests.cs b/tests/SharpClaw.Code.UnitTests/McpPlugins/PluginManifestValidatorTests.cs index 4eda172..18e3c11 100644 --- a/tests/SharpClaw.Code.UnitTests/McpPlugins/PluginManifestValidatorTests.cs +++ b/tests/SharpClaw.Code.UnitTests/McpPlugins/PluginManifestValidatorTests.cs @@ -10,6 +10,23 @@ namespace SharpClaw.Code.UnitTests.McpPlugins; /// public sealed class PluginManifestValidatorTests { + /// + /// Ensures install accepts only IDs the package catalog can later enable, disable, and remove. + /// + [Theory] + [InlineData("my plugin", false)] + [InlineData("plugin@1", false)] + [InlineData("acme.tools-v2_beta", true)] + public void Validate_should_apply_the_catalog_id_rule(string id, bool valid) + { + var manifest = new PluginManifest(id, "Plugin", "1.0.0", null, "entry", null, null, [], PluginTrustLevel.Untrusted); + + var act = () => new PluginManifestValidator().Validate(manifest); + + if (valid) act.Should().NotThrow(); + else act.Should().Throw().Which.Message.Should().Contain("letters, digits"); + } + /// /// Ensures untrusted plugins cannot expose silent destructive tools. /// From d9eac2f499debfe8b9d007cb0f0cb7c464af7751 Mon Sep 17 00:00:00 2001 From: telli Date: Tue, 10 Nov 2026 03:50:43 -0800 Subject: [PATCH 04/12] Persist streamed deltas in one append per run Each provider delta previously cost a lock-file acquire, log open, tail check, and flush. Contiguous deltas now go through PublishRangeAsync -> PersistRangeAsync -> AppendRangeAsync -> AppendLinesAsync, one write per run. Default interface implementations keep other implementations unchanged; event content, order, buffer, and sink fan-out are identical. Co-Authored-By: Claude Opus 5.5 --- .../Abstractions/IFileSystem.cs | 14 +++ .../Services/LocalFileSystem.cs | 19 ++- .../Orchestration/ConversationRuntime.cs | 52 +++++--- .../Abstractions/IEventStore.cs | 15 +++ .../EventStoreRuntimeEventPersistence.cs | 4 + .../Storage/HostAwareEventStore.cs | 4 + .../Storage/NdjsonEventStore.cs | 12 ++ .../Abstractions/IRuntimeEventPersistence.cs | 15 +++ .../Abstractions/IRuntimeEventPublisher.cs | 15 +++ .../Services/RuntimeEventPublisher.cs | 115 ++++++++++++------ .../Telemetry/TelemetryPublisherTests.cs | 60 +++++++++ 11 files changed, 271 insertions(+), 54 deletions(-) diff --git a/src/SharpClaw.Code.Infrastructure/Abstractions/IFileSystem.cs b/src/SharpClaw.Code.Infrastructure/Abstractions/IFileSystem.cs index 0ab574b..7ed5a41 100644 --- a/src/SharpClaw.Code.Infrastructure/Abstractions/IFileSystem.cs +++ b/src/SharpClaw.Code.Infrastructure/Abstractions/IFileSystem.cs @@ -89,6 +89,20 @@ public interface IFileSystem /// The cancellation token. Task AppendLineAsync(string path, string line, CancellationToken cancellationToken); + /// + /// Appends several lines to a file in order. Implementations should take one append lock and flush once. + /// + /// The file path. + /// The lines to append. + /// The cancellation token. + async Task AppendLinesAsync(string path, IReadOnlyList lines, CancellationToken cancellationToken) + { + foreach (var line in lines) + { + await AppendLineAsync(path, line, cancellationToken).ConfigureAwait(false); + } + } + /// /// Deletes a directory and all of its contents if the directory exists. /// diff --git a/src/SharpClaw.Code.Infrastructure/Services/LocalFileSystem.cs b/src/SharpClaw.Code.Infrastructure/Services/LocalFileSystem.cs index c957163..0c92cd9 100644 --- a/src/SharpClaw.Code.Infrastructure/Services/LocalFileSystem.cs +++ b/src/SharpClaw.Code.Infrastructure/Services/LocalFileSystem.cs @@ -168,8 +168,17 @@ public async Task CopyFileAsync(string sourcePath, string destinationPath, Cance } /// - public async Task AppendLineAsync(string path, string line, CancellationToken cancellationToken) + public Task AppendLineAsync(string path, string line, CancellationToken cancellationToken) + => AppendLinesAsync(path, [line], cancellationToken); + + /// + public async Task AppendLinesAsync(string path, IReadOnlyList lines, CancellationToken cancellationToken) { + if (lines.Count == 0) + { + return; + } + var directory = Path.GetDirectoryName(path); if (!string.IsNullOrWhiteSpace(directory)) { @@ -194,7 +203,13 @@ public async Task AppendLineAsync(string path, string line, CancellationToken ca } } stream.Position = stream.Length; - var bytes = Encoding.UTF8.GetBytes(line + "\n"); + var builder = new StringBuilder(); + foreach (var line in lines) + { + builder.Append(line).Append('\n'); + } + + var bytes = Encoding.UTF8.GetBytes(builder.ToString()); await stream.WriteAsync(bytes, cancellationToken).ConfigureAwait(false); await stream.FlushAsync(cancellationToken).ConfigureAwait(false); } diff --git a/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs b/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs index 59e98b6..7e3d041 100644 --- a/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs +++ b/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs @@ -1347,29 +1347,27 @@ await AppendEventAsync( collectedEvents, cancellationToken).ConfigureAwait(false); + // Persist each run of streamed deltas in one append; a delta-per-write costs a lock, open, and flush per chunk. + var pendingDeltas = new List(); foreach (var providerEvent in turnRunResult.ProviderEvents ?? []) { if (!providerEvent.IsTerminal && !string.IsNullOrEmpty(providerEvent.Content)) { - await AppendEventAsync( - workspacePath, - sessionId, - new ProviderDeltaEvent( - EventId: CreateIdentifier("event"), - SessionId: sessionId, - TurnId: turnId, - OccurredAtUtc: providerEvent.CreatedAtUtc, - ProviderName: providerRequest.ProviderName, - Model: providerRequest.Model, - ProviderEventId: providerEvent.Id, - Kind: providerEvent.Kind, - Content: providerEvent.Content), - collectedEvents, - cancellationToken).ConfigureAwait(false); + pendingDeltas.Add(new ProviderDeltaEvent( + EventId: CreateIdentifier("event"), + SessionId: sessionId, + TurnId: turnId, + OccurredAtUtc: providerEvent.CreatedAtUtc, + ProviderName: providerRequest.ProviderName, + Model: providerRequest.Model, + ProviderEventId: providerEvent.Id, + Kind: providerEvent.Kind, + Content: providerEvent.Content)); } if (providerEvent.IsTerminal) { + await FlushDeltaEventsAsync(workspacePath, sessionId, pendingDeltas, collectedEvents, cancellationToken).ConfigureAwait(false); await AppendEventAsync( workspacePath, sessionId, @@ -1387,6 +1385,30 @@ await AppendEventAsync( cancellationToken).ConfigureAwait(false); } } + + await FlushDeltaEventsAsync(workspacePath, sessionId, pendingDeltas, collectedEvents, cancellationToken).ConfigureAwait(false); + } + + /// Publishes buffered delta events as one batch. Deltas never trigger hooks, so none are dispatched. + private async Task FlushDeltaEventsAsync(string workspacePath, string sessionId, List pendingDeltas, List collectedEvents, CancellationToken cancellationToken) + { + if (pendingDeltas.Count == 0) + { + return; + } + + await eventPublisher + .PublishRangeAsync( + pendingDeltas.ToArray(), + new RuntimeEventPublishOptions( + workspacePath, + sessionId, + PersistToSessionStore: true, + ThrowIfPersistenceFails: true), + cancellationToken) + .ConfigureAwait(false); + collectedEvents.AddRange(pendingDeltas); + pendingDeltas.Clear(); } private async Task EnsureRecoverableFromFailedForPromptAsync( diff --git a/src/SharpClaw.Code.Sessions/Abstractions/IEventStore.cs b/src/SharpClaw.Code.Sessions/Abstractions/IEventStore.cs index 6210289..69854bc 100644 --- a/src/SharpClaw.Code.Sessions/Abstractions/IEventStore.cs +++ b/src/SharpClaw.Code.Sessions/Abstractions/IEventStore.cs @@ -16,6 +16,21 @@ public interface IEventStore /// The cancellation token. Task AppendAsync(string workspacePath, string sessionId, RuntimeEvent runtimeEvent, CancellationToken cancellationToken); + /// + /// Appends several runtime events in order. Durable backends should write them in one operation. + /// + /// The workspace root path. + /// The session identifier. + /// The runtime events to append. + /// The cancellation token. + async Task AppendRangeAsync(string workspacePath, string sessionId, IReadOnlyList runtimeEvents, CancellationToken cancellationToken) + { + foreach (var runtimeEvent in runtimeEvents) + { + await AppendAsync(workspacePath, sessionId, runtimeEvent, cancellationToken).ConfigureAwait(false); + } + } + /// /// Reads all runtime events for a session. /// diff --git a/src/SharpClaw.Code.Sessions/Storage/EventStoreRuntimeEventPersistence.cs b/src/SharpClaw.Code.Sessions/Storage/EventStoreRuntimeEventPersistence.cs index 8239bad..15084ab 100644 --- a/src/SharpClaw.Code.Sessions/Storage/EventStoreRuntimeEventPersistence.cs +++ b/src/SharpClaw.Code.Sessions/Storage/EventStoreRuntimeEventPersistence.cs @@ -12,4 +12,8 @@ public sealed class EventStoreRuntimeEventPersistence(IEventStore eventStore) : /// public Task PersistAsync(string workspacePath, string sessionId, RuntimeEvent runtimeEvent, CancellationToken cancellationToken) => eventStore.AppendAsync(workspacePath, sessionId, runtimeEvent, cancellationToken); + + /// + public Task PersistRangeAsync(string workspacePath, string sessionId, IReadOnlyList runtimeEvents, CancellationToken cancellationToken) + => eventStore.AppendRangeAsync(workspacePath, sessionId, runtimeEvents, cancellationToken); } diff --git a/src/SharpClaw.Code.Sessions/Storage/HostAwareEventStore.cs b/src/SharpClaw.Code.Sessions/Storage/HostAwareEventStore.cs index e517530..e38e11a 100644 --- a/src/SharpClaw.Code.Sessions/Storage/HostAwareEventStore.cs +++ b/src/SharpClaw.Code.Sessions/Storage/HostAwareEventStore.cs @@ -18,6 +18,10 @@ public sealed class HostAwareEventStore( public Task AppendAsync(string workspacePath, string sessionId, RuntimeEvent runtimeEvent, CancellationToken cancellationToken) => ResolveStore().AppendAsync(workspacePath, sessionId, runtimeEvent, cancellationToken); + /// + public Task AppendRangeAsync(string workspacePath, string sessionId, IReadOnlyList runtimeEvents, CancellationToken cancellationToken) + => ResolveStore().AppendRangeAsync(workspacePath, sessionId, runtimeEvents, cancellationToken); + /// public Task> ReadAllAsync(string workspacePath, string sessionId, CancellationToken cancellationToken) => ResolveStore().ReadAllAsync(workspacePath, sessionId, cancellationToken); diff --git a/src/SharpClaw.Code.Sessions/Storage/NdjsonEventStore.cs b/src/SharpClaw.Code.Sessions/Storage/NdjsonEventStore.cs index c549a2f..c6c93f8 100644 --- a/src/SharpClaw.Code.Sessions/Storage/NdjsonEventStore.cs +++ b/src/SharpClaw.Code.Sessions/Storage/NdjsonEventStore.cs @@ -21,6 +21,18 @@ public Task AppendAsync(string workspacePath, string sessionId, RuntimeEvent run return fileSystem.AppendLineAsync(path, json, cancellationToken); } + /// + public Task AppendRangeAsync(string workspacePath, string sessionId, IReadOnlyList runtimeEvents, CancellationToken cancellationToken) + { + var lines = new string[runtimeEvents.Count]; + for (var index = 0; index < lines.Length; index++) + { + lines[index] = JsonSerializer.Serialize(runtimeEvents[index], ProtocolJsonContext.Default.RuntimeEvent); + } + + return fileSystem.AppendLinesAsync(storagePathResolver.GetEventsPath(workspacePath, sessionId), lines, cancellationToken); + } + /// public async Task> ReadAllAsync(string workspacePath, string sessionId, CancellationToken cancellationToken) { diff --git a/src/SharpClaw.Code.Telemetry/Abstractions/IRuntimeEventPersistence.cs b/src/SharpClaw.Code.Telemetry/Abstractions/IRuntimeEventPersistence.cs index ace9d0f..debc16b 100644 --- a/src/SharpClaw.Code.Telemetry/Abstractions/IRuntimeEventPersistence.cs +++ b/src/SharpClaw.Code.Telemetry/Abstractions/IRuntimeEventPersistence.cs @@ -16,4 +16,19 @@ public interface IRuntimeEventPersistence /// The event to append. /// The cancellation token. Task PersistAsync(string workspacePath, string sessionId, RuntimeEvent runtimeEvent, CancellationToken cancellationToken); + + /// + /// Persists several events in order, in one store operation where the backend supports it. + /// + /// The workspace root path. + /// The session identifier. + /// The events to append. + /// The cancellation token. + async Task PersistRangeAsync(string workspacePath, string sessionId, IReadOnlyList runtimeEvents, CancellationToken cancellationToken) + { + foreach (var runtimeEvent in runtimeEvents) + { + await PersistAsync(workspacePath, sessionId, runtimeEvent, cancellationToken).ConfigureAwait(false); + } + } } diff --git a/src/SharpClaw.Code.Telemetry/Abstractions/IRuntimeEventPublisher.cs b/src/SharpClaw.Code.Telemetry/Abstractions/IRuntimeEventPublisher.cs index a5ab6ff..5e2e869 100644 --- a/src/SharpClaw.Code.Telemetry/Abstractions/IRuntimeEventPublisher.cs +++ b/src/SharpClaw.Code.Telemetry/Abstractions/IRuntimeEventPublisher.cs @@ -15,6 +15,21 @@ public interface IRuntimeEventPublisher /// The cancellation token. ValueTask PublishAsync(RuntimeEvent runtimeEvent, RuntimeEventPublishOptions? options = null, CancellationToken cancellationToken = default); + /// + /// Publishes several events in order with the same routing. Implementations should persist them in one store operation; + /// observable results (ring buffer, usage, sink order) match publishing each event individually. + /// + /// The events to publish, in order. + /// Routing options shared by every event. + /// The cancellation token. + async ValueTask PublishRangeAsync(IReadOnlyList runtimeEvents, RuntimeEventPublishOptions? options = null, CancellationToken cancellationToken = default) + { + foreach (var runtimeEvent in runtimeEvents) + { + await PublishAsync(runtimeEvent, options, cancellationToken).ConfigureAwait(false); + } + } + /// /// Returns a snapshot of recent events retained in the in-process buffer (for export or debugging). /// diff --git a/src/SharpClaw.Code.Telemetry/Services/RuntimeEventPublisher.cs b/src/SharpClaw.Code.Telemetry/Services/RuntimeEventPublisher.cs index 2f50cad..0f9935e 100644 --- a/src/SharpClaw.Code.Telemetry/Services/RuntimeEventPublisher.cs +++ b/src/SharpClaw.Code.Telemetry/Services/RuntimeEventPublisher.cs @@ -48,41 +48,82 @@ public RuntimeEventPublisher( } /// - public async ValueTask PublishAsync( + public ValueTask PublishAsync( RuntimeEvent runtimeEvent, RuntimeEventPublishOptions? options = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(runtimeEvent); + return PublishRangeAsync([runtimeEvent], options, cancellationToken); + } + + /// + public async ValueTask PublishRangeAsync( + IReadOnlyList runtimeEvents, + RuntimeEventPublishOptions? options = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(runtimeEvents); + if (runtimeEvents.Count == 0) + { + return; + } + var routing = options ?? new RuntimeEventPublishOptions(); - AppendToBuffer(runtimeEvent); - if (runtimeEvent is UsageUpdatedEvent usageEvt) + foreach (var runtimeEvent in runtimeEvents) + { + ArgumentNullException.ThrowIfNull(runtimeEvent); + AppendToBuffer(runtimeEvent); + if (runtimeEvent is UsageUpdatedEvent usageEvt) + { + usageTracker.ApplyUsage(usageEvt.SessionId, usageEvt.Usage); + } + } + + await PersistAsync(runtimeEvents, routing, cancellationToken).ConfigureAwait(false); + + if (sinks.Length > 0) { - usageTracker.ApplyUsage(usageEvt.SessionId, usageEvt.Usage); + foreach (var runtimeEvent in runtimeEvents) + { + await PublishToSinksAsync(runtimeEvent, routing, cancellationToken).ConfigureAwait(false); + } } + } + private async Task PersistAsync(IReadOnlyList runtimeEvents, RuntimeEventPublishOptions routing, CancellationToken cancellationToken) + { if (routing.ShouldPersist && persistence is not null) { if (string.IsNullOrWhiteSpace(routing.WorkspacePath) || string.IsNullOrWhiteSpace(routing.SessionId)) { this.logger.LogWarning( "Runtime event {EventId} requested persistence but WorkspacePath or SessionId is null.", - runtimeEvent.EventId); + runtimeEvents[0].EventId); } else { try { - await persistence - .PersistAsync(routing.WorkspacePath, routing.SessionId, runtimeEvent, cancellationToken) - .ConfigureAwait(false); + if (runtimeEvents.Count == 1) + { + await persistence + .PersistAsync(routing.WorkspacePath, routing.SessionId, runtimeEvents[0], cancellationToken) + .ConfigureAwait(false); + } + else + { + await persistence + .PersistRangeAsync(routing.WorkspacePath, routing.SessionId, runtimeEvents, cancellationToken) + .ConfigureAwait(false); + } } catch (Exception exception) { this.logger.LogError( exception, "Failed to persist runtime event {EventId} for workspace {WorkspacePath} session {SessionId}.", - runtimeEvent.EventId, + runtimeEvents[0].EventId, routing.WorkspacePath, routing.SessionId); if (routing.ThrowIfPersistenceFails) @@ -96,38 +137,38 @@ await persistence { this.logger.LogDebug( "Runtime event {EventId} requested session persistence but no IRuntimeEventPersistence is registered.", - runtimeEvent.EventId); + runtimeEvents[0].EventId); } + } - if (sinks.Length > 0) + private async Task PublishToSinksAsync(RuntimeEvent runtimeEvent, RuntimeEventPublishOptions routing, CancellationToken cancellationToken) + { + var hostContext = routing.HostContext ?? hostContextAccessor?.Current; + var envelope = new RuntimeEventEnvelope( + EventType: runtimeEvent.GetType().Name, + OccurredAtUtc: runtimeEvent.OccurredAtUtc, + Event: runtimeEvent, + WorkspacePath: routing.WorkspacePath, + SessionId: routing.SessionId ?? runtimeEvent.SessionId, + TenantId: hostContext?.TenantId, + HostId: hostContext?.HostId); + foreach (var sink in sinks) { - var hostContext = routing.HostContext ?? hostContextAccessor?.Current; - var envelope = new RuntimeEventEnvelope( - EventType: runtimeEvent.GetType().Name, - OccurredAtUtc: runtimeEvent.OccurredAtUtc, - Event: runtimeEvent, - WorkspacePath: routing.WorkspacePath, - SessionId: routing.SessionId ?? runtimeEvent.SessionId, - TenantId: hostContext?.TenantId, - HostId: hostContext?.HostId); - foreach (var sink in sinks) + try { - try - { - await sink.PublishAsync(envelope, cancellationToken).ConfigureAwait(false); - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - throw; - } - catch (Exception exception) - { - logger.LogWarning( - exception, - "Runtime event {EventId} failed to publish to sink {SinkType}.", - runtimeEvent.EventId, - sink.GetType().Name); - } + await sink.PublishAsync(envelope, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (Exception exception) + { + logger.LogWarning( + exception, + "Runtime event {EventId} failed to publish to sink {SinkType}.", + runtimeEvent.EventId, + sink.GetType().Name); } } } diff --git a/tests/SharpClaw.Code.UnitTests/Telemetry/TelemetryPublisherTests.cs b/tests/SharpClaw.Code.UnitTests/Telemetry/TelemetryPublisherTests.cs index 5e04bc3..bd5085a 100644 --- a/tests/SharpClaw.Code.UnitTests/Telemetry/TelemetryPublisherTests.cs +++ b/tests/SharpClaw.Code.UnitTests/Telemetry/TelemetryPublisherTests.cs @@ -115,6 +115,66 @@ await publisher.PublishAsync( usageTracker.TryGetCumulative("s1")!.TotalTokens.Should().Be(5); } + /// + /// Ensures a batch persists in one store call while buffer and sink order match per-event publishing. + /// + [Fact] + public async Task RuntimeEventPublisher_should_persist_a_batch_once_and_fan_out_in_order() + { + var persistence = new RecordingPersistence(); + var sink = new RecordingSink(); + var publisher = new RuntimeEventPublisher( + Options.Create(new TelemetryOptions { RuntimeEventRingBufferCapacity = 100 }), + new UsageTracker(), + persistence: persistence, + sinks: [sink]); + var deltas = Enumerable.Range(1, 5) + .Select(index => (RuntimeEvent)new ProviderDeltaEvent($"e{index}", "s1", "t1", DateTimeOffset.UtcNow, "p", "m", $"p{index}", "text", $"chunk{index}")) + .ToArray(); + + await publisher.PublishRangeAsync(deltas, new RuntimeEventPublishOptions("/tmp/ws", "s1", PersistToSessionStore: true), CancellationToken.None); + + persistence.Calls.Should().ContainSingle().Which.Select(e => e.EventId).Should().Equal("e1", "e2", "e3", "e4", "e5"); + sink.Envelopes.Select(envelope => envelope.Event.EventId).Should().Equal("e1", "e2", "e3", "e4", "e5"); + publisher.GetRecentEventsSnapshot().Select(e => e.EventId).Should().Equal("e1", "e2", "e3", "e4", "e5"); + } + + /// + /// Ensures a batched append writes every line once and still repairs a torn trailing record. + /// + [Fact] + public async Task LocalFileSystem_batched_append_writes_all_lines_after_repairing_a_torn_tail() + { + var path = Path.Combine(Path.GetTempPath(), $"sharpclaw-batch-{Guid.NewGuid():N}.ndjson"); + try + { + await File.WriteAllTextAsync(path, "{\"ok\":1}\n{\"torn\":"); + var files = new SharpClaw.Code.Infrastructure.Services.LocalFileSystem(); + + await files.AppendLinesAsync(path, ["{\"a\":1}", "{\"b\":2}"], CancellationToken.None); + + (await File.ReadAllLinesAsync(path)).Should().Equal("{\"ok\":1}", "{\"a\":1}", "{\"b\":2}"); + } + finally { File.Delete(path); } + } + + private sealed class RecordingPersistence : SharpClaw.Code.Telemetry.Abstractions.IRuntimeEventPersistence + { + public List> Calls { get; } = []; + + public Task PersistAsync(string workspacePath, string sessionId, RuntimeEvent runtimeEvent, CancellationToken cancellationToken) + { + Calls.Add([runtimeEvent]); + return Task.CompletedTask; + } + + public Task PersistRangeAsync(string workspacePath, string sessionId, IReadOnlyList runtimeEvents, CancellationToken cancellationToken) + { + Calls.Add(runtimeEvents.ToArray()); + return Task.CompletedTask; + } + } + private sealed class ThrowingSink : SharpClaw.Code.Telemetry.Abstractions.IRuntimeEventSink { public Task PublishAsync(RuntimeEventEnvelope envelope, CancellationToken cancellationToken) From 6f0c55a829cbcbbafd528ca85f71c2c2e2c79e98 Mon Sep 17 00:00:00 2001 From: telli Date: Tue, 10 Nov 2026 03:53:13 -0800 Subject: [PATCH 05/12] Reparse SharpClaw config only when its text changes Config is loaded on every hook dispatch and by many commands; JSONC comments made each load throw from the source-generated parser and fall back to a reflection parse. Parsed documents are now cached per path and reused while the file text is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../Configuration/SharpClawConfigService.cs | 16 ++++++++++++++ .../Runtime/SharpClawConfigServiceTests.cs | 22 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/src/SharpClaw.Code.Runtime/Configuration/SharpClawConfigService.cs b/src/SharpClaw.Code.Runtime/Configuration/SharpClawConfigService.cs index 3057855..784c0f0 100644 --- a/src/SharpClaw.Code.Runtime/Configuration/SharpClawConfigService.cs +++ b/src/SharpClaw.Code.Runtime/Configuration/SharpClawConfigService.cs @@ -14,6 +14,8 @@ public sealed class SharpClawConfigService( IFileSystem fileSystem, IPathService pathService) : ISharpClawConfigService { + private readonly System.Collections.Concurrent.ConcurrentDictionary parsedDocuments = new(StringComparer.Ordinal); + private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true, @@ -63,6 +65,20 @@ public async Task GetConfigAsync(string workspaceRoot, return null; } + // Config is read on every hook dispatch and many commands; reparse only when the file text changes. + // JSONC comments make the source-generated parse throw, so an uncached read costs an exception plus a reflection parse. + if (parsedDocuments.TryGetValue(path, out var cached) && string.Equals(cached.Content, content, StringComparison.Ordinal)) + { + return cached.Document; + } + + var document = Parse(content); + parsedDocuments[path] = (content, document); + return document; + } + + private static SharpClawConfigDocument? Parse(string content) + { try { return JsonSerializer.Deserialize(content, ProtocolJsonContext.Default.SharpClawConfigDocument) diff --git a/tests/SharpClaw.Code.UnitTests/Runtime/SharpClawConfigServiceTests.cs b/tests/SharpClaw.Code.UnitTests/Runtime/SharpClawConfigServiceTests.cs index 6f9f091..3f65119 100644 --- a/tests/SharpClaw.Code.UnitTests/Runtime/SharpClawConfigServiceTests.cs +++ b/tests/SharpClaw.Code.UnitTests/Runtime/SharpClawConfigServiceTests.cs @@ -96,6 +96,28 @@ await File.WriteAllTextAsync( snapshot.Document.Agents.Should().Contain(agent => agent.Id == "shared-agent" && agent.Model == "gpt-workspace" && agent.Name == "Workspace Shared"); } + [Fact] + public async Task GetConfigAsync_reflects_workspace_edits_between_cached_reads() + { + var workspace = Path.Combine(tempRoot, "cached-workspace"); + Directory.CreateDirectory(Path.Combine(workspace, ".sharpclaw")); + Environment.SetEnvironmentVariable("HOME", Path.Combine(tempRoot, "empty-home")); + Environment.SetEnvironmentVariable("USERPROFILE", Path.Combine(tempRoot, "empty-home")); + Environment.SetEnvironmentVariable("APPDATA", Path.Combine(tempRoot, "empty-appdata")); + var configPath = Path.Combine(workspace, ".sharpclaw", "config.jsonc"); + var service = new SharpClawConfigService(new LocalFileSystem(), new PathService()); + + await File.WriteAllTextAsync(configPath, "{ // first\n \"defaultAgentId\": \"first\" }"); + (await service.GetConfigAsync(workspace, CancellationToken.None)).Document.DefaultAgentId.Should().Be("first"); + (await service.GetConfigAsync(workspace, CancellationToken.None)).Document.DefaultAgentId.Should().Be("first"); + + await File.WriteAllTextAsync(configPath, "{ // second\n \"defaultAgentId\": \"second\" }"); + (await service.GetConfigAsync(workspace, CancellationToken.None)).Document.DefaultAgentId.Should().Be("second"); + + File.Delete(configPath); + (await service.GetConfigAsync(workspace, CancellationToken.None)).WorkspaceConfigPath.Should().BeNull(); + } + public void Dispose() { Environment.SetEnvironmentVariable("HOME", originalHome); From 21cadc23f476a42ae3b3762f92a07d719936925b Mon Sep 17 00:00:00 2001 From: telli Date: Tue, 10 Nov 2026 03:56:00 -0800 Subject: [PATCH 06/12] Remove dead session layout, help handler, and context window code - SessionStorageLayout duplicated RuntimeStoragePathResolver without its tenant routing or the new ID validation; nothing referenced it. - HelpSlashCommandHandler was never registered; the REPL handles /help. - ContextWindowManager was referenced only by its own tests. - Tool output artifacts no longer double-wrap an already atomic write. Co-Authored-By: Claude Opus 5.5 --- docs/sessions.md | 4 +- .../Handlers/HelpSlashCommandHandler.cs | 37 ------ .../Context/ContextWindowManager.cs | 95 -------------- .../Storage/FileToolOutputArtifactStore.cs | 12 +- .../Storage/SessionStorageLayout.cs | 69 ----------- .../Runtime/ContextWindowManagerTests.cs | 117 ------------------ 6 files changed, 5 insertions(+), 329 deletions(-) delete mode 100644 src/SharpClaw.Code.Commands/Handlers/HelpSlashCommandHandler.cs delete mode 100644 src/SharpClaw.Code.Runtime/Context/ContextWindowManager.cs delete mode 100644 src/SharpClaw.Code.Sessions/Storage/SessionStorageLayout.cs delete mode 100644 tests/SharpClaw.Code.UnitTests/Runtime/ContextWindowManagerTests.cs diff --git a/docs/sessions.md b/docs/sessions.md index 035a298..7f71bf7 100644 --- a/docs/sessions.md +++ b/docs/sessions.md @@ -4,7 +4,7 @@ SharpClaw persists **per-workspace** conversation state under **`.sharpclaw/`** ## Layout -Defined in **`SessionStorageLayout`** (`src/SharpClaw.Code.Sessions/Storage/SessionStorageLayout.cs`): +Resolved by **`IRuntimeStoragePathResolver`** (`src/SharpClaw.Code.Infrastructure/Services/RuntimeStoragePathResolver.cs`), which also validates session and checkpoint IDs as single path segments. Embedded hosts with a storage root or tenant use a host-scoped root instead of `{workspace}/.sharpclaw`: | Path | Purpose | |------|---------| @@ -21,7 +21,7 @@ Creating a session ensures **`.sharpclaw`** exists (`ConversationRuntime.CreateS - **`ISessionStore`** — `SaveAsync`, `GetByIdAsync`, `GetLatestAsync`, `ListAllAsync` (implementation: **`FileSessionStore`**). - **`IMutationSetStore`** — durable **`MutationSetDocument`** payloads under **`mutations/`** (**`FileMutationSetStore`**). - **`IWorkspaceSessionAttachmentStore`** — reads/writes **`active-session.json`** (**`FileWorkspaceSessionAttachmentStore`**). -- **`IEventStore`** — `AppendAsync`, `ReadAllAsync` (implementation: **`NdjsonEventStore`**). +- **`IEventStore`** — `AppendAsync`, `AppendRangeAsync`, `ReadAllAsync` (implementations: **`NdjsonEventStore`**, **`SqliteEventStore`**, selected per host by **`HostAwareEventStore`**). - **`IRuntimeEventPersistence`** — bridges telemetry to the event store (**`EventStoreRuntimeEventPersistence`**). When **`IRuntimeEventPublisher.PublishAsync`** is called with **`RuntimeEventPublishOptions`** that request persistence (see **`ToolExecutor`** / runtime), events are appended to **`events.ndjson`** for the active session. diff --git a/src/SharpClaw.Code.Commands/Handlers/HelpSlashCommandHandler.cs b/src/SharpClaw.Code.Commands/Handlers/HelpSlashCommandHandler.cs deleted file mode 100644 index 2419c34..0000000 --- a/src/SharpClaw.Code.Commands/Handlers/HelpSlashCommandHandler.cs +++ /dev/null @@ -1,37 +0,0 @@ -using SharpClaw.Code.Commands.Models; -using SharpClaw.Code.Protocol.Commands; -using SharpClaw.Code.Protocol.Enums; - -namespace SharpClaw.Code.Commands; - -/// -/// Implements the REPL help slash command. -/// -public sealed class HelpSlashCommandHandler(ICommandRegistry commandRegistry, OutputRendererDispatcher outputRendererDispatcher) : ISlashCommandHandler -{ - /// - public string CommandName => "help"; - - /// - public string Description => "Lists available REPL slash commands."; - - /// - public async Task ExecuteAsync(SlashCommandParseResult command, CommandExecutionContext context, CancellationToken cancellationToken) - { - var message = string.Join(Environment.NewLine, commandRegistry - .GetSlashCommandHandlers() - .Select(handler => $"/{handler.CommandName} - {handler.Description}")); - - await outputRendererDispatcher.RenderCommandResultAsync( - new CommandResult( - Succeeded: true, - ExitCode: 0, - OutputFormat: context.OutputFormat, - Message: message, - DataJson: null), - context.OutputFormat, - cancellationToken); - - return 0; - } -} diff --git a/src/SharpClaw.Code.Runtime/Context/ContextWindowManager.cs b/src/SharpClaw.Code.Runtime/Context/ContextWindowManager.cs deleted file mode 100644 index d934446..0000000 --- a/src/SharpClaw.Code.Runtime/Context/ContextWindowManager.cs +++ /dev/null @@ -1,95 +0,0 @@ -using SharpClaw.Code.Protocol.Models; - -namespace SharpClaw.Code.Runtime.Context; - -/// -/// Trims conversation history to fit within a token budget using a simple -/// character-based token estimate (characters ÷ 4). -/// -public static class ContextWindowManager -{ - private const int CharsPerTokenEstimate = 4; - - /// - /// Returns a subset of that fits within - /// estimated tokens. - /// - /// Rules applied in priority order: - /// - /// The system message (role == "system") is always kept. - /// The most-recent non-system message is always kept. - /// Oldest non-system messages are dropped until the budget is satisfied. - /// - /// - /// The full conversation history to truncate. - /// The maximum number of estimated tokens to allow. - /// A (possibly shorter) ordered array of objects. - public static ChatMessage[] Truncate(IReadOnlyList messages, int maxTokenBudget) - { - ArgumentNullException.ThrowIfNull(messages); - if (maxTokenBudget <= 0) - { - throw new ArgumentOutOfRangeException(nameof(maxTokenBudget), "Token budget must be positive."); - } - - if (messages.Count == 0) - { - return []; - } - - // Fast path: everything fits already. - if (EstimateTokens(messages) <= maxTokenBudget) - { - return [.. messages]; - } - - // Separate the system message from the rest. - var systemMessage = messages.FirstOrDefault(m => - string.Equals(m.Role, "system", StringComparison.OrdinalIgnoreCase)); - - // Build a list of non-system messages with precomputed token estimates. - var working = messages - .Where(m => !string.Equals(m.Role, "system", StringComparison.OrdinalIgnoreCase)) - .ToList(); - - var systemTokens = systemMessage is not null ? EstimateTokens(systemMessage) : 0; - var runningTotal = working.Sum(EstimateTokens) + systemTokens; - - // Drop oldest messages until budget is satisfied (O(n) via running total). - // Always preserve at least the last message (most recent non-system turn). - var dropIndex = 0; - while (dropIndex < working.Count - 1 && runningTotal > maxTokenBudget) - { - runningTotal -= EstimateTokens(working[dropIndex]); - dropIndex++; - } - - if (dropIndex > 0) - { - working = working.GetRange(dropIndex, working.Count - dropIndex); - } - - // Reassemble with system message first (if present). - var result = new List(working.Count + 1); - if (systemMessage is not null) - { - result.Add(systemMessage); - } - - result.AddRange(working); - return [.. result]; - } - - private static int EstimateTokens(IEnumerable messages) - => messages.Sum(EstimateTokens); - - private static int EstimateTokens(ChatMessage message) - { - var charCount = message.Content.Sum(block => - (block.Text?.Length ?? 0) - + (block.ToolName?.Length ?? 0) - + (block.ToolInputJson?.Length ?? 0)); - - return (charCount + CharsPerTokenEstimate - 1) / CharsPerTokenEstimate; - } -} diff --git a/src/SharpClaw.Code.Sessions/Storage/FileToolOutputArtifactStore.cs b/src/SharpClaw.Code.Sessions/Storage/FileToolOutputArtifactStore.cs index 02c703d..8ba5836 100644 --- a/src/SharpClaw.Code.Sessions/Storage/FileToolOutputArtifactStore.cs +++ b/src/SharpClaw.Code.Sessions/Storage/FileToolOutputArtifactStore.cs @@ -14,16 +14,10 @@ public async Task SaveAsync(string workspace, string session { var artifact = new ToolOutputArtifact("artifact-" + Guid.NewGuid().ToString("N"), sessionId, turnId, toolName, DateTimeOffset.UtcNow, content); var path = Resolve(workspace, sessionId, artifact.Id); - var temporary = path + ".tmp"; files.CreateDirectory(Path.GetDirectoryName(path)!); - try - { - await files.WriteAllTextAsync(temporary, JsonSerializer.Serialize(artifact, ProtocolJsonContext.Default.ToolOutputArtifact), cancellationToken).ConfigureAwait(false); - cancellationToken.ThrowIfCancellationRequested(); - File.Move(temporary, path); - return artifact; - } - finally { files.TryDeleteFile(temporary); } + // IFileSystem.WriteAllTextAsync already writes through a same-directory temporary file and atomic replace. + await files.WriteAllTextAsync(path, JsonSerializer.Serialize(artifact, ProtocolJsonContext.Default.ToolOutputArtifact), cancellationToken).ConfigureAwait(false); + return artifact; } /// diff --git a/src/SharpClaw.Code.Sessions/Storage/SessionStorageLayout.cs b/src/SharpClaw.Code.Sessions/Storage/SessionStorageLayout.cs deleted file mode 100644 index 98519a0..0000000 --- a/src/SharpClaw.Code.Sessions/Storage/SessionStorageLayout.cs +++ /dev/null @@ -1,69 +0,0 @@ -using SharpClaw.Code.Infrastructure.Abstractions; - -namespace SharpClaw.Code.Sessions.Storage; - -/// -/// Builds local storage paths under the workspace .sharpclaw directory. -/// -public static class SessionStorageLayout -{ - /// Returns {workspace}/.sharpclaw. - public static string GetSharpClawRoot(IPathService pathService, string workspacePath) - => pathService.Combine(workspacePath, ".sharpclaw"); - - /// Returns the directory containing all session folders. - public static string GetSessionsRoot(IPathService pathService, string workspacePath) - => pathService.Combine(GetSharpClawRoot(pathService, workspacePath), "sessions"); - - /// Returns the root directory for a single session id. - public static string GetSessionRoot(IPathService pathService, string workspacePath, string sessionId) - => pathService.Combine(GetSessionsRoot(pathService, workspacePath), sessionId); - - /// Returns the durable session.json snapshot path. - public static string GetSessionSnapshotPath(IPathService pathService, string workspacePath, string sessionId) - => pathService.Combine(GetSessionRoot(pathService, workspacePath, sessionId), "session.json"); - - /// Returns the cross-process lock file path used to serialize turns for a session. - public static string GetSessionTurnLockPath(IPathService pathService, string workspacePath, string sessionId) - => pathService.Combine(GetSessionRoot(pathService, workspacePath, sessionId), ".turn.lock"); - - /// Returns the append-only NDJSON event log path. - public static string GetEventsPath(IPathService pathService, string workspacePath, string sessionId) - => pathService.Combine(GetSessionRoot(pathService, workspacePath, sessionId), "events.ndjson"); - - /// Returns the checkpoints directory for a session. - public static string GetCheckpointsRoot(IPathService pathService, string workspacePath, string sessionId) - => pathService.Combine(GetSessionRoot(pathService, workspacePath, sessionId), "checkpoints"); - - /// Returns a single checkpoint payload path. - public static string GetCheckpointPath(IPathService pathService, string workspacePath, string sessionId, string checkpointId) - => pathService.Combine(GetCheckpointsRoot(pathService, workspacePath, sessionId), $"{checkpointId}.json"); - - /// Returns the directory holding reversible mutation-set JSON documents. - public static string GetMutationsRoot(IPathService pathService, string workspacePath, string sessionId) - => pathService.Combine(GetSessionRoot(pathService, workspacePath, sessionId), "mutations"); - - /// Returns the path for one mutation set document (checkpoint-aligned id). - public static string GetMutationSetPath(IPathService pathService, string workspacePath, string sessionId, string mutationSetId) - => pathService.Combine(GetMutationsRoot(pathService, workspacePath, sessionId), $"{mutationSetId}.json"); - - /// Returns the workspace attachment pointer (active-session.json). - public static string GetWorkspaceActiveSessionPath(IPathService pathService, string workspacePath) - => pathService.Combine(GetSharpClawRoot(pathService, workspacePath), "active-session.json"); - - /// Returns the share snapshot directory. - public static string GetSharesRoot(IPathService pathService, string workspacePath) - => pathService.Combine(GetSharpClawRoot(pathService, workspacePath), "shares"); - - /// Returns a shared session snapshot payload path. - public static string GetShareSnapshotPath(IPathService pathService, string workspacePath, string shareId) - => pathService.Combine(GetSharesRoot(pathService, workspacePath), $"{shareId}.json"); - - /// Returns the workspace todo snapshot path. - public static string GetWorkspaceTodosPath(IPathService pathService, string workspacePath) - => pathService.Combine(GetSharpClawRoot(pathService, workspacePath), "tasks.json"); - - /// Returns the cross-process workspace todo lock path. - public static string GetWorkspaceTodosLockPath(IPathService pathService, string workspacePath) - => pathService.Combine(GetSharpClawRoot(pathService, workspacePath), ".tasks.lock"); -} diff --git a/tests/SharpClaw.Code.UnitTests/Runtime/ContextWindowManagerTests.cs b/tests/SharpClaw.Code.UnitTests/Runtime/ContextWindowManagerTests.cs deleted file mode 100644 index 8167e3f..0000000 --- a/tests/SharpClaw.Code.UnitTests/Runtime/ContextWindowManagerTests.cs +++ /dev/null @@ -1,117 +0,0 @@ -using FluentAssertions; -using SharpClaw.Code.Protocol.Models; -using SharpClaw.Code.Runtime.Context; - -namespace SharpClaw.Code.UnitTests.Runtime; - -/// -/// Verifies that correctly trims conversation history -/// to satisfy a token budget. -/// -public sealed class ContextWindowManagerTests -{ - // ── Helpers ───────────────────────────────────────────────────────────── - - private static ChatMessage UserMessage(string text) => - new("user", [new ContentBlock(ContentBlockKind.Text, text, null, null, null, null)]); - - private static ChatMessage AssistantMessage(string text) => - new("assistant", [new ContentBlock(ContentBlockKind.Text, text, null, null, null, null)]); - - private static ChatMessage SystemMessage(string text) => - new("system", [new ContentBlock(ContentBlockKind.Text, text, null, null, null, null)]); - - // ── Tests ──────────────────────────────────────────────────────────────── - - [Fact] - public void Returns_all_when_within_budget() - { - var messages = new ChatMessage[] - { - UserMessage("Hello"), - AssistantMessage("Hi there"), - UserMessage("How are you?"), - AssistantMessage("I am well."), - }; - - // Budget is very generous — all messages should be returned. - var result = ContextWindowManager.Truncate(messages, 10_000); - - result.Should().HaveCount(4); - } - - [Fact] - public void Truncates_oldest_messages_when_over_budget() - { - // Each message has ~400 chars → ~100 tokens. - // 10 messages → ~1000 tokens total. Budget: 500 tokens → expect roughly half. - var filler = new string('x', 400); - var messages = Enumerable.Range(0, 10) - .Select(i => i % 2 == 0 ? UserMessage($"{i}: {filler}") : AssistantMessage($"{i}: {filler}")) - .ToArray(); - - var result = ContextWindowManager.Truncate(messages, 500); - - // Should keep fewer messages than the original. - result.Length.Should().BeLessThan(messages.Length); - - // The most recent message must be present. - result[^1].Should().Be(messages[^1]); - } - - [Fact] - public void Always_keeps_system_message() - { - var systemMsg = SystemMessage("You are a helpful assistant."); - var filler = new string('x', 2000); // ~500 tokens each - - var messages = new ChatMessage[] - { - systemMsg, - UserMessage(filler), - AssistantMessage(filler), - UserMessage(filler), - AssistantMessage(filler), - }; - - // Very tight budget — only slightly above system message cost. - var systemTokens = systemMsg.Content.Sum(b => (b.Text?.Length ?? 0)) / 4; - var budget = systemTokens + 10; // small extra room - - var result = ContextWindowManager.Truncate(messages, budget); - - result.Should().Contain(m => m.Role == "system"); - } - - [Fact] - public void Always_keeps_most_recent_message_even_under_extreme_budget() - { - var messages = new ChatMessage[] - { - UserMessage(new string('a', 4000)), - AssistantMessage(new string('b', 4000)), - UserMessage("final question"), - }; - - // Budget too small for anything substantial. - var result = ContextWindowManager.Truncate(messages, 1); - - result.Should().NotBeEmpty(); - result[^1].Should().Be(messages[^1]); - } - - [Fact] - public void Returns_empty_for_empty_input() - { - var result = ContextWindowManager.Truncate([], 1000); - - result.Should().BeEmpty(); - } - - [Fact] - public void Throws_for_non_positive_budget() - { - var act = () => ContextWindowManager.Truncate([UserMessage("hi")], 0); - act.Should().Throw(); - } -} From 881082b440e6a2916d020b662b06fd774cbc52ec Mon Sep 17 00:00:00 2001 From: telli Date: Tue, 10 Nov 2026 04:00:04 -0800 Subject: [PATCH 07/12] Test HTTP clamps and CLI scheduler removal; correct docs - New tests: HTTP prompt JSON cannot raise the host permission mode or leave host-selected Research mode (mutation-checked); CLI host registers no ScheduledPromptRunner. - Launch findings review no longer claims automated PTY or JSON-envelope tests, and lists what remains untested. - Document the server token in runtime.md, argument-scoped approval memory, the real /v1/admin/events/stream route, and the fixed McpDoctor backlog item. Co-Authored-By: Claude Opus 5.5 --- ARCHITECTURE-NOTES.md | 2 +- CLAUDE.md | 1 - README.md | 2 +- docs/launch-findings-review.md | 16 +++--- docs/permissions.md | 2 +- docs/runtime.md | 5 +- .../Runtime/WorkspaceHttpServerAdminTests.cs | 50 +++++++++++++++++++ .../Smoke/CliHostBuilderTests.cs | 12 +++++ 8 files changed, 78 insertions(+), 12 deletions(-) diff --git a/ARCHITECTURE-NOTES.md b/ARCHITECTURE-NOTES.md index 7d2fee2..6d60a43 100644 --- a/ARCHITECTURE-NOTES.md +++ b/ARCHITECTURE-NOTES.md @@ -8,7 +8,7 @@ High-effort or cross-cutting items identified during review. Low/medium fixes ar ## Stable JSON for MCP diagnostics -- **TODO:** `McpDoctorService` builds `DataJson` with anonymous objects and reflection-based `JsonSerializer.Serialize`. Align with `ProtocolJsonContext` by introducing explicit DTOs (for example `McpWorkspaceStatusReport`, `McpDoctorReport`) in `SharpClaw.Code.Protocol` and source-generated serialization, similar to operational reports. +- **Done:** `McpDoctorService` serializes typed payloads through its source-generated `McpDoctorJsonContext`. ## Plugin manifest parsing diff --git a/CLAUDE.md b/CLAUDE.md index cac9913..0e98803 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -79,7 +79,6 @@ Mock provider scenarios: `streaming_text`, `stream_failure`, `stream_slow`, `rea ## Known Backlog (ARCHITECTURE-NOTES.md) - Commands project directly references Mcp/Plugins (should go through abstractions) -- `McpDoctorService` uses anonymous objects instead of typed DTOs for JSON - Plugin manifest parsing uses `JsonSerializerDefaults.Web` instead of `ProtocolJsonContext` - Telemetry sinks not yet wired for production (OpenTelemetry, file traces) - Runtime directly references Agents (acceptable for now, seam needed if multiple backends appear) diff --git a/README.md b/README.md index ba1c1a4..b575a49 100644 --- a/README.md +++ b/README.md @@ -314,7 +314,7 @@ All options are validated at startup via `IValidateOptions` implementations. - Operational commands support stable JSON output via `--output-format json`, which makes them suitable for scripts, editors, and automation. - Every embedded HTTP endpoint requires a host secret: set `SHARPCLAW_SERVER_TOKEN` to at least 32 non-whitespace characters. Send it as `Authorization: Bearer `, or use `X-SharpClaw-Server-Token` when `Authorization` carries a separate OIDC approval identity. Browser Origin requests and unexpected Host values are rejected. Share links also require authentication. - HTTP requests cannot raise the host permission mode or select tenant/storage roots. Hosts bind identity and storage through `RuntimeCommandContext.HostContext`. -- `/v1/events/stream` streams runtime envelopes. `/v1/prompt` SSE replays buffered turn events after completion; ACP currently sends final assistant text. Neither promises incremental model-token delivery. +- `/v1/admin/events/stream` streams runtime envelopes. `/v1/prompt` SSE replays buffered turn events after completion; ACP currently sends final assistant text. Neither promises incremental model-token delivery. - See [launch findings review](docs/launch-findings-review.md) for fixes, evidence, and remaining limitations. ## Contributing diff --git a/docs/launch-findings-review.md b/docs/launch-findings-review.md index b5ee2b3..0b9c508 100644 --- a/docs/launch-findings-review.md +++ b/docs/launch-findings-review.md @@ -13,7 +13,7 @@ Reviewed against the working tree on November 5, 2026. The supplied report ident | Permission rules bypass the mode | Valid. Mode restrictions and all deny rules win before any approval. Invalid runtime mode enums are denied. Non-rememberable security rules cannot consume scope auto-approval. | | `RequiresApproval` ignored | Valid. Enforced outside explicitly selected DangerFullAccess. Existing noninteractive write fixtures now supply file approval or a scripted approver. | | Broad, opaque remembered approvals | Valid. Prompts include tool, working directory, and exact arguments. Memory keys include arguments, and expired approvals are ignored. Authenticated hosts revalidate each approval before any memory/auto-approval shortcut, closing an additional tenant-identity bypass found during testing. | -| `web_fetch` SSRF | Valid. Uses network approval scope. Production HTTP connections validate and pin public DNS answers, disable proxy routing, validate redirects, and block private/loopback/link-local destinations. Supported schemes are HTTP(S), without URL credentials. | +| `web_fetch` SSRF | Valid. Uses network approval scope. Production HTTP connections validate and pin public DNS answers, disable proxy routing, validate redirects, and block private, loopback, link-local, documentation (TEST-NET, 2001:db8::/32), and IPv4-embedding transition (6to4, Teredo) destinations, while public 192.0.x hosts remain reachable. Supported schemes are HTTP(S), without URL credentials. Response bodies are read up to 5 MiB. | | Plugin/skill path traversal | Valid. Package IDs reject path syntax on all platforms, canonical package directories must remain in the catalog, and workspace-local catalogs cannot resolve outside the workspace through links. | | Dangling link write escape | Valid. Canonicalization resolves link targets even when the destination does not exist, with a link-depth limit. | | HTTP tenant/storage header injection and event leakage | Valid. Identity and storage routing come from the host context, not request headers or JSON. Event filtering always compares tenant IDs, including the absence of a tenant. | @@ -27,8 +27,8 @@ Reviewed against the working tree on November 5, 2026. The supplied report ident | H2: ordinary `@` text becomes missing files | Valid for the supplied examples. Email boundaries are respected; nonexistent ordinary mentions remain literal, while existing extensionless files/directories still expand and explicit relative/absolute missing references retain diagnostics. Text references have a 200 KiB limit. | | H3: whitespace stream chunks dropped | Valid. Both agent output assembly and persisted provider delta events preserve whitespace-only chunks. | | H4: retired Anthropic default | Valid. Default changed to `claude-sonnet-5-5`, an active model in the [Anthropic lifecycle documentation](https://platform.claude.com/docs/en/about-claude/model-deprecations). Custom model aliases remain under host control. | -| H5: Ctrl+C terminates REPL | Valid at CLI composition. The REPL already has turn controls, but starting ConsoleLifetime also canceled its lifetime. CLI commands now own their lifetime. A pseudo-terminal smoke test cancels a blocked local mock-provider request, verifies the REPL remains alive, then exits normally. | -| H6: stack traces, broken JSON errors, slash failures | Valid. CLI invocation disables the default exception printer and emits the selected error envelope, including parser/option errors. Slash-command exceptions are contained by the REPL. Five direct JSON error cases cover bad modes, auto-approval, session, and working directory. | +| H5: Ctrl+C terminates REPL | Valid at CLI composition. The REPL already has turn controls, but starting ConsoleLifetime also canceled its lifetime. CLI commands now own their lifetime. This was checked manually with a pseudo-terminal against a blocked local mock-provider request; there is no automated regression test. | +| H6: stack traces, broken JSON errors, slash failures | Valid. CLI invocation disables the default exception printer and emits the selected error envelope, including parser/option errors. Slash-command exceptions are contained by the REPL. The JSON envelope cases were checked manually; automated coverage is limited to invalid-mode rejection. | | H7: invalid modes become permissive defaults | Valid. Unknown permission, primary, output, and store modes raise explicit errors. | | H8: OpenAI finish reason drops tool calls | Early termination is confirmed; the report's claim about every live tool call was not proven. Adapter now drains later tool and usage updates and rejects length/content-filter termination. A regression stream puts the function call and usage after the finish reason. No paid/live API request was made. | | H9: main-agent outbound MCP calls absent | Valid for workspace registrations. Documentation now states lifecycle/discovery support only. Inbound MCP tool serving and the direct Parallel Search example do execute tools; they are separate paths. Main-agent outbound tool invocation remains unimplemented. | @@ -42,7 +42,7 @@ Reviewed against the working tree on November 5, 2026. The supplied report ident | CLI overrides agent/saved primary modes | Valid. Omitted primary mode remains unspecified at the runtime boundary; saved session mode wins over agent defaults on resume. | | Anthropic token accounting absent | Valid. Message-start and cumulative delta usage are recorded, including cache-read and cache-creation input. Providers that omit usage still use the existing approximate fallback. | | Provider stop reason ignored | Valid. Anthropic tool calls are buffered until a successful message stop; truncated, interrupted, or unsupported continuation responses fail without releasing tools. OpenAI length/content-filter responses also fail. | -| Empty responses create fake replies | Valid. Empty provider responses now fail explicitly; the unused placeholder helper was removed. | +| Empty responses create fake replies | Valid. A turn that produced neither text nor tool results now fails explicitly; a turn that ran tools and ended without closing text completes. The unused placeholder helper was removed. | | Circuit breaker reset by failed events | Valid. Failed events count as failures, with authentication classification retained. Regression verifies a 429 failed event opens the circuit. | | Session saved before turn lock | Valid. Preference writes happen after the mutex, cross-process lock, and snapshot reload. | | Undo/redo cancellation strands edits | Valid. Cancellation is accepted before mutation begins; once application starts, the operation finishes and saves its state despite caller cancellation. Filesystem failure or process death still requires the existing recovery mechanisms; this is not a filesystem transaction. | @@ -51,16 +51,18 @@ Reviewed against the working tree on November 5, 2026. The supplied report ident | MCP cancellation leaves Starting | Valid. Interrupted startup persists Faulted using a cleanup token and disposes a newly established session if needed. Stop checks cancellation before removing the tracked client. | | ACP ignores cancel notifications | Valid for notifications without IDs. A spec-shaped `session/cancel` notification (only `sessionId`, optional `cwd`) cancels that session's live-controlled prompts on the connection, without a JSON-RPC response. Prompts that did not opt into `liveTurnControl` are not tracked and cannot yet be cancelled this way. Request-form cancels keep their `promptRequestId` targeting. | | Every CLI command starts scheduler | Valid. CLI bootstrap removes the scheduler hosted service and no longer starts the host implicitly. Embedded-host scheduling remains available; explicit schedule commands retain their own workspace context. | -| Bash lacks bounds and denylist misses variants | Valid. Shared process execution defaults to two minutes and one MiB characters per output stream, kills on failure/cancellation, and observes reader tasks. Verification explicitly retains its configured deadline. Recursive-rm flag permutations and find deletion/execution patterns receive a non-auto-approvable gate. These patterns are not a complete shell sandbox. | +| Bash lacks bounds and denylist misses variants | Valid. Process execution defaults to a two-minute deadline; agent shell commands get ten minutes and external agents thirty. Each output stream retains at most one MiB characters (head and tail, with an omission marker) instead of failing, and a background child that keeps the pipe open no longer blocks completion. Processes are killed on failure or cancellation. Recursive `rm` in any flag form (`-r`, `-rf`, `-Rf`, `-f -r`, `--recursive`) and `find` delete/exec actions receive a non-auto-approvable gate. These patterns are not a complete shell sandbox. | ## Performance and feature limits - Fixed: Anthropic client reuse; Anthropic automatic cache control; private SQLite caches with WAL and busy timeout; generated/dependency-directory pruning and link avoidance in grep/glob; reusable bounded glob regexes; grep regex timeout, binary detection, and large-file exclusion; read-file and text-reference size limits. - Still valid and open: webhook deliveries block their publishing call; hook configuration is reread for lifecycle events; event appends reopen the log; source traversal does not implement full `.gitignore` semantics. -- Prompt SSE currently replays events after execution, and ACP sends final assistant text. `/v1/events/stream` does stream runtime envelopes. Documentation now distinguishes these behaviors; incremental model-token delivery remains a larger provider/fallback orchestration change. +- Prompt SSE currently replays events after execution, and ACP sends final assistant text. `/v1/admin/events/stream` does stream runtime envelopes. Documentation now distinguishes these behaviors; incremental model-token delivery remains a larger provider/fallback orchestration change. - No benchmark establishes the report's exact latency or cost multipliers. The existing fallback character-based token estimate is still approximate when a provider omits usage. - Main-agent outbound MCP calls are deliberately not advertised as implemented. Adding them requires tool discovery, namespacing, permission-aware invocation, and lifecycle tests, rather than only exposing the SDK client. ## Validation -Validation results are recorded in the delivery message. Regression coverage includes actual SQLite FTS, dangling links, path IDs, private HTTP destinations and redirects, permission-mode precedence, exact approval arguments, post-finish tool calls, Anthropic usage/truncation, circuit-breaker failures, HTTP authentication/Origin/Host checks, tenant identity, snapshot replacement, torn log repair, and bounded process output. Direct CLI smoke checks use a temporary workspace and local mock provider with a fake API key. No production provider key was sent in those checks. +Regression coverage includes actual SQLite FTS, dangling links, path and session IDs, private and public HTTP destinations and redirects, bounded fetch bodies, permission-mode precedence, recursive-delete variants, exact approval arguments, post-finish tool calls, tool-only turns, Anthropic usage/truncation, circuit-breaker failures, HTTP authentication/Origin checks, HTTP prompt permission and primary-mode clamping, tenant identity, custom-command mode preservation, CLI scheduler removal, spec-shaped ACP cancel notifications, snapshot replacement with preserved file modes, torn log repair, batched event appends, and bounded process output. + +Not covered by automated tests: the Ctrl+C REPL behavior and CLI JSON error envelopes (checked manually), the Host-header rejection (the loopback listener rejects foreign hosts itself, so the application check is defense in depth for wildcard prefixes), MCP Faulted-on-cancel, undo/redo under cancellation, and the two-minute default deadline. Direct CLI smoke checks used a temporary workspace and local mock provider with a fake API key. No production provider key was sent. diff --git a/docs/permissions.md b/docs/permissions.md index 8d4c0e3..ce483d1 100644 --- a/docs/permissions.md +++ b/docs/permissions.md @@ -80,7 +80,7 @@ Authenticated approvals are tenant-bound. If the runtime host context carries `T ### Remembered approvals -**`ISessionApprovalMemory`** (**`SessionApprovalMemory`**) stores **approved** decisions in a **process-scoped** dictionary keyed by **`sessionId`** and a composite key (**tool name, scope, source, working directory, originating plugin id/trust**). +**`ISessionApprovalMemory`** (**`SessionApprovalMemory`**) stores **approved** decisions in a **process-scoped** dictionary keyed by **`sessionId`** and a composite key (**tool name, scope, source, working directory, originating plugin id/trust, and the exact tool arguments**). Expired entries are ignored, and authenticated hosts revalidate every approval instead of reusing memory. When a rule returns **`RequireApproval`** with **`CanRememberApproval`**, an approved outcome may be **`Store`**d and reused via **`TryGet`**. In embedded-host flows, the remembered approval remains scoped to the current session and tenant context. diff --git a/docs/runtime.md b/docs/runtime.md index b4eee56..29cff94 100644 --- a/docs/runtime.md +++ b/docs/runtime.md @@ -122,7 +122,10 @@ These services are intentionally small and runtime-owned rather than separate or ## Embedded server -**`IWorkspaceHttpServer`** / **`WorkspaceHttpServer`** expose a minimal local HTTP surface for editor and automation clients: +**`IWorkspaceHttpServer`** / **`WorkspaceHttpServer`** expose a minimal local HTTP surface for editor and automation clients. + +The server refuses to start unless `SHARPCLAW_SERVER_TOKEN` holds a secret of at least 32 non-whitespace characters, and every endpoint (including `/s/{shareId}`) requires it as `Authorization: Bearer ` or `X-SharpClaw-Server-Token: `. Use the header form when `Authorization` carries an OIDC approval identity. Requests with an `Origin` header or an unexpected `Host` are rejected. Request JSON cannot raise the host's permission mode or leave a host-selected Plan/Research mode, and session IDs must be single path segments. + - `POST /v1/prompt` - `GET /v1/sessions` diff --git a/tests/SharpClaw.Code.IntegrationTests/Runtime/WorkspaceHttpServerAdminTests.cs b/tests/SharpClaw.Code.IntegrationTests/Runtime/WorkspaceHttpServerAdminTests.cs index 823880a..ade29d3 100644 --- a/tests/SharpClaw.Code.IntegrationTests/Runtime/WorkspaceHttpServerAdminTests.cs +++ b/tests/SharpClaw.Code.IntegrationTests/Runtime/WorkspaceHttpServerAdminTests.cs @@ -168,6 +168,56 @@ await httpClient.GetStringAsync("v1/admin/events/recent"), } } + /// + /// Ensures prompt JSON cannot raise the host's permission mode or leave a host-selected research mode. + /// + [Fact] + public async Task Prompt_requests_cannot_raise_host_permission_or_primary_mode() + { + Environment.SetEnvironmentVariable("SHARPCLAW_SERVER_TOKEN", "integration-test-server-token-32-characters"); + var workspaceRoot = CreateTemporaryWorkspace(); + var services = new ServiceCollection(); + services.AddSharpClawRuntime(); + services.AddDeterministicMockModelProvider(); + using var serviceProvider = services.BuildServiceProvider(); + var server = serviceProvider.GetRequiredService(); + var port = FindFreePort(); + using var serverCts = new CancellationTokenSource(); + var serverTask = server.RunAsync( + workspaceRoot, + "127.0.0.1", + port, + new RuntimeCommandContext( + WorkingDirectory: workspaceRoot, + Model: "default", + PermissionMode: PermissionMode.ReadOnly, + OutputFormat: OutputFormat.Json, + PrimaryMode: PrimaryMode.Research), + serverCts.Token); + + try + { + using var httpClient = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{port}/"), Timeout = TimeSpan.FromSeconds(10) }; + httpClient.DefaultRequestHeaders.Add("X-SharpClaw-Server-Token", "integration-test-server-token-32-characters"); + await WaitForServerAsync(httpClient, CancellationToken.None); + + using var promptResponse = await httpClient.PostAsync( + "v1/prompt", + new StringContent("""{"prompt":"escalate","model":"default","permissionMode":"dangerFullAccess","primaryMode":"build"}""", Encoding.UTF8, "application/json"), + CancellationToken.None); + promptResponse.EnsureSuccessStatusCode(); + var result = JsonSerializer.Deserialize(await promptResponse.Content.ReadAsStringAsync(), ProtocolJsonContext.Default.TurnExecutionResult)!; + + result.Session.PermissionMode.Should().Be(PermissionMode.ReadOnly); + result.Session.Metadata![SharpClawWorkflowMetadataKeys.PrimaryMode].Should().BeEquivalentTo(nameof(PrimaryMode.Research)); + } + finally + { + serverCts.Cancel(); + await serverTask; + } + } + private static async Task WaitForServerAsync(HttpClient httpClient, CancellationToken cancellationToken) { var attempts = 0; diff --git a/tests/SharpClaw.Code.IntegrationTests/Smoke/CliHostBuilderTests.cs b/tests/SharpClaw.Code.IntegrationTests/Smoke/CliHostBuilderTests.cs index 3af33b1..6260957 100644 --- a/tests/SharpClaw.Code.IntegrationTests/Smoke/CliHostBuilderTests.cs +++ b/tests/SharpClaw.Code.IntegrationTests/Smoke/CliHostBuilderTests.cs @@ -23,4 +23,16 @@ public async Task BuildHost_should_register_cli_command_factory() rootCommand.Description.Should().Be("SharpClaw Code CLI. Starts interactive mode when no command is supplied."); } + + /// + /// Ensures ordinary CLI invocations never start the background prompt scheduler. + /// + [Fact] + public void BuildHost_should_not_register_the_scheduled_prompt_runner() + { + using var host = CliHostBuilder.BuildHost(); + + host.Services.GetServices() + .Should().NotContain(service => service is SharpClaw.Code.Runtime.Workflow.ScheduledPromptRunner); + } } From 749dfdff1106c09de084348a4719fc9626e4a6c6 Mon Sep 17 00:00:00 2001 From: telli Date: Tue, 10 Nov 2026 04:02:37 -0800 Subject: [PATCH 08/12] Drop unused Agent Framework package references from Runtime No Runtime source uses Microsoft.Agents.AI or Microsoft.Extensions.AI.OpenAI; both still flow transitively through SharpClaw.Code.Agents and Providers. Co-Authored-By: Claude Opus 5.5 --- src/SharpClaw.Code.Runtime/SharpClaw.Code.Runtime.csproj | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/SharpClaw.Code.Runtime/SharpClaw.Code.Runtime.csproj b/src/SharpClaw.Code.Runtime/SharpClaw.Code.Runtime.csproj index 9af0e15..37e8049 100644 --- a/src/SharpClaw.Code.Runtime/SharpClaw.Code.Runtime.csproj +++ b/src/SharpClaw.Code.Runtime/SharpClaw.Code.Runtime.csproj @@ -1,12 +1,10 @@ - Production runtime orchestration for SharpClaw Code agents, built on Microsoft Agent Framework. + Production runtime orchestration for SharpClaw Code agents; agent execution uses Microsoft Agent Framework through SharpClaw.Code.Agents. - - From ed90940d49b571d4d62cc93e988c3d64255d0454 Mon Sep 17 00:00:00 2001 From: telli Date: Tue, 10 Nov 2026 04:56:07 -0800 Subject: [PATCH 09/12] Extract SessionTurnLock from ConversationRuntime RunPromptAsync and ExecuteWithSessionLockAsync each implemented the in-process mutex plus cross-process lock file inline; RunPromptAsync's copy had left half its body un-indented inside the try. Both now use SessionTurnLock, with the same acquisition and release order. The mutex table stays process-wide. Co-Authored-By: Claude Opus 5.5 --- .../RuntimeServiceCollectionExtensions.cs | 1 + .../Orchestration/ConversationRuntime.cs | 68 ++++----------- .../Orchestration/SessionTurnLock.cs | 86 +++++++++++++++++++ .../Runtime/SessionTurnLockTests.cs | 65 ++++++++++++++ 4 files changed, 168 insertions(+), 52 deletions(-) create mode 100644 src/SharpClaw.Code.Runtime/Orchestration/SessionTurnLock.cs create mode 100644 tests/SharpClaw.Code.UnitTests/Runtime/SessionTurnLockTests.cs diff --git a/src/SharpClaw.Code.Runtime/Composition/RuntimeServiceCollectionExtensions.cs b/src/SharpClaw.Code.Runtime/Composition/RuntimeServiceCollectionExtensions.cs index 6b8cad2..76633b8 100644 --- a/src/SharpClaw.Code.Runtime/Composition/RuntimeServiceCollectionExtensions.cs +++ b/src/SharpClaw.Code.Runtime/Composition/RuntimeServiceCollectionExtensions.cs @@ -185,6 +185,7 @@ private static IServiceCollection AddSharpClawRuntimeCore( services.AddSingleton(); services.AddSingleton(); AddOperationalDiagnostics(services); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(serviceProvider => serviceProvider.GetRequiredService()); services.AddSingleton(serviceProvider => serviceProvider.GetRequiredService()); diff --git a/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs b/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs index 7e3d041..728b02e 100644 --- a/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs +++ b/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs @@ -1,4 +1,3 @@ -using System.Collections.Concurrent; using System.Globalization; using System.Text.Json; using Microsoft.Extensions.Logging; @@ -57,6 +56,7 @@ public sealed class ConversationRuntime( IShareSessionService shareSessionService, IConversationCompactionService conversationCompactionService, IHookDispatcher hookDispatcher, + SessionTurnLock sessionTurnLock, ILogger logger, TurnMutationJournal? mutationJournal = null, IMutationSetStore? mutationSets = null) : IConversationRuntime, IRuntimeCommandService @@ -65,11 +65,6 @@ public sealed class ConversationRuntime( private const string CanceledTurnReason = "The turn was canceled."; private const string FailedTurnReason = "The turn failed."; - private static readonly ConcurrentDictionary SessionMutexes = new(StringComparer.Ordinal); - - private static SemaphoreSlim GetSessionMutex(string workspacePath, string sessionId) - => SessionMutexes.GetOrAdd($"{workspacePath}\u0000{sessionId}", static _ => new SemaphoreSlim(1, 1)); - /// public async Task CreateSessionAsync(string workspacePath, PermissionMode permissionMode, OutputFormat outputFormat, CancellationToken cancellationToken) { @@ -131,21 +126,14 @@ public async Task RunPromptAsync(RunPromptRequest request, throw new InvalidOperationException($"Unable to resume session '{request.SessionId}'."); } - var sessionMutex = GetSessionMutex(workspacePath, session.Id); - await sessionMutex.WaitAsync(cancellationToken).ConfigureAwait(false); - try - { - var turnLockPath = storagePathResolver.GetSessionTurnLockPath(workspacePath, session.Id); - await using var crossProcessTurnLock = await fileSystem - .AcquireExclusiveFileLockAsync(turnLockPath, cancellationToken) - .ConfigureAwait(false); + await using var sessionLock = await sessionTurnLock.AcquireAsync(workspacePath, session.Id, cancellationToken).ConfigureAwait(false); - // Re-read the session inside the lock so the turn sequence read-modify-write is consistent across concurrent prompts. - var refreshed = await sessionStore.GetByIdAsync(workspacePath, session.Id, cancellationToken).ConfigureAwait(false); - if (refreshed is not null) - { - session = refreshed; - } + // Re-read the session inside the lock so the turn sequence read-modify-write is consistent across concurrent prompts. + var refreshed = await sessionStore.GetByIdAsync(workspacePath, session.Id, cancellationToken).ConfigureAwait(false); + if (refreshed is not null) + { + session = refreshed; + } if (explicitPrimaryMode is null && session.Metadata is not null && session.Metadata.TryGetValue(SharpClawWorkflowMetadataKeys.PrimaryMode, out var savedMode) @@ -154,12 +142,12 @@ public async Task RunPromptAsync(RunPromptRequest request, session = await EnsurePrimaryModePersistedAsync(workspacePath, session, request.PrimaryMode, cancellationToken).ConfigureAwait(false); session = await EnsureApprovalSettingsPersistedAsync(workspacePath, session, request.ApprovalSettings, cancellationToken).ConfigureAwait(false); - session = await EnsureRecoverableFromFailedForPromptAsync( - workspacePath, - session, - runtimeEvents, - cancellationToken) - .ConfigureAwait(false); + session = await EnsureRecoverableFromFailedForPromptAsync( + workspacePath, + session, + runtimeEvents, + cancellationToken) + .ConfigureAwait(false); if (isNewSession) { @@ -497,11 +485,6 @@ await AppendEventAsync( { mutationJournal?.End(session.Id, turnId); } - } - finally - { - sessionMutex.Release(); - } } /// @@ -1624,31 +1607,12 @@ private Task DispatchHookAsync(string workspacePath, RuntimeEvent runtimeEvent, private string NormalizeWorkspacePath(string? workspacePath) => pathService.GetFullPath(string.IsNullOrWhiteSpace(workspacePath) ? pathService.GetCurrentDirectory() : workspacePath); - private async Task ExecuteWithSessionLockAsync( + private Task ExecuteWithSessionLockAsync( string workspacePath, string sessionId, Func> operation, CancellationToken cancellationToken) - { - ArgumentException.ThrowIfNullOrWhiteSpace(workspacePath); - ArgumentException.ThrowIfNullOrWhiteSpace(sessionId); - ArgumentNullException.ThrowIfNull(operation); - - var sessionMutex = GetSessionMutex(workspacePath, sessionId); - await sessionMutex.WaitAsync(cancellationToken).ConfigureAwait(false); - try - { - var turnLockPath = storagePathResolver.GetSessionTurnLockPath(workspacePath, sessionId); - await using var crossProcessTurnLock = await fileSystem - .AcquireExclusiveFileLockAsync(turnLockPath, cancellationToken) - .ConfigureAwait(false); - return await operation(cancellationToken).ConfigureAwait(false); - } - finally - { - sessionMutex.Release(); - } - } + => sessionTurnLock.ExecuteAsync(workspacePath, sessionId, operation, cancellationToken); private static string CreateIdentifier(string prefix) => $"{prefix}-{Guid.NewGuid():N}"; diff --git a/src/SharpClaw.Code.Runtime/Orchestration/SessionTurnLock.cs b/src/SharpClaw.Code.Runtime/Orchestration/SessionTurnLock.cs new file mode 100644 index 0000000..1220c07 --- /dev/null +++ b/src/SharpClaw.Code.Runtime/Orchestration/SessionTurnLock.cs @@ -0,0 +1,86 @@ +using System.Collections.Concurrent; +using SharpClaw.Code.Infrastructure.Abstractions; + +namespace SharpClaw.Code.Runtime.Orchestration; + +/// +/// Serializes work on one session: an in-process mutex per workspace/session pair, then the session's cross-process turn lock file. +/// Prompt turns, undo/redo, share/unshare, and compaction all hold this lock so they never interleave. +/// +public sealed class SessionTurnLock(IFileSystem fileSystem, IRuntimeStoragePathResolver storagePathResolver) +{ + // Process-wide so separate runtime instances in one process still exclude each other. + private static readonly ConcurrentDictionary SessionMutexes = new(StringComparer.Ordinal); + + /// + /// Waits for the session's in-process mutex, then its cross-process lock file. + /// Disposing the result releases the lock file first and the mutex second. + /// + /// The normalized workspace path. + /// The session identifier. + /// The cancellation token for both waits. + /// A handle that releases both locks when disposed. + public async Task AcquireAsync(string workspacePath, string sessionId, CancellationToken cancellationToken) + { + var sessionMutex = SessionMutexes.GetOrAdd($"{workspacePath}\u0000{sessionId}", static _ => new SemaphoreSlim(1, 1)); + await sessionMutex.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + var turnLockPath = storagePathResolver.GetSessionTurnLockPath(workspacePath, sessionId); + var crossProcessTurnLock = await fileSystem + .AcquireExclusiveFileLockAsync(turnLockPath, cancellationToken) + .ConfigureAwait(false); + return new Handle(crossProcessTurnLock, sessionMutex); + } + catch + { + sessionMutex.Release(); + throw; + } + } + + /// + /// Runs while holding the session lock. + /// + /// The operation result type. + /// The normalized workspace path. + /// The session identifier. + /// The work to run under the lock. + /// The cancellation token passed to the waits and the operation. + /// The operation result. + public async Task ExecuteAsync( + string workspacePath, + string sessionId, + Func> operation, + CancellationToken cancellationToken) + { + ArgumentException.ThrowIfNullOrWhiteSpace(workspacePath); + ArgumentException.ThrowIfNullOrWhiteSpace(sessionId); + ArgumentNullException.ThrowIfNull(operation); + + await using var sessionLock = await AcquireAsync(workspacePath, sessionId, cancellationToken).ConfigureAwait(false); + return await operation(cancellationToken).ConfigureAwait(false); + } + + private sealed class Handle(IAsyncDisposable crossProcessTurnLock, SemaphoreSlim sessionMutex) : IAsyncDisposable + { + private int disposed; + + public async ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref disposed, 1) != 0) + { + return; + } + + try + { + await crossProcessTurnLock.DisposeAsync().ConfigureAwait(false); + } + finally + { + sessionMutex.Release(); + } + } + } +} diff --git a/tests/SharpClaw.Code.UnitTests/Runtime/SessionTurnLockTests.cs b/tests/SharpClaw.Code.UnitTests/Runtime/SessionTurnLockTests.cs new file mode 100644 index 0000000..026f9ab --- /dev/null +++ b/tests/SharpClaw.Code.UnitTests/Runtime/SessionTurnLockTests.cs @@ -0,0 +1,65 @@ +using FluentAssertions; +using SharpClaw.Code.Infrastructure.Services; +using SharpClaw.Code.Runtime.Orchestration; +using SharpClaw.Code.UnitTests.Support; + +namespace SharpClaw.Code.UnitTests.Runtime; + +/// +/// Verifies the per-session lock shared by prompt turns and session-mutating commands. +/// +public sealed class SessionTurnLockTests +{ + [Fact] + public async Task Second_holder_waits_until_the_first_releases() + { + var workspace = CreateWorkspace(); + var turnLock = new SessionTurnLock(new LocalFileSystem(), TestRuntimeStorageResolver.Create(workspace)); + var first = await turnLock.AcquireAsync(workspace, "session-a", CancellationToken.None); + + var second = turnLock.AcquireAsync(workspace, "session-a", CancellationToken.None); + await Task.Delay(200); + second.IsCompleted.Should().BeFalse(); + + await first.DisposeAsync(); + await using var acquired = await second.WaitAsync(TimeSpan.FromSeconds(5)); + } + + [Fact] + public async Task Different_sessions_do_not_block_each_other() + { + var workspace = CreateWorkspace(); + var turnLock = new SessionTurnLock(new LocalFileSystem(), TestRuntimeStorageResolver.Create(workspace)); + await using var first = await turnLock.AcquireAsync(workspace, "session-a", CancellationToken.None); + + await using var other = await turnLock.AcquireAsync(workspace, "session-b", CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(5)); + } + + [Fact] + public async Task Cancelled_wait_does_not_leak_the_mutex() + { + var workspace = CreateWorkspace(); + var turnLock = new SessionTurnLock(new LocalFileSystem(), TestRuntimeStorageResolver.Create(workspace)); + var first = await turnLock.AcquireAsync(workspace, "session-a", CancellationToken.None); + using var cancel = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); + + await FluentActions.Awaiting(() => turnLock.AcquireAsync(workspace, "session-a", cancel.Token)) + .Should().ThrowAsync(); + + await first.DisposeAsync(); + await first.DisposeAsync(); // Idempotent: a double dispose must not over-release the mutex. + await using var again = await turnLock.AcquireAsync(workspace, "session-a", CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(5)); + var blocked = turnLock.AcquireAsync(workspace, "session-a", CancellationToken.None); + await Task.Delay(200); + blocked.IsCompleted.Should().BeFalse(); + await again.DisposeAsync(); + await using var last = await blocked.WaitAsync(TimeSpan.FromSeconds(5)); + } + + private static string CreateWorkspace() + { + var workspace = Path.Combine(Path.GetTempPath(), "sharpclaw-turn-lock-tests", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(workspace); + return workspace; + } +} From fc1780a0c5cd76eb3bfcaea77a70f846684320ff Mon Sep 17 00:00:00 2001 From: telli Date: Tue, 10 Nov 2026 04:58:55 -0800 Subject: [PATCH 10/12] Move status, doctor, and inspect commands to RuntimeDiagnosticsCommands Method bodies moved verbatim; ConversationRuntime keeps the IRuntimeCommandService members as one-line delegations and no longer takes IOperationalDiagnosticsCoordinator. Co-Authored-By: Claude Opus 5.5 --- .../RuntimeServiceCollectionExtensions.cs | 1 + .../Orchestration/ConversationRuntime.cs | 117 +-------------- .../RuntimeDiagnosticsCommands.cs | 133 ++++++++++++++++++ 3 files changed, 141 insertions(+), 110 deletions(-) create mode 100644 src/SharpClaw.Code.Runtime/Orchestration/RuntimeDiagnosticsCommands.cs diff --git a/src/SharpClaw.Code.Runtime/Composition/RuntimeServiceCollectionExtensions.cs b/src/SharpClaw.Code.Runtime/Composition/RuntimeServiceCollectionExtensions.cs index 76633b8..4db491b 100644 --- a/src/SharpClaw.Code.Runtime/Composition/RuntimeServiceCollectionExtensions.cs +++ b/src/SharpClaw.Code.Runtime/Composition/RuntimeServiceCollectionExtensions.cs @@ -186,6 +186,7 @@ private static IServiceCollection AddSharpClawRuntimeCore( services.AddSingleton(); AddOperationalDiagnostics(services); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(serviceProvider => serviceProvider.GetRequiredService()); services.AddSingleton(serviceProvider => serviceProvider.GetRequiredService()); diff --git a/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs b/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs index 728b02e..7447bf1 100644 --- a/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs +++ b/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs @@ -41,7 +41,6 @@ public sealed class ConversationRuntime( IPathService pathService, IRuntimeStoragePathResolver storagePathResolver, IRuntimeHostContextAccessor hostContextAccessor, - IOperationalDiagnosticsCoordinator operationalDiagnostics, ICustomCommandDiscoveryService customCommandDiscovery, ISessionExportService sessionExportService, IWorkspaceSessionAttachmentStore workspaceSessionAttachmentStore, @@ -57,6 +56,7 @@ public sealed class ConversationRuntime( IConversationCompactionService conversationCompactionService, IHookDispatcher hookDispatcher, SessionTurnLock sessionTurnLock, + RuntimeDiagnosticsCommands diagnosticsCommands, ILogger logger, TurnMutationJournal? mutationJournal = null, IMutationSetStore? mutationSets = null) : IConversationRuntime, IRuntimeCommandService @@ -567,89 +567,16 @@ public async Task ExecuteCustomCommandAsync( } /// - public async Task GetStatusAsync(RuntimeCommandContext context, CancellationToken cancellationToken) - { - using var hostScope = hostContextAccessor.BeginScope(context.HostContext); - var input = new OperationalDiagnosticsInput( - context.WorkingDirectory, - context.Model, - context.PermissionMode, - context.OutputFormat, - context.PrimaryMode, - context.ApprovalSettings); - var report = await operationalDiagnostics - .BuildStatusReportAsync(input, cancellationToken) - .ConfigureAwait(false); - var payload = JsonSerializer.Serialize(report, ProtocolJsonContext.Default.RuntimeStatusReport); - var message = FormatStatusMessage(report); - - return new CommandResult( - Succeeded: true, - ExitCode: 0, - OutputFormat: context.OutputFormat, - Message: message, - DataJson: payload); - } + public Task GetStatusAsync(RuntimeCommandContext context, CancellationToken cancellationToken) + => diagnosticsCommands.GetStatusAsync(context, cancellationToken); /// - public async Task RunDoctorAsync(RuntimeCommandContext context, CancellationToken cancellationToken) - { - using var hostScope = hostContextAccessor.BeginScope(context.HostContext); - var input = new OperationalDiagnosticsInput( - context.WorkingDirectory, - context.Model, - context.PermissionMode, - context.OutputFormat, - context.PrimaryMode, - context.ApprovalSettings); - var report = await operationalDiagnostics.RunDoctorAsync(input, cancellationToken).ConfigureAwait(false); - var payload = JsonSerializer.Serialize(report, ProtocolJsonContext.Default.DoctorReport); - var exitCode = report.OverallStatus == OperationalCheckStatus.Error ? 1 : 0; - var message = FormatDoctorMessage(report); - - return new CommandResult( - Succeeded: exitCode == 0, - ExitCode: exitCode, - OutputFormat: context.OutputFormat, - Message: message, - DataJson: payload); - } + public Task RunDoctorAsync(RuntimeCommandContext context, CancellationToken cancellationToken) + => diagnosticsCommands.RunDoctorAsync(context, cancellationToken); /// - public async Task InspectSessionAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) - { - using var hostScope = hostContextAccessor.BeginScope(context.HostContext); - var input = new OperationalDiagnosticsInput( - context.WorkingDirectory, - context.Model, - context.PermissionMode, - context.OutputFormat, - context.PrimaryMode, - context.ApprovalSettings); - var inspection = await operationalDiagnostics - .InspectSessionAsync(sessionId, input, cancellationToken) - .ConfigureAwait(false); - if (inspection is null) - { - return new CommandResult( - Succeeded: false, - ExitCode: 1, - OutputFormat: context.OutputFormat, - Message: "No matching session found.", - DataJson: null); - } - - var payload = JsonSerializer.Serialize(inspection, ProtocolJsonContext.Default.SessionInspectionReport); - var message = - $"{inspection.Session.Id} ({inspection.Session.State}) · {inspection.PersistedEventCount} persisted events"; - - return new CommandResult( - Succeeded: true, - ExitCode: 0, - OutputFormat: context.OutputFormat, - Message: message, - DataJson: payload); - } + public Task InspectSessionAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) + => diagnosticsCommands.InspectSessionAsync(sessionId, context, cancellationToken); /// public async Task ForkSessionAsync( @@ -1140,36 +1067,6 @@ private async Task EnsureApprovalSettingsPersistedAsync( return updated; } - private static string FormatDoctorMessage(DoctorReport report) - => string.Join( - Environment.NewLine, - report.Checks.Select(static c => - { - var detail = string.IsNullOrWhiteSpace(c.Detail) ? string.Empty : $" — {c.Detail}"; - return $"[{c.Status}] {c.Id}: {c.Summary}{detail}"; - })); - - private static string FormatStatusMessage(RuntimeStatusReport report) - { - var sessionLabel = report.LatestSessionId is null - ? "no session" - : $"{report.LatestSessionId} ({report.LatestSessionState})"; - var approvalLabel = report.ApprovalSettings is null - ? "manual approvals" - : report.ApprovalSettings.AutoApproveScopes.Count == 0 - ? "manual approvals" - : report.ApprovalSettings.AutoApproveBudget is { } budget - ? $"auto-approve {string.Join(',', report.ApprovalSettings.AutoApproveScopes)} (budget {budget})" - : $"auto-approve {string.Join(',', report.ApprovalSettings.AutoApproveScopes)}"; - var headline = - $"Ready · {report.WorkspaceRoot} · model {report.SelectedModel} · mode {report.PrimaryMode} · approvals {approvalLabel} · latest {sessionLabel} · " - + $"MCP {report.McpReadyCount}/{report.McpServerCount} · plugins {report.PluginEnabledCount}/{report.PluginInstalledCount} · " - + $"LSP {report.LspServerCount} · diagnostics {report.DiagnosticsErrorCount} error(s), {report.DiagnosticsWarningCount} warning(s)"; - var notable = report.Checks.FirstOrDefault(static c - => c.Status is not OperationalCheckStatus.Ok and not OperationalCheckStatus.Skipped); - return notable is null ? headline : $"{headline}{Environment.NewLine}[{notable.Status}] {notable.Id}: {notable.Summary}"; - } - private static string FormatProviderFailureReason(ProviderExecutionException exception) => $"Provider failure ({exception.Kind}): {exception.Message}"; diff --git a/src/SharpClaw.Code.Runtime/Orchestration/RuntimeDiagnosticsCommands.cs b/src/SharpClaw.Code.Runtime/Orchestration/RuntimeDiagnosticsCommands.cs new file mode 100644 index 0000000..03788d1 --- /dev/null +++ b/src/SharpClaw.Code.Runtime/Orchestration/RuntimeDiagnosticsCommands.cs @@ -0,0 +1,133 @@ +using System.Text.Json; +using SharpClaw.Code.Protocol.Abstractions; +using SharpClaw.Code.Protocol.Commands; +using SharpClaw.Code.Protocol.Operational; +using SharpClaw.Code.Protocol.Serialization; +using SharpClaw.Code.Runtime.Abstractions; +using SharpClaw.Code.Runtime.Diagnostics; + +namespace SharpClaw.Code.Runtime.Orchestration; + +/// +/// Status, doctor, and session-inspection commands. Stateless over the operational diagnostics coordinator; +/// exposes them through . +/// +public sealed class RuntimeDiagnosticsCommands( + IRuntimeHostContextAccessor hostContextAccessor, + IOperationalDiagnosticsCoordinator operationalDiagnostics) +{ + /// Builds the runtime status report for the command context. + public async Task GetStatusAsync(RuntimeCommandContext context, CancellationToken cancellationToken) + { + using var hostScope = hostContextAccessor.BeginScope(context.HostContext); + var input = new OperationalDiagnosticsInput( + context.WorkingDirectory, + context.Model, + context.PermissionMode, + context.OutputFormat, + context.PrimaryMode, + context.ApprovalSettings); + var report = await operationalDiagnostics + .BuildStatusReportAsync(input, cancellationToken) + .ConfigureAwait(false); + var payload = JsonSerializer.Serialize(report, ProtocolJsonContext.Default.RuntimeStatusReport); + var message = FormatStatusMessage(report); + + return new CommandResult( + Succeeded: true, + ExitCode: 0, + OutputFormat: context.OutputFormat, + Message: message, + DataJson: payload); + } + + /// Runs doctor checks; exits 1 when any check reports an error. + public async Task RunDoctorAsync(RuntimeCommandContext context, CancellationToken cancellationToken) + { + using var hostScope = hostContextAccessor.BeginScope(context.HostContext); + var input = new OperationalDiagnosticsInput( + context.WorkingDirectory, + context.Model, + context.PermissionMode, + context.OutputFormat, + context.PrimaryMode, + context.ApprovalSettings); + var report = await operationalDiagnostics.RunDoctorAsync(input, cancellationToken).ConfigureAwait(false); + var payload = JsonSerializer.Serialize(report, ProtocolJsonContext.Default.DoctorReport); + var exitCode = report.OverallStatus == OperationalCheckStatus.Error ? 1 : 0; + var message = FormatDoctorMessage(report); + + return new CommandResult( + Succeeded: exitCode == 0, + ExitCode: exitCode, + OutputFormat: context.OutputFormat, + Message: message, + DataJson: payload); + } + + /// Inspects one session, or the latest when is null. + public async Task InspectSessionAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) + { + using var hostScope = hostContextAccessor.BeginScope(context.HostContext); + var input = new OperationalDiagnosticsInput( + context.WorkingDirectory, + context.Model, + context.PermissionMode, + context.OutputFormat, + context.PrimaryMode, + context.ApprovalSettings); + var inspection = await operationalDiagnostics + .InspectSessionAsync(sessionId, input, cancellationToken) + .ConfigureAwait(false); + if (inspection is null) + { + return new CommandResult( + Succeeded: false, + ExitCode: 1, + OutputFormat: context.OutputFormat, + Message: "No matching session found.", + DataJson: null); + } + + var payload = JsonSerializer.Serialize(inspection, ProtocolJsonContext.Default.SessionInspectionReport); + var message = + $"{inspection.Session.Id} ({inspection.Session.State}) · {inspection.PersistedEventCount} persisted events"; + + return new CommandResult( + Succeeded: true, + ExitCode: 0, + OutputFormat: context.OutputFormat, + Message: message, + DataJson: payload); + } + + private static string FormatDoctorMessage(DoctorReport report) + => string.Join( + Environment.NewLine, + report.Checks.Select(static c => + { + var detail = string.IsNullOrWhiteSpace(c.Detail) ? string.Empty : $" — {c.Detail}"; + return $"[{c.Status}] {c.Id}: {c.Summary}{detail}"; + })); + + private static string FormatStatusMessage(RuntimeStatusReport report) + { + var sessionLabel = report.LatestSessionId is null + ? "no session" + : $"{report.LatestSessionId} ({report.LatestSessionState})"; + var approvalLabel = report.ApprovalSettings is null + ? "manual approvals" + : report.ApprovalSettings.AutoApproveScopes.Count == 0 + ? "manual approvals" + : report.ApprovalSettings.AutoApproveBudget is { } budget + ? $"auto-approve {string.Join(',', report.ApprovalSettings.AutoApproveScopes)} (budget {budget})" + : $"auto-approve {string.Join(',', report.ApprovalSettings.AutoApproveScopes)}"; + var headline = + $"Ready · {report.WorkspaceRoot} · model {report.SelectedModel} · mode {report.PrimaryMode} · approvals {approvalLabel} · latest {sessionLabel} · " + + $"MCP {report.McpReadyCount}/{report.McpServerCount} · plugins {report.PluginEnabledCount}/{report.PluginInstalledCount} · " + + $"LSP {report.LspServerCount} · diagnostics {report.DiagnosticsErrorCount} error(s), {report.DiagnosticsWarningCount} warning(s)"; + var notable = report.Checks.FirstOrDefault(static c + => c.Status is not OperationalCheckStatus.Ok and not OperationalCheckStatus.Skipped); + return notable is null ? headline : $"{headline}{Environment.NewLine}[{notable.Status}] {notable.Id}: {notable.Summary}"; + } +} From bccbadac205a276d88336231b21d537e0c3bf9e5 Mon Sep 17 00:00:00 2001 From: telli Date: Tue, 10 Nov 2026 05:02:14 -0800 Subject: [PATCH 11/12] Move session admin commands to SessionAdminCommands Fork (both overloads), export, portable bundles, list/attach/detach, share/unshare, compact, and undo/redo move verbatim with their private helpers. Identifier and metadata helpers shared with the turn pipeline move to SessionMetadataHelpers (imported statically, so call sites are unchanged). ConversationRuntime delegates the interface members and drops five dependencies it no longer reads. ConversationRuntime: 1,704 -> 1,171 lines. Co-Authored-By: Claude Opus 5.5 --- .../RuntimeServiceCollectionExtensions.cs | 1 + .../Orchestration/ConversationRuntime.cs | 492 ++---------------- .../Orchestration/SessionAdminCommands.cs | 480 +++++++++++++++++ .../Orchestration/SessionMetadataHelpers.cs | 64 +++ 4 files changed, 574 insertions(+), 463 deletions(-) create mode 100644 src/SharpClaw.Code.Runtime/Orchestration/SessionAdminCommands.cs create mode 100644 src/SharpClaw.Code.Runtime/Orchestration/SessionMetadataHelpers.cs diff --git a/src/SharpClaw.Code.Runtime/Composition/RuntimeServiceCollectionExtensions.cs b/src/SharpClaw.Code.Runtime/Composition/RuntimeServiceCollectionExtensions.cs index 4db491b..a084b01 100644 --- a/src/SharpClaw.Code.Runtime/Composition/RuntimeServiceCollectionExtensions.cs +++ b/src/SharpClaw.Code.Runtime/Composition/RuntimeServiceCollectionExtensions.cs @@ -187,6 +187,7 @@ private static IServiceCollection AddSharpClawRuntimeCore( AddOperationalDiagnostics(services); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(serviceProvider => serviceProvider.GetRequiredService()); services.AddSingleton(serviceProvider => serviceProvider.GetRequiredService()); diff --git a/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs b/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs index 7447bf1..567a766 100644 --- a/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs +++ b/src/SharpClaw.Code.Runtime/Orchestration/ConversationRuntime.cs @@ -24,6 +24,8 @@ using SharpClaw.Code.Telemetry; using SharpClaw.Code.Telemetry.Abstractions; +using static SharpClaw.Code.Runtime.Orchestration.SessionMetadataHelpers; + namespace SharpClaw.Code.Runtime.Orchestration; /// @@ -31,7 +33,6 @@ namespace SharpClaw.Code.Runtime.Orchestration; /// public sealed class ConversationRuntime( ISessionStore sessionStore, - IEventStore eventStore, IRuntimeEventPublisher eventPublisher, ICheckpointStore checkpointStore, ITurnRunner turnRunner, @@ -42,26 +43,22 @@ public sealed class ConversationRuntime( IRuntimeStoragePathResolver storagePathResolver, IRuntimeHostContextAccessor hostContextAccessor, ICustomCommandDiscoveryService customCommandDiscovery, - ISessionExportService sessionExportService, IWorkspaceSessionAttachmentStore workspaceSessionAttachmentStore, IEditorContextBuffer editorContextBuffer, CheckpointMutationCoordinator checkpointMutationCoordinator, - ISessionCoordinator sessionCoordinator, - IPortableSessionBundleService portableSessionBundleService, IPlanWorkflowService planWorkflowService, ISpecWorkflowService specWorkflowService, ISharpClawConfigService sharpClawConfigService, IAgentCatalogService agentCatalogService, IShareSessionService shareSessionService, - IConversationCompactionService conversationCompactionService, IHookDispatcher hookDispatcher, SessionTurnLock sessionTurnLock, RuntimeDiagnosticsCommands diagnosticsCommands, + SessionAdminCommands sessionAdminCommands, ILogger logger, TurnMutationJournal? mutationJournal = null, IMutationSetStore? mutationSets = null) : IConversationRuntime, IRuntimeCommandService { - private const string LastTurnSequenceKey = "lastTurnSequence"; private const string CanceledTurnReason = "The turn was canceled."; private const string FailedTurnReason = "The turn failed."; @@ -579,403 +576,56 @@ public Task InspectSessionAsync(string? sessionId, RuntimeCommand => diagnosticsCommands.InspectSessionAsync(sessionId, context, cancellationToken); /// - public async Task ForkSessionAsync( - string? sourceSessionId, - RuntimeCommandContext context, - CancellationToken cancellationToken) - { - using var hostScope = hostContextAccessor.BeginScope(context.HostContext); - try - { - var child = await ForkSessionAsync(NormalizeWorkspacePath(context.WorkingDirectory), sourceSessionId, cancellationToken) - .ConfigureAwait(false); - var payload = JsonSerializer.Serialize(child, ProtocolJsonContext.Default.ConversationSession); - return new CommandResult( - true, - 0, - context.OutputFormat, - $"Forked session {child.Id} from '{child.Metadata?.GetValueOrDefault(SharpClawWorkflowMetadataKeys.ParentSessionId) ?? "?"}'.", - payload); - } - catch (Exception ex) - { - return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); - } - } + public Task ForkSessionAsync(string? sourceSessionId, RuntimeCommandContext context, CancellationToken cancellationToken) + => sessionAdminCommands.ForkSessionAsync(sourceSessionId, context, cancellationToken); /// - public async Task ExportSessionAsync( - string? sessionId, - SessionExportFormat format, - string? outputFilePath, - RuntimeCommandContext context, - CancellationToken cancellationToken) - { - using var hostScope = hostContextAccessor.BeginScope(context.HostContext); - try - { - var workspace = NormalizeWorkspacePath(context.WorkingDirectory); - var (document, ext) = await sessionExportService - .BuildDocumentAsync(workspace, sessionId, format, cancellationToken) - .ConfigureAwait(false); - - var exportsDir = storagePathResolver.GetExportsRoot(workspace); - fileSystem.CreateDirectory(exportsDir); - var fileName = - $"{document.Session.Id}-{document.ExportedAtUtc:yyyyMMddTHHmmss}.{ext}"; - var targetPath = string.IsNullOrWhiteSpace(outputFilePath) - ? pathService.Combine(exportsDir, fileName) - : pathService.GetFullPath(outputFilePath); - - var text = format == SessionExportFormat.Json - ? JsonSerializer.Serialize(document, ProtocolJsonContext.Default.SessionExportDocument) - : sessionExportService.RenderMarkdown(document); - - await fileSystem.WriteAllTextAsync(targetPath, text, cancellationToken).ConfigureAwait(false); - - return new CommandResult( - true, - 0, - context.OutputFormat, - $"Exported session to '{targetPath}'.", - JsonSerializer.Serialize( - new Dictionary { ["path"] = targetPath, ["format"] = ext }, - ProtocolJsonContext.Default.DictionaryStringString)); - } - catch (Exception ex) - { - return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); - } - } + public Task ExportSessionAsync(string? sessionId, SessionExportFormat format, string? outputFilePath, RuntimeCommandContext context, CancellationToken cancellationToken) + => sessionAdminCommands.ExportSessionAsync(sessionId, format, outputFilePath, context, cancellationToken); /// - public async Task UndoAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) - { - using var hostScope = hostContextAccessor.BeginScope(context.HostContext); - try - { - var workspace = NormalizeWorkspacePath(context.WorkingDirectory); - var sid = await ResolveCommandSessionIdAsync(workspace, sessionId, context.SessionId, cancellationToken).ConfigureAwait(false); - if (string.IsNullOrWhiteSpace(sid)) - { - return new CommandResult(false, 1, context.OutputFormat, "No session resolved for undo.", null); - } - - var result = await checkpointMutationCoordinator - .TryUndoAsync( - workspace, - sid, - cancellationToken, - operation => ExecuteWithSessionLockAsync(workspace, sid, operation, cancellationToken)) - .ConfigureAwait(false); - var payload = JsonSerializer.Serialize(result, ProtocolJsonContext.Default.UndoRedoActionResult); - return new CommandResult(result.Succeeded, result.Succeeded ? 0 : 1, context.OutputFormat, result.Message, payload); - } - catch (Exception ex) - { - return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); - } - } + public Task UndoAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) + => sessionAdminCommands.UndoAsync(sessionId, context, cancellationToken); /// - public async Task RedoAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) - { - using var hostScope = hostContextAccessor.BeginScope(context.HostContext); - try - { - var workspace = NormalizeWorkspacePath(context.WorkingDirectory); - var sid = await ResolveCommandSessionIdAsync(workspace, sessionId, context.SessionId, cancellationToken).ConfigureAwait(false); - if (string.IsNullOrWhiteSpace(sid)) - { - return new CommandResult(false, 1, context.OutputFormat, "No session resolved for redo.", null); - } - - var result = await checkpointMutationCoordinator - .TryRedoAsync( - workspace, - sid, - cancellationToken, - operation => ExecuteWithSessionLockAsync(workspace, sid, operation, cancellationToken)) - .ConfigureAwait(false); - var payload = JsonSerializer.Serialize(result, ProtocolJsonContext.Default.UndoRedoActionResult); - return new CommandResult(result.Succeeded, result.Succeeded ? 0 : 1, context.OutputFormat, result.Message, payload); - } - catch (Exception ex) - { - return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); - } - } + public Task RedoAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) + => sessionAdminCommands.RedoAsync(sessionId, context, cancellationToken); /// - public async Task ExportPortableSessionBundleAsync( - string? sessionId, - string? outputZipPath, - RuntimeCommandContext context, - CancellationToken cancellationToken) - { - using var hostScope = hostContextAccessor.BeginScope(context.HostContext); - try - { - var workspace = NormalizeWorkspacePath(context.WorkingDirectory); - var path = await portableSessionBundleService - .CreateBundleZipAsync(workspace, sessionId, outputZipPath, cancellationToken) - .ConfigureAwait(false); - return new CommandResult( - true, - 0, - context.OutputFormat, - $"Portable bundle written to '{path}'.", - JsonSerializer.Serialize( - new Dictionary { ["path"] = path }, - ProtocolJsonContext.Default.DictionaryStringString)); - } - catch (Exception ex) - { - return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); - } - } + public Task ExportPortableSessionBundleAsync(string? sessionId, string? outputZipPath, RuntimeCommandContext context, CancellationToken cancellationToken) + => sessionAdminCommands.ExportPortableSessionBundleAsync(sessionId, outputZipPath, context, cancellationToken); /// - public async Task ImportPortableSessionBundleAsync( - string bundleZipPath, - bool replaceExisting, - bool attachAfterImport, - RuntimeCommandContext context, - CancellationToken cancellationToken) - { - using var hostScope = hostContextAccessor.BeginScope(context.HostContext); - try - { - var workspace = NormalizeWorkspacePath(context.WorkingDirectory); - var zip = pathService.GetFullPath(bundleZipPath); - var result = await portableSessionBundleService - .ImportBundleZipAsync(workspace, zip, replaceExisting, cancellationToken) - .ConfigureAwait(false); - if (attachAfterImport) - { - await sessionCoordinator.AttachSessionAsync(workspace, result.SessionId, cancellationToken).ConfigureAwait(false); - } - - var message = attachAfterImport - ? $"Imported session '{result.SessionId}' and attached it for this workspace." - : $"Imported session '{result.SessionId}'."; - var payload = JsonSerializer.Serialize(result, ProtocolJsonContext.Default.PortableBundleImportResult); - return new CommandResult(true, 0, context.OutputFormat, message, payload); - } - catch (Exception ex) - { - return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); - } - } + public Task ImportPortableSessionBundleAsync(string bundleZipPath, bool replaceExisting, bool attachAfterImport, RuntimeCommandContext context, CancellationToken cancellationToken) + => sessionAdminCommands.ImportPortableSessionBundleAsync(bundleZipPath, replaceExisting, attachAfterImport, context, cancellationToken); /// - public async Task ListSessionsAsync(RuntimeCommandContext context, CancellationToken cancellationToken) - { - using var hostScope = hostContextAccessor.BeginScope(context.HostContext); - try - { - var workspace = NormalizeWorkspacePath(context.WorkingDirectory); - var rows = await sessionCoordinator.ListSessionsAsync(workspace, cancellationToken).ConfigureAwait(false); - var payload = JsonSerializer.Serialize(rows, ProtocolJsonContext.Default.ListSessionSummaryRow); - return new CommandResult(true, 0, context.OutputFormat, $"{rows.Count} session(s).", payload); - } - catch (Exception ex) - { - return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); - } - } + public Task ListSessionsAsync(RuntimeCommandContext context, CancellationToken cancellationToken) + => sessionAdminCommands.ListSessionsAsync(context, cancellationToken); /// - public async Task AttachSessionAsync(string sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) - { - using var hostScope = hostContextAccessor.BeginScope(context.HostContext); - try - { - var workspace = NormalizeWorkspacePath(context.WorkingDirectory); - await sessionCoordinator.AttachSessionAsync(workspace, sessionId, cancellationToken).ConfigureAwait(false); - return new CommandResult( - true, - 0, - context.OutputFormat, - $"Attached session '{sessionId}' for workspace prompts.", - JsonSerializer.Serialize( - new Dictionary { ["sessionId"] = sessionId }, - ProtocolJsonContext.Default.DictionaryStringString)); - } - catch (Exception ex) - { - return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); - } - } + public Task AttachSessionAsync(string sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) + => sessionAdminCommands.AttachSessionAsync(sessionId, context, cancellationToken); /// - public async Task DetachSessionAsync(RuntimeCommandContext context, CancellationToken cancellationToken) - { - using var hostScope = hostContextAccessor.BeginScope(context.HostContext); - try - { - var workspace = NormalizeWorkspacePath(context.WorkingDirectory); - await sessionCoordinator.DetachSessionAsync(workspace, cancellationToken).ConfigureAwait(false); - return new CommandResult(true, 0, context.OutputFormat, "Detached explicit workspace session.", null); - } - catch (Exception ex) - { - return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); - } - } + public Task DetachSessionAsync(RuntimeCommandContext context, CancellationToken cancellationToken) + => sessionAdminCommands.DetachSessionAsync(context, cancellationToken); /// - public async Task ShareSessionAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) - { - using var hostScope = hostContextAccessor.BeginScope(context.HostContext); - try - { - var workspace = NormalizeWorkspacePath(context.WorkingDirectory); - var sid = await ResolveCommandSessionIdAsync(workspace, sessionId, context.SessionId, cancellationToken).ConfigureAwait(false); - if (string.IsNullOrWhiteSpace(sid)) - { - return new CommandResult(false, 1, context.OutputFormat, "No session resolved for sharing.", null); - } - - var share = await ExecuteWithSessionLockAsync( - workspace, - sid, - ct => shareSessionService.CreateShareAsync(workspace, sid, ct), - cancellationToken) - .ConfigureAwait(false); - var payload = JsonSerializer.Serialize(share, ProtocolJsonContext.Default.ShareSessionRecord); - return new CommandResult(true, 0, context.OutputFormat, $"Shared session '{sid}' at {share.Url}.", payload); - } - catch (Exception ex) - { - return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); - } - } + public Task ShareSessionAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) + => sessionAdminCommands.ShareSessionAsync(sessionId, context, cancellationToken); /// - public async Task UnshareSessionAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) - { - using var hostScope = hostContextAccessor.BeginScope(context.HostContext); - try - { - var workspace = NormalizeWorkspacePath(context.WorkingDirectory); - var sid = await ResolveCommandSessionIdAsync(workspace, sessionId, context.SessionId, cancellationToken).ConfigureAwait(false); - if (string.IsNullOrWhiteSpace(sid)) - { - return new CommandResult(false, 1, context.OutputFormat, "No session resolved for unshare.", null); - } - - var removed = await ExecuteWithSessionLockAsync( - workspace, - sid, - ct => shareSessionService.RemoveShareAsync(workspace, sid, ct), - cancellationToken) - .ConfigureAwait(false); - return new CommandResult( - removed, - removed ? 0 : 1, - context.OutputFormat, - removed ? $"Removed share for session '{sid}'." : $"Session '{sid}' is not currently shared.", - null); - } - catch (Exception ex) - { - return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); - } - } + public Task UnshareSessionAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) + => sessionAdminCommands.UnshareSessionAsync(sessionId, context, cancellationToken); /// - public async Task CompactSessionAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) - { - using var hostScope = hostContextAccessor.BeginScope(context.HostContext); - try - { - var workspace = NormalizeWorkspacePath(context.WorkingDirectory); - var sid = await ResolveCommandSessionIdAsync(workspace, sessionId, context.SessionId, cancellationToken).ConfigureAwait(false); - if (string.IsNullOrWhiteSpace(sid)) - { - return new CommandResult(false, 1, context.OutputFormat, "No session resolved for compaction.", null); - } - - var result = await ExecuteWithSessionLockAsync( - workspace, - sid, - ct => conversationCompactionService.CompactAsync(workspace, sid, ct), - cancellationToken) - .ConfigureAwait(false); - var payload = JsonSerializer.Serialize(result.Session, ProtocolJsonContext.Default.ConversationSession); - return new CommandResult(true, 0, context.OutputFormat, result.Summary, payload); - } - catch (Exception ex) - { - return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); - } - } + public Task CompactSessionAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) + => sessionAdminCommands.CompactSessionAsync(sessionId, context, cancellationToken); /// - public async Task ForkSessionAsync(string workspacePath, string? sourceSessionId, CancellationToken cancellationToken) - { - var normalized = NormalizeWorkspacePath(workspacePath); - var parent = string.IsNullOrWhiteSpace(sourceSessionId) - ? await sessionStore.GetLatestAsync(normalized, cancellationToken).ConfigureAwait(false) - : await sessionStore.GetByIdAsync(normalized, sourceSessionId, cancellationToken).ConfigureAwait(false); - if (parent is null) - { - throw new InvalidOperationException("Source session was not found."); - } - - var events = await eventStore.ReadAllAsync(normalized, parent.Id, cancellationToken).ConfigureAwait(false); - var summary = BuildForkHistorySummary(events); - - fileSystem.CreateDirectory(storagePathResolver.GetSharpClawRoot(normalized)); - - var childId = CreateIdentifier("session"); - var md = CloneMetadata(parent.Metadata); - md.Remove(SharpClawWorkflowMetadataKeys.UndoRedoStateJson); - md.Remove(CheckpointMutationCoordinator.PartialMutationKey); - md[SharpClawWorkflowMetadataKeys.ParentSessionId] = parent.Id; - md[SharpClawWorkflowMetadataKeys.ForkedAtUtc] = systemClock.UtcNow.ToString("O", CultureInfo.InvariantCulture); - md[SharpClawWorkflowMetadataKeys.ForkHistorySummary] = summary; - md[LastTurnSequenceKey] = "0"; - - var child = new ConversationSession( - Id: childId, - Title: $"Fork of {parent.Id[..Math.Min(8, parent.Id.Length)]}", - State: SessionLifecycleState.Created, - PermissionMode: parent.PermissionMode, - OutputFormat: parent.OutputFormat, - WorkingDirectory: normalized, - RepositoryRoot: normalized, - CreatedAtUtc: systemClock.UtcNow, - UpdatedAtUtc: systemClock.UtcNow, - ActiveTurnId: null, - LastCheckpointId: null, - Metadata: md); - - await sessionStore.SaveAsync(normalized, child, cancellationToken).ConfigureAwait(false); - - await eventPublisher.PublishAsync( - new SessionForkedEvent( - EventId: CreateIdentifier("event"), - SessionId: childId, - TurnId: null, - OccurredAtUtc: systemClock.UtcNow, - ParentSessionId: parent.Id, - ChildSessionId: childId, - ForkedFromCheckpointId: parent.LastCheckpointId), - new RuntimeEventPublishOptions(normalized, childId, PersistToSessionStore: true), - cancellationToken).ConfigureAwait(false); - - return child; - } - - private static string BuildForkHistorySummary(IReadOnlyList events) - { - var completedTurns = events.OfType().Count(); - return completedTurns == 0 - ? "Forked from parent session (no completed turns in persisted event log)." - : $"Forked from parent session with {completedTurns} completed turn(s) in the persisted log."; - } + public Task ForkSessionAsync(string workspacePath, string? sourceSessionId, CancellationToken cancellationToken) + => sessionAdminCommands.ForkSessionAsync(workspacePath, sourceSessionId, cancellationToken); private async Task EnsurePrimaryModePersistedAsync( string workspacePath, @@ -1375,34 +1025,6 @@ await AppendEventAsync( return updatedSession; } - private async Task ResolveCommandSessionIdAsync( - string workspacePath, - string? explicitSessionId, - string? contextSessionId, - CancellationToken cancellationToken) - { - if (!string.IsNullOrWhiteSpace(explicitSessionId)) - { - return explicitSessionId; - } - - if (!string.IsNullOrWhiteSpace(contextSessionId)) - { - return contextSessionId; - } - - var attached = await workspaceSessionAttachmentStore - .GetAttachedSessionIdAsync(workspacePath, cancellationToken) - .ConfigureAwait(false); - if (!string.IsNullOrWhiteSpace(attached)) - { - return attached; - } - - var latest = await sessionStore.GetLatestAsync(workspacePath, cancellationToken).ConfigureAwait(false); - return latest?.Id; - } - private async Task ApplyAgentAndConfigDefaultsAsync( string workspacePath, RunPromptRequest request, @@ -1504,62 +1126,6 @@ private Task DispatchHookAsync(string workspacePath, RuntimeEvent runtimeEvent, private string NormalizeWorkspacePath(string? workspacePath) => pathService.GetFullPath(string.IsNullOrWhiteSpace(workspacePath) ? pathService.GetCurrentDirectory() : workspacePath); - private Task ExecuteWithSessionLockAsync( - string workspacePath, - string sessionId, - Func> operation, - CancellationToken cancellationToken) - => sessionTurnLock.ExecuteAsync(workspacePath, sessionId, operation, cancellationToken); - - private static string CreateIdentifier(string prefix) - => $"{prefix}-{Guid.NewGuid():N}"; - - private static int GetLastTurnSequence(ConversationSession session) - => session.Metadata is not null - && session.Metadata.TryGetValue(LastTurnSequenceKey, out var sequenceText) - && int.TryParse(sequenceText, CultureInfo.InvariantCulture, out var sequence) - ? sequence - : 0; - - private static Dictionary CloneMetadata(Dictionary? metadata) - => metadata is null - ? [] - : new Dictionary(metadata, StringComparer.Ordinal); - - private static Dictionary MergeMetadata( - Dictionary? metadata, - PermissionMode permissionMode, - OutputFormat outputFormat, - PrimaryMode primaryMode, - ApprovalSettings? approvalSettings) - { - var merged = CloneMetadata(metadata); - merged["permissionMode"] = permissionMode.ToString(); - merged["outputFormat"] = outputFormat.ToString(); - merged[SharpClawWorkflowMetadataKeys.PrimaryMode] = primaryMode.ToString(); - if (approvalSettings is not null && approvalSettings.AutoApproveScopes.Count > 0) - { - merged[SharpClawWorkflowMetadataKeys.ApprovalAutoApproveScopesJson] = JsonSerializer.Serialize( - approvalSettings.AutoApproveScopes.ToList(), - ProtocolJsonContext.Default.ListApprovalScope); - } - else - { - merged.Remove(SharpClawWorkflowMetadataKeys.ApprovalAutoApproveScopesJson); - } - - if (approvalSettings?.AutoApproveBudget is { } budget) - { - merged[SharpClawWorkflowMetadataKeys.ApprovalAutoApproveBudget] = budget.ToString(CultureInfo.InvariantCulture); - } - else - { - merged.Remove(SharpClawWorkflowMetadataKeys.ApprovalAutoApproveBudget); - } - - return merged; - } - /// /// Workspace markdown cannot raise permission above the caller's mode; lower modes win. /// diff --git a/src/SharpClaw.Code.Runtime/Orchestration/SessionAdminCommands.cs b/src/SharpClaw.Code.Runtime/Orchestration/SessionAdminCommands.cs new file mode 100644 index 0000000..9e59a17 --- /dev/null +++ b/src/SharpClaw.Code.Runtime/Orchestration/SessionAdminCommands.cs @@ -0,0 +1,480 @@ +using System.Globalization; +using System.Text.Json; +using SharpClaw.Code.Infrastructure.Abstractions; +using SharpClaw.Code.Protocol.Abstractions; +using SharpClaw.Code.Protocol.Commands; +using SharpClaw.Code.Protocol.Enums; +using SharpClaw.Code.Protocol.Events; +using SharpClaw.Code.Protocol.Models; +using SharpClaw.Code.Protocol.Serialization; +using SharpClaw.Code.Runtime.Abstractions; +using SharpClaw.Code.Runtime.Export; +using SharpClaw.Code.Runtime.Mutations; +using SharpClaw.Code.Runtime.Workflow; +using SharpClaw.Code.Sessions.Abstractions; +using SharpClaw.Code.Telemetry; +using SharpClaw.Code.Telemetry.Abstractions; +using static SharpClaw.Code.Runtime.Orchestration.SessionMetadataHelpers; + +namespace SharpClaw.Code.Runtime.Orchestration; + +/// +/// Session administration commands: fork, export, portable bundles, attach/detach, list, share/unshare, compact, undo/redo. +/// Commands that mutate a session hold so they never interleave with a running turn. +/// exposes them through and . +/// +public sealed class SessionAdminCommands( + ISessionStore sessionStore, + IEventStore eventStore, + IRuntimeEventPublisher eventPublisher, + ISystemClock systemClock, + IFileSystem fileSystem, + IPathService pathService, + IRuntimeStoragePathResolver storagePathResolver, + IRuntimeHostContextAccessor hostContextAccessor, + ISessionExportService sessionExportService, + IWorkspaceSessionAttachmentStore workspaceSessionAttachmentStore, + CheckpointMutationCoordinator checkpointMutationCoordinator, + ISessionCoordinator sessionCoordinator, + IPortableSessionBundleService portableSessionBundleService, + IShareSessionService shareSessionService, + IConversationCompactionService conversationCompactionService, + SessionTurnLock sessionTurnLock) +{ + /// + public async Task ForkSessionAsync( + string? sourceSessionId, + RuntimeCommandContext context, + CancellationToken cancellationToken) + { + using var hostScope = hostContextAccessor.BeginScope(context.HostContext); + try + { + var child = await ForkSessionAsync(NormalizeWorkspacePath(context.WorkingDirectory), sourceSessionId, cancellationToken) + .ConfigureAwait(false); + var payload = JsonSerializer.Serialize(child, ProtocolJsonContext.Default.ConversationSession); + return new CommandResult( + true, + 0, + context.OutputFormat, + $"Forked session {child.Id} from '{child.Metadata?.GetValueOrDefault(SharpClawWorkflowMetadataKeys.ParentSessionId) ?? "?"}'.", + payload); + } + catch (Exception ex) + { + return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); + } + } + + /// + public async Task ExportSessionAsync( + string? sessionId, + SessionExportFormat format, + string? outputFilePath, + RuntimeCommandContext context, + CancellationToken cancellationToken) + { + using var hostScope = hostContextAccessor.BeginScope(context.HostContext); + try + { + var workspace = NormalizeWorkspacePath(context.WorkingDirectory); + var (document, ext) = await sessionExportService + .BuildDocumentAsync(workspace, sessionId, format, cancellationToken) + .ConfigureAwait(false); + + var exportsDir = storagePathResolver.GetExportsRoot(workspace); + fileSystem.CreateDirectory(exportsDir); + var fileName = + $"{document.Session.Id}-{document.ExportedAtUtc:yyyyMMddTHHmmss}.{ext}"; + var targetPath = string.IsNullOrWhiteSpace(outputFilePath) + ? pathService.Combine(exportsDir, fileName) + : pathService.GetFullPath(outputFilePath); + + var text = format == SessionExportFormat.Json + ? JsonSerializer.Serialize(document, ProtocolJsonContext.Default.SessionExportDocument) + : sessionExportService.RenderMarkdown(document); + + await fileSystem.WriteAllTextAsync(targetPath, text, cancellationToken).ConfigureAwait(false); + + return new CommandResult( + true, + 0, + context.OutputFormat, + $"Exported session to '{targetPath}'.", + JsonSerializer.Serialize( + new Dictionary { ["path"] = targetPath, ["format"] = ext }, + ProtocolJsonContext.Default.DictionaryStringString)); + } + catch (Exception ex) + { + return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); + } + } + + /// + public async Task UndoAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) + { + using var hostScope = hostContextAccessor.BeginScope(context.HostContext); + try + { + var workspace = NormalizeWorkspacePath(context.WorkingDirectory); + var sid = await ResolveCommandSessionIdAsync(workspace, sessionId, context.SessionId, cancellationToken).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(sid)) + { + return new CommandResult(false, 1, context.OutputFormat, "No session resolved for undo.", null); + } + + var result = await checkpointMutationCoordinator + .TryUndoAsync( + workspace, + sid, + cancellationToken, + operation => ExecuteWithSessionLockAsync(workspace, sid, operation, cancellationToken)) + .ConfigureAwait(false); + var payload = JsonSerializer.Serialize(result, ProtocolJsonContext.Default.UndoRedoActionResult); + return new CommandResult(result.Succeeded, result.Succeeded ? 0 : 1, context.OutputFormat, result.Message, payload); + } + catch (Exception ex) + { + return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); + } + } + + /// + public async Task RedoAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) + { + using var hostScope = hostContextAccessor.BeginScope(context.HostContext); + try + { + var workspace = NormalizeWorkspacePath(context.WorkingDirectory); + var sid = await ResolveCommandSessionIdAsync(workspace, sessionId, context.SessionId, cancellationToken).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(sid)) + { + return new CommandResult(false, 1, context.OutputFormat, "No session resolved for redo.", null); + } + + var result = await checkpointMutationCoordinator + .TryRedoAsync( + workspace, + sid, + cancellationToken, + operation => ExecuteWithSessionLockAsync(workspace, sid, operation, cancellationToken)) + .ConfigureAwait(false); + var payload = JsonSerializer.Serialize(result, ProtocolJsonContext.Default.UndoRedoActionResult); + return new CommandResult(result.Succeeded, result.Succeeded ? 0 : 1, context.OutputFormat, result.Message, payload); + } + catch (Exception ex) + { + return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); + } + } + + /// + public async Task ExportPortableSessionBundleAsync( + string? sessionId, + string? outputZipPath, + RuntimeCommandContext context, + CancellationToken cancellationToken) + { + using var hostScope = hostContextAccessor.BeginScope(context.HostContext); + try + { + var workspace = NormalizeWorkspacePath(context.WorkingDirectory); + var path = await portableSessionBundleService + .CreateBundleZipAsync(workspace, sessionId, outputZipPath, cancellationToken) + .ConfigureAwait(false); + return new CommandResult( + true, + 0, + context.OutputFormat, + $"Portable bundle written to '{path}'.", + JsonSerializer.Serialize( + new Dictionary { ["path"] = path }, + ProtocolJsonContext.Default.DictionaryStringString)); + } + catch (Exception ex) + { + return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); + } + } + + /// + public async Task ImportPortableSessionBundleAsync( + string bundleZipPath, + bool replaceExisting, + bool attachAfterImport, + RuntimeCommandContext context, + CancellationToken cancellationToken) + { + using var hostScope = hostContextAccessor.BeginScope(context.HostContext); + try + { + var workspace = NormalizeWorkspacePath(context.WorkingDirectory); + var zip = pathService.GetFullPath(bundleZipPath); + var result = await portableSessionBundleService + .ImportBundleZipAsync(workspace, zip, replaceExisting, cancellationToken) + .ConfigureAwait(false); + if (attachAfterImport) + { + await sessionCoordinator.AttachSessionAsync(workspace, result.SessionId, cancellationToken).ConfigureAwait(false); + } + + var message = attachAfterImport + ? $"Imported session '{result.SessionId}' and attached it for this workspace." + : $"Imported session '{result.SessionId}'."; + var payload = JsonSerializer.Serialize(result, ProtocolJsonContext.Default.PortableBundleImportResult); + return new CommandResult(true, 0, context.OutputFormat, message, payload); + } + catch (Exception ex) + { + return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); + } + } + + /// + public async Task ListSessionsAsync(RuntimeCommandContext context, CancellationToken cancellationToken) + { + using var hostScope = hostContextAccessor.BeginScope(context.HostContext); + try + { + var workspace = NormalizeWorkspacePath(context.WorkingDirectory); + var rows = await sessionCoordinator.ListSessionsAsync(workspace, cancellationToken).ConfigureAwait(false); + var payload = JsonSerializer.Serialize(rows, ProtocolJsonContext.Default.ListSessionSummaryRow); + return new CommandResult(true, 0, context.OutputFormat, $"{rows.Count} session(s).", payload); + } + catch (Exception ex) + { + return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); + } + } + + /// + public async Task AttachSessionAsync(string sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) + { + using var hostScope = hostContextAccessor.BeginScope(context.HostContext); + try + { + var workspace = NormalizeWorkspacePath(context.WorkingDirectory); + await sessionCoordinator.AttachSessionAsync(workspace, sessionId, cancellationToken).ConfigureAwait(false); + return new CommandResult( + true, + 0, + context.OutputFormat, + $"Attached session '{sessionId}' for workspace prompts.", + JsonSerializer.Serialize( + new Dictionary { ["sessionId"] = sessionId }, + ProtocolJsonContext.Default.DictionaryStringString)); + } + catch (Exception ex) + { + return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); + } + } + + /// + public async Task DetachSessionAsync(RuntimeCommandContext context, CancellationToken cancellationToken) + { + using var hostScope = hostContextAccessor.BeginScope(context.HostContext); + try + { + var workspace = NormalizeWorkspacePath(context.WorkingDirectory); + await sessionCoordinator.DetachSessionAsync(workspace, cancellationToken).ConfigureAwait(false); + return new CommandResult(true, 0, context.OutputFormat, "Detached explicit workspace session.", null); + } + catch (Exception ex) + { + return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); + } + } + + /// + public async Task ShareSessionAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) + { + using var hostScope = hostContextAccessor.BeginScope(context.HostContext); + try + { + var workspace = NormalizeWorkspacePath(context.WorkingDirectory); + var sid = await ResolveCommandSessionIdAsync(workspace, sessionId, context.SessionId, cancellationToken).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(sid)) + { + return new CommandResult(false, 1, context.OutputFormat, "No session resolved for sharing.", null); + } + + var share = await ExecuteWithSessionLockAsync( + workspace, + sid, + ct => shareSessionService.CreateShareAsync(workspace, sid, ct), + cancellationToken) + .ConfigureAwait(false); + var payload = JsonSerializer.Serialize(share, ProtocolJsonContext.Default.ShareSessionRecord); + return new CommandResult(true, 0, context.OutputFormat, $"Shared session '{sid}' at {share.Url}.", payload); + } + catch (Exception ex) + { + return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); + } + } + + /// + public async Task UnshareSessionAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) + { + using var hostScope = hostContextAccessor.BeginScope(context.HostContext); + try + { + var workspace = NormalizeWorkspacePath(context.WorkingDirectory); + var sid = await ResolveCommandSessionIdAsync(workspace, sessionId, context.SessionId, cancellationToken).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(sid)) + { + return new CommandResult(false, 1, context.OutputFormat, "No session resolved for unshare.", null); + } + + var removed = await ExecuteWithSessionLockAsync( + workspace, + sid, + ct => shareSessionService.RemoveShareAsync(workspace, sid, ct), + cancellationToken) + .ConfigureAwait(false); + return new CommandResult( + removed, + removed ? 0 : 1, + context.OutputFormat, + removed ? $"Removed share for session '{sid}'." : $"Session '{sid}' is not currently shared.", + null); + } + catch (Exception ex) + { + return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); + } + } + + /// + public async Task CompactSessionAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken) + { + using var hostScope = hostContextAccessor.BeginScope(context.HostContext); + try + { + var workspace = NormalizeWorkspacePath(context.WorkingDirectory); + var sid = await ResolveCommandSessionIdAsync(workspace, sessionId, context.SessionId, cancellationToken).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(sid)) + { + return new CommandResult(false, 1, context.OutputFormat, "No session resolved for compaction.", null); + } + + var result = await ExecuteWithSessionLockAsync( + workspace, + sid, + ct => conversationCompactionService.CompactAsync(workspace, sid, ct), + cancellationToken) + .ConfigureAwait(false); + var payload = JsonSerializer.Serialize(result.Session, ProtocolJsonContext.Default.ConversationSession); + return new CommandResult(true, 0, context.OutputFormat, result.Summary, payload); + } + catch (Exception ex) + { + return new CommandResult(false, 1, context.OutputFormat, ex.Message, null); + } + } + + /// + public async Task ForkSessionAsync(string workspacePath, string? sourceSessionId, CancellationToken cancellationToken) + { + var normalized = NormalizeWorkspacePath(workspacePath); + var parent = string.IsNullOrWhiteSpace(sourceSessionId) + ? await sessionStore.GetLatestAsync(normalized, cancellationToken).ConfigureAwait(false) + : await sessionStore.GetByIdAsync(normalized, sourceSessionId, cancellationToken).ConfigureAwait(false); + if (parent is null) + { + throw new InvalidOperationException("Source session was not found."); + } + + var events = await eventStore.ReadAllAsync(normalized, parent.Id, cancellationToken).ConfigureAwait(false); + var summary = BuildForkHistorySummary(events); + + fileSystem.CreateDirectory(storagePathResolver.GetSharpClawRoot(normalized)); + + var childId = CreateIdentifier("session"); + var md = CloneMetadata(parent.Metadata); + md.Remove(SharpClawWorkflowMetadataKeys.UndoRedoStateJson); + md.Remove(CheckpointMutationCoordinator.PartialMutationKey); + md[SharpClawWorkflowMetadataKeys.ParentSessionId] = parent.Id; + md[SharpClawWorkflowMetadataKeys.ForkedAtUtc] = systemClock.UtcNow.ToString("O", CultureInfo.InvariantCulture); + md[SharpClawWorkflowMetadataKeys.ForkHistorySummary] = summary; + md[LastTurnSequenceKey] = "0"; + + var child = new ConversationSession( + Id: childId, + Title: $"Fork of {parent.Id[..Math.Min(8, parent.Id.Length)]}", + State: SessionLifecycleState.Created, + PermissionMode: parent.PermissionMode, + OutputFormat: parent.OutputFormat, + WorkingDirectory: normalized, + RepositoryRoot: normalized, + CreatedAtUtc: systemClock.UtcNow, + UpdatedAtUtc: systemClock.UtcNow, + ActiveTurnId: null, + LastCheckpointId: null, + Metadata: md); + + await sessionStore.SaveAsync(normalized, child, cancellationToken).ConfigureAwait(false); + + await eventPublisher.PublishAsync( + new SessionForkedEvent( + EventId: CreateIdentifier("event"), + SessionId: childId, + TurnId: null, + OccurredAtUtc: systemClock.UtcNow, + ParentSessionId: parent.Id, + ChildSessionId: childId, + ForkedFromCheckpointId: parent.LastCheckpointId), + new RuntimeEventPublishOptions(normalized, childId, PersistToSessionStore: true), + cancellationToken).ConfigureAwait(false); + + return child; + } + + private static string BuildForkHistorySummary(IReadOnlyList events) + { + var completedTurns = events.OfType().Count(); + return completedTurns == 0 + ? "Forked from parent session (no completed turns in persisted event log)." + : $"Forked from parent session with {completedTurns} completed turn(s) in the persisted log."; + } + + private async Task ResolveCommandSessionIdAsync( + string workspacePath, + string? explicitSessionId, + string? contextSessionId, + CancellationToken cancellationToken) + { + if (!string.IsNullOrWhiteSpace(explicitSessionId)) + { + return explicitSessionId; + } + + if (!string.IsNullOrWhiteSpace(contextSessionId)) + { + return contextSessionId; + } + + var attached = await workspaceSessionAttachmentStore + .GetAttachedSessionIdAsync(workspacePath, cancellationToken) + .ConfigureAwait(false); + if (!string.IsNullOrWhiteSpace(attached)) + { + return attached; + } + + var latest = await sessionStore.GetLatestAsync(workspacePath, cancellationToken).ConfigureAwait(false); + return latest?.Id; + } + + private string NormalizeWorkspacePath(string? workspacePath) + => pathService.GetFullPath(string.IsNullOrWhiteSpace(workspacePath) ? pathService.GetCurrentDirectory() : workspacePath); + + private Task ExecuteWithSessionLockAsync( + string workspacePath, + string sessionId, + Func> operation, + CancellationToken cancellationToken) + => sessionTurnLock.ExecuteAsync(workspacePath, sessionId, operation, cancellationToken); +} diff --git a/src/SharpClaw.Code.Runtime/Orchestration/SessionMetadataHelpers.cs b/src/SharpClaw.Code.Runtime/Orchestration/SessionMetadataHelpers.cs new file mode 100644 index 0000000..63ca77d --- /dev/null +++ b/src/SharpClaw.Code.Runtime/Orchestration/SessionMetadataHelpers.cs @@ -0,0 +1,64 @@ +using System.Globalization; +using System.Text.Json; +using SharpClaw.Code.Protocol.Enums; +using SharpClaw.Code.Protocol.Models; +using SharpClaw.Code.Protocol.Serialization; + +namespace SharpClaw.Code.Runtime.Orchestration; + +/// +/// Identifier and session-metadata helpers shared by the turn pipeline and session admin commands. +/// +internal static class SessionMetadataHelpers +{ + internal const string LastTurnSequenceKey = "lastTurnSequence"; + + internal static string CreateIdentifier(string prefix) + => $"{prefix}-{Guid.NewGuid():N}"; + + internal static int GetLastTurnSequence(ConversationSession session) + => session.Metadata is not null + && session.Metadata.TryGetValue(LastTurnSequenceKey, out var sequenceText) + && int.TryParse(sequenceText, CultureInfo.InvariantCulture, out var sequence) + ? sequence + : 0; + + internal static Dictionary CloneMetadata(Dictionary? metadata) + => metadata is null + ? [] + : new Dictionary(metadata, StringComparer.Ordinal); + + internal static Dictionary MergeMetadata( + Dictionary? metadata, + PermissionMode permissionMode, + OutputFormat outputFormat, + PrimaryMode primaryMode, + ApprovalSettings? approvalSettings) + { + var merged = CloneMetadata(metadata); + merged["permissionMode"] = permissionMode.ToString(); + merged["outputFormat"] = outputFormat.ToString(); + merged[SharpClawWorkflowMetadataKeys.PrimaryMode] = primaryMode.ToString(); + if (approvalSettings is not null && approvalSettings.AutoApproveScopes.Count > 0) + { + merged[SharpClawWorkflowMetadataKeys.ApprovalAutoApproveScopesJson] = JsonSerializer.Serialize( + approvalSettings.AutoApproveScopes.ToList(), + ProtocolJsonContext.Default.ListApprovalScope); + } + else + { + merged.Remove(SharpClawWorkflowMetadataKeys.ApprovalAutoApproveScopesJson); + } + + if (approvalSettings?.AutoApproveBudget is { } budget) + { + merged[SharpClawWorkflowMetadataKeys.ApprovalAutoApproveBudget] = budget.ToString(CultureInfo.InvariantCulture); + } + else + { + merged.Remove(SharpClawWorkflowMetadataKeys.ApprovalAutoApproveBudget); + } + + return merged; + } +} From 6c0c37c15fdf156f9d7933c629125d45c5443363 Mon Sep 17 00:00:00 2001 From: telli Date: Tue, 10 Nov 2026 05:06:01 -0800 Subject: [PATCH 12/12] Fix session, schedule, and evolution list commands They passed IReadOnlyList values (arrays at runtime) with a List JsonTypeInfo, which binds the non-generic Serialize(object, JsonTypeInfo) overload and throws InvalidCastException. 'session list', 'schedule list', 'evolution list', and 'evolution analyze' always failed; the schedule and proposal stores had the same latent bug on save. Found while smoke-testing the ConversationRuntime split; adds a session-list regression test. Co-Authored-By: Claude Opus 5.5 --- .../Handlers/EvolutionCommandHandler.cs | 4 ++-- .../Handlers/ScheduleCommandHandler.cs | 2 +- .../Orchestration/SessionAdminCommands.cs | 2 +- .../Storage/FileEvolutionProposalStore.cs | 2 +- .../Storage/FileScheduledPromptStore.cs | 2 +- .../Runtime/SpecModeWorkflowTests.cs | 20 +++++++++++++++++++ 6 files changed, 26 insertions(+), 6 deletions(-) diff --git a/src/SharpClaw.Code.Commands/Handlers/EvolutionCommandHandler.cs b/src/SharpClaw.Code.Commands/Handlers/EvolutionCommandHandler.cs index ca011f5..cd6835b 100644 --- a/src/SharpClaw.Code.Commands/Handlers/EvolutionCommandHandler.cs +++ b/src/SharpClaw.Code.Commands/Handlers/EvolutionCommandHandler.cs @@ -100,7 +100,7 @@ private async Task ExecuteAnalyzeAsync(CommandExecutionContext context, Can { var proposals = await evolutionProposalService.AnalyzeAsync(context.WorkingDirectory, context.SessionId, cancellationToken).ConfigureAwait(false); await outputRendererDispatcher.RenderCommandResultAsync( - new CommandResult(true, 0, context.OutputFormat, $"{proposals.Count} evolution proposal(s).", JsonSerializer.Serialize(proposals, ProtocolJsonContext.Default.ListEvolutionProposal)), + new CommandResult(true, 0, context.OutputFormat, $"{proposals.Count} evolution proposal(s).", JsonSerializer.Serialize(proposals.ToList(), ProtocolJsonContext.Default.ListEvolutionProposal)), context.OutputFormat, cancellationToken).ConfigureAwait(false); return 0; @@ -110,7 +110,7 @@ private async Task ExecuteListAsync(CommandExecutionContext context, Cancel { var proposals = await evolutionProposalService.ListAsync(context.WorkingDirectory, cancellationToken).ConfigureAwait(false); await outputRendererDispatcher.RenderCommandResultAsync( - new CommandResult(true, 0, context.OutputFormat, $"{proposals.Count} evolution proposal(s).", JsonSerializer.Serialize(proposals, ProtocolJsonContext.Default.ListEvolutionProposal)), + new CommandResult(true, 0, context.OutputFormat, $"{proposals.Count} evolution proposal(s).", JsonSerializer.Serialize(proposals.ToList(), ProtocolJsonContext.Default.ListEvolutionProposal)), context.OutputFormat, cancellationToken).ConfigureAwait(false); return 0; diff --git a/src/SharpClaw.Code.Commands/Handlers/ScheduleCommandHandler.cs b/src/SharpClaw.Code.Commands/Handlers/ScheduleCommandHandler.cs index e346935..3340010 100644 --- a/src/SharpClaw.Code.Commands/Handlers/ScheduleCommandHandler.cs +++ b/src/SharpClaw.Code.Commands/Handlers/ScheduleCommandHandler.cs @@ -180,7 +180,7 @@ private async Task ExecuteListAsync(CommandExecutionContext context, Cancel { var schedules = await scheduledPromptService.ListAsync(context.WorkingDirectory, cancellationToken).ConfigureAwait(false); await outputRendererDispatcher.RenderCommandResultAsync( - new CommandResult(true, 0, context.OutputFormat, $"{schedules.Count} scheduled prompt(s).", JsonSerializer.Serialize(schedules, ProtocolJsonContext.Default.ListScheduledPromptDefinition)), + new CommandResult(true, 0, context.OutputFormat, $"{schedules.Count} scheduled prompt(s).", JsonSerializer.Serialize(schedules.ToList(), ProtocolJsonContext.Default.ListScheduledPromptDefinition)), context.OutputFormat, cancellationToken).ConfigureAwait(false); return 0; diff --git a/src/SharpClaw.Code.Runtime/Orchestration/SessionAdminCommands.cs b/src/SharpClaw.Code.Runtime/Orchestration/SessionAdminCommands.cs index 9e59a17..8dc6910 100644 --- a/src/SharpClaw.Code.Runtime/Orchestration/SessionAdminCommands.cs +++ b/src/SharpClaw.Code.Runtime/Orchestration/SessionAdminCommands.cs @@ -239,7 +239,7 @@ public async Task ListSessionsAsync(RuntimeCommandContext context { var workspace = NormalizeWorkspacePath(context.WorkingDirectory); var rows = await sessionCoordinator.ListSessionsAsync(workspace, cancellationToken).ConfigureAwait(false); - var payload = JsonSerializer.Serialize(rows, ProtocolJsonContext.Default.ListSessionSummaryRow); + var payload = JsonSerializer.Serialize(rows.ToList(), ProtocolJsonContext.Default.ListSessionSummaryRow); return new CommandResult(true, 0, context.OutputFormat, $"{rows.Count} session(s).", payload); } catch (Exception ex) diff --git a/src/SharpClaw.Code.Sessions/Storage/FileEvolutionProposalStore.cs b/src/SharpClaw.Code.Sessions/Storage/FileEvolutionProposalStore.cs index 30c45f0..6510774 100644 --- a/src/SharpClaw.Code.Sessions/Storage/FileEvolutionProposalStore.cs +++ b/src/SharpClaw.Code.Sessions/Storage/FileEvolutionProposalStore.cs @@ -80,6 +80,6 @@ private async Task> LoadAsync(string path, Canc private Task SaveAsync(string path, IReadOnlyList items, CancellationToken cancellationToken) => fileSystem.WriteAllTextAsync( path, - JsonSerializer.Serialize(items, ProtocolJsonContext.Default.ListEvolutionProposal), + JsonSerializer.Serialize(items.ToList(), ProtocolJsonContext.Default.ListEvolutionProposal), cancellationToken); } diff --git a/src/SharpClaw.Code.Sessions/Storage/FileScheduledPromptStore.cs b/src/SharpClaw.Code.Sessions/Storage/FileScheduledPromptStore.cs index 6494358..3ed2355 100644 --- a/src/SharpClaw.Code.Sessions/Storage/FileScheduledPromptStore.cs +++ b/src/SharpClaw.Code.Sessions/Storage/FileScheduledPromptStore.cs @@ -81,6 +81,6 @@ private async Task> LoadAsync(string pa private Task SaveAsync(string path, IReadOnlyList items, CancellationToken cancellationToken) => fileSystem.WriteAllTextAsync( path, - JsonSerializer.Serialize(items, ProtocolJsonContext.Default.ListScheduledPromptDefinition), + JsonSerializer.Serialize(items.ToList(), ProtocolJsonContext.Default.ListScheduledPromptDefinition), cancellationToken); } diff --git a/tests/SharpClaw.Code.IntegrationTests/Runtime/SpecModeWorkflowTests.cs b/tests/SharpClaw.Code.IntegrationTests/Runtime/SpecModeWorkflowTests.cs index 6d69033..febcf13 100644 --- a/tests/SharpClaw.Code.IntegrationTests/Runtime/SpecModeWorkflowTests.cs +++ b/tests/SharpClaw.Code.IntegrationTests/Runtime/SpecModeWorkflowTests.cs @@ -194,6 +194,26 @@ await File.WriteAllTextAsync( .Should().BeEquivalentTo(nameof(PrimaryMode.Research)); } + /// + /// Ensures listing sessions succeeds and returns JSON rows (the payload type once failed to cast). + /// + [Fact] + public async Task ListSessions_should_return_rows_for_created_sessions() + { + var workspacePath = CreateTemporaryWorkspace(); + using var serviceProvider = CreateRuntimeServices(_ => { }); + var conversation = serviceProvider.GetRequiredService(); + var commands = serviceProvider.GetRequiredService(); + var session = await conversation.CreateSessionAsync(workspacePath, PermissionMode.WorkspaceWrite, OutputFormat.Json, CancellationToken.None); + + var result = await commands.ListSessionsAsync( + new RuntimeCommandContext(workspacePath, null, PermissionMode.WorkspaceWrite, OutputFormat.Json), + CancellationToken.None); + + result.Succeeded.Should().BeTrue(result.Message); + result.DataJson.Should().Contain(session.Id); + } + private static string CreateTemporaryWorkspace() { var workspacePath = Path.Combine(Path.GetTempPath(), "sharpclaw-spec-mode-tests", Guid.NewGuid().ToString("N"));