Debian Codegraph @

prompt_test.go

raw
1 package clnkr
2
3 import (
4 "os"
5 "path/filepath"
6 "strings"
7 "testing"
8 )
9
10 func TestLoadPromptWithOptions_BasePrompt(t *testing.T) {
11 prompt := loadPromptWithCleanEnv(t, PromptOptions{})
12
13 mustContainAll(t, prompt, []string{
14 `"type":"act"`,
15 `Set type to exactly one of "act", "clarify", or "done".`,
16 `"verification"`,
17 `"known_risks"`,
18 "verified, partially_verified, or not_verified",
19 `grep 'A\\\\|B' file.txt`,
20 "Each bash.commands item is an object whose command value is a JSON string",
21 canonicalPromptActExample,
22 `Include reasoning in every response; use a string when it helps and null when you have nothing to add.`,
23 "Exported environment changes and environment updates from source or . also persist between commands.",
24 "The host may require approval before running commands.",
25 "Batch only mechanical follow-up steps that do not require interpreting earlier command output.",
26 "Do not emit multiple JSON objects in one response.",
27 "Do not emit an act turn and a done turn together.",
28 "When the user refers to the current repo, current directory, or cwd, work in the current directory without adding cd.",
29 "If the user names a file or path, inspect that exact path first.",
30 `You may also receive JSON host state messages such as {"type":"state","source":"clnkr","cwd":"/repo"} and resource_state`,
31 "resource_state may include pressure and guidance",
32 "commands_used",
33 "commands_remaining",
34 "model_turns_used",
35 `"stdout"`,
36 `"stderr"`,
37 `"outcome"`,
38 `"observation" metadata when stdout/stderr were compressed`,
39 "clean pre-command git baseline",
40 `do not emit "done" until you have completed the change with at least one "act" turn`,
41 "Before done, run the cheapest task-visible check of the exact deliverable when feasible.",
42 "If a check fails, inspect the failure and change one hypothesis; do not repeat the same failed command blindly.",
43 "Never claim to have created, modified, or verified something unless that happened through a prior command result in this conversation.",
44 "If a verification command shows the result does not match the request exactly, issue another \"act\" turn to fix it instead of emitting \"done\".",
45 "For exact literal text writes, prefer quoted literals such as printf 'hello\\n' > note.txt instead of shell-fragile format strings.",
46 "When writing plain-text file contents like hello, write a newline-terminated line unless the user explicitly asks for no trailing newline or exact byte-for-byte content.",
47 "<protocol-error-recovery>",
48 "If you receive a [protocol_error] block, fix your format and respond with exactly one valid turn object.",
49 "If you receive a [protocol_error] block, your previous response was rejected and no command ran.",
50 "If you receive a [protocol_error] block, your previous response was rejected and no command ran. Fix the format and respond with exactly one valid turn object.",
51 })
52 mustNotContainAny(t, prompt, []string{
53 `"turn":{`,
54 `top-level "turn" field`,
55 "```bash",
56 "<done/>",
57 `{"type":"clarify"`,
58 `{"type":"done","summary"`,
59 "Use 1 or 2 commands in each act turn.",
60 "[command]",
61 "[stdout]",
62 "[command_feedback]",
63 "check status before and after making changes",
64 "For targeted edits use sed.",
65 "legacy parser path",
66 })
67 }
68
69 func TestLoadPromptWithOptions_SurfaceBoundaries(t *testing.T) {
70 tests := []struct {
71 name string
72 opts PromptOptions
73 want []string
74 }{
75 {
76 name: "inline protocol",
77 want: []string{
78 "<surface-boundaries>",
79 "Bash is your only tool. Work in the current `clnkr` session unless the user explicitly asks you to run another process.",
80 "`clnkr -p` is the unattended one-shot CLI surface.",
81 "`clnkrd` is a stdio JSONL adapter for external tools that embed clnkr behavior.",
82 "Do not treat it as default delegation, subagent, or review-loop machinery inside this session.",
83 "If the user writes `/delegate ...`, treat it as ordinary prompt text, not as a host command and not as an instruction that requires `clnkrd`.",
84 },
85 },
86 {
87 name: "tool-call protocol",
88 opts: PromptOptions{ActProtocol: ActProtocolToolCalls},
89 want: []string{
90 "<surface-boundaries>",
91 "`clnkr -p` is the unattended one-shot CLI surface.",
92 "`clnkrd` is a stdio JSONL adapter for external tools that embed clnkr behavior.",
93 "If the user writes `/delegate ...`, treat it as ordinary prompt text, not as a host command and not as an instruction that requires `clnkrd`.",
94 },
95 },
96 }
97
98 for _, tc := range tests {
99 t.Run(tc.name, func(t *testing.T) {
100 prompt := loadPromptWithCleanEnv(t, tc.opts)
101 mustContainAll(t, prompt, tc.want)
102 mustNotContainAny(t, prompt, []string{
103 "<parallel-work>",
104 "asking you to launch `clnkrd`",
105 "clnkrd --event-log",
106 "workdir=$(mktemp -d /tmp/clnkr-processes",
107 })
108 })
109 }
110 }
111
112 func TestLoadPromptWithOptions_UnattendedPrompt(t *testing.T) {
113 prompt := loadPromptWithCleanEnv(t, PromptOptions{Unattended: true})
114
115 if strings.Contains(prompt, "clarify") {
116 t.Fatalf("unattended prompt contains clarify: %q", prompt)
117 }
118 mustContainAll(t, prompt, []string{
119 `Set type to exactly one of "act" or "done".`,
120 `"verification"`,
121 `"known_risks"`,
122 "resource_state",
123 "commands_used",
124 "commands_remaining",
125 "model_turns_used",
126 "Assume no human rescue during unattended work.",
127 "Prefer cheap inspection before expensive builds, downloads, training runs, or brute force.",
128 "When execution pressure is critical, stop broad exploration",
129 })
130 }
131
132 func TestLoadPromptWithOptions_ToolCallsPromptMentionsPressure(t *testing.T) {
133 prompt := loadPromptWithCleanEnv(t, PromptOptions{ActProtocol: ActProtocolToolCalls})
134
135 mustContainAll(t, prompt, []string{
136 "resource_state may include pressure and guidance",
137 "Before done, run the cheapest task-visible check of the exact deliverable when feasible.",
138 "If a check fails, inspect the failure and change one hypothesis; do not repeat the same failed command blindly.",
139 })
140 }
141
142 func TestPromptExamplesParseSuccessfully(t *testing.T) {
143 prompt := loadPromptWithCleanEnv(t, PromptOptions{})
144
145 if count := strings.Count(prompt, canonicalPromptActExample); count != 1 {
146 t.Fatalf("prompt should contain exactly 1 canonical turn example, found %d", count)
147 }
148 got, err := CanonicalTurnJSON(&ActTurn{
149 Bash: BashBatch{Commands: []BashAction{
150 {Command: "ls -la /tmp"},
151 {Command: "sed -n '1,40p' README.md"},
152 }},
153 Reasoning: "Inspect the directory and the file before deciding.",
154 })
155 if err != nil {
156 t.Fatalf("CanonicalTurnJSON(example): %v", err)
157 }
158 if got != canonicalPromptActExample {
159 t.Fatalf("canonical prompt example drifted: got %q want %q", got, canonicalPromptActExample)
160 }
161 if strings.Contains(
162 prompt,
163 `{"turn":{"type":"act","bash":{"command":"grep 'A\\\\|B' file.txt","workdir":null}`,
164 ) {
165 t.Error(
166 "prompt should teach shell escaping with a JSON string example, not a wrapped turn object",
167 )
168 }
169 }
170
171 func TestLoadPromptWithOptions_Options(t *testing.T) {
172 t.Run("OmitSystemPrompt returns empty string", func(t *testing.T) {
173 dir := t.TempDir()
174 writeAgents(t, dir, "Should not appear.")
175
176 prompt := LoadPromptWithOptions(dir, PromptOptions{OmitSystemPrompt: true})
177 if prompt != "" {
178 t.Errorf("OmitSystemPrompt should return empty string, got %d bytes", len(prompt))
179 }
180 })
181
182 t.Run(
183 "OmitSystemPrompt with SystemPromptAppend returns only the appended text",
184 func(t *testing.T) {
185 prompt := LoadPromptWithOptions(t.TempDir(), PromptOptions{
186 OmitSystemPrompt: true,
187 SystemPromptAppend: "custom prompt only",
188 })
189 if prompt != "custom prompt only" {
190 t.Errorf("expected only appended text, got %q", prompt)
191 }
192 },
193 )
194
195 t.Run("SystemPromptAppend appends after AGENTS.md layers", func(t *testing.T) {
196 home := t.TempDir()
197 t.Setenv("HOME", home)
198 t.Setenv("XDG_CONFIG_HOME", t.TempDir())
199
200 dir := t.TempDir()
201 projectContent := "Project layer content."
202 writeAgents(t, dir, projectContent)
203
204 appendText := "Extra instructions appended at the end."
205 prompt := LoadPromptWithOptions(dir, PromptOptions{SystemPromptAppend: appendText})
206
207 mustContainAll(t, prompt, []string{projectContent, appendText})
208 projectIdx := strings.Index(prompt, projectContent)
209 appendIdx := strings.Index(prompt, appendText)
210 if projectIdx >= appendIdx {
211 t.Error("appended text should appear after project instructions")
212 }
213 if !strings.HasSuffix(prompt, appendText) {
214 t.Error("appended text should be at the end of the prompt")
215 }
216 })
217 }
218
219 func TestLoadPromptWithOptions_LayeredAgentsMD(t *testing.T) {
220 t.Run("loads tagged HOME, config, and project layers in order", func(t *testing.T) {
221 home := t.TempDir()
222 configDir := t.TempDir()
223 projectDir := t.TempDir()
224 t.Setenv("HOME", home)
225 t.Setenv("XDG_CONFIG_HOME", configDir)
226
227 homeContent := "Home layer."
228 configContent := "Config layer."
229 projectContent := "Project layer."
230 writeAgents(t, home, homeContent)
231 writeConfigAgents(t, configDir, configContent)
232 writeAgents(t, projectDir, projectContent)
233
234 prompt := LoadPromptWithOptions(projectDir, PromptOptions{})
235 mustContainAll(t, prompt, []string{
236 homeContent,
237 "<user-instructions>",
238 configContent,
239 "<config-instructions>",
240 projectContent,
241 "<project-instructions>",
242 })
243
244 homeIdx := strings.Index(prompt, homeContent)
245 configIdx := strings.Index(prompt, configContent)
246 projectIdx := strings.Index(prompt, projectContent)
247 if homeIdx >= configIdx {
248 t.Error("home layer should appear before config layer")
249 }
250 if configIdx >= projectIdx {
251 t.Error("config layer should appear before project layer")
252 }
253 })
254
255 t.Run("project dir matching HOME is not loaded twice", func(t *testing.T) {
256 home := t.TempDir()
257 t.Setenv("HOME", home)
258 t.Setenv("XDG_CONFIG_HOME", t.TempDir())
259
260 content := "Home instructions should only appear once."
261 writeAgents(t, home, content)
262
263 prompt := LoadPromptWithOptions(home, PromptOptions{})
264 if got := strings.Count(prompt, content); got != 1 {
265 t.Fatalf("content appeared %d times, want 1", got)
266 }
267 if !strings.Contains(prompt, "<user-instructions>") {
268 t.Error("prompt should keep the HOME layer when project dir matches HOME")
269 }
270 if strings.Contains(
271 prompt,
272 "<project-instructions>\n"+content+"\n</project-instructions>",
273 ) {
274 t.Error("prompt should not duplicate HOME AGENTS.md as project instructions")
275 }
276 })
277
278 t.Run("XDG_CONFIG_HOME defaults to HOME/.config", func(t *testing.T) {
279 home := t.TempDir()
280 t.Setenv("HOME", home)
281 t.Setenv("XDG_CONFIG_HOME", "")
282
283 content := "Default config path."
284 writeConfigAgents(t, filepath.Join(home, ".config"), content)
285
286 prompt := LoadPromptWithOptions(t.TempDir(), PromptOptions{})
287 if !strings.Contains(prompt, content) {
288 t.Error(
289 "prompt should load from $HOME/.config/clnkr/AGENTS.md when XDG_CONFIG_HOME is unset",
290 )
291 }
292 })
293
294 t.Run("missing layers are silently skipped", func(t *testing.T) {
295 prompt := loadPromptWithCleanEnv(t, PromptOptions{})
296 mustNotContainAny(t, prompt, []string{
297 "<user-instructions>",
298 "<config-instructions>",
299 "<project-instructions>",
300 })
301 })
302 }
303
304 func loadPromptWithCleanEnv(t *testing.T, opts PromptOptions) string {
305 t.Helper()
306 dir := t.TempDir()
307 t.Setenv("HOME", t.TempDir())
308 t.Setenv("XDG_CONFIG_HOME", t.TempDir())
309 return LoadPromptWithOptions(dir, opts)
310 }
311
312 func writeAgents(t *testing.T, dir, content string) {
313 t.Helper()
314 if err := os.WriteFile(filepath.Join(dir, "AGENTS.md"), []byte(content), 0644); err != nil {
315 t.Fatalf("write AGENTS.md: %v", err)
316 }
317 }
318
319 func writeConfigAgents(t *testing.T, configDir, content string) {
320 t.Helper()
321 clnkrConfigDir := filepath.Join(configDir, "clnkr")
322 if err := os.MkdirAll(clnkrConfigDir, 0755); err != nil {
323 t.Fatalf("mkdir config AGENTS.md dir: %v", err)
324 }
325 writeAgents(t, clnkrConfigDir, content)
326 }
327
328 func mustContainAll(t *testing.T, text string, wants []string) {
329 t.Helper()
330 for _, want := range wants {
331 if !strings.Contains(text, want) {
332 t.Fatalf("missing %q", want)
333 }
334 }
335 }
336
337 func mustNotContainAny(t *testing.T, text string, unwanted []string) {
338 t.Helper()
339 for _, s := range unwanted {
340 if strings.Contains(text, s) {
341 t.Fatalf("contains unwanted %q", s)
342 }
343 }
344 }