-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhooks_test.go
More file actions
414 lines (383 loc) · 15.2 KB
/
Copy pathhooks_test.go
File metadata and controls
414 lines (383 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
package hpatch
import (
"bytes"
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestErrorHookReceivesFailureAndRepairContext(t *testing.T) {
root := t.TempDir()
if err := os.WriteFile(filepath.Join(root, "note.txt"), []byte("present words\n"), 0o644); err != nil {
t.Fatal(err)
}
dataDirectory := t.TempDir()
bodyPath := filepath.Join(t.TempDir(), "body.md")
writeSettingsForTest(t, dataDirectory, []string{
"printf '%s' {{shellquote (format_markdown .)}} > " + shellQuote(bodyPath),
})
script := "in note.txt\ntype 1:" + hashLine("present words") + " \"missing\" \"replacement\"\n"
var stdout, stderr bytes.Buffer
exitCode := Run(nil, strings.NewReader(script), &stdout, &stderr, root, dataDirectory)
if exitCode != 1 || stdout.Len() != 0 {
t.Fatalf("Run() = exit %d, stdout %q, stderr %q", exitCode, stdout.String(), stderr.String())
}
body, err := os.ReadFile(bodyPath)
if err != nil {
t.Fatal(err)
}
for _, fragment := range []string{
"Command: 2 `type`",
"Source: note.txt:2",
} {
if !strings.Contains(string(body), fragment) {
t.Fatalf("hook body does not contain %q:\n%s", fragment, body)
}
}
for _, omitted := range []string{"# hpatch command failed", "Description:", "Outcome:", "Category:", "Failed command", "Failure", "Diagnostic", "Repair context"} {
if strings.Contains(string(body), omitted) {
t.Fatalf("hook body unexpectedly contains %q:\n%s", omitted, body)
}
}
if strings.Contains(stderr.String(), "warning:") {
t.Fatalf("successful hook produced warning: %q", stderr.String())
}
}
func TestReportIssueRunsDiagnoseHooksWithExactMarkdown(t *testing.T) {
dataDirectory := t.TempDir()
bodyPath := filepath.Join(t.TempDir(), "body.md")
diagnoseHooks := NewDiagnoseHooks(dataDirectory)
content, err := json.Marshal(settings{Hooks: hooks{
Error: []string{"exit 9"},
Diagnose: []string{
"printf '%s' {{shellquote (format_markdown .)}} > " + shellQuote(bodyPath),
},
}})
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dataDirectory, settingsFilename), content, 0o600); err != nil {
t.Fatal(err)
}
markdown := "# Misleading repair context\n\nThe suggested target cannot match."
if err := diagnoseHooks.Report(t.Context(), markdown); err != nil {
t.Fatal(err)
}
body, err := os.ReadFile(bodyPath)
if err != nil {
t.Fatal(err)
}
if string(body) != markdown {
t.Fatalf("diagnose hook body = %q, want %q", body, markdown)
}
}
func TestReportIssueReturnsDiagnoseHookFailure(t *testing.T) {
dataDirectory := t.TempDir()
diagnoseHooks := NewDiagnoseHooks(dataDirectory)
content, err := json.Marshal(settings{Hooks: hooks{Diagnose: []string{"exit 9"}}})
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dataDirectory, settingsFilename), content, 0o600); err != nil {
t.Fatal(err)
}
err = diagnoseHooks.Report(t.Context(), "diagnostic")
if err == nil || !strings.Contains(err.Error(), "running diagnose hook 1: exit status 9") {
t.Fatalf("ReportIssue() error = %v", err)
}
}
func TestErrorHookReceivesMalformedCommand(t *testing.T) {
root := t.TempDir()
dataDirectory := t.TempDir()
bodyPath := filepath.Join(t.TempDir(), "body.md")
writeSettingsForTest(t, dataDirectory, []string{
"printf '%s' {{shellquote .Body}} > " + shellQuote(bodyPath),
})
var stdout, stderr bytes.Buffer
exitCode := Run(nil, strings.NewReader("select the file\n"), &stdout, &stderr, root, dataDirectory)
if exitCode != 1 {
t.Fatalf("Run() = exit %d, stdout %q, stderr %q", exitCode, stdout.String(), stderr.String())
}
body, err := os.ReadFile(bodyPath)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(body), "Command: 1 `select`") {
t.Fatalf("hook body does not contain command:\n%s", body)
}
if strings.Contains(string(body), "Description:") || strings.HasPrefix(string(body), "#") {
t.Fatalf("error hook body unexpectedly contains title or description:\n%s", body)
}
}
func TestErrorHookFailureDoesNotReplaceDiagnostic(t *testing.T) {
root := t.TempDir()
dataDirectory := t.TempDir()
writeSettingsForTest(t, dataDirectory, []string{"exit 7"})
var stdout, stderr bytes.Buffer
exitCode := Run(nil, strings.NewReader("del\n"), &stdout, &stderr, root, dataDirectory)
if exitCode != 1 || stdout.Len() != 0 {
t.Fatalf("Run() = exit %d, stdout %q, stderr %q", exitCode, stdout.String(), stderr.String())
}
if !strings.HasPrefix(stderr.String(), "del: command 1, reason script-syntax: unknown or malformed command\n") {
t.Fatalf("original diagnostic was not preserved: %q", stderr.String())
}
if !strings.Contains(stderr.String(), "hpatch: warning: running error hook 1: exit status 7\n") {
t.Fatalf("hook failure was not reported: %q", stderr.String())
}
}
func TestSettingsAreReadOnlyForEvaluationFailures(t *testing.T) {
root := t.TempDir()
dataDirectory := t.TempDir()
if err := os.WriteFile(filepath.Join(dataDirectory, settingsFilename), []byte("not JSON"), 0o600); err != nil {
t.Fatal(err)
}
var stdout, stderr bytes.Buffer
if exitCode := Run(nil, strings.NewReader("new note.txt\ntype \"ok\"\n"), &stdout, &stderr, root, dataDirectory); exitCode != 0 {
t.Fatalf("successful Run() = exit %d, stdout %q, stderr %q", exitCode, stdout.String(), stderr.String())
}
stdout.Reset()
stderr.Reset()
exitCode := Run(nil, strings.NewReader("del\n"), &stdout, &stderr, root, dataDirectory)
if exitCode != 1 || !strings.Contains(stderr.String(), "hpatch: warning: decoding settings:") {
t.Fatalf("failed Run() = exit %d, stdout %q, stderr %q", exitCode, stdout.String(), stderr.String())
}
}
func TestEnvironmentalCommandFailureDoesNotRunErrorHook(t *testing.T) {
root := t.TempDir()
if err := os.Mkdir(filepath.Join(root, "folder"), 0o755); err != nil {
t.Fatal(err)
}
dataDirectory := t.TempDir()
bodyPath := filepath.Join(t.TempDir(), "body.md")
writeSettingsForTest(t, dataDirectory, []string{"touch " + shellQuote(bodyPath)})
var stdout, stderr bytes.Buffer
exitCode := Run(nil, strings.NewReader("in folder\n"), &stdout, &stderr, root, dataDirectory)
if exitCode != 1 || !strings.Contains(stderr.String(), "folder is not a regular file") {
t.Fatalf("Run() = exit %d, stdout %q, stderr %q", exitCode, stdout.String(), stderr.String())
}
if _, err := os.Stat(bodyPath); !os.IsNotExist(err) {
t.Fatalf("environmental failure ran hook: stat error %v", err)
}
}
func TestExecuteErrorHookTimesOut(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond)
defer cancel()
started := time.Now()
err := executeErrorHook(ctx, "sleep 10")
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("executeErrorHook() error = %v", err)
}
if elapsed := time.Since(started); elapsed > time.Second {
t.Fatalf("executeErrorHook() took %s", elapsed)
}
}
func TestAggregatedErrorHooksShareOneTimeout(t *testing.T) {
dataDirectory := t.TempDir()
writeSettingsForTest(t, dataDirectory, []string{"sleep 10"})
sourceErrors := []*commandError{
{Reason: reasonSyntax, Command: 1, Line: 1, Operation: "bad", Category: "syntax", Source: "bad", Message: "unknown command"},
{Reason: reasonSyntax, Command: 2, Line: 2, Operation: "bad", Category: "syntax", Source: "bad", Message: "unknown command"},
}
started := time.Now()
errs := runCommandErrorHooks(t.Context(), dataDirectory, sourceErrors, "failed", 20*time.Millisecond)
if elapsed := time.Since(started); elapsed > time.Second {
t.Fatalf("runCommandErrorHooks() took %s", elapsed)
}
if len(errs) != 1 || !errors.Is(errs[0], context.DeadlineExceeded) {
t.Fatalf("runCommandErrorHooks() errors = %v", errs)
}
}
func TestErrorHooksShareOneTimeout(t *testing.T) {
dataDirectory := t.TempDir()
writeSettingsForTest(t, dataDirectory, []string{"sleep 10", "sleep 10"})
sourceError := &commandError{Reason: reasonSyntax, Command: 1, Line: 1, Operation: "bad", Category: "syntax", Source: "bad", Message: "unknown command"}
started := time.Now()
errs := runCommandErrorHooks(t.Context(), dataDirectory, []*commandError{sourceError}, failureDiagnostic(sourceError.Error()), 20*time.Millisecond)
if elapsed := time.Since(started); elapsed > time.Second {
t.Fatalf("runCommandErrorHooks() took %s", elapsed)
}
if len(errs) != 1 || !errors.Is(errs[0], context.DeadlineExceeded) {
t.Fatalf("runCommandErrorHooks() errors = %v", errs)
}
}
func TestReadSettingsRejectsOversizeContent(t *testing.T) {
dataDirectory := t.TempDir()
content := append([]byte(`{"hooks":{"error":[]}}`), bytes.Repeat([]byte(" "), maxSettingsBytes)...)
if err := os.WriteFile(filepath.Join(dataDirectory, settingsFilename), content, 0o600); err != nil {
t.Fatal(err)
}
_, err := readSettings(dataDirectory)
if err == nil || !strings.Contains(err.Error(), "file exceeds 1048576 bytes") {
t.Fatalf("readSettings() error = %v", err)
}
}
func TestMarkdownCodeSpanHandlesBackticks(t *testing.T) {
body := formatErrorHookMarkdown(errorHookEvent{Command: 1, Operation: "type`quoted"})
if !strings.Contains(body, "Command: 1 `` type`quoted ``") {
t.Fatalf("formatErrorHookMarkdown() = %q", body)
}
}
func TestOutcomeHookMarkdownUsesSafeFence(t *testing.T) {
event := outcomeHookEvent{
attemptHookFields: attemptHookFields{Outcome: "succeeded"},
Title: "hpatch attempt succeeded",
Script: "type <<PATCH\n```\nPATCH\n",
}
body := formatOutcomeHookMarkdown(event)
if event.Title != "hpatch attempt succeeded" {
t.Fatalf("outcome title = %q", event.Title)
}
if !strings.Contains(body, "````hpatch\ntype <<PATCH\n```\nPATCH\n````") {
t.Fatalf("formatOutcomeHookMarkdown() = %q", body)
}
if strings.HasPrefix(body, "#") {
t.Fatalf("outcome hook body unexpectedly contains title: %q", body)
}
}
func TestOutcomeHookFailureWarnsWithoutReplacingSuccess(t *testing.T) {
root, err := os.OpenRoot(t.TempDir())
if err != nil {
t.Fatal(err)
}
defer root.Close()
dataDirectory := t.TempDir()
content, err := json.Marshal(settings{Hooks: hooks{Outcome: []string{"exit 9"}}})
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dataDirectory, settingsFilename), content, 0o600); err != nil {
t.Fatal(err)
}
ctx := WithAttemptMetadata(t.Context(), AttemptMetadata{SessionID: "session", CorrelationID: "chain", CallID: "call", Attempt: 1})
translated, err := TranslateForHost(ctx, Workspace{Root: root}, "new note.txt\ntype \"ok\"\n", dataDirectory)
if err != nil || len(translated.Patch) == 0 {
t.Fatalf("translation = %+v, error %v", translated, err)
}
if !strings.Contains(translated.Diagnostic, "warning: running outcome hook 1: exit status 9") {
t.Fatalf("outcome warning = %q", translated.Diagnostic)
}
}
func TestRejectedAttemptReportsSettingsFailureOnce(t *testing.T) {
root, err := os.OpenRoot(t.TempDir())
if err != nil {
t.Fatal(err)
}
defer root.Close()
dataDirectory := t.TempDir()
if err := os.WriteFile(filepath.Join(dataDirectory, settingsFilename), []byte("{"), 0o600); err != nil {
t.Fatal(err)
}
ctx := WithAttemptMetadata(t.Context(), AttemptMetadata{SessionID: "session", CorrelationID: "chain", CallID: "call", Attempt: 1})
translated, err := TranslateForHost(ctx, Workspace{Root: root}, "del\n", dataDirectory)
if err == nil {
t.Fatalf("TranslateForHost() translation = %+v, want rejection", translated)
}
if count := strings.Count(translated.Diagnostic, "hpatch: warning: decoding settings:"); count != 1 {
t.Fatalf("settings warning count = %d, diagnostic:\n%s", count, translated.Diagnostic)
}
}
func TestErrorAndOutcomeHooksReceiveAttemptMetadata(t *testing.T) {
rootPath := t.TempDir()
root, err := os.OpenRoot(rootPath)
if err != nil {
t.Fatal(err)
}
defer root.Close()
dataDirectory := t.TempDir()
errorPath := filepath.Join(t.TempDir(), "error.md")
outcomePath := filepath.Join(t.TempDir(), "outcome.md")
metadataPath := filepath.Join(t.TempDir(), "metadata.txt")
content, err := json.Marshal(settings{Hooks: hooks{
Error: []string{
"printf '%s' {{shellquote (format_markdown .)}} > " + shellQuote(errorPath),
"printf '%s' {{shellquote .Title}} > " + shellQuote(filepath.Join(filepath.Dir(metadataPath), "error-title.txt")),
},
Outcome: []string{
"printf '%s' {{shellquote (format_markdown .)}} > " + shellQuote(outcomePath),
"printf '%s' {{shellquote .CorrelationID}}'|'{{shellquote .CallID}}'|'{{.Attempt}}'|'{{.Correction}}'|'{{shellquote .Outcome}} > " + shellQuote(metadataPath),
"printf '%s' {{shellquote .Title}} > " + shellQuote(filepath.Join(filepath.Dir(metadataPath), "outcome-title.txt")),
},
}})
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dataDirectory, settingsFilename), content, 0o600); err != nil {
t.Fatal(err)
}
metadata := AttemptMetadata{SessionID: "session-1", CorrelationID: "chain-1", CallID: "call-2", Attempt: 2, Correction: true, Model: "gpt-5.6-sol medium"}
ctx := WithAttemptMetadata(t.Context(), metadata)
failed, err := TranslateForHost(ctx, Workspace{Root: root}, "del\n", dataDirectory)
if err == nil || failed.Diagnostic == "" {
t.Fatalf("failed translation = %+v, error %v", failed, err)
}
body, err := os.ReadFile(errorPath)
if err != nil {
t.Fatal(err)
}
for _, want := range []string{"Model: gpt-5.6-sol medium", "Session ID: session-1", "Call ID: call-2", "Attempt: 2", "Correction: true"} {
if !strings.Contains(string(body), want) {
t.Fatalf("error hook lacks %q:\n%s", want, body)
}
}
if strings.Contains(string(body), "Correlation ID:") {
t.Fatalf("error hook unexpectedly exposes correlation ID:\n%s", body)
}
if strings.Contains(string(body), "Outcome:") {
t.Fatalf("error hook unexpectedly exposes outcome:\n%s", body)
}
titleBody, err := os.ReadFile(filepath.Join(filepath.Dir(metadataPath), "error-title.txt"))
if err != nil {
t.Fatal(err)
}
if string(titleBody) != "hpatch command failed" {
t.Fatalf("error hook title = %q", titleBody)
}
outcome, err := os.ReadFile(outcomePath)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(outcome), "```hpatch\ndel\n```") ||
strings.Contains(string(outcome), "# hpatch attempt rejected") {
t.Fatalf("rejected outcome hook = %q", outcome)
}
translated, err := TranslateForHost(ctx, Workspace{Root: root}, "new note.txt\ntype \"ok\"\n", dataDirectory)
if err != nil || translated.Diagnostic != "" {
t.Fatalf("successful translation = %+v, error %v", translated, err)
}
outcomeTitle, err := os.ReadFile(filepath.Join(filepath.Dir(metadataPath), "outcome-title.txt"))
if err != nil {
t.Fatal(err)
}
if string(outcomeTitle) != "hpatch attempt corrected" {
t.Fatalf("outcome hook title = %q", outcomeTitle)
}
outcome, err = os.ReadFile(outcomePath)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(outcome), "```hpatch\nnew note.txt\ntype \"ok\"\n```") ||
strings.Contains(string(outcome), "# hpatch attempt corrected") {
t.Fatalf("corrected outcome hook = %q", outcome)
}
metadataBody, err := os.ReadFile(metadataPath)
if err != nil {
t.Fatal(err)
}
if string(metadataBody) != "chain-1|call-2|2|true|corrected" {
t.Fatalf("outcome metadata = %q", metadataBody)
}
}
func writeSettingsForTest(t *testing.T, dataDirectory string, errorHooks []string) {
t.Helper()
content, err := json.Marshal(settings{Hooks: hooks{Error: errorHooks}})
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dataDirectory, settingsFilename), content, 0o600); err != nil {
t.Fatal(err)
}
}