Repository navigation
Expand file tree
/
Copy pathchat_test.go
More file actions
873 lines (826 loc) · 37.5 KB
/
Copy pathchat_test.go
File metadata and controls
873 lines (826 loc) · 37.5 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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"github.com/Agent-Field/agentfield/sdk/go/ai"
"github.com/Agent-Field/codeaf/internal/config"
"github.com/Agent-Field/codeaf/internal/exec"
"github.com/Agent-Field/codeaf/internal/profile"
"github.com/Agent-Field/codeaf/internal/provider"
"github.com/Agent-Field/codeaf/internal/provider/pool"
"github.com/Agent-Field/codeaf/internal/resident"
"github.com/Agent-Field/codeaf/internal/revision"
"github.com/Agent-Field/codeaf/internal/router"
"github.com/Agent-Field/codeaf/internal/store"
)
// adoptLiveClient wraps a scripted provider in the switchable client every
// structuring call in this surface talks through. It is the moved constructor
// under one name: the type is internal/provider/pool's now, and a test that
// used to write the struct literal writes this instead.
func adoptLiveClient(settings config.Config, model string, client router.Client) *liveClient {
return pool.Adopt(settings, model, client)
}
type gateCaptureClient struct {
model string
messages []ai.Message
class provider.CallClass
responseMode bool
response string
}
func (c *gateCaptureClient) CompleteWithMessages(ctx context.Context, messages []ai.Message, options ...ai.Option) (*ai.Response, error) {
c.messages = messages
c.class = provider.CallClassFrom(ctx)
request := &ai.Request{}
for _, option := range options {
if err := option(request); err != nil {
return nil, err
}
}
c.responseMode = request.ResponseFormat != nil
text := c.response
if text == "" {
text = `{"pass":true}`
}
return &ai.Response{Choices: []ai.Choice{{
Message: ai.Message{Role: "assistant", Content: []ai.ContentPart{{Type: "text", Text: text}}},
}}}, nil
}
func (c *gateCaptureClient) Model() string { return c.model }
func TestDeliveryGateSeesNotebookPreferencesAndNoPanelStaysBare(t *testing.T) {
graph, err := store.Open(filepath.Join(t.TempDir(), "graph.db"))
if err != nil {
t.Fatal(err)
}
defer graph.Close()
if _, err := graph.RecordFact("", "user", store.FactPreference,
"the user always wants benchmark evidence named explicitly"); err != nil {
t.Fatal(err)
}
const settledTaste = "the user wants written comparisons kept under a page"
candidate, err := graph.RecordTasteCandidate("", "user", settledTaste)
if err != nil {
t.Fatal(err)
}
if _, err := graph.PromoteTasteRule(candidate.Seq); err != nil {
t.Fatal(err)
}
settings := config.Config{Model: "worker/model"}
capture := &gateCaptureClient{model: "worker/model"}
client := adoptLiveClient(settings, capture.model, capture)
// The job's own working decisions ride the brief the resident anchored them
// onto, which is what the gate is handed as the compiled goal. An assumption
// that never leaves the receipt is a promise nobody is held to.
const securityDecision = "review the diff for security regressions before pushing"
node := store.Node{
ID: "job",
Brief: "compare the approaches with evidence\n\n" +
resident.WorkingDecisionsHeader + "\n- " + securityDecision,
Provenance: store.Provenance{Intent: "recommend an approach", SessionID: "s1"},
}
judgment := revision.JudgeDeliverable(context.Background(), settings, client, graph, node, "approach A wins", "", revision.Evidence{}, "worker/model")
if !judgment.Checked || !judgment.Pass {
t.Fatalf("judgment = %+v, want a checked pass", judgment)
}
if capture.class != provider.ClassPlanAudit {
t.Fatalf("gate class = %q, want a planning-shaped audit call", capture.class)
}
if capture.responseMode {
t.Fatal("no-panel gate added structured-output request options; want the bare adapter request")
}
body := capture.messages[len(capture.messages)-1].Content[0].Text
if !strings.Contains(body, "the user always wants benchmark evidence named explicitly") {
t.Fatalf("gate input omitted the standing user preference: %q", body)
}
// The digest block runs from its heading to the request that follows it —
// it stopped being the tail of the prompt when the standing blocks moved
// ahead of the job, so its bound is measured against its own end.
digestHeading := revision.GateLessonsHeading
marker := strings.Index(body, digestHeading)
end := strings.Index(body, "Verbatim request:\n")
if marker < 0 || end <= marker || len(body[marker:end]) > revision.GateNotebookBytes+len(digestHeading)+len("\n\n") {
t.Fatalf("gate notebook block is absent or over its bound: marker=%d end=%d", marker, end)
}
// Settled taste is not one lesson among eight — it is what an acceptable
// answer looks like, so it is read before the digest and cannot be crowded
// out by the digest's byte budget.
taste := strings.Index(body, "Settled taste — hold to these:\n")
if taste < 0 || !strings.Contains(body[taste:], settledTaste) {
t.Fatalf("gate input omitted the settled taste rule: %q", body)
}
if notebook := strings.Index(body, revision.GateLessonsHeading); taste > notebook {
t.Fatalf("settled taste ranked after the notebook digest: taste=%d notebook=%d", taste, notebook)
}
if !strings.Contains(body, resident.WorkingDecisionsHeader) || !strings.Contains(body, securityDecision) {
t.Fatalf("gate input omitted the job's working decisions: %q", body)
}
if !strings.Contains(revision.DeliverablePrompt, "Working decisions declared in the goal are part of what was promised") {
t.Fatal("the gate prompt does not hold the deliverable to the decisions it is shown")
}
}
func TestParseLearnedFactsCarriesSkillCandidate(t *testing.T) {
learned := parseLearnedFacts(`{"facts":[{"scope":"tool:git","kind":"skill","body":"git-audit checks a repository","skill":{"artifact":" /workspace/git-audit "}}]}`, 5)
if len(learned) != 1 || learned[0].Kind != store.FactSkill || learned[0].Skill == nil ||
learned[0].Skill.Artifact != "/workspace/git-audit" {
t.Fatalf("parsed skill candidate = %+v", learned)
}
malformed := parseLearnedFacts(`{"facts":[
{"scope":"tool:git","kind":"skill","body":"missing artifact"},
{"scope":"tool:git","kind":"lesson","body":"wrong kind","skill":{"artifact":"/tmp/x"}}
]}`, 5)
if len(malformed) != 1 || malformed[0].Kind != store.FactSkill || malformed[0].Skill != nil {
t.Fatalf("malformed candidate handling = %+v", malformed)
}
}
func TestParseLearnedFactsAcceptsDistilledAndConsolidatedPlaybooks(t *testing.T) {
distilled := parseLearnedFacts(`{"facts":[{"scope":"tool:pdftotext","kind":"playbook","body":"Try pdftotext before OCR; the text route preserved columns in trial #42"}]}`, 5)
if len(distilled) != 1 || distilled[0].Kind != store.FactPlaybook ||
distilled[0].Scope != "tool:pdftotext" {
t.Fatalf("parsed distilled playbook = %+v", distilled)
}
consolidated := parseLearnedFacts(`{"facts":[{"scope":"repo:parser","kind":"playbook","body":"Run make check; it configures generated fixtures","sources":[17,11],"replaces":17}]}`, 8)
if len(consolidated) != 1 || consolidated[0].Kind != store.FactPlaybook ||
consolidated[0].Replaces != 17 || len(consolidated[0].Sources) != 2 {
t.Fatalf("parsed consolidated playbook = %+v", consolidated)
}
for name, prompt := range map[string]string{
"distiller": distillerSystemPrompt, "consolidator": consolidatorSystemPrompt,
} {
if !strings.Contains(prompt, "playbook") {
t.Errorf("%s prompt does not offer playbook output", name)
}
}
}
func TestConsolidatorRendersPlaybookScope(t *testing.T) {
graph, err := store.Open(filepath.Join(t.TempDir(), "graph.db"))
if err != nil {
t.Fatal(err)
}
defer graph.Close()
fact, err := graph.RecordFact("", "repo:parser", store.FactPlaybook,
"Run make check; it configures generated fixtures")
if err != nil {
t.Fatal(err)
}
settings := config.Config{Model: "talk/model"}
capture := &gateCaptureClient{model: "talk/model"}
client := adoptLiveClient(settings, capture.model, capture)
if _, err := consolidateFacts(settings, client, graph)(context.Background(), fact.Scope, []store.Fact{fact}, nil); err != nil {
t.Fatal(err)
}
user := capture.messages[1].Content[0].Text
want := fmt.Sprintf("#%d [repo:parser · playbook · ", fact.Seq)
if !strings.Contains(user, want) {
t.Fatalf("consolidator playbook input omitted scope: %q", user)
}
}
func TestConsolidatorSeesBadRidePatternAndCausationCaution(t *testing.T) {
graph, err := store.Open(filepath.Join(t.TempDir(), "graph.db"))
if err != nil {
t.Fatal(err)
}
defer graph.Close()
if err := graph.Splice(store.RootID, store.Subtree{Nodes: []store.NodeSpec{
{ID: "job", Brief: "exercise bad rides", Stage: 0},
{ID: "bad-a", Parent: "job", Brief: "first bad ride", Stage: 1},
{ID: "bad-b", Parent: "job", Brief: "second bad ride", Stage: 1},
}}, store.Provenance{Origin: store.OriginUser, Intent: "exercise bad rides"}); err != nil {
t.Fatal(err)
}
fact, err := graph.RecordFact("", "repo:test", store.FactLesson, "always skip verification")
if err != nil {
t.Fatal(err)
}
for _, nodeID := range []string{"bad-a", "bad-b"} {
if err := graph.RecordFactInjection(nodeID, []int64{fact.Seq}); err != nil {
t.Fatal(err)
}
claim, won, err := graph.Claim(nodeID, "worker")
if err != nil || !won {
t.Fatalf("claim %s: won=%t err=%v", nodeID, won, err)
}
if err := graph.Fail(claim, "verification was skipped"); err != nil {
t.Fatal(err)
}
}
facts, err := graph.ActiveFacts("repo:test", 10)
if err != nil {
t.Fatal(err)
}
settings := config.Config{Model: "talk/model"}
capture := &gateCaptureClient{model: "talk/model"}
client := adoptLiveClient(settings, capture.model, capture)
if _, err := consolidateFacts(settings, client, graph)(context.Background(), "repo:test", facts, nil); err != nil {
t.Fatal(err)
}
if len(capture.messages) != 2 {
t.Fatalf("consolidator messages = %d, want 2", len(capture.messages))
}
system := capture.messages[0].Content[0].Text
for _, want := range []string{"Co-occurrence is not causation", "one bad job is never enough", "quarantines"} {
if !strings.Contains(system, want) {
t.Errorf("consolidator doctrine omitted %q", want)
}
}
user := capture.messages[1].Content[0].Text
wantRide := fmt.Sprintf("#%d [lesson · ", fact.Seq)
if !strings.Contains(user, wantRide) || !strings.Contains(user, "rode 2 jobs, 2 ended badly") {
t.Fatalf("consolidator input omitted bad rides: %q", user)
}
}
func TestSingleLeafProfileCarriesPolishedGateVerdict(t *testing.T) {
dir := t.TempDir()
settings := config.Config{Model: "configured/model", ProfileDir: dir}
node := store.Node{Brief: "deliver every requested section", Title: "Complete delivery"}
outcome := &exec.Outcome{
Turns: 6, Stop: exec.StopDone, Verdict: provider.ReadingSemanticFailure,
Usage: exec.Usage{PromptTokens: 120, CompletionTokens: 30},
}
recordSingleLeaf(settings, "polish/model", node, outcome)
measured, err := profile.Load(dir, "polish/model", "linear")
if err != nil {
t.Fatal(err)
}
if len(measured.Records) != 1 || measured.Records[0].Verdict != provider.ReadingSemanticFailure ||
measured.Records[0].Tokens != 150 || measured.Model != "polish/model" {
t.Fatalf("profile = %+v, want the polished worker and gate failure", measured)
}
}
func TestRetrospectivePrioritizesAndRendersSurprise(t *testing.T) {
graph, err := store.Open(filepath.Join(t.TempDir(), "reflection.db"))
if err != nil {
t.Fatal(err)
}
defer graph.Close()
settings := config.Config{Model: "talk/model"}
capture := &gateCaptureClient{model: settings.Model}
client := adoptLiveClient(settings, capture.model, capture)
surprise := 1.875
jobs := []resident.JobSketch{{
Title: "Mispredicted report", Ask: "write the report", Outcome: "report delivered", Age: "today",
NodeCount: 2, PromptTokens: 140, CompletionTokens: 25, Cost: 0.0125,
SurpriseTokens: 165, ExpectedTokens: 72, Surprise: &surprise,
}}
if _, err := reflectAcrossJobs(settings, client, graph)(context.Background(), jobs); err != nil {
t.Fatal(err)
}
if len(capture.messages) != 2 {
t.Fatalf("reflection messages = %d, want 2", len(capture.messages))
}
system := capture.messages[0].Content[0].Text
if !strings.Contains(system, "Consider the most mispredicted jobs first") ||
!strings.Contains(system, "where the self-model is most wrong") {
t.Fatalf("reflection prompt omitted surprise priority: %q", system)
}
user := capture.messages[1].Content[0].Text
for _, want := range []string{
"2 nodes · 165 tok · $0.0125",
"predicted 72 tok — 2.3× over",
} {
if !strings.Contains(user, want) {
t.Errorf("reflection input = %q, want %q", user, want)
}
}
}
func TestParseLearnedFactsKeepsStructuredUnsettledPair(t *testing.T) {
raw := `{"facts":[{"scope":"domain:parsing","kind":"unsettled","body":"ignored projection","unsettled":{"approaches":[{"approach":"table-driven","scope":"stable grammars","evidence":[11]},{"approach":"combinators","scope":"changing grammars","evidence":[17]}]},"sources":[11,17]}]}`
learned := parseLearnedFacts(raw, 5)
if len(learned) != 1 || learned[0].Kind != store.FactUnsettled || learned[0].Unsettled == nil {
t.Fatalf("parsed facts = %+v", learned)
}
pair := learned[0].Unsettled
if len(pair.Approaches) != 2 || pair.Approaches[0].Evidence[0] != 11 || pair.Approaches[1].Scope != "changing grammars" {
t.Fatalf("parsed unsettled pair = %+v", pair)
}
if learned[0].Body != store.FormatUnsettledPair(*pair) {
t.Fatalf("body = %q, want canonical projection %q", learned[0].Body, store.FormatUnsettledPair(*pair))
}
}
func TestParseLearnedFactsAcceptsQuarantineOnlyDecision(t *testing.T) {
learned := parseLearnedFacts(`{"facts":[{"quarantines":[12,13]}]}`, 8)
if len(learned) != 1 || len(learned[0].Quarantines) != 2 ||
learned[0].Quarantines[0] != 12 || learned[0].Quarantines[1] != 13 {
t.Fatalf("parsed quarantine = %+v", learned)
}
}
func TestParseConsolidationKeepsOneScopeAliasJudgment(t *testing.T) {
parsed := parseConsolidation(`{"facts":[],"scope_alias":{"merge":true,"canonical":"domain:podcast"}}`, 8)
if parsed.ScopeAlias == nil || !parsed.ScopeAlias.Merge || parsed.ScopeAlias.Canonical != "domain:podcast" {
t.Fatalf("scope alias judgment = %+v", parsed.ScopeAlias)
}
}
func TestConsolidatorOffersExactlyOneScopeCandidateJudgment(t *testing.T) {
graph, err := store.Open(filepath.Join(t.TempDir(), "graph.db"))
if err != nil {
t.Fatal(err)
}
defer graph.Close()
settings := config.Config{Model: "talk/model"}
capture := &gateCaptureClient{model: "talk/model"}
client := adoptLiveClient(settings, capture.model, capture)
candidate := &resident.ScopePair{First: "domain:podcast", Second: "domain:podcasts"}
if _, err := consolidateFacts(settings, client, graph)(context.Background(), "", nil, candidate); err != nil {
t.Fatal(err)
}
if len(capture.messages) != 2 {
t.Fatalf("consolidator messages = %d, want 2", len(capture.messages))
}
system := capture.messages[0].Content[0].Text
if !strings.Contains(system, "make exactly one additional judgment") ||
!strings.Contains(system, `{"merge":false,"canonical":""}`) {
t.Fatalf("scope gardening doctrine missing from prompt: %q", system)
}
user := capture.messages[1].Content[0].Text
if strings.Count(user, "Scope-gardening candidate:") != 1 ||
strings.Count(user, "- "+candidate.First+"\n") != 1 ||
strings.Count(user, "- "+candidate.Second+"\n") != 1 {
t.Fatalf("scope candidate input = %q", user)
}
}
func TestReflexEnvelopeSkipsDeliveryGate(t *testing.T) {
if reflexTurns != 4 || reflexTokens != chatLeafTokens/8 {
t.Fatalf("reflex envelope = %d turns/%d tokens", reflexTurns, reflexTokens)
}
outcome := &exec.Outcome{Stop: exec.StopDone}
reflex := store.Node{ID: "reflex-1", Parent: store.RootID, Group: resident.ReflexGroup}
if shouldGate(reflex, outcome, false) {
t.Fatal("reflex reached delivery gate")
}
if !shouldPromoteReflex(reflex, &exec.Outcome{Stop: exec.StopBudget}) {
t.Fatal("budget-stopped reflex did not promote")
}
ordinary := store.Node{ID: "task-1", Parent: store.RootID}
if !shouldGate(ordinary, outcome, false) {
t.Fatal("ordinary root leaf unexpectedly skipped delivery gate")
}
if shouldPromoteReflex(ordinary, &exec.Outcome{Stop: exec.StopBudget}) {
t.Fatal("ordinary budget stop was mislabeled reflex promotion")
}
if shouldGate(ordinary, &exec.Outcome{Stop: exec.StopBudget}, true) {
t.Fatal("budget partial reached delivery gate")
}
repair := store.Node{ID: "task-1-x2-n1", Parent: store.RootID}
if !shouldGate(repair, &exec.Outcome{Stop: exec.StopDone}, false) {
t.Fatal("completed continuation skipped the final delivery gate")
}
if got, want := continuationMessage(3), "splitting the remaining work -- 3 pieces queued"; got != want {
t.Fatalf("continuation message = %q, want %q", got, want)
}
// The other splice path arrives here by the same door and by no other. A
// repair the revision sentinel adds because a leaf failed is judged when it
// stands on the spine — which is where resident.ApplyRevisionGoverned puts
// one that nothing in its job is left to gather — and is not judged when it
// stands inside a job, because there the deliverable that gathers it is what
// the gate reads. The parent is the whole of the test; there is no second
// predicate for spliced work.
revised := store.Node{ID: "task-1-n3", Parent: store.RootID}
if !shouldGate(revised, outcome, false) {
t.Fatal("a revision repair standing on the spine skipped the delivery gate")
}
gathered := store.Node{ID: "task-1-n3", Parent: "task-1"}
if shouldGate(gathered, outcome, false) {
t.Fatal("a node its own job gathers was judged as a deliverable")
}
}
func TestRecordReflexPersistsBoundaryEvidence(t *testing.T) {
dir := t.TempDir()
settings := config.Config{Model: "configured/model", ProfileDir: dir}
node := store.Node{Brief: "quick local action", Title: "Quick action"}
outcome := &exec.Outcome{
Turns: 4, Stop: exec.StopBudget, Verdict: provider.ReadingBudgetStop,
Usage: exec.Usage{PromptTokens: 80, CompletionTokens: 20, Cost: 0.0125},
}
recordReflex(settings, "worker/model", node, outcome, true)
measured, err := profile.Load(dir, "worker/model", "linear")
if err != nil {
t.Fatal(err)
}
if len(measured.Records) != 1 {
t.Fatalf("profile records = %+v", measured.Records)
}
record := measured.Records[0]
if record.Size != profile.BucketReflex || !record.Promoted || record.Cost != 0.0125 ||
record.Tokens != 100 || record.Turns != 4 || record.Verdict != provider.ReadingBudgetStop {
t.Fatalf("reflex profile record = %+v", record)
}
}
func TestBudgetStoppedReflexCarriesPartialIntoCompiledJob(t *testing.T) {
graph, err := store.Open(filepath.Join(t.TempDir(), "reflex.db"))
if err != nil {
t.Fatal(err)
}
defer graph.Close()
ask := "Inspect the parser and fix its edge case."
command, err := graph.RequestCommand(store.Command{
SessionID: "budget-promotion", Kind: store.CommandSplice, Reflex: true, Instruction: ask,
})
if err != nil {
t.Fatal(err)
}
var compiledInstruction, compiledContext string
reconciler := resident.New(graph,
func(_ context.Context, instruction, graphContext string) (resident.Compiled, error) {
compiledInstruction, compiledContext = instruction, graphContext
return resident.Compiled{Goal: "Fix and verify the parser edge case"}, nil
},
func(_ context.Context, compiled resident.Compiled) (store.Subtree, error) {
return store.Subtree{Nodes: []store.NodeSpec{{
ID: "compiled-after-budget", Brief: compiled.Goal, Stage: 1,
}}}, nil
},
)
if err := reconciler.Tick(context.Background()); err != nil {
t.Fatal(err)
}
reflexID := fmt.Sprintf("reflex-%d", command.Seq)
budgetOutcome := &exec.Outcome{
Stop: exec.StopBudget, Text: "partial: isolated the malformed escape sequence",
}
runner := resident.NewRunner(graph, func(_ context.Context, node store.Node) (resident.ExecResult, error) {
return resident.ExecResult{
Summary: budgetOutcome.Text,
Promote: shouldPromoteReflex(node, budgetOutcome),
}, nil
}, "budget-reflex", 1)
if _, err := runner.Tick(context.Background()); err != nil {
t.Fatal(err)
}
runner.Wait()
if err := reconciler.Tick(context.Background()); err != nil {
t.Fatal(err)
}
if compiledInstruction != ask {
t.Fatalf("compiled instruction = %q, want %q", compiledInstruction, ask)
}
for _, want := range []string{reflexID, ask, budgetOutcome.Text} {
if !strings.Contains(compiledContext, want) {
t.Errorf("compiled context omitted %q:\n%s", want, compiledContext)
}
}
node, found, err := graph.Node("compiled-after-budget")
if err != nil || !found || node.Provenance.Intent != ask {
t.Fatalf("compiled job = %+v found=%t err=%v", node, found, err)
}
}
// With no learned voice the user-facing prompts are the stable prompt plus the
// unconditional register, exactly — nothing else drifts, and the register is
// what a fresh machine used to be missing entirely.
func TestResidentUserFacingPromptsKeepEmptyNotebookBytes(t *testing.T) {
graph, err := store.Open(filepath.Join(t.TempDir(), "graph.db"))
if err != nil {
t.Fatal(err)
}
defer graph.Close()
settings := config.Config{Model: "talk/model"}
capture := &gateCaptureClient{model: "talk/model"}
client := adoptLiveClient(settings, capture.model, capture)
node := store.Node{
ID: "job", Parent: store.RootID, Brief: "assemble the finished report",
Provenance: store.Provenance{Intent: "prepare the report"},
}
wantBrief := node.Brief + "\n\n" + resident.VoiceRegister
if got := residentDeliveryBrief(graph, node); got != wantBrief {
t.Fatalf("empty-notebook delivery brief changed:\n got %q\nwant %q", got, wantBrief)
}
initial := exec.Task{Brief: residentDeliveryBrief(graph, node)}
polish := initial
if initial.Brief != wantBrief || polish.Brief != wantBrief {
t.Fatalf("empty-notebook initial/polish briefs changed: initial=%q polish=%q", initial.Brief, polish.Brief)
}
const deliverable = "the finished report"
judgment := revision.JudgeDeliverable(context.Background(), settings, client, graph, node, deliverable, "", revision.Evidence{}, "worker/model")
if !judgment.Checked || !judgment.Pass {
t.Fatalf("judgment = %+v, want checked pass", judgment)
}
if got := capture.messages[0].Content[0].Text; got != revision.DeliverablePrompt {
t.Fatalf("empty-notebook gate system prompt changed:\n got %q\nwant %q", got, revision.DeliverablePrompt)
}
wantBody := "Verbatim request:\n" + node.Provenance.Intent +
"\n\nCompiled goal:\n" + node.Brief +
"\n\nDeliverable as produced:\n" + revision.FenceDeliverable(deliverable)
if got := capture.messages[1].Content[0].Text; got != wantBody {
t.Fatalf("empty-notebook gate body changed:\n got %q\nwant %q", got, wantBody)
}
}
func TestResidentDeliveryAndPolishBriefShareLearnedVoice(t *testing.T) {
graph, err := store.Open(filepath.Join(t.TempDir(), "graph.db"))
if err != nil {
t.Fatal(err)
}
defer graph.Close()
const preference = "keep answers short; no preamble"
if _, err := graph.RecordFact("", "user", store.FactPreference, preference); err != nil {
t.Fatal(err)
}
node := store.Node{
ID: "job", Parent: store.RootID, Brief: "assemble the finished report",
Provenance: store.Provenance{Intent: "prepare the report"},
}
initial := exec.Task{Brief: residentDeliveryBrief(graph, node)}
polish := initial
for name, brief := range map[string]string{"delivery": initial.Brief, "polish": polish.Brief} {
if !strings.Contains(brief, preference) {
t.Fatalf("%s brief omitted learned voice: %q", name, brief)
}
}
child := node
child.Parent = node.ID
if got := residentDeliveryBrief(graph, child); strings.Contains(got, preference) {
t.Fatalf("worker-to-worker child brief gained user voice: %q", got)
}
}
func TestDistillerParsesVoiceCorrectionAsUserPreference(t *testing.T) {
graph, err := store.Open(filepath.Join(t.TempDir(), "graph.db"))
if err != nil {
t.Fatal(err)
}
defer graph.Close()
settings := config.Config{Model: "talk/model"}
capture := &gateCaptureClient{
model: "talk/model",
response: `{"facts":[{"scope":"user","kind":"preference","body":"keep answers short; no preamble"}]}`,
}
client := adoptLiveClient(settings, capture.model, capture)
learned, err := distillFacts(settings, client, graph)(
context.Background(),
"Revise the earlier report",
"The user corrected the delivery: make it shorter and remove the preamble.",
false,
)
if err != nil {
t.Fatal(err)
}
if len(learned) != 1 || learned[0].Scope != "user" ||
learned[0].Kind != store.FactPreference ||
learned[0].Body != "keep answers short; no preamble" {
t.Fatalf("distilled voice correction = %+v", learned)
}
system := capture.messages[0].Content[0].Text
for _, want := range []string{"HOW something was communicated", `scope "user"`, `kind "preference"`, "direct instruction"} {
if !strings.Contains(system, want) {
t.Errorf("distiller voice judgment omitted %q", want)
}
}
if user := capture.messages[1].Content[0].Text; !strings.Contains(user, "make it shorter and remove the preamble") {
t.Fatalf("distiller input omitted the voice correction: %q", user)
}
}
// The document-staging journey moved to internal/exec, where copy-at-mention
// and copy-at-run are one seam. Its tests moved with it.
func TestAttachedDocumentsAreNamedInTheBrief(t *testing.T) {
brief := withDocumentAttachmentBrief("Summarise the filing.", []string{"attachments/q3-filing-ab12cd34.pdf"})
if !strings.Contains(brief, "read_document") ||
!strings.Contains(brief, "attachments/q3-filing-ab12cd34.pdf") ||
!strings.HasPrefix(brief, "Summarise the filing.") {
t.Fatalf("brief = %q", brief)
}
if plain := withDocumentAttachmentBrief("Summarise the filing.", nil); plain != "Summarise the filing." {
t.Fatalf("unattached brief changed: %q", plain)
}
}
// The gate waved through a deliverable that described itself. "The deliverable
// is written and verified against the actual repo source" became the node's
// summary, and the summary is the one source every later surface reads, so the
// verdict the user asked for existed nowhere they or the head could reach. The
// contract is expressed as a value rather than a phrase list, because the next
// way to report work instead of doing it is always a phrasing nobody wrote
// down; what is pinned here is that the value is stated and that the gate is
// still a gate.
func TestTheGateHoldsTheAnswerFirstContractWithoutBecomingACritic(t *testing.T) {
for _, required := range []string{
"What you are handed IS the deliverable",
"has described the deliverable in place of being it",
"A pointer to where the answer lives is not the answer",
} {
if !strings.Contains(revision.DeliverablePrompt, required) {
t.Fatalf("the gate no longer states the answer-first contract: %q missing", required)
}
}
// The character of the gate is law: its default is pass, and the new clause
// must not turn it into the critic that always finds something.
for _, required := range []string{
"Default to PASS",
"The gate exists for real gaps, not polish",
"This is still one absence and not a second style test",
} {
if !strings.Contains(revision.DeliverablePrompt, required) {
t.Fatalf("the gate lost its default-pass character: %q missing", required)
}
}
// No phrase list anywhere: the gate must never be taught to match on the
// sentences one worker happened to write.
for _, forbidden := range []string{
"deliverable is written and verified", "if the text contains", "phrases such as",
} {
if strings.Contains(strings.ToLower(revision.DeliverablePrompt), strings.ToLower(forbidden)) {
t.Fatalf("the gate grew a cue list: %q", forbidden)
}
}
}
// The gate cannot open the workspace, so the only verification it can hold is
// whether the deliverable shows the finished thing being used the way it will
// be used. A leaf that exercised every part in a harness and reported the whole
// verified is the case: the claim is a promise about evidence like any other,
// and it is a gap when the evidence is an inference. The honest exit passes, or
// the clause would be teaching the lie it exists to catch.
func TestTheGateHoldsAClaimOfVerifiedToAnActualRun(t *testing.T) {
for name, required := range map[string]string{
"a claim of evidence is a commitment": "A claim that the work was checked, proven or verified is itself such a commitment",
"the whole thing, used as it is used": "shows the finished thing exercised the way it will actually be used",
"no inference from the parts": "rather than its parts checked one by one and the whole inferred from them",
"the honest gap passes": "is not a gap: it is the honest form of the same claim and it passes",
} {
if !strings.Contains(revision.DeliverablePrompt, required) {
t.Errorf("the gate no longer holds %s: %q missing", name, required)
}
}
// Still a gate and not a critic: the clause rides the paragraph that was
// already about promised evidence rather than opening a second test.
decisions := strings.Index(revision.DeliverablePrompt, "Working decisions declared in the goal")
claim := strings.Index(revision.DeliverablePrompt, "A claim that the work was checked")
substance := strings.Index(revision.DeliverablePrompt, "One absence counts exactly like every other")
if decisions < 0 || claim < decisions || substance < claim {
t.Fatalf("the verification clause left its paragraph: decisions=%d claim=%d substance=%d",
decisions, claim, substance)
}
}
// A named gap is what buys the one revision pass, and the revision is told the
// thing the first attempt demonstrably did not hear.
func TestNamedGapEarnsARevisionThatIsToldWhereTheAnswerGoes(t *testing.T) {
graph, err := store.Open(filepath.Join(t.TempDir(), "graph.db"))
if err != nil {
t.Fatal(err)
}
defer graph.Close()
node := store.Node{
ID: "task-6979", Parent: store.RootID, Brief: "judge whether the plan is valid",
Provenance: store.Provenance{Intent: "see if their architecture plan is valid"},
}
settings := config.Config{Model: "worker/model"}
const gap = "the verdict itself: the text says the assessment is complete but never says whether the plan is valid"
failing := &gateCaptureClient{model: "worker/model",
response: `{"pass":false,"gaps":"` + gap + `"}`}
judgment := revision.JudgeDeliverable(context.Background(), settings,
adoptLiveClient(settings, failing.model, failing), graph, node,
"The deliverable is written and verified against the actual repo source.", "", revision.Evidence{}, "worker/model")
if !judgment.Checked || judgment.Pass || judgment.Gaps != gap {
t.Fatalf("a meta-only deliverable did not draw a checked gap: %+v", judgment)
}
// Substance passes, and passing is the default: the gate must not have
// become a second opinion on every finished job.
passing := &gateCaptureClient{model: "worker/model"}
settled := revision.JudgeDeliverable(context.Background(), settings,
adoptLiveClient(settings, passing.model, passing), graph, node,
"The plan is valid: the plugin boundary it assumes already exists and the migration is reversible.",
"", revision.Evidence{}, "worker/model")
if !settled.Checked || !settled.Pass {
t.Fatalf("a deliverable carrying its answer did not pass: %+v", settled)
}
// The revision pass is handed the previous attempt plus the contract that
// attempt broke, so a second round cannot close the gap inside a file and
// report that it did so.
for _, required := range []string{
"final message is the deliverable", "never in place of it",
} {
if !strings.Contains(revision.GateRevisionContract, required) {
t.Fatalf("the revision contract no longer says where the answer goes: %q missing", required)
}
}
}
// ONCE THE HARNESS HAS CONCLUDED NOTHING IS CHANGING, IT STOPS SPENDING ON THAT
// JOB. Two of the three doors that spending goes through are here: the gate and
// the repair round it buys, both of which are skipped on a tree with no diff.
//
// The stamp is a before-and-after of the same record, so the question it answers
// is "did THIS attempt move anything" and not "is there anything on disk". A
// resumed leaf inherits its predecessor's files and must not read them as its
// own work; a leaf that wrote its first file has moved the world and is judged
// exactly as it always was.
func TestALeafThatChangedNothingIsNotJudgedOrRepaired(t *testing.T) {
root := t.TempDir()
before := filepath.Join(root, "inherited.md")
if err := os.WriteFile(before, []byte("what the last attempt wrote\n"), 0o644); err != nil {
t.Fatal(err)
}
startedWorldAs := revision.TreeStamp([]string{before})
ranOut := &exec.Outcome{Stop: exec.StopBudget}
if !nothingChanged(ranOut, startedWorldAs, revision.TreeStamp([]string{before})) {
t.Fatal("a leaf that ran out over an untouched tree was read as having moved it")
}
// The same reading with the leaf's own first file in it: the tree moved, so
// there is something to judge and something a repair could build on.
written := filepath.Join(root, "report.md")
if err := os.WriteFile(written, []byte("the answer\n"), 0o644); err != nil {
t.Fatal(err)
}
if nothingChanged(ranOut, startedWorldAs, revision.TreeStamp([]string{before, written})) {
t.Fatal("a leaf that wrote its first file skipped the gate")
}
// And a leaf that FINISHED is none of this business, whatever the tree did.
// The law is about work that stopped, not about work that produced nothing
// because nothing needed producing.
if nothingChanged(&exec.Outcome{Stop: exec.StopDone}, startedWorldAs, startedWorldAs) {
t.Fatal("a leaf that finished inside its budget was denied its gate")
}
if nothingChanged(nil, startedWorldAs, startedWorldAs) {
t.Fatal("a leaf with no outcome at all was read as a standstill")
}
}
// What the person reads when the gate is not asked. It is the governor's own
// sentence wherever the governor spoke, because that sentence is already on the
// stream and in the record by the time this is composed, plus the one fact the
// governor cannot know: that nothing was bought off the back of it.
func TestTheUnaskedGateSaysWhyInTheGovernorsWords(t *testing.T) {
said := unchangedHandoverWords(resident.CauseStandstill)
if !strings.HasPrefix(said, resident.RefusedStandstill) {
t.Fatalf("handover = %q, want the governor's own sentence first", said)
}
if !strings.Contains(said, "Nothing further was started") {
t.Fatalf("handover = %q, want it to say nothing more was bought", said)
}
// And where no governor spoke — a first fruitless round, or a cap — the
// observation is still stated rather than left to silence.
plain := unchangedHandoverWords("")
if !strings.HasPrefix(plain, unchangedHandover) || !strings.Contains(plain, "Nothing further was started") {
t.Fatalf("handover with no governor = %q", plain)
}
}
// AND THE UNASKED GATE IS JOURNALED, THROUGH THE STORE THAT WILL ACTUALLY BE
// ASKED TO TAKE IT.
//
// The sentence above was only ever checked as a string. The row it rides was
// refused by the real validator on every real run — a gate that did not pass had
// to name a gap, and a declined judgement names none — so what landed was
// `note: could not journal the unasked gate on task-2-x1: record delivery gate:
// invalid graph mutation: a failed gate must name the gap` and no row at all.
// The promise of the change was a row a ledger could read; this writes exactly
// what the surface writes and reads it back.
func TestTheUnaskedGateIsJournaledAgainstTheRealStore(t *testing.T) {
graph, err := store.Open(filepath.Join(t.TempDir(), "graph.db"))
if err != nil {
t.Fatal(err)
}
defer graph.Close()
if err := graph.Splice(store.RootID, store.Subtree{Nodes: []store.NodeSpec{
{ID: "task-2-x1", Brief: "finish the migration", Stage: 0},
}}, store.Provenance{Origin: store.OriginUser, Intent: "finish the migration"}); err != nil {
t.Fatal(err)
}
handover := unchangedHandoverWords(resident.CauseStandstill)
if err := graph.RecordDeliveryGate("task-2-x1", store.DeliveryGate{
Refused: handover, Unclosed: true,
}); err != nil {
t.Fatalf("the unasked gate was not journaled: %v", err)
}
gate, ok, err := graph.DeliveryGateFor("task-2-x1")
if err != nil || !ok {
t.Fatalf("DeliveryGateFor = %v, %v", ok, err)
}
if gate.Pass || !gate.Unclosed || gate.Refused != handover {
t.Fatalf("journaled gate = %+v, want the refusal standing and the delivery unclosed", gate)
}
// Never a pass: the exit code turns on this reading, and a run that changed
// nothing handed over less than it promised.
if gate.Whole() {
t.Fatal("a delivery nothing judged read as whole")
}
// And the person watching is told, in the governor's own words. The row
// names no gap, so a reader that asks it for one says nothing at the end of
// a run that was never judged.
finding, reason, standing := gateStanding(gate)
if !standing || !strings.HasPrefix(finding, resident.RefusedStandstill) {
t.Fatalf("gateStanding = %q, %q, %t; want the refusal as the finding", finding, reason, standing)
}
if verdict, detail := gateWords(gate); verdict != "refused" || detail == "" {
t.Fatalf("gateWords = %q, %q; want the refusal read as one", verdict, detail)
}
}
// The verdict rides the result, and only the two causes that read the world set
// it. Everything else — a cap, the wall, the rail, an ordinary leaf — leaves the
// field empty, which is what the scheduler reads as "requeue as you always did".
func TestOnlyAWorldReadingRefusalRidesTheResult(t *testing.T) {
for _, cause := range []string{resident.CauseStandstill, resident.CauseFixedPoint} {
if _, stopped := resident.GrowthStopped(cause); !stopped {
t.Fatalf("%q did not stop the job", cause)
}
}
for _, cause := range []string{"", resident.CauseRounds, resident.CauseCeiling, resident.CauseRail} {
if _, stopped := resident.GrowthStopped(cause); stopped {
t.Fatalf("%q stopped the job", cause)
}
}
// And the field is on the result the leaf hands the scheduler, filled from
// the one place that can know it.
result := leafSpend(exec.Usage{}, nil, "worker/model", exec.Usage{},
&exec.Outcome{Stop: exec.StopBudget}, false)
if result.RefusedGrowth != "" {
t.Fatalf("a leaf nobody refused carried %q", result.RefusedGrowth)
}
result.RefusedGrowth = resident.CauseStandstill
if !result.RanOut() {
t.Fatal("a refused leaf with nothing continuing it is not being read as having run out")
}
}