-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhooks_test.go
More file actions
491 lines (460 loc) · 16.7 KB
/
Copy pathhooks_test.go
File metadata and controls
491 lines (460 loc) · 16.7 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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
package hpatch
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"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"
result, applyErr := applyForHostAtTest(t, root, script, dataDirectory)
if applyErr == nil {
t.Fatal("ApplyForHost() unexpectedly succeeded")
}
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(result.Diagnostic, "warning:") {
t.Fatalf("successful hook produced warning: %q", result.Diagnostic)
}
}
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\n%s' {{shellquote .Title}} {{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)
}
want := "hpatch diagnostic\n" + markdown
if string(body) != want {
t.Fatalf("diagnose hook output = %q, want %q", body, want)
}
}
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),
})
if _, err := applyForHostAtTest(t, root, "select the file\n", dataDirectory); err == nil {
t.Fatal("ApplyForHost() unexpectedly succeeded")
}
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"})
result, err := applyForHostAtTest(t, root, "unknown-command\n", dataDirectory)
if err == nil {
t.Fatal("ApplyForHost() unexpectedly succeeded")
}
if !strings.HasPrefix(result.Diagnostic, "unknown-command: command 1, reason script-syntax: unknown or malformed command\n") {
t.Fatalf("original diagnostic was not preserved: %q", result.Diagnostic)
}
if !strings.Contains(result.Diagnostic, "hpatch: warning: running error hook 1: exit status 7\n") {
t.Fatalf("hook failure was not reported: %q", result.Diagnostic)
}
}
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)
}
if _, err := applyForHostAtTest(t, root, "new note.txt\ntype \"ok\"\n", dataDirectory); err != nil {
t.Fatalf("successful ApplyForHost() error = %v", err)
}
result, err := applyForHostAtTest(t, root, "unknown-command\n", dataDirectory)
if err == nil || !strings.Contains(result.Diagnostic, "hpatch: warning: decoding settings:") {
t.Fatalf("failed ApplyForHost() error = %v, diagnostic %q", err, result.Diagnostic)
}
}
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)})
result, err := applyForHostAtTest(t, root, "in folder\n", dataDirectory)
if err == nil || !strings.Contains(result.Diagnostic, "folder is not a regular file") {
t.Fatalf("ApplyForHost() error = %v, diagnostic %q", err, result.Diagnostic)
}
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",
EmittedPayload: "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 := translateForHostForTest(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 := translateForHostForTest(ctx, Workspace{Root: root}, "unknown-command\n", dataDirectory)
if err == nil {
t.Fatalf("translateForHostForTest() 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")
titlePath := filepath.Join(filepath.Dir(metadataPath), "outcome-title.txt")
content, err := json.Marshal(settings{Hooks: hooks{
Error: []string{
"printf '%s' {{shellquote (format_markdown .)}} > " + shellQuote(errorPath),
},
Outcome: []string{
"printf '%s' {{shellquote (format_markdown .)}} > " + shellQuote(outcomePath),
"printf '%s' {{shellquote .CorrelationID}}'|'{{shellquote .CallID}}'|'{{.Attempt}}'|'{{.Correction}}'|'{{shellquote .ToolName}}'|'{{shellquote .Stage}}'|'{{shellquote .Outcome}}'|'{{.EmittedBytes}}'|'{{.EvaluatedBytes}}'|'{{.PatchBytes}} > " + shellQuote(metadataPath),
"printf '%s' {{shellquote .Title}} > " + shellQuote(titlePath),
},
}})
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dataDirectory, settingsFilename), content, 0o600); err != nil {
t.Fatal(err)
}
rejectedScript := "unknown-command\n"
rejectedMetadata := AttemptMetadata{
SessionID: "session-1",
CorrelationID: "chain-1",
CallID: "call-1",
Attempt: 1,
Model: "gpt-5.6-sol medium",
ToolName: "functions.hpatch",
EmittedPayload: rejectedScript,
EvaluatedScript: rejectedScript,
}
failed, err := translateForHostForTest(
WithAttemptMetadata(t.Context(), rejectedMetadata),
Workspace{Root: root},
rejectedScript,
dataDirectory,
)
if err == nil || failed.Diagnostic == "" {
t.Fatalf("failed translation = %+v, error %v", failed, err)
}
if _, err := os.Stat(errorPath); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("routed rejection invoked command-error hook: %v", err)
}
outcome, err := os.ReadFile(outcomePath)
if err != nil {
t.Fatal(err)
}
for _, want := range []string{
"Tool: `functions.hpatch`",
"Stage: `evaluated`",
"Outcome: `rejected`",
"## Emitted hpatch script",
"```hpatch\nunknown-command\n```",
} {
if !strings.Contains(string(outcome), want) {
t.Fatalf("rejected outcome hook lacks %q:\n%s", want, outcome)
}
}
evaluatedScript := "new note.txt\ntype \"ok\"\n"
recoveryPayload := "C2:abcd 2:bbbb"
delta := "C2:abcd: 1:aaaa -> 2:bbbb"
recoveryMetadata := AttemptMetadata{
SessionID: "session-1",
CorrelationID: "chain-1",
CallID: "call-2",
Attempt: 2,
Correction: true,
Model: "gpt-5.6-sol medium",
ToolName: "functions.hpatch_recover",
EmittedPayload: recoveryPayload,
EvaluatedScript: evaluatedScript,
RecoveryDelta: delta,
Title: "Update note",
}
translated, err := translateForHostForTest(
WithAttemptMetadata(t.Context(), recoveryMetadata),
Workspace{Root: root},
evaluatedScript,
dataDirectory,
)
if err != nil || translated.Diagnostic != "" {
t.Fatalf("successful translation = %+v, error %v", translated, err)
}
outcomeTitle, err := os.ReadFile(titlePath)
if err != nil {
t.Fatal(err)
}
if string(outcomeTitle) != "hpatch recovery attempt succeeded: Update note" {
t.Fatalf("outcome hook title = %q", outcomeTitle)
}
outcome, err = os.ReadFile(outcomePath)
if err != nil {
t.Fatal(err)
}
for _, want := range []string{
"Tool: `functions.hpatch_recover`",
"Stage: `translated`",
"Outcome: `succeeded`",
"## Emitted recovery payload",
"```hpatch-recover\n" + recoveryPayload + "\n```",
"## Resolved recovery delta",
" " + delta,
fmt.Sprintf("Router rebuilt a %d-byte complete HPATCH script; it was not model-emitted.", len(evaluatedScript)),
} {
if !strings.Contains(string(outcome), want) {
t.Fatalf("recovery outcome hook lacks %q:\n%s", want, outcome)
}
}
if strings.Contains(string(outcome), "```hpatch\n"+evaluatedScript) {
t.Fatalf("recovery outcome presents rebuilt script as emitted:\n%s", outcome)
}
metadataBody, err := os.ReadFile(metadataPath)
if err != nil {
t.Fatal(err)
}
wantMetadata := fmt.Sprintf(
"chain-1|call-2|2|true|functions.hpatch_recover|translated|succeeded|%d|%d|%d",
len(recoveryPayload),
len(evaluatedScript),
len(translated.Patch),
)
if string(metadataBody) != wantMetadata {
t.Fatalf("outcome metadata = %q, want %q", metadataBody, wantMetadata)
}
}
func TestApplicationFailureReportsAppliedStage(t *testing.T) {
dataDirectory := t.TempDir()
metadataPath := filepath.Join(t.TempDir(), "metadata.txt")
content, err := json.Marshal(settings{Hooks: hooks{Outcome: []string{
"printf '%s' {{shellquote .Stage}}'|'{{shellquote .Outcome}} > " + shellQuote(metadataPath),
}}})
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",
CorrelationID: "chain",
CallID: "call",
Attempt: 1,
ToolName: "functions.hpatch",
EmittedPayload: "new note.txt\ntype \"ok\"\n",
EvaluatedScript: "new note.txt\ntype \"ok\"\n",
}
_, err = finishHostChange(
WithAttemptMetadata(t.Context(), metadata),
dataDirectory,
metadata.EvaluatedScript,
HostTranslation{},
"applied",
errors.New("changing note.txt: permission denied"),
true,
)
if err == nil {
t.Fatal("application failure succeeded")
}
got, err := os.ReadFile(metadataPath)
if err != nil {
t.Fatal(err)
}
if string(got) != "applied|failed" {
t.Fatalf("outcome metadata = %q", got)
}
}
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)
}
}