-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoverage.html
More file actions
1370 lines (1230 loc) · 60.3 KB
/
coverage.html
File metadata and controls
1370 lines (1230 loc) · 60.3 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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>execution: Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">github.com/toasterbook88/axis/internal/execution/guarded.go (59.8%)</option>
<option value="file1">github.com/toasterbook88/axis/internal/execution/nix.go (75.9%)</option>
<option value="file2">github.com/toasterbook88/axis/internal/execution/rusage_unix.go (0.0%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">not covered</span>
<span class="cov8">covered</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">package execution
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"time"
"al.essio.dev/pkg/shellescape"
"github.com/toasterbook88/axis/internal/config"
"github.com/toasterbook88/axis/internal/knowledge"
"github.com/toasterbook88/axis/internal/models"
"github.com/toasterbook88/axis/internal/placement"
"github.com/toasterbook88/axis/internal/reservation"
"github.com/toasterbook88/axis/internal/runtimectx"
"github.com/toasterbook88/axis/internal/safety"
"github.com/toasterbook88/axis/internal/scripts"
"github.com/toasterbook88/axis/internal/skills"
"github.com/toasterbook88/axis/internal/state"
"github.com/toasterbook88/axis/internal/transport"
"github.com/toasterbook88/axis/internal/turboexec"
)
const (
ModeScript = "script"
ModeExec = "exec"
ConfirmWord = "YES"
StateChangeExecutionReserved = "execution-reserved"
StateChangeExecutionFinished = "execution-finished"
OwnerSurfaceGuardedExec = "guarded-exec"
OwnerSurfaceTaskRun = "task-run"
OwnerSurfaceHTTPRun = "http-run"
OwnerSurfaceAgentRunShell = "agent-run-shell"
)
var executionHeartbeatInterval = 15 * time.Second
var heartbeatTask = func(ledger *reservation.Ledger, ledgerExecID string) error <span class="cov0" title="0">{
if ledger != nil && ledgerExecID != "" </span><span class="cov0" title="0">{
return ledger.Heartbeat(ledgerExecID)
}</span>
<span class="cov0" title="0">return nil</span>
}
var localExecutionHostname = os.Hostname
var sharedSafetyEvaluator = safety.NewEvaluator(safety.DefaultRuleSet())
func generateExecID(node string) string <span class="cov8" title="1">{
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil </span><span class="cov0" title="0">{
// Extreme rare fallback
return fmt.Sprintf("%d-%s", time.Now().UnixNano(), node)
}</span>
<span class="cov8" title="1">return fmt.Sprintf("%s-%s", hex.EncodeToString(b), node)</span>
}
type GuardedExecutionRequest struct {
Description string `json:"description"`
Mode string `json:"mode,omitempty"`
Confirm string `json:"confirm,omitempty"`
OwnerSurface string `json:"-"`
OwnerLabel string `json:"-"`
OriginOverride models.ExecutionOrigin `json:"-"`
Stdout io.Writer `json:"-"`
Stderr io.Writer `json:"-"`
OnReady func(GuardedExecutionResult) `json:"-"`
OnStateChange func(context.Context, string, GuardedExecutionResult) `json:"-"`
}
type GuardedExecutionResult struct {
OK bool `json:"ok"`
Description string `json:"description"`
Mode string `json:"mode,omitempty"`
Intent string `json:"intent,omitempty"`
Command string `json:"command,omitempty"`
Node string `json:"node,omitempty"`
Tool string `json:"tool,omitempty"`
Workload models.WorkloadProfileMatch `json:"workload,omitempty"`
FitScore int `json:"fit_score,omitempty"`
IsLocal bool `json:"is_local,omitempty"`
Reasoning []string `json:"reasoning,omitempty"`
Blocked bool `json:"blocked,omitempty"`
BlockReason string `json:"block_reason,omitempty"`
DumbScore int `json:"dumb_score,omitempty"`
Output string `json:"output,omitempty"`
Error string `json:"error,omitempty"`
ExitCode int `json:"exit_code,omitempty"`
SnapshotStatus models.SnapshotStatus `json:"snapshot_status,omitempty"`
Summary *models.ClusterSummary `json:"summary,omitempty"`
}
type PreparedExecution struct {
Request GuardedExecutionRequest
Intent Intent
Requirements models.TaskRequirements
Result GuardedExecutionResult
ReservationMB int64
Command string
ExtraEnv []string
ContextJSON []byte
TargetNode models.NodeFacts
TargetConfig config.NodeConfig
Owner state.ExecutionOwner
SkillStore *skills.Store
State *state.ClusterState
Ledger *reservation.Ledger
Err error
}
type Intent struct {
Command string
Label string
MatchedScript *scripts.Script
MatchedSkill *skills.LearnedSkill
}
type ValidationError struct {
Message string
}
func (e *ValidationError) Error() string <span class="cov0" title="0">{
return e.Message
}</span>
type RemoteExecutor interface {
Run(context.Context, string) (string, error)
Close() error
}
type StreamingRemoteExecutor interface {
RemoteExecutor
Stream(context.Context, string, io.Writer, io.Writer) error
}
var NewRemoteExecutor = func(nc config.NodeConfig) RemoteExecutor <span class="cov8" title="1">{
return transport.NewSSHExecutor(nc.Hostname, nc.EffectiveSSHPort(), nc.SSHUser, nc.EffectiveTimeout())
}</span>
// RunLocalShell executes command in a login bash shell and returns its combined
// output, the peak RSS of the child process in MB (0 if unavailable), and any
// error. The second return value is populated from cmd.ProcessState.SysUsage()
// after the process exits, giving per-execution accuracy.
var RunLocalShell = func(ctx context.Context, command string, env []string) ([]byte, int64, error) <span class="cov0" title="0">{
// Intentional ModeExec shell boundary: raw commands retain full shell
// semantics under guarded execution after confirm=YES, safety.Check,
// reservation heartbeats, and provenance tracking.
// codeql[go/command-injection]
cmd := exec.CommandContext(ctx, "bash", "-lc", command)
cmd.Env = env
out, err := cmd.CombinedOutput()
return out, peakRAMFromProcessState(cmd.ProcessState), err
}</span>
// StreamLocalShell executes command in a login bash shell, streaming output to
// the supplied writers. Returns the peak RSS in MB (0 if unavailable) and any
// error.
var StreamLocalShell = func(ctx context.Context, command string, env []string, stdout, stderr io.Writer) (int64, error) <span class="cov0" title="0">{
// Intentional ModeExec shell boundary: raw commands retain full shell
// semantics under guarded execution after confirm=YES, safety.Check,
// reservation heartbeats, and provenance tracking.
// codeql[go/command-injection]
cmd := exec.CommandContext(ctx, "bash", "-lc", command)
cmd.Env = env
cmd.Stdout = stdout
cmd.Stderr = stderr
err := cmd.Run()
return peakRAMFromProcessState(cmd.ProcessState), err
}</span>
var PlanNixExecution = PlanNixWrapper
var ProbeLocalAvailableRAMMB = probeLocalAvailableRAMMB
func NormalizeRequest(req *GuardedExecutionRequest) <span class="cov8" title="1">{
if req == nil </span><span class="cov0" title="0">{
return
}</span>
<span class="cov8" title="1">req.Description = strings.TrimSpace(req.Description)
req.Mode = strings.ToLower(strings.TrimSpace(req.Mode))
req.Confirm = strings.TrimSpace(req.Confirm)
req.OwnerSurface = strings.TrimSpace(req.OwnerSurface)
req.OwnerLabel = strings.TrimSpace(req.OwnerLabel)
req.OriginOverride = req.OriginOverride.Normalized()</span>
}
func ValidateRequest(req GuardedExecutionRequest) error <span class="cov8" title="1">{
switch </span>{
case req.Description == "":<span class="cov0" title="0">
return &ValidationError{Message: "description is required"}</span>
case req.Mode == "":<span class="cov0" title="0">
return &ValidationError{Message: "mode is required (use script or exec)"}</span>
case req.Mode != ModeScript && req.Mode != ModeExec:<span class="cov0" title="0">
return &ValidationError{Message: "mode must be script or exec"}</span>
case req.Confirm != ConfirmWord:<span class="cov0" title="0">
return &ValidationError{Message: "confirm must be YES to authorize execution"}</span>
default:<span class="cov8" title="1">
return nil</span>
}
}
func executionOwner(rt *runtimectx.Context, req GuardedExecutionRequest) state.ExecutionOwner <span class="cov8" title="1">{
origin := req.OriginOverride.Normalized()
if origin.IsZero() </span><span class="cov8" title="1">{
origin = resolveExecutionOrigin(rt)
}</span>
<span class="cov8" title="1">owner := state.ExecutionOwner{
Surface: strings.TrimSpace(req.OwnerSurface),
Label: strings.TrimSpace(req.OwnerLabel),
Origin: origin,
}
if owner.Surface == "" </span><span class="cov8" title="1">{
owner.Surface = OwnerSurfaceGuardedExec
}</span>
<span class="cov8" title="1">return owner</span>
}
// LocalExecutionOrigin derives the trusted local AXIS execution origin from
// the current runtime context.
func LocalExecutionOrigin(rt *runtimectx.Context) models.ExecutionOrigin <span class="cov0" title="0">{
return resolveExecutionOrigin(rt)
}</span>
func resolveExecutionOrigin(rt *runtimectx.Context) models.ExecutionOrigin <span class="cov8" title="1">{
if rt != nil && rt.Snapshot != nil </span><span class="cov8" title="1">{
if localNode, ok := models.FindLocalNode(rt.Snapshot.Nodes); ok </span><span class="cov8" title="1">{
return models.ExecutionOriginFromNode(localNode)
}</span>
}
<span class="cov8" title="1">if rt != nil && rt.Config != nil </span><span class="cov8" title="1">{
for _, nc := range rt.Config.Nodes </span><span class="cov8" title="1">{
if models.IsLocalConfig(nc.Name, nc.Hostname, nc.StableID) </span><span class="cov8" title="1">{
return models.NewExecutionOrigin(nc.Name, nc.Hostname, nc.StableID)
}</span>
}
}
<span class="cov8" title="1">hostname, _ := localExecutionHostname()
return models.NewExecutionOrigin("", hostname, models.CurrentLocalStableID())</span>
}
func ResolveIntent(description, mode string, skillStore *skills.Store) (Intent, error) <span class="cov8" title="1">{
var intent Intent
if skillStore != nil </span><span class="cov8" title="1">{
if skill, ok := skillStore.BestMatch(description); ok </span><span class="cov0" title="0">{
skillCopy := skill
intent.MatchedSkill = &skillCopy
}</span>
}
<span class="cov8" title="1">if script, ok := scripts.GetBestScript(description); ok </span><span class="cov8" title="1">{
scriptCopy := script
intent.MatchedScript = &scriptCopy
}</span>
<span class="cov8" title="1">switch mode </span>{
case ModeScript:<span class="cov0" title="0">
if intent.MatchedScript != nil </span><span class="cov0" title="0">{
intent.Command = intent.MatchedScript.Command
intent.Label = fmt.Sprintf("fallback script %q", intent.MatchedScript.Name)
return intent, nil
}</span>
<span class="cov0" title="0">if intent.MatchedSkill != nil </span><span class="cov0" title="0">{
intent.Command = intent.MatchedSkill.Command
intent.Label = fmt.Sprintf("learned skill %q", intent.MatchedSkill.ID)
return intent, nil
}</span>
<span class="cov0" title="0">return Intent{}, fmt.Errorf("no known script or learned skill matches %q", description)</span>
case ModeExec:<span class="cov8" title="1">
intent.Command = description
intent.Label = "raw command"
return intent, nil</span>
default:<span class="cov0" title="0">
return Intent{}, fmt.Errorf("unsupported mode %q", mode)</span>
}
}
func ReservationMBForRequirements(reqs models.TaskRequirements) int64 <span class="cov8" title="1">{
return reqs.MinFreeRAMMB + 1024
}</span>
func CanReserve(snap *models.ClusterSnapshot, node string, mb int64) bool <span class="cov8" title="1">{
if mb <= 0 || snap == nil </span><span class="cov0" title="0">{
return true
}</span>
<span class="cov8" title="1">for _, n := range snap.Nodes </span><span class="cov8" title="1">{
if n.Name == node </span><span class="cov8" title="1">{
return n.RAMReservedMB+mb <= n.ReservableRAM()
}</span>
}
<span class="cov0" title="0">return true</span>
}
func PrepareGuardedExecution(ctx context.Context, rt *runtimectx.Context, req GuardedExecutionRequest) (PreparedExecution, error) <span class="cov8" title="1">{
// CRITICAL INVARIANT: operator-requested task execution in this package's
// guarded execution path must go through RunGuarded rather than bypassing it.
NormalizeRequest(&req)
prepared := PreparedExecution{
Request: req,
Result: GuardedExecutionResult{
Description: req.Description,
Mode: req.Mode,
},
}
if err := ValidateRequest(req); err != nil </span><span class="cov0" title="0">{
prepared.Result.Error = err.Error()
prepared.Err = err
return prepared, err
}</span>
<span class="cov8" title="1">if rt == nil || rt.Config == nil || rt.Snapshot == nil </span><span class="cov0" title="0">{
err := fmt.Errorf("runtime context unavailable")
prepared.Result.Error = err.Error()
prepared.Err = err
return prepared, err
}</span>
<span class="cov8" title="1">prepared.Result.SnapshotStatus = rt.Snapshot.Status
prepared.Result.Summary = &rt.Snapshot.Summary
skillStore := rt.Skills
if skillStore == nil </span><span class="cov0" title="0">{
skillStore = &skills.Store{}
}</span>
<span class="cov8" title="1">prepared.SkillStore = skillStore
prepared.State = rt.State
prepared.Ledger = rt.Ledger
prepared.Owner = executionOwner(rt, req)
intent, err := ResolveIntent(req.Description, req.Mode, skillStore)
if err != nil </span><span class="cov0" title="0">{
prepared.Result.Error = err.Error()
prepared.Err = err
return prepared, err
}</span>
<span class="cov8" title="1">prepared.Intent = intent
prepared.Result.Intent = intent.Label
prepared.Result.Command = intent.Command
reqs := prepareRequirements(req.Description, req.Mode, intent)
prepared.Requirements = reqs
decision := placement.SelectBestNode(reqs, rt.Snapshot.Nodes, rt.State)
prepared.Result.Reasoning = runtimectx.PrependWarningReasoning(decision.Reasoning, rt.Snapshot.Warnings)
prepared.Result.Node = decision.Node
prepared.Result.Tool = decision.Tool
prepared.Result.Workload = decision.Workload
prepared.Result.FitScore = decision.FitScore
prepared.Result.IsLocal = decision.IsLocal
if !decision.OK </span><span class="cov0" title="0">{
err := fmt.Errorf("no suitable node found")
prepared.Result.Error = err.Error()
prepared.Err = err
return prepared, err
}</span>
<span class="cov8" title="1">targetNode, ok := findNodeFacts(rt.Snapshot, decision.Node)
if !ok </span><span class="cov0" title="0">{
err := fmt.Errorf("node %q not found in snapshot", decision.Node)
prepared.Result.Error = err.Error()
prepared.Err = err
return prepared, err
}</span>
<span class="cov8" title="1">prepared.TargetNode = targetNode
// Check for node config if remote
var targetConfig config.NodeConfig
isLocal := models.IsLocalNode(targetNode)
if !isLocal </span><span class="cov8" title="1">{
var ok bool
targetConfig, ok = rt.Config.FindNode(decision.Node)
if !ok </span><span class="cov0" title="0">{
err := fmt.Errorf("node %q not found in config", decision.Node)
prepared.Result.Error = err.Error()
prepared.Err = err
return prepared, err
}</span>
<span class="cov8" title="1">prepared.TargetConfig = targetConfig</span>
}
<span class="cov8" title="1">reservationMB := ReservationMBForRequirements(reqs)
prepared.ReservationMB = reservationMB
if !CanReserve(rt.Snapshot, decision.Node, reservationMB) </span><span class="cov0" title="0">{
err := fmt.Errorf("reservation cap exceeded")
prepared.Result.Error = fmt.Sprintf("node %s cannot reserve %d MB (current reservations exceed cap)", decision.Node, reservationMB)
prepared.Err = err
return prepared, err
}</span>
<span class="cov8" title="1">prepared.Result.Reasoning = append(prepared.Result.Reasoning, fmt.Sprintf("reservation headroom protected: %dMB", reservationMB))
if err := enforceLocalExecutionSafety(ctx, targetNode, reqs, &prepared.Result); err != nil </span><span class="cov8" title="1">{
prepared.Result.Error = err.Error()
prepared.Err = err
return prepared, err
}</span>
<span class="cov8" title="1">turboPlan := turboexec.Prepare(targetNode, reqs, intent.Command)
prepared.Result.Reasoning = append(prepared.Result.Reasoning, turboPlan.Notes...)
commandToRun := turboPlan.Command
safetyDecision := sharedSafetyEvaluator.Evaluate(commandToRun, req.OwnerSurface)
if safetyDecision.Verdict == safety.VerdictDeny </span><span class="cov0" title="0">{
prepared.Result.Blocked = true
prepared.Result.BlockReason = strings.Join(safetyDecision.Reasons, "; ")
prepared.Result.DumbScore = 100
prepared.Result.Error = prepared.Result.BlockReason
return prepared, nil
}</span>
<span class="cov8" title="1">contextJSON, err := knowledge.ExecutionContextJSON(rt.Snapshot, rt.State, decision, req.Description, intent.MatchedScript, intent.MatchedSkill)
if err != nil </span><span class="cov0" title="0">{
prepared.Result.Error = err.Error()
prepared.Err = err
return prepared, err
}</span>
<span class="cov8" title="1">prepared.ContextJSON = contextJSON
nixPlan := PlanNixExecution(targetNode, reqs, commandToRun)
prepared.Result.Command = commandToRun
if nixPlan.Enabled </span><span class="cov0" title="0">{
commandToRun = nixPlan.Command
prepared.Result.Command = commandToRun
prepared.Result.Reasoning = append(prepared.Result.Reasoning, nixPlan.Notes...)
}</span>
<span class="cov8" title="1">prepared.Command = commandToRun
prepared.ExtraEnv = append(turboPlan.Env, nixPlan.Env...)
return prepared, nil</span>
}
func RunPreparedExecution(ctx context.Context, prepared PreparedExecution) (GuardedExecutionResult, error) <span class="cov8" title="1">{
if prepared.Err != nil || prepared.Result.Blocked </span><span class="cov0" title="0">{
return prepared.Result, prepared.Err
}</span>
<span class="cov8" title="1">if prepared.Request.OnReady != nil </span><span class="cov8" title="1">{
prepared.Request.OnReady(prepared.Result)
}</span>
<span class="cov8" title="1">if models.IsLocalNode(prepared.TargetNode) </span><span class="cov8" title="1">{
return runLocal(
ctx,
prepared.State,
prepared.SkillStore,
prepared.Owner,
prepared.Request,
prepared.Requirements,
prepared.Result,
prepared.ReservationMB,
prepared.Command,
prepared.ExtraEnv,
prepared.ContextJSON,
prepared.Ledger,
)
}</span>
<span class="cov8" title="1">return runRemote(
ctx,
prepared.State,
prepared.SkillStore,
prepared.Owner,
prepared.Request,
prepared.Requirements,
prepared.Result,
prepared.TargetConfig,
prepared.ReservationMB,
prepared.Command,
prepared.ExtraEnv,
prepared.ContextJSON,
prepared.Ledger,
)</span>
}
func RunGuarded(ctx context.Context, rt *runtimectx.Context, req GuardedExecutionRequest) (GuardedExecutionResult, error) <span class="cov8" title="1">{
prepared, err := PrepareGuardedExecution(ctx, rt, req)
if err != nil || prepared.Result.Blocked </span><span class="cov8" title="1">{
return prepared.Result, err
}</span>
<span class="cov8" title="1">return RunPreparedExecution(ctx, prepared)</span>
}
func prepareRequirements(description, mode string, intent Intent) models.TaskRequirements <span class="cov8" title="1">{
reqs := placement.InferRequirements(description)
if mode == ModeScript && intent.MatchedScript != nil </span><span class="cov0" title="0">{
reqs.RequiredTools = append([]string(nil), intent.MatchedScript.RequiredTools...)
if intent.MatchedScript.EstRAMMB > reqs.MinFreeRAMMB </span><span class="cov0" title="0">{
reqs.MinFreeRAMMB = intent.MatchedScript.EstRAMMB
}</span>
}
<span class="cov8" title="1">return reqs</span>
}
func enforceLocalExecutionSafety(ctx context.Context, node models.NodeFacts, reqs models.TaskRequirements, resp *GuardedExecutionResult) error <span class="cov8" title="1">{
if !models.IsLocalNode(node) || !isInferenceExecution(reqs) </span><span class="cov8" title="1">{
return nil
}</span>
<span class="cov8" title="1">minNeeded := placement.MinFreeRAMForNode(reqs, node)
if node.Resources != nil && node.Resources.RAMTotalMB > 0 && node.Resources.RAMTotalMB <= 8192 && minNeeded >= 4096 </span><span class="cov8" title="1">{
reason := fmt.Sprintf("local model execution disabled on constrained %dMB host; run this on a remote node or use a smaller explicitly bounded model", node.Resources.RAMTotalMB)
resp.Reasoning = append(resp.Reasoning, reason)
return fmt.Errorf("%s", reason)
}</span>
<span class="cov8" title="1">liveFree, err := ProbeLocalAvailableRAMMB(ctx)
if err != nil </span><span class="cov8" title="1">{
reason := fmt.Sprintf("live local memory preflight unavailable; refusing local inference execution: %v", err)
resp.Reasoning = append(resp.Reasoning, reason)
return fmt.Errorf("%s", reason)
}</span>
<span class="cov8" title="1">resp.Reasoning = append(resp.Reasoning, fmt.Sprintf("live local memory preflight: %dMB available", liveFree))
if minNeeded > 0 && liveFree < minNeeded </span><span class="cov8" title="1">{
reason := fmt.Sprintf("live local memory preflight failed: need %dMB free, have %dMB", minNeeded, liveFree)
resp.Reasoning = append(resp.Reasoning, reason)
return fmt.Errorf("%s", reason)
}</span>
<span class="cov0" title="0">return nil</span>
}
func isInferenceExecution(reqs models.TaskRequirements) bool <span class="cov8" title="1">{
if reqs.ContextWindowTokens > 0 || reqs.PrefersTurboQuant </span><span class="cov0" title="0">{
return true
}</span>
<span class="cov8" title="1">if reqs.MinFreeRAMMB >= 4096 </span><span class="cov8" title="1">{
return true
}</span>
<span class="cov8" title="1">for _, tool := range reqs.RequiredTools </span><span class="cov0" title="0">{
switch strings.ToLower(tool) </span>{
case "ollama", "llama-server", "apple-foundation-models":<span class="cov0" title="0">
return true</span>
}
}
<span class="cov8" title="1">for _, backend := range reqs.PreferredBackends </span><span class="cov0" title="0">{
switch strings.ToLower(backend) </span>{
case "llama.cpp", "mlx", "apple-foundation-models":<span class="cov0" title="0">
return true</span>
}
}
<span class="cov8" title="1">return false</span>
}
func probeLocalAvailableRAMMB(ctx context.Context) (int64, error) <span class="cov0" title="0">{
switch runtime.GOOS </span>{
case "darwin":<span class="cov0" title="0">
out, err := exec.CommandContext(ctx, "vm_stat").Output()
if err != nil </span><span class="cov0" title="0">{
return 0, fmt.Errorf("vm_stat: %w", err)
}</span>
<span class="cov0" title="0">return parseDarwinAvailableRAMMB(string(out))</span>
case "linux":<span class="cov0" title="0">
data, err := os.ReadFile("/proc/meminfo")
if err != nil </span><span class="cov0" title="0">{
return 0, fmt.Errorf("read /proc/meminfo: %w", err)
}</span>
<span class="cov0" title="0">return parseLinuxAvailableRAMMB(string(data))</span>
default:<span class="cov0" title="0">
return 0, fmt.Errorf("unsupported local RAM probe OS %q", runtime.GOOS)</span>
}
}
func parseDarwinAvailableRAMMB(out string) (int64, error) <span class="cov0" title="0">{
var (
pageSize int64 = 4096
pages int64
)
for _, line := range strings.Split(out, "\n") </span><span class="cov0" title="0">{
trimmed := strings.TrimSpace(line)
switch </span>{
case strings.Contains(trimmed, "page size of ") && strings.Contains(trimmed, " bytes"):<span class="cov0" title="0">
start := strings.Index(trimmed, "page size of ")
end := strings.Index(trimmed, " bytes")
if start >= 0 && end > start </span><span class="cov0" title="0">{
value := trimmed[start+len("page size of ") : end]
parsed, err := strconv.ParseInt(strings.TrimSpace(value), 10, 64)
if err == nil && parsed > 0 </span><span class="cov0" title="0">{
pageSize = parsed
}</span>
}
case strings.HasPrefix(trimmed, "Pages free:"),
strings.HasPrefix(trimmed, "Pages inactive:"),
strings.HasPrefix(trimmed, "Pages speculative:"):<span class="cov0" title="0">
count, err := parseVMStatPageCount(trimmed)
if err != nil </span><span class="cov0" title="0">{
return 0, err
}</span>
<span class="cov0" title="0">pages += count</span>
}
}
<span class="cov0" title="0">if pages <= 0 </span><span class="cov0" title="0">{
return 0, fmt.Errorf("vm_stat did not report reclaimable pages")
}</span>
<span class="cov0" title="0">return pages * pageSize / (1024 * 1024), nil</span>
}
func parseVMStatPageCount(line string) (int64, error) <span class="cov0" title="0">{
parts := strings.SplitN(line, ":", 2)
if len(parts) != 2 </span><span class="cov0" title="0">{
return 0, fmt.Errorf("invalid vm_stat line %q", line)
}</span>
<span class="cov0" title="0">value := strings.TrimSpace(parts[1])
value = strings.TrimSuffix(value, ".")
value = strings.ReplaceAll(value, ".", "")
value = strings.ReplaceAll(value, ",", "")
count, err := strconv.ParseInt(value, 10, 64)
if err != nil </span><span class="cov0" title="0">{
return 0, fmt.Errorf("parse vm_stat count %q: %w", line, err)
}</span>
<span class="cov0" title="0">return count, nil</span>
}
func parseLinuxAvailableRAMMB(out string) (int64, error) <span class="cov0" title="0">{
for _, line := range strings.Split(out, "\n") </span><span class="cov0" title="0">{
if !strings.HasPrefix(line, "MemAvailable:") </span><span class="cov0" title="0">{
continue</span>
}
<span class="cov0" title="0">fields := strings.Fields(line)
if len(fields) < 2 </span><span class="cov0" title="0">{
return 0, fmt.Errorf("invalid MemAvailable line %q", line)
}</span>
<span class="cov0" title="0">kb, err := strconv.ParseInt(fields[1], 10, 64)
if err != nil </span><span class="cov0" title="0">{
return 0, fmt.Errorf("parse MemAvailable: %w", err)
}</span>
<span class="cov0" title="0">return kb / 1024, nil</span>
}
<span class="cov0" title="0">return 0, fmt.Errorf("MemAvailable not found")</span>
}
func runLocal(
ctx context.Context,
st *state.ClusterState,
skillStore *skills.Store,
owner state.ExecutionOwner,
req GuardedExecutionRequest,
reqs models.TaskRequirements,
resp GuardedExecutionResult,
reservationMB int64,
command string,
extraEnv []string,
contextJSON []byte,
ledger *reservation.Ledger,
) (GuardedExecutionResult, error) <span class="cov8" title="1">{
runtimeChanged := false
defer func() </span><span class="cov8" title="1">{
if runtimeChanged </span><span class="cov8" title="1">{
notifyStateChange(ctx, req, StateChangeExecutionFinished, resp)
}</span>
}()
<span class="cov8" title="1">contextFile, err := os.CreateTemp("", "axis-knows-*.json")
if err != nil </span><span class="cov0" title="0">{
resp.Error = err.Error()
return resp, err
}</span>
<span class="cov8" title="1">defer os.Remove(contextFile.Name())
if _, err := contextFile.Write(contextJSON); err != nil </span><span class="cov0" title="0">{
_ = contextFile.Close()
resp.Error = err.Error()
return resp, err
}</span>
<span class="cov8" title="1">if err := contextFile.Close(); err != nil </span><span class="cov0" title="0">{
resp.Error = err.Error()
return resp, err
}</span>
<span class="cov8" title="1">env := append(os.Environ(),
"AXIS_CONTEXT_FILE="+contextFile.Name(),
"BEST_NODE="+resp.Node,
"AXIS_EXECUTION_MODE="+req.Mode,
"AXIS_CONFIRM="+req.Confirm,
fmt.Sprintf("AXIS_RESERVATION_MB=%d", reservationMB),
)
env = append(env, extraEnv...)
var execID string
if ledger != nil </span><span class="cov8" title="1">{
execID = generateExecID(resp.Node)
entry := reservation.Entry{
ID: execID,
Node: resp.Node,
OwnerExecID: execID,
OwnerSurface: owner.Surface,
OwnerPID: os.Getpid(),
OwnerOrigin: owner.Origin,
RAMMB: reservationMB,
Description: req.Description,
}
if _, acquireErr := ledger.Reserve(entry); acquireErr != nil </span><span class="cov0" title="0">{
resp.Error = acquireErr.Error()
return resp, acquireErr
}</span>
<span class="cov8" title="1">runtimeChanged = true
notifyStateChange(ctx, req, StateChangeExecutionReserved, resp)
defer func() </span><span class="cov8" title="1">{
if releaseErr := ledger.Release(execID); releaseErr != nil && resp.Error == "" </span><span class="cov0" title="0">{
resp.Error = releaseErr.Error()
}</span>
}()
}
<span class="cov8" title="1">startedAt := time.Now().UTC()
out, peakRAMMB, runErr := runWithReservationHeartbeat(ledger, execID, func() (string, int64, error) </span><span class="cov8" title="1">{
return runLocalWithOutput(ctx, command, env, req.Stdout, req.Stderr)
}</span>)
<span class="cov8" title="1">elapsed := time.Since(startedAt)
resp.Output = out
resp.ExitCode = exitCode(runErr)
if runErr != nil </span><span class="cov0" title="0">{
resp.Error = runErr.Error()
recordFailure(skillStore, req.Description, resp.ExitCode)
runtimeChanged = true
recordExecutionOutcome(st, reqs, resp, runErr, elapsed, peakRAMMB)
return resp, runErr
}</span>
<span class="cov8" title="1">recordSuccess(skillStore, req.Description, command, resp.Node)
runtimeChanged = true
recordExecutionOutcome(st, reqs, resp, nil, elapsed, peakRAMMB)
resp.OK = true
return resp, nil</span>
}
func runRemote(
ctx context.Context,
st *state.ClusterState,
skillStore *skills.Store,
owner state.ExecutionOwner,
req GuardedExecutionRequest,
reqs models.TaskRequirements,
resp GuardedExecutionResult,
targetConfig config.NodeConfig,
reservationMB int64,
command string,
extraEnv []string,
contextJSON []byte,
ledger *reservation.Ledger,
) (GuardedExecutionResult, error) <span class="cov8" title="1">{
runtimeChanged := false
defer func() </span><span class="cov8" title="1">{
if runtimeChanged </span><span class="cov8" title="1">{
notifyStateChange(ctx, req, StateChangeExecutionFinished, resp)
}</span>
}()
<span class="cov8" title="1">executor := NewRemoteExecutor(targetConfig)
defer executor.Close()
remoteContextPath := fmt.Sprintf("/tmp/axis-knows-%d.json", time.Now().UTC().UnixNano())
writeJSONCmd := fmt.Sprintf("cat > %s << 'AXIS_EOF'\n%s\nAXIS_EOF\n", shellescape.Quote(remoteContextPath), string(contextJSON))
if _, err := executor.Run(ctx, writeJSONCmd); err != nil </span><span class="cov8" title="1">{
resp.Error = err.Error()
resp.ExitCode = 1
return resp, err
}</span>
<span class="cov8" title="1">var execID string
if ledger != nil </span><span class="cov0" title="0">{
execID = generateExecID(resp.Node)
entry := reservation.Entry{
ID: execID,
Node: resp.Node,
OwnerExecID: execID,
OwnerSurface: owner.Surface,
OwnerPID: os.Getpid(),
OwnerOrigin: owner.Origin,
RAMMB: reservationMB,
Description: req.Description,
}
if _, acquireErr := ledger.Reserve(entry); acquireErr != nil </span><span class="cov0" title="0">{
resp.Error = acquireErr.Error()
return resp, acquireErr
}</span>
<span class="cov0" title="0">runtimeChanged = true
notifyStateChange(ctx, req, StateChangeExecutionReserved, resp)
defer func() </span><span class="cov0" title="0">{
if releaseErr := ledger.Release(execID); releaseErr != nil && resp.Error == "" </span><span class="cov0" title="0">{
resp.Error = releaseErr.Error()
}</span>
}()
}
<span class="cov8" title="1">env := append([]string{
"AXIS_EXECUTION_MODE=" + req.Mode,
"AXIS_CONFIRM=" + req.Confirm,
fmt.Sprintf("AXIS_RESERVATION_MB=%d", reservationMB),
}, extraEnv...)
runCmd := fmt.Sprintf(
"%s _axis_ctx=%s; trap 'rm -f \"$_axis_ctx\"' EXIT; bash -lc %s",
RemoteExecPrefix(resp.Node, remoteContextPath, env),
shellescape.Quote(remoteContextPath),
shellescape.Quote(command),
)
startedAt := time.Now().UTC()
out, _, runErr := runWithReservationHeartbeat(ledger, execID, func() (string, int64, error) </span><span class="cov8" title="1">{
out, err := runRemoteWithOutput(ctx, executor, runCmd, req.Stdout, req.Stderr)
return out, 0, err
}</span>)
<span class="cov8" title="1">elapsed := time.Since(startedAt)
resp.Output = out
resp.ExitCode = exitCode(runErr)
if runErr != nil </span><span class="cov8" title="1">{
resp.Error = runErr.Error()
recordFailure(skillStore, req.Description, resp.ExitCode)
runtimeChanged = true
recordExecutionOutcome(st, reqs, resp, runErr, elapsed, 0)
return resp, runErr
}</span>
<span class="cov8" title="1">recordSuccess(skillStore, req.Description, command, resp.Node)
runtimeChanged = true
recordExecutionOutcome(st, reqs, resp, nil, elapsed, 0)
resp.OK = true
return resp, nil</span>
}
func runLocalWithOutput(ctx context.Context, command string, env []string, stdout, stderr io.Writer) (string, int64, error) <span class="cov8" title="1">{
if stdout == nil && stderr == nil </span><span class="cov8" title="1">{
out, peak, err := RunLocalShell(ctx, command, env)
return string(out), peak, err
}</span>
<span class="cov0" title="0">var stdoutBuf, stderrBuf bytes.Buffer
outWriter := io.Writer(&stdoutBuf)
if stdout != nil </span><span class="cov0" title="0">{
outWriter = io.MultiWriter(stdout, &stdoutBuf)
}</span>
<span class="cov0" title="0">errWriter := io.Writer(&stderrBuf)
if stderr != nil </span><span class="cov0" title="0">{
errWriter = io.MultiWriter(stderr, &stderrBuf)
}</span>
<span class="cov0" title="0">peak, err := StreamLocalShell(ctx, command, env, outWriter, errWriter)
return combinedOutput(stdoutBuf.String(), stderrBuf.String()), peak, err</span>
}
func runRemoteWithOutput(ctx context.Context, executor RemoteExecutor, command string, stdout, stderr io.Writer) (string, error) <span class="cov8" title="1">{
if stdout == nil && stderr == nil </span><span class="cov8" title="1">{
return executor.Run(ctx, command)
}</span>
<span class="cov8" title="1">streamer, ok := executor.(StreamingRemoteExecutor)
if !ok </span><span class="cov8" title="1">{
out, err := executor.Run(ctx, command)
if stdout != nil && out != "" </span><span class="cov0" title="0">{
_, _ = io.WriteString(stdout, out)
}</span>
<span class="cov8" title="1">return out, err</span>
}
<span class="cov8" title="1">var stdoutBuf, stderrBuf bytes.Buffer
outWriter := io.Writer(&stdoutBuf)
if stdout != nil </span><span class="cov8" title="1">{
outWriter = io.MultiWriter(stdout, &stdoutBuf)
}</span>
<span class="cov8" title="1">errWriter := io.Writer(&stderrBuf)
if stderr != nil </span><span class="cov8" title="1">{
errWriter = io.MultiWriter(stderr, &stderrBuf)
}</span>
<span class="cov8" title="1">err := streamer.Stream(ctx, command, outWriter, errWriter)
return combinedOutput(stdoutBuf.String(), stderrBuf.String()), err</span>
}
func combinedOutput(stdout, stderr string) string <span class="cov8" title="1">{
stdout = strings.TrimSuffix(stdout, "\n")
stderr = strings.TrimSuffix(stderr, "\n")
switch </span>{
case stdout == "":<span class="cov0" title="0">
return stderr</span>
case stderr == "":<span class="cov0" title="0">
return stdout</span>
default:<span class="cov8" title="1">
return stdout + "\n" + stderr</span>
}
}
func runWithReservationHeartbeat(
ledger *reservation.Ledger,
ledgerExecID string,
run func() (string, int64, error),
) (string, int64, error) <span class="cov8" title="1">{
if ledger == nil || ledgerExecID == "" </span><span class="cov8" title="1">{
return run()
}</span>
<span class="cov8" title="1">type result struct {
out string
peak int64
err error
}
done := make(chan result, 1)
go func() </span><span class="cov8" title="1">{
out, peak, err := run()
done <- result{out: out, peak: peak, err: err}
}</span>()
<span class="cov8" title="1">ticker := time.NewTicker(executionHeartbeatInterval)
defer ticker.Stop()
for </span><span class="cov8" title="1">{
select </span>{
case res := <-done:<span class="cov8" title="1">
return res.out, res.peak, res.err</span>