Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Command Center (MCC)8 * File : services/internal/orchestrator/fakeagent/fakeagent.go9 * Module : services10 * Repository : https://git.spboucher.ai/maclustr-command-center11 * Project Website : https://clustr.spboucher.ai12 * Created : 2026-11-1813 * Last Modified : 2026-11-1814 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Package fakeagent is a TEST helper that plays both the ingest service43// (transport) and an agent, strictly through the database contract of44// migration 0002: it delivers pending agent_commands, verifies them exactly45// as a real agent does (protocol.Verify with a nonce journal), acknowledges,46// writes output and result, and notifies mcc_command_updates. It never47// touches the actions table.48package fakeagent4950import (51 "context"52 "crypto/ed25519"53 "sync"54 "time"5556 "github.com/google/uuid"57 "github.com/jackc/pgx/v5"58 "github.com/jackc/pgx/v5/pgxpool"5960 "clustr.spboucher.ai/mcc/internal/protocol"61)6263type nonces struct {64 mu sync.Mutex65 seen map[string]time.Time66}6768func (n *nonces) Remember(nonce string, until time.Time) (bool, error) {69 n.mu.Lock()70 defer n.mu.Unlock()71 if _, dup := n.seen[nonce]; dup {72 return false, nil73 }74 n.seen[nonce] = until75 return true, nil76}7778// Delivered is a command handed to the agent.79type Delivered struct {80 ID uuid.UUID81 ActionID uuid.UUID82 Signed protocol.SignedCommand83 Command *protocol.Command // nil when verification failed84 Err error // verification error85}8687// Behavior tells Run what the agent does with a verified command.88type Behavior struct {89 Refuse string // non-empty: local policy refusal with this reason90 Output []protocol.CommandOutput // streamed before the result91 Result *protocol.CommandResult // nil: the agent never answers92 Tamper func(*protocol.SignedCommand) // applied by the "transport" before verification93}9495type Agent struct {96 Pool *pgxpool.Pool97 AgentID uuid.UUID98 Now func() time.Time99 // Handle decides the behavior per command; nil = succeed with an empty result.100 Handle func(c *protocol.Command) Behavior101102 mu sync.Mutex103 nonces nonces104 executed []string // ids of commands actually executed (accepted and run)105 rejected []error // verification failures106}107108func New(pool *pgxpool.Pool, agentID uuid.UUID) *Agent {109 return &Agent{Pool: pool, AgentID: agentID, Now: func() time.Time { return time.Now().UTC() }, nonces: nonces{seen: map[string]time.Time{}}}110}111112// Executed returns the ids of the commands the agent really executed.113func (a *Agent) Executed() []string {114 a.mu.Lock()115 defer a.mu.Unlock()116 return append([]string(nil), a.executed...)117}118119// Rejected returns the verification errors met so far.120func (a *Agent) Rejected() []error {121 a.mu.Lock()122 defer a.mu.Unlock()123 return append([]error(nil), a.rejected...)124}125126func (a *Agent) keys(ctx context.Context) (map[string]ed25519.PublicKey, error) {127 rows, err := a.Pool.Query(ctx, `select key_id, public_key from command_keys where retired_at is null`)128 if err != nil {129 return nil, err130 }131 defer rows.Close()132 out := map[string]ed25519.PublicKey{}133 for rows.Next() {134 var id string135 var pk []byte136 if err := rows.Scan(&id, &pk); err != nil {137 return nil, err138 }139 out[id] = ed25519.PublicKey(pk)140 }141 return out, rows.Err()142}143144// Deliver plays the long-poll: pending, unexpired commands of this agent145// become `delivered` and are verified by the agent. tamper may alter what the146// transport hands over.147func (a *Agent) Deliver(ctx context.Context, tamper func(*protocol.SignedCommand)) ([]Delivered, error) {148 now := a.Now()149 rows, err := a.Pool.Query(ctx, `update agent_commands set state='delivered', delivered_at=$2150 where id in (select id from agent_commands where agent_id=$1 and state='pending' and expires_at > $2 order by issued_at for update skip locked)151 returning id, action_id, envelope, signature, key_id`, a.AgentID, now)152 if err != nil {153 return nil, err154 }155 out, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (Delivered, error) {156 var d Delivered157 err := r.Scan(&d.ID, &d.ActionID, &d.Signed.Payload, &d.Signed.Signature, &d.Signed.KeyID)158 return d, err159 })160 if err != nil {161 return nil, err162 }163 keys, err := a.keys(ctx)164 if err != nil {165 return nil, err166 }167 for i := range out {168 if tamper != nil {169 tamper(&out[i].Signed)170 }171 out[i].Command, out[i].Err = protocol.Verify(out[i].Signed, keys, a.AgentID.String(), now, &a.nonces)172 if out[i].Err != nil {173 a.mu.Lock()174 a.rejected = append(a.rejected, out[i].Err)175 a.mu.Unlock()176 }177 }178 return out, nil179}180181func (a *Agent) notify(ctx context.Context, id uuid.UUID) error {182 _, err := a.Pool.Exec(ctx, `select pg_notify('mcc_command_updates', $1)`, id.String())183 return err184}185186// Ack records the agent's acknowledgement. A refusal finishes the command.187func (a *Agent) Ack(ctx context.Context, d Delivered, accepted bool, reason string) error {188 var err error189 if accepted {190 _, err = a.Pool.Exec(ctx, `update agent_commands set state='acked', acked_at=$2, ack_accepted=true where id=$1 and state='delivered'`, d.ID, a.Now())191 } else {192 _, err = a.Pool.Exec(ctx, `update agent_commands set state='finished', acked_at=$2, finished_at=$2, ack_accepted=false, ack_reason=$3193 where id=$1 and state='delivered'`, d.ID, a.Now(), reason)194 }195 if err != nil {196 return err197 }198 return a.notify(ctx, d.ID)199}200201// Output stores one output chunk of a running command.202func (a *Agent) Output(ctx context.Context, d Delivered, o protocol.CommandOutput) error {203 if _, err := a.Pool.Exec(ctx, `insert into action_events(action_id, ts, kind, stream, data) values ($1,$2,'output',$3,$4)`, d.ActionID, a.Now(), o.Stream, o.Data); err != nil {204 return err205 }206 _, err := a.Pool.Exec(ctx, `update agent_commands set output_lines=output_lines+1, output_bytes=output_bytes+$2 where id=$1`, d.ID, len(o.Data))207 return err208}209210// Result stores the final result of a command.211func (a *Agent) Result(ctx context.Context, d Delivered, r protocol.CommandResult) error {212 res := map[string]any{"duration_s": r.Duration}213 for k, v := range r.Result {214 res[k] = v215 }216 if r.ExitCode != nil {217 res["exit_code"] = *r.ExitCode218 }219 if r.Error != "" {220 res["error"] = r.Error221 }222 if _, err := a.Pool.Exec(ctx, `update agent_commands set state='finished', finished_at=$2, result_status=$3, result=$4 where id=$1 and state='acked'`,223 d.ID, a.Now(), r.Status, res); err != nil {224 return err225 }226 return a.notify(ctx, d.ID)227}228229// CancelRequested plays the `cancel` list of the long-poll answer.230func (a *Agent) CancelRequested(ctx context.Context, d Delivered) (bool, error) {231 var at *time.Time232 if err := a.Pool.QueryRow(ctx, `update agent_commands set cancel_sent_at=coalesce(cancel_sent_at, case when cancel_requested_at is not null then $2::timestamptz end)233 where id=$1 returning cancel_requested_at`, d.ID, a.Now()).Scan(&at); err != nil {234 return false, err235 }236 return at != nil, nil237}238239// MarkExecuted records that the agent ran a command (for exactly-once assertions).240func (a *Agent) MarkExecuted(d Delivered) {241 a.mu.Lock()242 a.executed = append(a.executed, d.ID.String())243 a.mu.Unlock()244}245246// Run delivers and fully processes what is pending, once. It returns the247// number of commands delivered.248func (a *Agent) Run(ctx context.Context) (int, error) {249 ds, err := a.Deliver(ctx, nil)250 if err != nil {251 return 0, err252 }253 for _, d := range ds {254 if d.Err != nil {255 if err := a.Ack(ctx, d, false, "verification failed: "+d.Err.Error()); err != nil {256 return 0, err257 }258 continue259 }260 b := Behavior{Result: &protocol.CommandResult{Status: "succeeded"}}261 if a.Handle != nil {262 b = a.Handle(d.Command)263 }264 if b.Refuse != "" {265 if err := a.Ack(ctx, d, false, b.Refuse); err != nil {266 return 0, err267 }268 continue269 }270 if err := a.Ack(ctx, d, true, ""); err != nil {271 return 0, err272 }273 a.MarkExecuted(d)274 for _, o := range b.Output {275 if err := a.Output(ctx, d, o); err != nil {276 return 0, err277 }278 }279 if b.Result != nil {280 if err := a.Result(ctx, d, *b.Result); err != nil {281 return 0, err282 }283 }284 }285 return len(ds), nil286}287288// Loop runs the agent until ctx ends.289func (a *Agent) Loop(ctx context.Context, every time.Duration) {290 t := time.NewTicker(every)291 defer t.Stop()292 for {293 a.Run(ctx)294 select {295 case <-ctx.Done():296 return297 case <-t.C:298 }299 }300}301