2 Commits
Author SHA1 Message Date
owen 8ffc5284e3 Refine system prompt for v0.2.4
CI / Test (push) Waiting to run
CI / Build (push) Waiting to run
2026-06-24 20:46:27 -05:00
owen 7f0f1619af Update roadmap planned release section 2026-06-24 03:33:23 -05:00
9 changed files with 844 additions and 105 deletions
Generated
+1 -1
View File
@@ -151,7 +151,7 @@ checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593"
[[package]]
name = "cassady"
version = "0.2.3"
version = "0.2.4"
dependencies = [
"anyhow",
"async-trait",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "cassady"
version = "0.2.3"
version = "0.2.4"
edition = "2021"
description = "Cassady/Cass minimal terminal coding agent"
license = "MIT"
+1 -1
View File
@@ -105,7 +105,7 @@ Cassady stores user-editable files in `~/.cass`:
- `config.json`: active defaults and preferences.
- `providers.json`: provider base URLs and API key references.
- `models.json`: model metadata.
- `global.md`: optional global instructions added to new chats.
- `global.md`: optional global instructions added to new chat system prompts when they fit the active request; they cannot override access modes, tool denials, approvals, or workspace boundaries.
- `docs/`: bundled documentation installed from the current binary.
API key references should usually be written as environment variables such as `"$OPENAI_API_KEY"`.
+137 -85
View File
@@ -1,102 +1,56 @@
# Cassady (Cass) Roadmap
## v0.2.4 — Windows CLI Usability
## v0.2.4 — System Prompt Refinement
This release focuses on making Cassady feel reliable and native when the CLI is run on Windows. It covers runtime usability after `cass` or `cassady` is already available on the machine; installers, package managers, PATH setup, code signing, and update delivery are intentionally out of scope.
This release focuses on making Cassady's system prompt clearer, more intuitive, and more useful for everyday coding work without letting it become bulky. The target is a well-structured prompt around 1,000 tokens that gives the model enough product context, safety expectations, and workflow guidance to behave consistently across read-only, workspace-edit, and full-access sessions. See `plans/V0_2_4_SYSTEM_PROMPT_REFINEMENT_PLAN.md`.
### Terminal Experience
### Prompt Structure and Content
- [ ] **Make interactive rendering robust in Windows terminals.** Ensure chat, setup, confirmation prompts, streamed output, spinners, diffs, and tool summaries render cleanly in Windows Terminal, PowerShell, Command Prompt, and common VS Code integrated terminals.
- Enable or gracefully detect ANSI/VT support instead of emitting broken escape sequences.
- Respect `NO_COLOR`, non-interactive output, redirected stdout/stderr, and narrow terminal widths.
- Avoid relying on glyphs, emoji, box drawing, or cursor control sequences that render poorly on default Windows fonts.
- Keep wrapping and cursor positioning correct for multi-line input, Markdown output, and long tool-call summaries.
- [x] **Restructure the prompt into clear sections.** Replace the current compact prompt with a polished, scannable structure that explains identity, operating principles, tool use, editing, safety, and response style in a predictable order.
- Keep headings short and model-friendly so the prompt is easy to follow during long sessions.
- Preserve the existing split between the reusable base prompt, user global instructions, and runtime constraints.
- Avoid duplicating long documentation that already lives in README or bundled docs.
- [ ] **Harden keyboard handling on Windows.** Make the TUI and prompts respond predictably to Windows console input events.
- Verify `Enter`, `Backspace`, `Delete`, arrow keys, `Home`, `End`, `PageUp`, `PageDown`, `Tab`, and paste behavior.
- Preserve existing `Ctrl-C` cancellation semantics and handle `Ctrl-Break`/console close events gracefully where supported.
- Ensure `Esc` cancellation and prompt dismissal work consistently across PowerShell, Command Prompt, and Windows Terminal.
- [x] **Add enough product context for intuitive behavior.** Teach the model what Cassady is, how the terminal chat works, and what the user can see without over-explaining implementation details.
- Explain that tool calls, tool results, diffs, approvals, and streamed assistant text are visible in the transcript.
- Clarify that Cassady is a coding assistant for real project work, so it should inspect before changing files, make targeted edits, and summarize outcomes honestly.
- Include guidance for asking focused follow-up questions only when necessary, instead of over-planning or guessing.
- [ ] **Improve plain CLI output for Windows users.** Commands such as `cass check`, setup diagnostics, validation errors, and usage text should remain readable without a fully interactive terminal.
- Prefer actionable Windows examples using PowerShell syntax when the current platform is Windows.
- Avoid POSIX-only command snippets in runtime guidance unless explicitly labeled.
- Keep error messages copy/paste-friendly and free of terminal control characters when output is redirected.
- [x] **Keep the prompt intentionally compact.** Aim for roughly 900-1,100 tokens for the normal effective system prompt, including runtime access-mode guidance but excluding user-provided global instructions.
- Prefer dense, high-signal instructions over broad lists of examples.
- Remove redundant wording when new guidance overlaps with existing safety or response rules.
- Add a lightweight test or snapshot check so future prompt changes do not accidentally grow far beyond the intended size.
### Windows Paths and Files
### Tool, Editing, and Safety Guidance
- [ ] **Support Windows path syntax everywhere the CLI accepts paths.** Normalize and validate paths consistently across arguments, tool calls, diffs, session metadata, and model-visible file references.
- Handle drive-letter paths such as `C:\Users\name\project`, rooted paths such as `\temp`, UNC paths such as `\\server\share\repo`, and mixed `/`/`\` separators.
- Preserve user-facing paths in a readable Windows form while using canonicalized paths for safety decisions.
- Avoid treating `:` in drive letters as URL schemes or command separators.
- Add tests for relative path resolution from Windows workspaces and for paths containing spaces, apostrophes, parentheses, brackets, and non-ASCII characters.
- [x] **Improve tool-use instructions.** Make the prompt explicit about when to read, grep, edit, write, and shell while still letting the model choose the right tool for the task.
- Encourage targeted inspection before edits and `grep`/search before opening large or unknown files.
- Explain that the model should request tools directly when useful; Cassady will enforce access policy, denials, and approval prompts at runtime.
- Remind the model not to claim a tool succeeded until the tool result confirms it.
- [ ] **Respect Windows filesystem semantics in workspace policy.** Keep read, write, edit, and shell safety checks correct on NTFS and common Windows filesystems.
- Account for case-insensitive path comparisons, symlinks, junctions, directory symlinks, and network shares.
- Prevent workspace escapes through `..`, junctions, symlink targets, alternate path spellings, and UNC aliases.
- Handle reserved device names, trailing dots/spaces, invalid filename characters, and long-path edge cases with clear errors.
- Preserve current access modes (`read-only`, `workspace-edit`, `full-access`) with Windows-specific authorization tests.
- [x] **Sharpen editing guidance.** Make file-change behavior safer and more reliable, especially for exact-text edits.
- Prefer `edit` for focused modifications and `write` only for new files or intentional full rewrites.
- Instruct the model to keep replacements minimal, unique, and non-overlapping.
- Encourage running or suggesting relevant tests after meaningful code changes.
- [ ] **Handle line endings and encodings cleanly.** Make file reads, edits, diffs, and generated files predictable on Windows projects.
- Preserve existing CRLF/LF style when editing files where practical.
- Render diffs clearly even when files use CRLF line endings.
- Avoid corrupting UTF-8 with BOM, UTF-16, or non-UTF-8 files; detect unsupported text encodings and explain the limitation.
- Keep binary-file detection reliable for Windows executables, images, archives, and generated build artifacts.
- [x] **Make access-mode behavior easy for the model to follow.** Rewrite read-only, workspace-edit, and full-access guidance in plain language that maps directly to available tools.
- Keep workspace and bundled-doc boundaries clear.
- State that shell approval is handled by Cassady's UI rather than by asking for permission in chat.
- Preserve conservative behavior when a task requires permissions the current mode does not allow.
### Shell and Process Integration
### Validation and Documentation
- [ ] **Use the right shell behavior on Windows.** Make `shell` tool execution, approval prompts, command summaries, cancellation, and exit status reporting work with Windows process semantics.
- Prefer PowerShell-friendly examples and diagnostics while still supporting `cmd.exe`-style commands when users provide them.
- Quote paths with spaces safely and avoid POSIX-only escaping in Windows-generated commands.
- Surface the actual executable, working directory, exit code, stdout, and stderr in a way users can debug.
- Cancel long-running child processes cleanly, including process trees where possible.
- [x] **Add prompt-focused tests.** Verify that the generated prompt includes the required sections, preserves global instructions, reflects the active access mode, and stays within the intended size range.
- Cover read-only, workspace-edit, and full-access effective prompts.
- Include a regression check for prompt ordering so runtime constraints remain near the end.
- [ ] **Normalize environment-variable handling.** Ensure provider API key checks, diagnostics, setup guidance, and spawned tools work with Windows environment conventions.
- Treat environment variable names consistently despite Windows case-insensitive lookup behavior.
- Show PowerShell examples such as `$env:OPENAI_API_KEY = "..."` for temporary values.
- Avoid relying on POSIX shell expansion, `export`, `$VAR`, or `~` in Windows-specific guidance.
- [x] **Update user-facing references to global instructions.** Refresh docs only where needed to explain how `~/.cass/global.md` fits into the structured prompt.
- Avoid exposing the full internal prompt in documentation.
- Mention that user global instructions are respected unless they conflict with runtime safety constraints.
- [ ] **Support common Windows external commands and editors.** When Cassady suggests or launches helper commands, make the behavior compatible with typical Windows environments.
- Detect missing tools and explain alternatives rather than assuming Unix utilities are present.
- Avoid hard dependencies on `sh`, `bash`, `grep`, `sed`, `cat`, `less`, or `/tmp` during normal CLI operation.
- Respect configured editor/browser commands and quote file paths correctly when opening files or URLs.
## v0.2.3 — Documentation and README Refresh ✅ Completed
### Config, State, and Session Usability
- [ ] **Use Windows-appropriate runtime locations.** Keep config, logs, caches, sessions, temporary files, and diagnostics in locations that align with Windows conventions.
- Prefer the existing cross-platform directory abstraction where available, and verify behavior with `APPDATA`, `LOCALAPPDATA`, `TEMP`, and `USERPROFILE`.
- Expand `~` and environment-derived paths consistently in config values.
- Keep session history portable enough to display Windows paths without breaking transcript replay.
- [ ] **Make diagnostics expose Windows-specific context.** Improve `cass check` and error reports so Windows users can understand terminal, filesystem, shell, and config problems quickly.
- Include OS, architecture, terminal detection, active shell, config path, workspace path, and access mode when relevant.
- Clearly distinguish provider/API-key failures from Windows runtime issues.
- Recommend Windows-native remediation steps without mentioning installation tasks.
- [ ] **Keep aliases and command parsing consistent.** Ensure `cass` and `cassady` subcommands, flags, config overrides, and path arguments behave the same on Windows as on Unix-like systems.
- Validate quoting behavior for arguments containing spaces and backslashes.
- Ensure help text and examples do not imply shell features unavailable in PowerShell or Command Prompt.
- Keep machine-readable output stable across platforms when output is consumed by scripts.
### Verification and Documentation
- [ ] **Add Windows-focused automated coverage.** Add unit and integration tests that exercise Windows path parsing, policy checks, config discovery, line endings, environment variables, and command rendering.
- Use platform-gated tests for behavior that can only run on Windows.
- Add platform-independent tests for Windows path strings where possible.
- Include regression tests for spaces in paths, UNC paths, CRLF edits, and workspace escape attempts.
- [ ] **Run a manual Windows CLI acceptance pass.** Validate the release on a real Windows environment, not just cross-compilation.
- Test PowerShell, Command Prompt, Windows Terminal, and VS Code integrated terminal.
- Exercise interactive chat, first-run setup, `cass check`, tool approvals, file read/edit/diff, shell cancellation, and redirected output.
- Record any unsupported terminal or shell behavior as explicit known limitations.
- [ ] **Update runtime documentation for Windows usage.** Refresh README and bundled docs with Windows-specific CLI usage guidance while avoiding installation instructions.
- Document PowerShell environment-variable examples, path examples, terminal expectations, and known limitations.
- Include troubleshooting for broken colors, bad wrapping, path authorization failures, CRLF diffs, and missing Unix helper commands.
- Keep all Windows guidance consistent with existing access modes and safety policies.
## v0.2.3 — Documentation and README Refresh
This release focuses on making Cassady understandable, trustworthy, and easy to operate by rewriting the README and bringing all bundled documentation up to date with the current CLI behavior. The work should cover user-facing documentation only; broad CLI feature work and Windows-specific runtime improvements are deferred to v0.2.4. See `plans/V0_2_3_DOCUMENTATION_README_REFRESH_PLAN.md`.
This release focuses on making Cassady understandable, trustworthy, and easy to operate by rewriting the README and bringing all bundled documentation up to date with the current CLI behavior. The work should cover user-facing documentation only; broad CLI feature work and Windows-specific runtime improvements are deferred to the planned Windows CLI usability work. See `plans/V0_2_3_DOCUMENTATION_README_REFRESH_PLAN.md`.
### README Rewrite
@@ -156,9 +110,9 @@ This release focuses on making Cassady understandable, trustworthy, and easy to
- Updating config or switching providers/models.
- Resuming work after a failed provider request or cancelled turn.
- [x] **Document platform expectations without duplicating future Windows work.** Add accurate notes for macOS, Linux, and Windows users while keeping deep Windows CLI usability improvements scoped to v0.2.4.
- [x] **Document platform expectations without duplicating future Windows work.** Add accurate notes for macOS, Linux, and Windows users while keeping deep Windows CLI usability improvements scoped to the planned Windows CLI usability work.
- Include path, shell, and environment-variable examples for each platform when documentation needs them.
- Mark known Windows limitations clearly until the v0.2.4 work lands.
- Mark known Windows limitations clearly until the planned Windows CLI usability work lands.
- Avoid promising installer, package manager, or auto-update behavior that is not implemented.
### Documentation Quality and Maintenance
@@ -274,3 +228,101 @@ This release focuses on making Cass easier to interrupt, easier to audit, and sa
- [x] **Edit diff output.** Make `edit` changes reviewable in the transcript.
- First version: show a unified before/after diff after the edit is applied.
- Later versions may add pre-apply approval, but that requires a confirmation flow between tools and the TUI.
## Planned within the next major release
These sections describe work Cassady intends to complete before or as part of the next major release, but which has not yet been assigned to a specific version. Scope, order, and version numbers may change.
### Windows CLI Usability
This work focuses on making Cassady feel reliable and native when the CLI is run on Windows. It covers runtime usability after `cass` or `cassady` is already available on the machine; installers, package managers, PATH setup, code signing, and update delivery are intentionally out of scope.
#### Terminal Experience
- [ ] **Make interactive rendering robust in Windows terminals.** Ensure chat, setup, confirmation prompts, streamed output, spinners, diffs, and tool summaries render cleanly in Windows Terminal, PowerShell, Command Prompt, and common VS Code integrated terminals.
- Enable or gracefully detect ANSI/VT support instead of emitting broken escape sequences.
- Respect `NO_COLOR`, non-interactive output, redirected stdout/stderr, and narrow terminal widths.
- Avoid relying on glyphs, emoji, box drawing, or cursor control sequences that render poorly on default Windows fonts.
- Keep wrapping and cursor positioning correct for multi-line input, Markdown output, and long tool-call summaries.
- [ ] **Harden keyboard handling on Windows.** Make the TUI and prompts respond predictably to Windows console input events.
- Verify `Enter`, `Backspace`, `Delete`, arrow keys, `Home`, `End`, `PageUp`, `PageDown`, `Tab`, and paste behavior.
- Preserve existing `Ctrl-C` cancellation semantics and handle `Ctrl-Break`/console close events gracefully where supported.
- Ensure `Esc` cancellation and prompt dismissal work consistently across PowerShell, Command Prompt, and Windows Terminal.
- [ ] **Improve plain CLI output for Windows users.** Commands such as `cass check`, setup diagnostics, validation errors, and usage text should remain readable without a fully interactive terminal.
- Prefer actionable Windows examples using PowerShell syntax when the current platform is Windows.
- Avoid POSIX-only command snippets in runtime guidance unless explicitly labeled.
- Keep error messages copy/paste-friendly and free of terminal control characters when output is redirected.
#### Windows Paths and Files
- [ ] **Support Windows path syntax everywhere the CLI accepts paths.** Normalize and validate paths consistently across arguments, tool calls, diffs, session metadata, and model-visible file references.
- Handle drive-letter paths such as `C:\Users\name\project`, rooted paths such as `\temp`, UNC paths such as `\\server\share\repo`, and mixed `/`/`\` separators.
- Preserve user-facing paths in a readable Windows form while using canonicalized paths for safety decisions.
- Avoid treating `:` in drive letters as URL schemes or command separators.
- Add tests for relative path resolution from Windows workspaces and for paths containing spaces, apostrophes, parentheses, brackets, and non-ASCII characters.
- [ ] **Respect Windows filesystem semantics in workspace policy.** Keep read, write, edit, and shell safety checks correct on NTFS and common Windows filesystems.
- Account for case-insensitive path comparisons, symlinks, junctions, directory symlinks, and network shares.
- Prevent workspace escapes through `..`, junctions, symlink targets, alternate path spellings, and UNC aliases.
- Handle reserved device names, trailing dots/spaces, invalid filename characters, and long-path edge cases with clear errors.
- Preserve current access modes (`read-only`, `workspace-edit`, `full-access`) with Windows-specific authorization tests.
- [ ] **Handle line endings and encodings cleanly.** Make file reads, edits, diffs, and generated files predictable on Windows projects.
- Preserve existing CRLF/LF style when editing files where practical.
- Render diffs clearly even when files use CRLF line endings.
- Avoid corrupting UTF-8 with BOM, UTF-16, or non-UTF-8 files; detect unsupported text encodings and explain the limitation.
- Keep binary-file detection reliable for Windows executables, images, archives, and generated build artifacts.
#### Shell and Process Integration
- [ ] **Use the right shell behavior on Windows.** Make `shell` tool execution, approval prompts, command summaries, cancellation, and exit status reporting work with Windows process semantics.
- Prefer PowerShell-friendly examples and diagnostics while still supporting `cmd.exe`-style commands when users provide them.
- Quote paths with spaces safely and avoid POSIX-only escaping in Windows-generated commands.
- Surface the actual executable, working directory, exit code, stdout, and stderr in a way users can debug.
- Cancel long-running child processes cleanly, including process trees where possible.
- [ ] **Normalize environment-variable handling.** Ensure provider API key checks, diagnostics, setup guidance, and spawned tools work with Windows environment conventions.
- Treat environment variable names consistently despite Windows case-insensitive lookup behavior.
- Show PowerShell examples such as `$env:OPENAI_API_KEY = "..."` for temporary values.
- Avoid relying on POSIX shell expansion, `export`, `$VAR`, or `~` in Windows-specific guidance.
- [ ] **Support common Windows external commands and editors.** When Cassady suggests or launches helper commands, make the behavior compatible with typical Windows environments.
- Detect missing tools and explain alternatives rather than assuming Unix utilities are present.
- Avoid hard dependencies on `sh`, `bash`, `grep`, `sed`, `cat`, `less`, or `/tmp` during normal CLI operation.
- Respect configured editor/browser commands and quote file paths correctly when opening files or URLs.
#### Config, State, and Session Usability
- [ ] **Use Windows-appropriate runtime locations.** Keep config, logs, caches, sessions, temporary files, and diagnostics in locations that align with Windows conventions.
- Prefer the existing cross-platform directory abstraction where available, and verify behavior with `APPDATA`, `LOCALAPPDATA`, `TEMP`, and `USERPROFILE`.
- Expand `~` and environment-derived paths consistently in config values.
- Keep session history portable enough to display Windows paths without breaking transcript replay.
- [ ] **Make diagnostics expose Windows-specific context.** Improve `cass check` and error reports so Windows users can understand terminal, filesystem, shell, and config problems quickly.
- Include OS, architecture, terminal detection, active shell, config path, workspace path, and access mode when relevant.
- Clearly distinguish provider/API-key failures from Windows runtime issues.
- Recommend Windows-native remediation steps without mentioning installation tasks.
- [ ] **Keep aliases and command parsing consistent.** Ensure `cass` and `cassady` subcommands, flags, config overrides, and path arguments behave the same on Windows as on Unix-like systems.
- Validate quoting behavior for arguments containing spaces and backslashes.
- Ensure help text and examples do not imply shell features unavailable in PowerShell or Command Prompt.
- Keep machine-readable output stable across platforms when output is consumed by scripts.
#### Verification and Documentation
- [ ] **Add Windows-focused automated coverage.** Add unit and integration tests that exercise Windows path parsing, policy checks, config discovery, line endings, environment variables, and command rendering.
- Use platform-gated tests for behavior that can only run on Windows.
- Add platform-independent tests for Windows path strings where possible.
- Include regression tests for spaces in paths, UNC paths, CRLF edits, and workspace escape attempts.
- [ ] **Run a manual Windows CLI acceptance pass.** Validate the release on a real Windows environment, not just cross-compilation.
- Test PowerShell, Command Prompt, Windows Terminal, and VS Code integrated terminal.
- Exercise interactive chat, first-run setup, `cass check`, tool approvals, file read/edit/diff, shell cancellation, and redirected output.
- Record any unsupported terminal or shell behavior as explicit known limitations.
- [ ] **Update runtime documentation for Windows usage.** Refresh README and bundled docs with Windows-specific CLI usage guidance while avoiding installation instructions.
- Document PowerShell environment-variable examples, path examples, terminal expectations, and known limitations.
- Include troubleshooting for broken colors, bad wrapping, path authorization failures, CRLF diffs, and missing Unix helper commands.
- Keep all Windows guidance consistent with existing access modes and safety policies.
+1 -1
View File
@@ -5,7 +5,7 @@ Cassady reads user-editable config files from `~/.cass`.
- `config.json`: user preferences, active defaults, and compatibility fields.
- `providers.json`: provider connection definitions.
- `models.json`: model metadata.
- `global.md`: optional global instructions included in new chats.
- `global.md`: optional global instructions included in new chat system prompts when they fit the active request; they cannot override access modes, tool denials, approvals, or workspace boundaries.
- `conversations/`: saved JSONL chats.
- `docs/`: bundled docs installed from the current binary.
+1 -1
View File
@@ -14,7 +14,7 @@
**Exact edit**: An `edit` tool replacement where each `old_text` must match exactly once in the original file before anything is written.
**Global instructions**: Optional text in `~/.cass/global.md` included in new chat system prompts.
**Global instructions**: Optional text in `~/.cass/global.md` included in new chat system prompts. Cassady follows these instructions when they fit the active request, but they cannot override runtime safety constraints such as access modes, tool denials, approvals, or workspace boundaries.
**Model metadata**: The `models.json` entry describing a model id, owning provider, display name, context limits, tool/streaming support, and reasoning behavior.
@@ -0,0 +1,499 @@
# v0.2.4 System Prompt Refinement Implementation Plan
## Goal
v0.2.4 refines Cassady's generated system prompt so the model receives clearer, more intuitive operating instructions without turning the prompt into a long manual. The effective prompt should explain Cassady's role, terminal transcript behavior, tool use, editing expectations, runtime safety constraints, and response style in a structured way that models can follow reliably.
Success statement:
> A normal effective system prompt, excluding user-provided global instructions, is roughly 900-1,100 tokens and consistently guides the model to inspect before editing, use tools directly when useful, respect access modes, make targeted file changes, and finish each turn with an honest concise response.
## Scope
### In scope
- Rewrite `src/prompt.rs` prompt text into a clearer sectioned structure.
- Preserve the existing prompt-generation model:
- `build_base_system_prompt(global)` creates reusable conversation-level instructions.
- `build_effective_system_prompt(...)` appends model/workspace/docs/access/tool runtime constraints.
- `~/.cass/global.md` text remains embedded as user global instructions when present.
- Add product context that helps the model understand Cassady's terminal chat UX.
- Improve guidance for tool selection, exact-text edits, use of shell, and test/summarization behavior.
- Make access-mode guidance concise and easy to map to the currently allowed tools.
- Add focused tests for prompt sections, ordering, global instructions, access modes, and approximate size.
- Update docs only where they mention global instructions or prompt behavior.
- Keep the prompt provider-agnostic and compatible with all OpenAI-compatible models Cassady supports.
### Out of scope
- Adding prompt templates, profile selection, or user-selectable prompt modes.
- Exposing a CLI command to print or edit the full generated system prompt.
- Changing the `~/.cass/global.md` file format or adding layered project instructions.
- Changing access-policy enforcement, tool schemas, approval UI, or security decisions.
- Adding new tools or changing tool argument formats.
- Implementing automatic prompt compression or conversation summarization.
- Maintaining separate prompts per provider/model family.
- Stuffing large reference documentation, provider catalogs, or CLI help into the system prompt.
## Context and Current State
Relevant files:
- `src/prompt.rs`: builds both the base and effective system prompts. The current prompt is short and functional but sparse.
- `src/app.rs`: reads global instructions and stores the base prompt in new conversations.
- `src/agent.rs`: calls `build_effective_system_prompt(...)` before provider requests.
- `src/conversation.rs`: persists the base system prompt in the conversation record and reuses it when a chat is resumed.
- `src/access.rs`: defines `read-only`, `workspace-edit`, and `full-access` modes.
- `src/security.rs`: central policy for tool availability, read/write boundaries, shell approval, and denials.
- `src/tools/*`: tool implementations and schemas for `ls`, `read`, `grep`, `write`, `edit`, and `shell`.
- `docs/glossary.md`: defines global instructions as optional text in `~/.cass/global.md` included in new chat system prompts.
- `tests/*`: no dedicated prompt tests exist yet; prompt behavior is only indirectly covered through agent/conversation tests.
Current prompt behavior to preserve:
- Cassady identifies itself as Cassady/Cass, a coding agent running in a terminal chat interface.
- User global instructions are included only when non-empty after trimming.
- Global instructions are subordinate to runtime safety constraints.
- The effective prompt includes:
- model id,
- active access mode,
- launch working directory,
- bundled docs directory,
- allowed tools,
- access-mode-specific instructions,
- final response behavior.
- Tool access is ultimately enforced by runtime policy, not by prompt wording alone.
Current gaps:
- The prompt is organized as numbered sections but does not fully explain Cassady's user-visible transcript model.
- Tool and editing guidance is too compact for models that need stronger direction on when to inspect, search, edit, write, or run shell.
- Access-mode text is accurate but can be made more direct and less repetitive.
- There is no automated check that future prompt edits preserve required sections or stay near the intended size.
- Documentation mentions global instructions, but not how they relate to runtime safety constraints in the refined prompt.
## Design Principles
1. **High signal, low bulk.** The prompt should contain the instructions most likely to improve model behavior, not a copy of the README.
2. **Runtime policy remains authoritative.** Prompt text should guide the model, while `src/security.rs` and tool availability continue to enforce real permissions.
3. **Structure beats length.** Use clear headings and dense paragraphs/bullets so models can find instructions during long sessions.
4. **Tell the model what the user can see.** Explain streamed output, visible tool calls/results, approvals, and edit diffs so the assistant does not narrate inaccurately.
5. **Prefer action over ceremony.** Encourage the model to use tools directly, inspect before changing files, and ask questions only when missing information materially blocks progress.
6. **Make editing rules concrete.** Exact-text edits are a core reliability constraint and should be stated plainly.
7. **Avoid provider-specific assumptions.** The prompt should work for small and large OpenAI-compatible models without relying on special model behavior.
8. **Keep user instructions safe.** Global instructions are important, but they must never override runtime access modes, tool denials, or user requests in the active chat.
## Prompt Architecture
Keep the two-stage prompt generation, but make the internal structure more intentional.
### Base prompt
`build_base_system_prompt(global)` should contain stable instructions that are true for every session:
1. Identity and role.
2. Operating principles.
3. User global instructions, when present.
4. Tool-use behavior.
5. Editing behavior.
6. Response behavior.
The base prompt is stored in the conversation when a chat is created. Because resumed chats reuse the stored base prompt, changing the base prompt affects new chats but not necessarily existing conversations. That behavior is acceptable and should be documented only if user-facing docs mention prompt changes.
### Effective prompt
`build_effective_system_prompt(...)` should append runtime-specific information near the end:
1. Current runtime context:
- model,
- access mode,
- launch working directory,
- bundled docs directory,
- allowed tools.
2. Access-mode rules for the active mode.
3. Final reminder that runtime policy and tool results are authoritative.
Runtime constraints should remain near the end so they are fresh in the model's context and can override earlier general instructions.
### Numbering and headings
Use stable Markdown-like headings rather than fragile sentence-only text. For example:
```text
# Cassady operating instructions
## Role
...
## Working style
...
```
Numbered headings are acceptable if tests are written against section names rather than exact numbers. Avoid deeply nested outlines.
## Target Prompt Content
The final wording can change during implementation, but it should cover the following content.
### 1. Role
Required ideas:
- You are Cassady, also called Cass.
- You are a coding assistant inside an interactive terminal chat.
- You help with real project work: reading code, explaining behavior, editing files, and running relevant commands when allowed.
- Work carefully and honestly; do not pretend to have inspected or changed files unless tool results confirm it.
Avoid:
- Overly broad claims such as being a general-purpose autonomous system.
- Long branding language.
- Any implication that prompt instructions can bypass runtime access policy.
### 2. Working style
Required ideas:
- Prefer concrete progress over long speculative plans.
- Inspect relevant files before making claims or edits.
- Ask a focused follow-up question only when the task is ambiguous or blocked.
- Keep explanations concise but include enough context for the user to review the work.
- If the user's request is impossible in the current mode, explain the limitation and the next viable step.
Suggested wording style:
```text
Make the smallest useful plan, then act. Do not over-plan routine code tasks. When information is missing, gather it with tools if possible; ask the user only when a choice or secret is genuinely required.
```
### 3. Transcript and UI awareness
Required ideas:
- Assistant text is streamed to the user.
- Tool calls and tool results are visible in the transcript.
- Edit diffs and approval prompts may be shown by Cassady's UI.
- The model should request tools directly rather than asking for chat permission before every tool call.
- Cassady handles access denials and approval UI separately.
This section should reduce behaviors such as:
- Saying "I will run X" and then not calling the tool.
- Asking "May I read the file?" when the tool is available.
- Claiming a shell command ran before its result arrives.
- Repeating huge summaries of tool output that the user can already see.
### 4. Tool use
Required guidance by tool area:
- `ls`: use for directory orientation.
- `grep`: use before reading large or unknown files, or to locate definitions/usages.
- `read`: use targeted reads for files or ranges that matter.
- `edit`: use for focused changes to existing files.
- `write`: use for new files or intentional full rewrites.
- `shell`: use for tests, builds, formatting, diagnostics, or project commands when allowed and useful.
General instructions:
- Use tools when current filesystem state matters.
- Prefer targeted inspection over guessing.
- Batch related reads when possible, but avoid reading unrelated files.
- Do not use shell for file inspection when `ls`/`grep`/`read` is safer and sufficient.
- If a tool is denied, adapt to the denial instead of repeating the same call.
### 5. Editing
Required ideas:
- Prefer `edit` for small and medium modifications to existing files.
- `edit` replacements must use exact old text that appears uniquely in the original file.
- Keep edits minimal, unique, and non-overlapping.
- Combine related replacements for the same file in one `edit` call when practical.
- Use `write` only for new files or full rewrites where that is safer and intentional.
- After meaningful code changes, run relevant tests/formatters when allowed, or tell the user what should be run.
- Mention changed files and verification in the final response.
### 6. Safety and access modes
The base prompt should state the general principle:
- Follow runtime constraints and active access mode.
- Do not try to bypass workspace boundaries, docs read-only rules, approvals, or tool denials.
The effective prompt should include active-mode-specific guidance:
#### read-only
- Allowed tools should normally be `ls`, `read`, and `grep`.
- Inspect only inside the launch workspace and bundled docs directory.
- Do not request `write`, `edit`, or `shell`.
- If changes or commands are needed, explain that a more permissive access mode is required.
#### workspace-edit
- Read/list/search inside the launch workspace and bundled docs directory.
- Write/edit only inside the launch workspace.
- Bundled docs are read-only.
- Shell may be requested when useful, but Cassady will show the approval UI; do not ask for shell permission in chat first.
- If a path escapes the workspace, choose an in-workspace alternative or explain the limitation.
#### full-access
- `ls`, `read`, `grep`, `write`, `edit`, and `shell` may be requested when needed.
- Shell runs from the launch working directory.
- Normal OS permissions still apply.
- Bundled docs remain read-only for write/edit.
- Even in full-access, keep changes targeted and avoid destructive commands unless the user explicitly requested them and the action is necessary.
### 7. Final response behavior
Required ideas:
- Always end the turn with a concise user-facing response after tool work.
- Do not finish with only tool calls.
- Summarize what changed, where, and how it was verified.
- If no changes were made, summarize findings or blockers.
- Be honest about failures, denials, skipped tests, or assumptions.
## Approximate Prompt Budget
Target size: roughly 900-1,100 tokens for the normal effective system prompt, excluding user global instructions.
Because Cassady does not currently include a tokenizer, implement a simple approximate check rather than adding a heavy tokenizer dependency unless the implementer strongly prefers otherwise.
Recommended helper for tests:
```rust
fn approximate_token_count(s: &str) -> usize {
s.split_whitespace().count() * 4 / 3
}
```
This heuristic is intentionally rough. The test should prevent accidental prompt bloat, not enforce an exact model-token count. Suggested limits:
- Base prompt without global instructions: approximately 650-850 heuristic tokens.
- Effective prompt in each access mode without global instructions: approximately 900-1,150 heuristic tokens.
If the final prompt is slightly outside the target but demonstrably better, prefer readability over gaming the heuristic. The acceptance target should remain "around 1,000 tokens," not an exact failure-prone threshold.
## Proposed Prompt Skeleton
This skeleton is illustrative, not a required exact implementation.
```text
# Cassady operating instructions
## Role
You are Cassady, also called Cass, a coding assistant running in an interactive terminal chat. Help with real project work: inspect files, explain code, make targeted edits, and run useful commands when allowed. Work carefully and do not claim that files were read, commands ran, or edits succeeded until tool results confirm it.
## Working style
Make the smallest useful plan, then act. Prefer current project evidence over guesses. Use tools to gather missing filesystem context. Ask a focused follow-up question only when a user choice, secret, or missing requirement blocks progress. Keep user-facing explanations concise and practical.
## Transcript and tools
Assistant text is streamed. Tool calls, tool results, approvals, and edit diffs are visible in the transcript. Request tools directly when they are the right next step; Cassady enforces access policy and shows approval prompts separately. If a tool is denied or fails, adapt and explain the limitation.
## Tool use
Use ls for directory orientation, grep to locate text or inspect large/unknown areas, read for relevant files or ranges, edit for targeted changes, write for new files or intentional full rewrites, and shell for tests/builds/diagnostics when allowed. Prefer targeted reads and related batched reads over broad exploration.
## Editing
Inspect before editing. For edit, each old text must match exactly and uniquely in the original file; keep replacements minimal and non-overlapping. Do not use write for small changes to existing files. After meaningful code changes, run relevant verification when allowed or state what should be run.
## User global instructions
...
## Runtime context
Model: ...
Access mode: ...
Launch working directory: ...
Bundled Cass docs directory: ...
Allowed tools this turn: ...
## Access rules for this session
...
## Final response
End every turn with a concise response. Summarize changed files and verification, or summarize findings/blockers if no change was made. Do not end with only tool calls.
```
## Implementation Steps
### 1. Inventory exact current behavior
- Review `src/prompt.rs`, `src/agent.rs`, `src/app.rs`, `src/conversation.rs`, `src/access.rs`, `src/security.rs`, and `src/tools/schema.rs`.
- Confirm current tool names and per-mode availability from `SecurityPolicy::tool_availability`.
- Confirm docs directory behavior and blocked write roots from app/tool context construction.
- Confirm how global instructions are loaded and trimmed.
- Confirm how resumed conversations reuse the stored base prompt.
### 2. Rewrite `build_base_system_prompt`
- Replace the current compact numbered prompt with structured, high-signal sections.
- Include identity, working style, transcript/tool visibility, general tool guidance, editing guidance, global instructions, and response behavior.
- Preserve trimming behavior for `global`.
- Keep global instructions clearly labelled and explicitly subordinate to runtime safety constraints.
- Avoid including runtime-only values in the base prompt.
### 3. Rewrite `build_effective_system_prompt`
- Keep appending to `base.trim_end()`.
- Add a clear `Runtime context` section with model, access mode, cwd, docs dir, and allowed tools.
- Add one active-mode-specific `Access rules for this session` paragraph/bullet set.
- Keep runtime constraints after global/base text.
- Keep the final response reminder either at the end of the base prompt or at the end of the effective prompt. If it remains in the base prompt, add a short final runtime-policy reminder after access rules.
### 4. Add prompt tests
Create `tests/prompt_tests.rs` or add focused unit tests in `src/prompt.rs`. Prefer integration tests in `tests/prompt_tests.rs` so prompt behavior is covered through the public crate API if exports allow it.
Recommended tests:
1. **Base prompt has required sections.**
- Build with `None`.
- Assert it contains headings/phrases for role, working style, tools, editing, and final response behavior.
- Assert it does not contain runtime-only paths or model labels.
2. **Global instructions are included and trimmed.**
- Build with whitespace-wrapped global text.
- Assert the exact trimmed content appears.
- Assert the prompt says global instructions cannot conflict with runtime safety constraints.
3. **Empty global instructions are omitted.**
- Build with `Some(" \n")`.
- Assert the global-instructions heading is absent.
4. **Effective prompt includes runtime context.**
- Use temporary or fixed paths for cwd/docs.
- Assert model, mode, cwd, docs dir, and allowed tools are present.
5. **Each access mode gets correct instructions.**
- `read-only`: contains no write/edit/shell request guidance and says more permissive mode is needed for modifications.
- `workspace-edit`: says write/edit only inside workspace and shell approval is handled by Cassady UI.
- `full-access`: says all tools may be requested, shell runs from cwd, docs remain read-only.
6. **Runtime constraints stay after global instructions.**
- Build base with global text, then effective prompt.
- Assert global text index is before runtime context index.
- Assert access rules appear after runtime context.
7. **Prompt size remains intentional.**
- Build effective prompts for all modes without global instructions.
- Use the approximate token helper.
- Assert each is within the chosen guardrail, for example `800..=1250` approximate tokens.
8. **Allowed tools list reflects caller input.**
- Pass a small custom tool list.
- Assert the rendered list matches it.
Test guidance:
- Avoid asserting the entire prompt as one giant snapshot unless the project already uses snapshot testing.
- Prefer stable phrases and section headings so minor copy edits do not make tests brittle.
- If a snapshot is added, keep it intentionally small or use one golden prompt plus semantic tests.
### 5. Update docs references
Update only docs that need to mention global instructions or prompt behavior.
Likely files:
- `docs/glossary.md`: expand `Global instructions` to say they are included in new chat system prompts and followed unless they conflict with runtime safety constraints.
- `docs/configuration.md` or `README.md` only if they already mention `~/.cass/global.md` and need clarification.
Do not publish the full internal system prompt in docs. It is implementation detail and will evolve.
### 6. Run verification
Required commands:
```sh
cargo fmt --check
cargo test --locked --all-targets
```
If prompt tests use temp paths or platform-dependent path display, run on the current platform and avoid hardcoding separators where possible.
## Tests
Automated tests to add:
- New prompt tests covering base prompt structure, global instruction behavior, effective runtime context, access-mode-specific wording, ordering, and approximate size.
- Existing agent/conversation/tool tests should continue to pass unchanged.
Manual checks:
- Read one generated prompt for each access mode and verify it is understandable as prose.
- Check that the prompt does not repeat the same instruction in several sections.
- Check that docs/global-instruction wording matches the generated prompt.
- Confirm a normal prompt is around 1,000 tokens by the chosen heuristic or an external tokenizer if one is available.
## Documentation
Required documentation updates are intentionally small:
- `docs/glossary.md`: update the `Global instructions` definition.
- Any existing README/configuration references to `~/.cass/global.md`: clarify that these instructions are included in new chat system prompts and cannot override safety constraints.
No new user guide is required for this release unless implementation adds user-visible commands or configuration, which is out of scope.
## Compatibility and Migration Notes
- Existing conversations keep the base system prompt stored when they were created. The refined base prompt will apply to new conversations.
- Runtime constraints are still generated at request time, so active access mode, cwd, docs dir, and allowed tools remain current for resumed chats.
- `~/.cass/global.md` remains plain text and does not require migration.
- No config schema changes are expected.
- No provider/model configuration changes are expected.
## Risks and Mitigations
### Risk: prompt grows too large
Mitigation:
- Add a size guardrail test.
- Keep docs/provider details out of the prompt.
- Prefer compact instructions over long examples.
### Risk: tests become brittle
Mitigation:
- Test for section presence and key behavior, not every exact sentence.
- Keep exact string assertions limited to stable safety-critical phrases.
### Risk: prompt implies permissions the runtime denies
Mitigation:
- Derive access-mode wording from `SecurityPolicy::tool_availability` and current policy behavior.
- Include allowed tools in the runtime context.
- Phrase guidance as "may request when allowed" rather than unconditional permission, except in mode-specific sections verified against code.
### Risk: global instructions appear stronger than safety rules
Mitigation:
- Place global instructions in a clearly labelled section.
- State that they are followed only when consistent with user requests and runtime safety constraints.
- Add a test for this wording.
### Risk: models ignore concise instructions
Mitigation:
- Use direct imperative wording.
- Put runtime constraints near the end.
- Avoid burying editing and safety rules in long paragraphs.
## Acceptance Criteria
- `src/prompt.rs` produces a structured, readable prompt with clear sections for role, working style, transcript/tool behavior, tool use, editing, runtime context, access rules, and final responses.
- The effective prompt for each access mode is roughly 900-1,100 tokens excluding user global instructions, with an automated guardrail preventing major accidental bloat.
- User global instructions are included only when non-empty, trimmed, clearly labelled, and subordinate to runtime safety constraints.
- Runtime context includes model, access mode, launch cwd, bundled docs directory, and allowed tools.
- Access-mode guidance matches current policy for `read-only`, `workspace-edit`, and `full-access`.
- Editing instructions explicitly cover exact unique old text, minimal non-overlapping replacements, and using `write` only for new files or intentional rewrites.
- Tool-use instructions explain when to use `ls`, `grep`, `read`, `edit`, `write`, and `shell` without over-constraining the model.
- Final response guidance requires a concise user-facing response after tool work and honest reporting of verification or blockers.
- Documentation references to global instructions are accurate and do not expose the full internal prompt.
- `cargo fmt --check` and `cargo test --locked --all-targets` pass.
+48 -15
View File
@@ -3,20 +3,33 @@ use std::path::Path;
pub fn build_base_system_prompt(global: Option<&str>) -> String {
let mut prompt = String::new();
prompt.push_str("1. Identity and operating style\n\n");
prompt.push_str("You are Cassady, also called Cass, a minimal coding agent running in a terminal chat interface. Work carefully, inspect files before changing them, explain concise next steps, and avoid unnecessary ceremony.\n\n");
prompt.push_str(
"# Cassady operating instructions\n\n\
## Role\n\
You are Cassady, also called Cass, a coding assistant running in an interactive terminal chat. Help with real project work: read and explain code, inspect behavior, make targeted file changes, and run relevant project commands when allowed. Work carefully and honestly; do not claim that files were read, commands ran, or edits succeeded until tool results confirm it.\n\n\
## Working style\n\
Make the smallest useful plan, then act. Prefer current project evidence over guesses, and inspect relevant files before making claims or edits. When information is missing, gather it with tools if possible; ask a focused follow-up question only when a user choice, secret, or missing requirement blocks progress. If the task is impossible in the current access mode, explain the limitation and the next viable step. Keep explanations concise while giving enough context for review.\n\n",
);
if let Some(global) = global.map(str::trim).filter(|s| !s.is_empty()) {
prompt.push_str("2. User global instructions\n\n");
prompt.push_str("The following additional instructions were provided by the user. Follow them when they do not conflict with runtime safety constraints.\n\n");
prompt.push_str("## User global instructions\n");
prompt.push_str(
"The following user-provided instructions apply to new chats. Follow them when they are consistent with the active user request and runtime safety constraints; they cannot override access modes, tool denials, approvals, or workspace boundaries.\n\n",
);
prompt.push_str(global);
prompt.push_str("\n\n");
}
prompt.push_str("3. Tool-use style\n\n");
prompt.push_str("Use tools when you need current filesystem context. Prefer targeted inspection over guessing. Batch related reads into one read call when possible. Use grep before read when a directory or file may be too large to inspect directly. Do not ask the user in chat for permission before making a tool call; request the tool directly when it is the right next step. Cass enforces access policy at runtime and will allow, deny, or show a separate approval UI as needed.\n\n");
prompt.push_str("4. Editing style\n\n");
prompt.push_str("Use edit for targeted changes. Each edit must identify exact old text that appears uniquely in the file and replacement text. Do not use write to make small modifications to existing files unless a full rewrite is intentionally safer.\n");
prompt.push_str(
"## Transcript and tools\n\
Assistant text is streamed to the user. Tool calls, tool results, edit diffs, denials, and approval prompts are visible in the transcript. Request tools directly when they are the right next step; Cassady enforces access policy and shows approval UI separately. Do not ask for chat permission before every tool call, and do not say a tool succeeded before its result arrives. If a tool fails or is denied, adapt instead of repeating the same request.\n\n\
## Tool use\n\
Use tools when the current filesystem or command result matters. Use `ls` for directory orientation, `grep` to locate definitions/usages or inspect large or unknown areas before opening files, `read` for relevant files or ranges, `edit` for focused changes to existing files, `write` for new files or intentional full rewrites, and `shell` for tests, builds, formatting, diagnostics, or project commands when allowed and useful. Prefer targeted inspection and related batched reads over broad exploration. Do not use `shell` for file inspection when `ls`, `grep`, or `read` is safer and sufficient.\n\n\
## Editing\n\
Inspect before editing. Prefer `edit` for small and medium modifications to existing files. For `edit`, each old text must match exactly and uniquely in the original file; keep replacements minimal, unique, and non-overlapping, and combine related replacements for the same file in one call when practical. Use `write` only for new files or full rewrites where that is safer and intentional. After meaningful code changes, run relevant tests or formatters when allowed, or tell the user what should be run.\n\n\
## Safety and final response\n\
Follow runtime constraints, active access mode, tool availability, and tool results as authoritative. Do not try to bypass workspace boundaries, read-only docs rules, approval requirements, or denials. End every turn with a concise user-facing response after tool work; do not finish with only tool calls. Summarize what changed, where, and how it was verified, or summarize findings, blockers, skipped tests, and assumptions if no change was made.\n",
);
prompt
}
@@ -30,23 +43,43 @@ pub fn build_effective_system_prompt(
) -> String {
let mut prompt = String::new();
prompt.push_str(base.trim_end());
prompt.push_str("\n\n5. Current runtime constraints\n\n");
prompt.push_str("\n\n## Runtime context\n");
prompt.push_str(&format!("Model: {model}.\n"));
prompt.push_str(&format!("Access mode: {}.\n", mode.as_str()));
prompt.push_str(&format!("Launch working directory: {}.\n", cwd.display()));
prompt.push_str(&format!(
"Bundled Cass docs directory: {}. This directory is read-only for tools. Use ls, read, and grep there when you need Cass documentation.\n",
"Bundled Cass docs directory: {}. Use this directory for Cass documentation; write/edit are blocked there.\n",
docs_dir.display()
));
prompt.push_str(&format!(
"Allowed tools this turn: {}.\n\n",
allowed_tools.join(", ")
render_allowed_tools(allowed_tools)
));
prompt.push_str("## Access rules for this session\n");
match mode {
AccessMode::ReadOnly => prompt.push_str("In read-only mode, you may inspect files with ls, read, and grep only inside the launch working directory or bundled Cass docs directory. Do not request write, edit, or shell. If a task requires modification, explain that a more permissive mode is needed.\n\n"),
AccessMode::WorkspaceEdit => prompt.push_str("In workspace-edit mode, you may inspect files with ls, read, and grep only inside the launch working directory or bundled Cass docs directory. You may write and edit files only inside the launch working directory. Bundled Cass docs are read-only. You may request shell when useful. Do not ask the user for shell permission in chat; call the shell tool directly and Cass will handle any required approval separately before execution.\n\n"),
AccessMode::FullAccess => prompt.push_str("In full-access mode, you may request ls, read, grep, write, edit, and shell when needed. The shell tool runs commands in the launch working directory. Cass does not restrict read paths to the launch directory, but normal operating-system permissions still apply. write and edit are still blocked under the bundled Cass docs directory.\n\n"),
AccessMode::ReadOnly => prompt.push_str(
"Read-only mode permits inspection only. Use `ls`, `read`, and `grep` only inside the launch workspace or bundled Cass docs directory. Do not request `write`, `edit`, or `shell`. If changes, commands, or out-of-scope paths are needed, explain that a more permissive access mode is required.\n\n",
),
AccessMode::WorkspaceEdit => prompt.push_str(
"Workspace-edit mode permits `ls`, `read`, and `grep` inside the launch workspace and bundled Cass docs directory. Write/edit only inside the launch workspace; bundled docs remain read-only. Shell may be requested when useful, but Cassady handles the approval UI, so do not ask for shell permission in chat first. If a path escapes the workspace, choose an in-workspace alternative or explain the limitation.\n\n",
),
AccessMode::FullAccess => prompt.push_str(
"Full-access mode permits `ls`, `read`, `grep`, `write`, `edit`, and `shell` when needed. Shell runs from the launch working directory, and normal operating-system permissions still apply. Bundled docs remain read-only for write/edit. Even in full-access, keep changes targeted and avoid destructive commands unless the user explicitly requested them and they are necessary.\n\n",
),
}
prompt.push_str("6. Response behavior\n\nAssistant output is streamed to the user. Keep user-facing text direct and useful. Tool calls and results are visible to the user, so avoid claiming work happened until the relevant tool result confirms it. After using tools or completing requested work, always end the turn with a concise final user-facing response. Do not finish a turn with only tool calls.\n");
prompt.push_str(
"## Runtime authority\n\
Runtime policy and tool results override general guidance and user global instructions. The allowed-tools list is the source of truth for this turn; if Cassady denies a tool or path, adapt and report the limitation. Always provide a concise final response after tool activity.\n",
);
prompt
}
fn render_allowed_tools(allowed_tools: &[String]) -> String {
if allowed_tools.is_empty() {
"<none>".into()
} else {
allowed_tools.join(", ")
}
}
+155
View File
@@ -0,0 +1,155 @@
use cassady::access::AccessMode;
use cassady::prompt::{build_base_system_prompt, build_effective_system_prompt};
use std::path::Path;
fn approximate_token_count(s: &str) -> usize {
s.split_whitespace().count() * 4 / 3
}
fn effective_prompt(mode: AccessMode, allowed_tools: &[&str]) -> String {
let base = build_base_system_prompt(None);
let allowed_tools = allowed_tools
.iter()
.map(|tool| tool.to_string())
.collect::<Vec<_>>();
build_effective_system_prompt(
&base,
mode,
Path::new("/workspace/project"),
Path::new("/home/user/.cass/docs"),
"test-model",
&allowed_tools,
)
}
#[test]
fn base_prompt_has_required_sections_without_runtime_context() {
let prompt = build_base_system_prompt(None);
for heading in [
"# Cassady operating instructions",
"## Role",
"## Working style",
"## Transcript and tools",
"## Tool use",
"## Editing",
"## Safety and final response",
] {
assert!(prompt.contains(heading), "missing {heading}");
}
assert!(prompt.contains("You are Cassady, also called Cass"));
assert!(prompt.contains("inspect relevant files before making claims or edits"));
assert!(prompt.contains(
"Tool calls, tool results, edit diffs, denials, and approval prompts are visible"
));
assert!(prompt.contains("each old text must match exactly and uniquely"));
assert!(prompt.contains("End every turn with a concise user-facing response"));
assert!(!prompt.contains("## Runtime context"));
assert!(!prompt.contains("Model:"));
assert!(!prompt.contains("Access mode:"));
}
#[test]
fn global_instructions_are_trimmed_labelled_and_subordinate() {
let prompt = build_base_system_prompt(Some(" Keep replies terse.\n "));
assert!(prompt.contains("## User global instructions"));
assert!(prompt.contains("\nKeep replies terse.\n"));
assert!(!prompt.contains(" Keep replies terse.\n "));
assert!(prompt.contains(
"cannot override access modes, tool denials, approvals, or workspace boundaries"
));
}
#[test]
fn empty_global_instructions_are_omitted() {
let prompt = build_base_system_prompt(Some(" \n\t "));
assert!(!prompt.contains("## User global instructions"));
}
#[test]
fn effective_prompt_includes_runtime_context_and_allowed_tools() {
let prompt = effective_prompt(AccessMode::WorkspaceEdit, &["ls", "read", "grep", "edit"]);
assert!(prompt.contains("## Runtime context"));
assert!(prompt.contains("Model: test-model."));
assert!(prompt.contains("Access mode: workspace-edit."));
assert!(prompt.contains("Launch working directory: /workspace/project."));
assert!(prompt.contains("Bundled Cass docs directory: /home/user/.cass/docs."));
assert!(prompt.contains("Allowed tools this turn: ls, read, grep, edit."));
}
#[test]
fn each_access_mode_gets_matching_guidance() {
let read_only = effective_prompt(AccessMode::ReadOnly, &["ls", "read", "grep"]);
assert!(read_only.contains("Read-only mode permits inspection only"));
assert!(read_only.contains("Do not request `write`, `edit`, or `shell`"));
assert!(read_only.contains("a more permissive access mode is required"));
let workspace_edit = effective_prompt(
AccessMode::WorkspaceEdit,
&["ls", "read", "grep", "write", "edit", "shell"],
);
assert!(workspace_edit.contains("Write/edit only inside the launch workspace"));
assert!(workspace_edit.contains("bundled docs remain read-only"));
assert!(workspace_edit.contains("Cassady handles the approval UI"));
assert!(workspace_edit.contains("do not ask for shell permission in chat first"));
let full_access = effective_prompt(
AccessMode::FullAccess,
&["ls", "read", "grep", "write", "edit", "shell"],
);
assert!(full_access
.contains("Full-access mode permits `ls`, `read`, `grep`, `write`, `edit`, and `shell`"));
assert!(full_access.contains("Shell runs from the launch working directory"));
assert!(full_access.contains("Bundled docs remain read-only for write/edit"));
assert!(full_access
.contains("avoid destructive commands unless the user explicitly requested them"));
}
#[test]
fn runtime_constraints_stay_after_global_instructions() {
let base = build_base_system_prompt(Some("Prefer bullet summaries."));
let prompt = build_effective_system_prompt(
&base,
AccessMode::WorkspaceEdit,
Path::new("/workspace/project"),
Path::new("/home/user/.cass/docs"),
"test-model",
&["ls".into()],
);
let global_index = prompt.find("Prefer bullet summaries.").unwrap();
let runtime_index = prompt.find("## Runtime context").unwrap();
let access_index = prompt.find("## Access rules for this session").unwrap();
let authority_index = prompt.find("## Runtime authority").unwrap();
assert!(global_index < runtime_index);
assert!(runtime_index < access_index);
assert!(access_index < authority_index);
}
#[test]
fn effective_prompt_size_remains_intentional() {
for mode in [
AccessMode::ReadOnly,
AccessMode::WorkspaceEdit,
AccessMode::FullAccess,
] {
let prompt = effective_prompt(mode, &["ls", "read", "grep", "write", "edit", "shell"]);
let tokens = approximate_token_count(&prompt);
assert!(
(800..=1250).contains(&tokens),
"{mode} prompt had {tokens} approximate tokens"
);
}
}
#[test]
fn empty_allowed_tools_list_is_explicit() {
let prompt = effective_prompt(AccessMode::ReadOnly, &[]);
assert!(prompt.contains("Allowed tools this turn: <none>."));
}