feat(client): deliver items only to clients with a matching label
- Add internal/labels: parse and validate the optional work-repo file
agent-lib.labels.json (version 1; unlabeled items go to every client;
names match across types)
- Add "labels" to the client config: absent = no filtering, [] = unlabeled
items only; labels from the admin default config are pinned and cannot be
overridden by user, env or flag configs; a broken admin config aborts
- Filter in prepare() before planning; deselected items follow the
upstream-deletion rules (unmodified removed, modified kept + warn,
--force removes) with reason "not selected for this client's labels"
- Abort sync before any change when the labels file does not validate;
names that match no item only warn on the client
- Report the active selection in sync output and status (--json: labels
object with client, source, labels_file, not_selected, unknown_names)
- validate checks the labels file, including that every name resolves to
an own, vendored or MCP item
- Document in README ("Client labels"), fleet handoff and the proposal;
revise the "client-side selection" non-goal
- Tests: labels parser, config precedence, planner deselection, e2e for
filter/remove/keep-modified/abort/unknown names, validate
Refs: agent_lib-fh4
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
39952ceb02
commit
59735c3b24
16 files changed
+904
-38
No files matched your search
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/m3tam3re/agent-lib/internal/labels"
|
||||
"github.com/m3tam3re/agent-lib/internal/lockfile"
|
||||
"github.com/m3tam3re/agent-lib/internal/vendor"
|
||||
)
|
||||
@@ -46,6 +47,9 @@ func newValidateCmd() *cobra.Command {
|
||||
w := cmd.OutOrStdout()
|
||||
if result.Valid {
|
||||
fmt.Fprintf(w, "lockfile valid (%d sources)\n", len(lf.Sources))
|
||||
if _, err := os.Stat(labels.FileName); err == nil {
|
||||
fmt.Fprintf(w, "%s valid\n", labels.FileName)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, e := range result.Errors {
|
||||
|
||||
+78
-10
@@ -11,6 +11,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/m3tam3re/agent-lib/internal/gitsource"
|
||||
"github.com/m3tam3re/agent-lib/internal/labels"
|
||||
)
|
||||
|
||||
// ClientConfig is the client configuration for sync: fleet-provided or
|
||||
@@ -20,6 +21,14 @@ type ClientConfig struct {
|
||||
Ref string `json:"ref,omitempty"`
|
||||
Token string `json:"token,omitempty"`
|
||||
TokenUser string `json:"token_user,omitempty"`
|
||||
// Labels restricts delivery to unlabeled items plus items carrying one
|
||||
// of these labels (see the labels package). nil = no filtering; an
|
||||
// empty list = only unlabeled items.
|
||||
Labels *[]string `json:"labels,omitempty"`
|
||||
|
||||
// LabelSource names where Labels came from: "admin", "user", "env",
|
||||
// "flag" or "" when no labels apply. Not part of the file format.
|
||||
LabelSource string `json:"-"`
|
||||
}
|
||||
|
||||
// ConfigEnv names the override environment variables.
|
||||
@@ -115,50 +124,102 @@ func (e *MissingConfigError) Error() string {
|
||||
// default — first existing file wins. Explicit flag/env paths that do not
|
||||
// exist are hard errors; a completely empty chain yields *MissingConfigError.
|
||||
func LoadClientConfig(flagPath string) (*ClientConfig, error) {
|
||||
path, ok, err := resolveConfigPath(flagPath)
|
||||
path, desc, ok, err := resolveConfigPath(flagPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, &MissingConfigError{Chain: ConfigSearchChain(flagPath)}
|
||||
}
|
||||
return readClientConfig(path)
|
||||
cfg, err := readClientConfig(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.LabelSource = labelSourceFor(cfg, desc)
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// LoadOptionalConfig behaves like LoadClientConfig but returns (nil, nil)
|
||||
// when no config exists anywhere — for runs that carry their own --repo.
|
||||
// Malformed existing configs are still hard errors.
|
||||
func LoadOptionalConfig(flagPath string) (*ClientConfig, error) {
|
||||
path, ok, err := resolveConfigPath(flagPath)
|
||||
path, desc, ok, err := resolveConfigPath(flagPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return readClientConfig(path)
|
||||
cfg, err := readClientConfig(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.LabelSource = labelSourceFor(cfg, desc)
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// resolveConfigPath walks the search chain and returns the config to read.
|
||||
// The flag and env legs must exist when set (explicit intent); the user and
|
||||
// admin legs are skipped when absent.
|
||||
func resolveConfigPath(flagPath string) (path string, found bool, err error) {
|
||||
func resolveConfigPath(flagPath string) (path, source string, found bool, err error) {
|
||||
if flagPath != "" {
|
||||
return flagPath, true, nil
|
||||
return flagPath, "flag", true, nil
|
||||
}
|
||||
if envPath := os.Getenv(ConfigEnv); envPath != "" {
|
||||
return envPath, true, nil
|
||||
return envPath, "env", true, nil
|
||||
}
|
||||
if p := UserConfigPath(); p != "" {
|
||||
if _, statErr := os.Stat(p); statErr == nil {
|
||||
return p, true, nil
|
||||
return p, "user", true, nil
|
||||
}
|
||||
}
|
||||
admin := DefaultConfigPath()
|
||||
if _, statErr := os.Stat(admin); statErr == nil {
|
||||
return admin, true, nil
|
||||
return admin, "admin", true, nil
|
||||
}
|
||||
return "", false, nil
|
||||
return "", "", false, nil
|
||||
}
|
||||
|
||||
func labelSourceFor(cfg *ClientConfig, source string) string {
|
||||
if cfg.Labels == nil {
|
||||
return ""
|
||||
}
|
||||
return source
|
||||
}
|
||||
|
||||
// ApplyAdminLabels enforces admin-pinned labels: when the admin default
|
||||
// config at adminPath exists and sets "labels", that value replaces
|
||||
// whatever the chosen config said — user-level, env and flag configs can
|
||||
// neither widen nor drop an admin selection. A missing admin file (or one
|
||||
// without "labels") leaves cfg untouched. An admin file that exists but
|
||||
// cannot be read or parsed is a hard error: the admin's intent is unknown,
|
||||
// so no selection may be guessed.
|
||||
func ApplyAdminLabels(cfg *ClientConfig, adminPath string) error {
|
||||
data, err := os.ReadFile(adminPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("reading admin config %s for labels: %w", adminPath, err)
|
||||
}
|
||||
var admin struct {
|
||||
Labels *[]string `json:"labels"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &admin); err != nil {
|
||||
return fmt.Errorf("admin config %s is not valid JSON: %w", adminPath, err)
|
||||
}
|
||||
if admin.Labels == nil {
|
||||
return nil
|
||||
}
|
||||
for _, l := range *admin.Labels {
|
||||
if !labels.ValidLabel(l) {
|
||||
return fmt.Errorf("admin config %s: label %q must be lowercase letters, digits and dashes", adminPath, l)
|
||||
}
|
||||
}
|
||||
pinned := append([]string{}, (*admin.Labels)...)
|
||||
cfg.Labels = &pinned
|
||||
cfg.LabelSource = "admin"
|
||||
return nil
|
||||
}
|
||||
|
||||
func readClientConfig(path string) (*ClientConfig, error) {
|
||||
@@ -173,6 +234,13 @@ func readClientConfig(path string) (*ClientConfig, error) {
|
||||
if cfg.RepoURL == "" {
|
||||
return nil, fmt.Errorf("client config %s: repo_url is required", path)
|
||||
}
|
||||
if cfg.Labels != nil {
|
||||
for _, l := range *cfg.Labels {
|
||||
if !labels.ValidLabel(l) {
|
||||
return nil, fmt.Errorf("client config %s: label %q must be lowercase letters, digits and dashes", path, l)
|
||||
}
|
||||
}
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -163,3 +163,103 @@ func TestFillTokenAuthEnvOnlyFillsEmptyToken(t *testing.T) {
|
||||
t.Errorf("env must never override a config token: %+v", configured)
|
||||
}
|
||||
}
|
||||
|
||||
func writeRaw(t *testing.T, path, content string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigLabelsAbsentEmptyAndSet(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cases := map[string]struct {
|
||||
body string
|
||||
want *[]string
|
||||
source string
|
||||
}{
|
||||
"absent": {`{"repo_url":"r"}`, nil, ""},
|
||||
"empty": {`{"repo_url":"r","labels":[]}`, &[]string{}, "flag"},
|
||||
"set": {`{"repo_url":"r","labels":["sales","lead"]}`, &[]string{"sales", "lead"}, "flag"},
|
||||
}
|
||||
for name, tc := range cases {
|
||||
p := filepath.Join(dir, name+".json")
|
||||
writeRaw(t, p, tc.body)
|
||||
cfg, err := LoadClientConfig(p)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
if (cfg.Labels == nil) != (tc.want == nil) {
|
||||
t.Fatalf("%s: labels nil-ness mismatch: %v", name, cfg.Labels)
|
||||
}
|
||||
if tc.want != nil && strings.Join(*cfg.Labels, ",") != strings.Join(*tc.want, ",") {
|
||||
t.Errorf("%s: labels = %v", name, *cfg.Labels)
|
||||
}
|
||||
if cfg.LabelSource != tc.source {
|
||||
t.Errorf("%s: source = %q, want %q", name, cfg.LabelSource, tc.source)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigRejectsMalformedLabel(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "c.json")
|
||||
writeRaw(t, p, `{"repo_url":"r","labels":["Sales"]}`)
|
||||
if _, err := LoadClientConfig(p); err == nil {
|
||||
t.Fatal("an uppercase label must be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminLabelsWinOverUserLabels(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
admin := filepath.Join(dir, "admin.json")
|
||||
writeRaw(t, admin, `{"repo_url":"r","labels":["finance"]}`)
|
||||
user := []string{"sales", "it"}
|
||||
cfg := &ClientConfig{RepoURL: "r", Labels: &user, LabelSource: "user"}
|
||||
if err := ApplyAdminLabels(cfg, admin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.LabelSource != "admin" || strings.Join(*cfg.Labels, ",") != "finance" {
|
||||
t.Fatalf("admin labels must replace user labels, got %v (%s)", *cfg.Labels, cfg.LabelSource)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminEmptyLabelsAlsoPin(t *testing.T) {
|
||||
admin := filepath.Join(t.TempDir(), "admin.json")
|
||||
writeRaw(t, admin, `{"repo_url":"r","labels":[]}`)
|
||||
user := []string{"sales"}
|
||||
cfg := &ClientConfig{Labels: &user, LabelSource: "user"}
|
||||
if err := ApplyAdminLabels(cfg, admin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Labels == nil || len(*cfg.Labels) != 0 {
|
||||
t.Fatalf("an admin [] must pin 'unlabeled only', got %v", cfg.Labels)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminWithoutLabelsLeavesUserLabels(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
admin := filepath.Join(dir, "admin.json")
|
||||
writeRaw(t, admin, `{"repo_url":"r"}`)
|
||||
user := []string{"sales"}
|
||||
cfg := &ClientConfig{Labels: &user, LabelSource: "user"}
|
||||
if err := ApplyAdminLabels(cfg, admin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.LabelSource != "user" || strings.Join(*cfg.Labels, ",") != "sales" {
|
||||
t.Fatalf("without admin labels the user's labels apply, got %v (%s)", *cfg.Labels, cfg.LabelSource)
|
||||
}
|
||||
if err := ApplyAdminLabels(cfg, filepath.Join(dir, "missing.json")); err != nil {
|
||||
t.Fatalf("a missing admin config is not an error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminConfigBrokenIsFatal(t *testing.T) {
|
||||
admin := filepath.Join(t.TempDir(), "admin.json")
|
||||
writeRaw(t, admin, `{`)
|
||||
if err := ApplyAdminLabels(&ClientConfig{}, admin); err == nil {
|
||||
t.Fatal("an unreadable admin config must abort: its label intent is unknown")
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,16 @@ const (
|
||||
ActKeep Action = "keep"
|
||||
)
|
||||
|
||||
// ReasonNotSelected explains removals caused by the client's labels.
|
||||
const ReasonNotSelected = "not selected for this client's labels"
|
||||
|
||||
// PlanOptions tune planning. Force overwrites/removes locally modified
|
||||
// managed items; Deselected holds manifest keys filtered out by labels.
|
||||
type PlanOptions struct {
|
||||
Force bool
|
||||
Deselected map[string]bool
|
||||
}
|
||||
|
||||
// PlannedItem is one deployable inventory item with its repo-side hash.
|
||||
type PlannedItem struct {
|
||||
Type string
|
||||
@@ -51,7 +61,12 @@ type PlanEntry struct {
|
||||
// locally modified managed items are overwritten with the upstream version
|
||||
// (and removed after upstream deletion) instead of being skipped; items
|
||||
// agent-lib never managed are never touched, even with force.
|
||||
func Plan(items []PlannedItem, manifest *Manifest, disk map[string]DiskFact, pathFor func(typ, name string) string, force bool) []PlanEntry {
|
||||
//
|
||||
// Deselected marks keys that exist upstream but are not selected for this
|
||||
// client's labels. Planning treats them exactly like upstream deletions —
|
||||
// only the reasons differ, so users learn why an item went away.
|
||||
func Plan(items []PlannedItem, manifest *Manifest, disk map[string]DiskFact, pathFor func(typ, name string) string, opts PlanOptions) []PlanEntry {
|
||||
force := opts.Force
|
||||
invByKey := map[string]PlannedItem{}
|
||||
for _, it := range items {
|
||||
invByKey[manifestKey(it.Type, it.Name)] = it
|
||||
@@ -87,6 +102,10 @@ func Plan(items []PlannedItem, manifest *Manifest, disk map[string]DiskFact, pat
|
||||
it, inInv := invByKey[key]
|
||||
rec := manifest.Items[key]
|
||||
fact := disk[key]
|
||||
gone := "upstream deleted"
|
||||
if opts.Deselected[key] {
|
||||
gone = ReasonNotSelected
|
||||
}
|
||||
|
||||
switch {
|
||||
case inInv && rec == nil:
|
||||
@@ -102,12 +121,12 @@ func Plan(items []PlannedItem, manifest *Manifest, disk map[string]DiskFact, pat
|
||||
case rec != nil && !fact.Exists:
|
||||
emit(ActRemove, PlannedItem{Type: rec.Type, Name: rec.Name, Origin: rec.Origin}, "already gone from disk; dropping manifest record")
|
||||
case rec != nil && fact.Hash == rec.Hash:
|
||||
emit(ActRemove, PlannedItem{Type: rec.Type, Name: rec.Name, Origin: rec.Origin}, "upstream deleted")
|
||||
emit(ActRemove, PlannedItem{Type: rec.Type, Name: rec.Name, Origin: rec.Origin}, gone)
|
||||
case rec != nil && force:
|
||||
emit(ActRemove, PlannedItem{Type: rec.Type, Name: rec.Name, Origin: rec.Origin}, "upstream deleted; forced removal of the locally modified copy")
|
||||
emit(ActRemove, PlannedItem{Type: rec.Type, Name: rec.Name, Origin: rec.Origin}, gone+"; forced removal of the locally modified copy")
|
||||
case rec != nil:
|
||||
emit(ActSkip, PlannedItem{Type: rec.Type, Name: rec.Name, Origin: rec.Origin},
|
||||
"upstream deleted but the local copy was modified; keeping it")
|
||||
gone+" but the local copy was modified; keeping it")
|
||||
default:
|
||||
emit(ActLeave, PlannedItem{Type: typeOfKey(key), Name: nameOfKey(key)},
|
||||
"unmanaged local item; left untouched")
|
||||
|
||||
@@ -98,7 +98,7 @@ func TestPlanMatrix(t *testing.T) {
|
||||
diskFacts[key] = DiskFact{Exists: true, Hash: hashMod}
|
||||
}
|
||||
|
||||
plan := Plan(items, manifest, diskFacts, testPathFor, false)
|
||||
plan := Plan(items, manifest, diskFacts, testPathFor, PlanOptions{})
|
||||
if tc.disk == diskNone && tc.up == upAbsent {
|
||||
if len(plan) != 0 {
|
||||
t.Fatalf("a key present nowhere must produce no entry, got %+v", plan)
|
||||
@@ -151,7 +151,7 @@ func TestPlanForceMatrix(t *testing.T) {
|
||||
}
|
||||
disk := map[string]DiskFact{key: {Exists: true, Hash: hashMod}}
|
||||
|
||||
plan := Plan(items, manifest, disk, testPathFor, true)
|
||||
plan := Plan(items, manifest, disk, testPathFor, PlanOptions{Force: true})
|
||||
if len(plan) != 1 {
|
||||
t.Fatalf("want exactly 1 entry, got %d: %+v", len(plan), plan)
|
||||
}
|
||||
@@ -164,7 +164,7 @@ func TestPlanForceMatrix(t *testing.T) {
|
||||
t.Run("never-managed occupancy stays skipped", func(t *testing.T) {
|
||||
items := []PlannedItem{{Type: "skills", Name: "alpha", RelPath: "skills/alpha", Hash: hashV1}}
|
||||
disk := map[string]DiskFact{manifestKey("skills", "alpha"): {Exists: true, Hash: hashMod}}
|
||||
plan := Plan(items, NewManifest(), disk, testPathFor, true)
|
||||
plan := Plan(items, NewManifest(), disk, testPathFor, PlanOptions{Force: true})
|
||||
if len(plan) != 1 || plan[0].Action != ActSkip {
|
||||
t.Fatalf("force must not deploy over a never-managed item: %+v", plan)
|
||||
}
|
||||
@@ -199,7 +199,7 @@ func TestPlanMixedFixture(t *testing.T) {
|
||||
"agents/helper": {Exists: true, Hash: hashV1}, // unmodified × unchanged
|
||||
}
|
||||
|
||||
plan := Plan(items, manifest, disk, testPathFor, false)
|
||||
plan := Plan(items, manifest, disk, testPathFor, PlanOptions{})
|
||||
got := map[string]Action{}
|
||||
for _, e := range plan {
|
||||
got[e.Type+"/"+e.Name] = e.Action
|
||||
@@ -243,8 +243,8 @@ func TestPlanPureGuarantee(t *testing.T) {
|
||||
manifest := manifestWith(map[string]*ManifestItem{"skills/b": {Name: "b", Type: "skills", Hash: hashV1}})
|
||||
disk := map[string]DiskFact{"skills/b": {Exists: true, Hash: hashV1}}
|
||||
|
||||
p1 := Plan(items, manifest, disk, testPathFor, false)
|
||||
p2 := Plan(items, manifest, disk, testPathFor, false)
|
||||
p1 := Plan(items, manifest, disk, testPathFor, PlanOptions{})
|
||||
p2 := Plan(items, manifest, disk, testPathFor, PlanOptions{})
|
||||
if len(p1) != len(p2) {
|
||||
t.Fatal("same inputs must yield same plan length")
|
||||
}
|
||||
@@ -257,3 +257,31 @@ func TestPlanPureGuarantee(t *testing.T) {
|
||||
t.Error("planner must not mutate its inputs")
|
||||
}
|
||||
}
|
||||
|
||||
// Deselected items follow the upstream-deleted rules exactly; only the
|
||||
// reason tells the user that labels, not a deletion, caused the change.
|
||||
func TestPlanDeselectedFollowsDeletionRules(t *testing.T) {
|
||||
key := manifestKey("skills", "alpha")
|
||||
cases := []struct {
|
||||
name string
|
||||
disk DiskFact
|
||||
force bool
|
||||
action Action
|
||||
reason string
|
||||
}{
|
||||
{"clean copy removed", DiskFact{Exists: true, Hash: hashV1}, false, ActRemove, ReasonNotSelected},
|
||||
{"modified copy kept", DiskFact{Exists: true, Hash: hashMod}, false, ActSkip, ReasonNotSelected + " but the local copy was modified; keeping it"},
|
||||
{"modified copy forced", DiskFact{Exists: true, Hash: hashMod}, true, ActRemove, ReasonNotSelected + "; forced removal of the locally modified copy"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
manifest := NewManifest()
|
||||
manifest.Items[key] = &ManifestItem{Name: "alpha", Type: "skills", Hash: hashV1}
|
||||
plan := Plan(nil, manifest, map[string]DiskFact{key: tc.disk}, testPathFor,
|
||||
PlanOptions{Force: tc.force, Deselected: map[string]bool{key: true}})
|
||||
if len(plan) != 1 || plan[0].Action != tc.action || plan[0].Reason != tc.reason {
|
||||
t.Fatalf("got %+v, want %s %q", plan, tc.action, tc.reason)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -15,14 +15,15 @@ type StatusEntry struct {
|
||||
|
||||
// StatusReport is the machine-readable local-state report.
|
||||
type StatusReport struct {
|
||||
Version string `json:"agent_lib_version"`
|
||||
DeployedRev string `json:"deployed_revision"`
|
||||
RepoRev string `json:"repository_revision"`
|
||||
InSync bool `json:"in_sync"`
|
||||
Drift bool `json:"problematic_drift"`
|
||||
Pending []StatusEntry `json:"pending_changes,omitempty"`
|
||||
Skipped []StatusEntry `json:"skipped_items,omitempty"`
|
||||
Unrecognized []StatusEntry `json:"unrecognized_items,omitempty"`
|
||||
Version string `json:"agent_lib_version"`
|
||||
DeployedRev string `json:"deployed_revision"`
|
||||
RepoRev string `json:"repository_revision"`
|
||||
InSync bool `json:"in_sync"`
|
||||
Drift bool `json:"problematic_drift"`
|
||||
Pending []StatusEntry `json:"pending_changes,omitempty"`
|
||||
Skipped []StatusEntry `json:"skipped_items,omitempty"`
|
||||
Unrecognized []StatusEntry `json:"unrecognized_items,omitempty"`
|
||||
Labels *LabelSelection `json:"labels,omitempty"`
|
||||
}
|
||||
|
||||
// Status reports the local state without mutating anything. Drift is true
|
||||
@@ -38,6 +39,7 @@ func Status(opts SyncOptions) (*StatusReport, error) {
|
||||
Version: version.Version,
|
||||
DeployedRev: p.manifest.Revision,
|
||||
RepoRev: p.pull.Rev,
|
||||
Labels: p.labels,
|
||||
}
|
||||
for _, e := range p.plan {
|
||||
item := e.Type + "/" + e.Name
|
||||
@@ -85,6 +87,12 @@ func PrintStatus(w io.Writer, r *StatusReport) bool {
|
||||
fmt.Fprintln(w)
|
||||
}
|
||||
}
|
||||
if r.Labels != nil {
|
||||
fmt.Fprintln(w, r.Labels.Summary())
|
||||
for _, n := range r.Labels.Unknown {
|
||||
fmt.Fprintf(w, " warning: labels file names %q, which matches no item\n", n)
|
||||
}
|
||||
}
|
||||
printSection("pending changes", r.Pending)
|
||||
printSection("skipped (local modifications)", r.Skipped)
|
||||
printSection("unrecognized local items", r.Unrecognized)
|
||||
|
||||
+103
-2
@@ -1,12 +1,17 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/go-git/go-git/v5/plumbing/object"
|
||||
|
||||
"github.com/m3tam3re/agent-lib/internal/gitsource"
|
||||
"github.com/m3tam3re/agent-lib/internal/labels"
|
||||
"github.com/m3tam3re/agent-lib/internal/target"
|
||||
)
|
||||
|
||||
@@ -29,6 +34,18 @@ type prepared struct {
|
||||
manifest *Manifest
|
||||
items []PlannedItem
|
||||
plan []PlanEntry
|
||||
labels *LabelSelection
|
||||
}
|
||||
|
||||
// LabelSelection describes an active label filter for one run: the client
|
||||
// labels, where they came from, which items were left out and which names
|
||||
// in the labels file match no item. nil when the client carries no labels.
|
||||
type LabelSelection struct {
|
||||
Client []string `json:"client"`
|
||||
Source string `json:"source"`
|
||||
File bool `json:"labels_file"`
|
||||
NotSelected []string `json:"not_selected,omitempty"`
|
||||
Unknown []string `json:"unknown_names,omitempty"`
|
||||
}
|
||||
|
||||
// prepare pulls, inventories, hashes and plans — the complete read-only
|
||||
@@ -66,11 +83,29 @@ func prepare(opts SyncOptions) (*prepared, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
lf, err := readLabelsFile(pull.Tree)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var sel *LabelSelection
|
||||
if cfg.Labels != nil {
|
||||
sel = &LabelSelection{Client: append([]string{}, (*cfg.Labels)...), Source: cfg.LabelSource, File: lf != nil}
|
||||
if lf != nil {
|
||||
sel.Unknown = unknownLabelNames(lf, inv)
|
||||
}
|
||||
}
|
||||
|
||||
items := make([]PlannedItem, 0, len(inv.Items))
|
||||
deselected := map[string]bool{}
|
||||
for _, it := range inv.Deployable() {
|
||||
if _, ok := oc.DeployPath(it.Type, it.Name); !ok {
|
||||
continue
|
||||
}
|
||||
if sel != nil && !lf.Selected(it.Name, sel.Client) {
|
||||
deselected[manifestKey(it.Type, it.Name)] = true
|
||||
sel.NotSelected = append(sel.NotSelected, it.Type+"/"+it.Name)
|
||||
continue
|
||||
}
|
||||
hash, err := HashItem(pull.Tree, it)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("hashing %s/%s: %w", it.Type, it.Name, err)
|
||||
@@ -82,13 +117,48 @@ func prepare(opts SyncOptions) (*prepared, error) {
|
||||
path, _ := oc.DeployPath(typ, name)
|
||||
return path
|
||||
}
|
||||
plan := Plan(items, manifest, diskFacts(oc, manifest, items), pathFor, opts.Force)
|
||||
plan := Plan(items, manifest, diskFacts(oc, manifest, items), pathFor, PlanOptions{Force: opts.Force, Deselected: deselected})
|
||||
for _, e := range plan {
|
||||
if !safePath(e.DstPath) {
|
||||
return nil, fmt.Errorf("refusing unsafe deploy path %q", e.DstPath)
|
||||
}
|
||||
}
|
||||
return &prepared{paths: paths, pull: pull, manifest: manifest, items: items, plan: plan}, nil
|
||||
return &prepared{paths: paths, pull: pull, manifest: manifest, items: items, plan: plan, labels: sel}, nil
|
||||
}
|
||||
|
||||
// readLabelsFile loads the labels file from the pulled revision. A missing
|
||||
// file restricts nothing (nil); a file that exists but does not validate
|
||||
// aborts the run before any mutation — never fall back to "everything".
|
||||
func readLabelsFile(tree *gitsource.GitTree) (*labels.File, error) {
|
||||
data, err := tree.ReadFile(labels.FileName)
|
||||
if err != nil {
|
||||
if errors.Is(err, object.ErrFileNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("reading %s: %w", labels.FileName, err)
|
||||
}
|
||||
lf, err := labels.Parse(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("work repository %w — sync aborted, nothing changed", err)
|
||||
}
|
||||
return lf, nil
|
||||
}
|
||||
|
||||
// unknownLabelNames lists names in the labels file that match no inventory
|
||||
// item of any type (MCP fragments included). Not fatal on the client: the
|
||||
// curator-side validate is the hard gate.
|
||||
func unknownLabelNames(lf *labels.File, inv *Inventory) []string {
|
||||
known := map[string]bool{}
|
||||
for _, it := range inv.Items {
|
||||
known[it.Name] = true
|
||||
}
|
||||
var out []string
|
||||
for _, n := range lf.Names() {
|
||||
if !known[n] {
|
||||
out = append(out, n)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// resolveRunConfig applies the --repo inline override to the config chain:
|
||||
@@ -101,6 +171,9 @@ func resolveRunConfig(opts SyncOptions) (*ClientConfig, error) {
|
||||
return nil, err
|
||||
}
|
||||
cfg.FillTokenAuth()
|
||||
if err := ApplyAdminLabels(cfg, DefaultConfigPath()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
cfg, err := LoadOptionalConfig(opts.ConfigPath)
|
||||
@@ -115,6 +188,9 @@ func resolveRunConfig(opts SyncOptions) (*ClientConfig, error) {
|
||||
cfg.Ref = opts.Ref
|
||||
}
|
||||
cfg.FillTokenAuth()
|
||||
if err := ApplyAdminLabels(cfg, DefaultConfigPath()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
@@ -127,6 +203,7 @@ func Sync(opts SyncOptions, stdout io.Writer) (*SyncReport, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
printLabelSelection(stdout, p.labels)
|
||||
return ExecutePlan(p.pull.Tree, p.plan, p.manifest, p.paths, p.pull.Rev, stdout)
|
||||
}
|
||||
|
||||
@@ -145,3 +222,27 @@ func safePath(dst string) bool {
|
||||
}
|
||||
return rel != ".." && rel != "." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
|
||||
}
|
||||
|
||||
// printLabelSelection reports an active label filter in one line, plus a
|
||||
// warning line per labels-file name that matches no item.
|
||||
func printLabelSelection(w io.Writer, sel *LabelSelection) {
|
||||
if sel == nil {
|
||||
return
|
||||
}
|
||||
fmt.Fprintln(w, sel.Summary())
|
||||
for _, n := range sel.Unknown {
|
||||
fmt.Fprintf(w, "warning: %s names %q, which matches no item in the repository\n", labels.FileName, n)
|
||||
}
|
||||
}
|
||||
|
||||
// Summary renders the selection as one human-readable line.
|
||||
func (s *LabelSelection) Summary() string {
|
||||
client := strings.Join(s.Client, ", ")
|
||||
if client == "" {
|
||||
client = "(none — unlabeled items only)"
|
||||
}
|
||||
if !s.File {
|
||||
return fmt.Sprintf("labels: %s (%s) — repository has no %s, nothing filtered", client, s.Source, labels.FileName)
|
||||
}
|
||||
return fmt.Sprintf("labels: %s (%s) — %d item(s) not selected", client, s.Source, len(s.NotSelected))
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package e2e
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func (e *syncEnv) writeLabelConfig(t *testing.T, labelsJSON string) {
|
||||
t.Helper()
|
||||
e.config = filepath.Join(e.configDir, "config.json")
|
||||
body := `{"repo_url":"` + filepath.ToSlash(e.workRepo) + `","ref":"main"`
|
||||
if labelsJSON != "" {
|
||||
body += `,"labels":` + labelsJSON
|
||||
}
|
||||
body += "}"
|
||||
if err := os.WriteFile(e.config, []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func commitLabels(t *testing.T, h *harness, dir, content string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(filepath.Join(dir, "agent-lib.labels.json"), []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.git(t, dir, "add", "-A")
|
||||
h.git(t, dir, "commit", "-m", "labels")
|
||||
}
|
||||
|
||||
func exists(p string) bool {
|
||||
_, err := os.Stat(p)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func TestSyncLabelsFilterAndRemove(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
env := newSyncEnv(t, h)
|
||||
buildWorkRepo(t, h, env.workRepo)
|
||||
commitLabels(t, h, env.workRepo, `{"version":1,"labels":{"ops":["deploy"],"dev":["helper","own-skill"]}}`)
|
||||
|
||||
skill := filepath.Join(env.home, ".agents/skills/own-skill")
|
||||
cmd := filepath.Join(env.home, ".config/opencode/commands/deploy.md")
|
||||
agent := filepath.Join(env.home, ".config/opencode/agents/helper.md")
|
||||
|
||||
// No labels field: no filtering at all (backward compatible).
|
||||
env.writeLabelConfig(t, "")
|
||||
if out, err := env.run(t); err != nil {
|
||||
t.Fatalf("sync failed: %v\n%s", err, out)
|
||||
}
|
||||
if !exists(skill) || !exists(cmd) || !exists(agent) {
|
||||
t.Fatal("without client labels every item must deploy")
|
||||
}
|
||||
|
||||
// labels ["ops"]: dev items go away, ops item stays.
|
||||
env.writeLabelConfig(t, `["ops"]`)
|
||||
out, err := env.run(t)
|
||||
if err != nil {
|
||||
t.Fatalf("sync failed: %v\n%s", err, out)
|
||||
}
|
||||
if !strings.Contains(out, "labels: ops") || !strings.Contains(out, "2 item(s) not selected") {
|
||||
t.Errorf("sync must report the active selection, got:\n%s", out)
|
||||
}
|
||||
if exists(skill) || exists(agent) {
|
||||
t.Error("deselected unmodified items must be removed")
|
||||
}
|
||||
if !exists(cmd) {
|
||||
t.Error("selected item must stay")
|
||||
}
|
||||
|
||||
// Second identical run is a no-op.
|
||||
out, err = env.run(t)
|
||||
if err != nil {
|
||||
t.Fatalf("sync failed: %v\n%s", err, out)
|
||||
}
|
||||
if !strings.Contains(out, "deployed: 0") || !strings.Contains(out, "removed: 0") || !strings.Contains(out, "updated: 0") {
|
||||
t.Errorf("second run must change nothing, got:\n%s", out)
|
||||
}
|
||||
|
||||
// [] = unlabeled items only: everything here is labeled.
|
||||
env.writeLabelConfig(t, `[]`)
|
||||
if out, err := env.run(t); err != nil {
|
||||
t.Fatalf("sync failed: %v\n%s", err, out)
|
||||
}
|
||||
if exists(cmd) {
|
||||
t.Error("labels [] must deliver unlabeled items only")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncLabelsKeepModifiedCopy(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
env := newSyncEnv(t, h)
|
||||
buildWorkRepo(t, h, env.workRepo)
|
||||
commitLabels(t, h, env.workRepo, `{"version":1,"labels":{"dev":["helper"]}}`)
|
||||
|
||||
env.writeLabelConfig(t, `["dev"]`)
|
||||
if out, err := env.run(t); err != nil {
|
||||
t.Fatalf("sync failed: %v\n%s", err, out)
|
||||
}
|
||||
agent := filepath.Join(env.home, ".config/opencode/agents/helper.md")
|
||||
if err := os.WriteFile(agent, []byte("my edit\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
env.writeLabelConfig(t, `["ops"]`)
|
||||
if out, err := env.run(t); err != nil {
|
||||
t.Fatalf("sync failed: %v\n%s", err, out)
|
||||
}
|
||||
if !exists(agent) {
|
||||
t.Fatal("a locally modified copy must survive deselection")
|
||||
}
|
||||
log, _ := os.ReadFile(filepath.Join(env.stateDir, "sync.log"))
|
||||
if !strings.Contains(string(log), "not selected for this client's labels") {
|
||||
t.Errorf("sync log must explain the label-based skip, got:\n%s", log)
|
||||
}
|
||||
|
||||
if out, err := env.run(t, "--force"); err != nil {
|
||||
t.Fatalf("sync --force failed: %v\n%s", err, out)
|
||||
}
|
||||
if exists(agent) {
|
||||
t.Error("--force must remove the deselected modified copy")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncInvalidLabelsFileAbortsWithoutChange(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
env := newSyncEnv(t, h)
|
||||
buildWorkRepo(t, h, env.workRepo)
|
||||
env.writeLabelConfig(t, `["ops"]`)
|
||||
if out, err := env.run(t); err != nil {
|
||||
t.Fatalf("sync failed: %v\n%s", err, out)
|
||||
}
|
||||
manifestBefore, _ := os.ReadFile(filepath.Join(env.stateDir, "manifest.json"))
|
||||
|
||||
commitLabels(t, h, env.workRepo, `{"version":1,"labels":{"Ops":["deploy"]}}`)
|
||||
out, err := env.run(t)
|
||||
if err == nil {
|
||||
t.Fatalf("an invalid labels file must fail the sync, got:\n%s", out)
|
||||
}
|
||||
if !strings.Contains(out, "agent-lib.labels.json") || !strings.Contains(out, "nothing changed") {
|
||||
t.Errorf("error must name the file and promise no change, got:\n%s", out)
|
||||
}
|
||||
manifestAfter, _ := os.ReadFile(filepath.Join(env.stateDir, "manifest.json"))
|
||||
if string(manifestBefore) != string(manifestAfter) {
|
||||
t.Error("an aborted sync must not touch the manifest")
|
||||
}
|
||||
if !exists(filepath.Join(env.home, ".config/opencode/commands/deploy.md")) {
|
||||
t.Error("an aborted sync must not remove anything")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncLabelsUnknownNameWarns(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
env := newSyncEnv(t, h)
|
||||
buildWorkRepo(t, h, env.workRepo)
|
||||
commitLabels(t, h, env.workRepo, `{"version":1,"labels":{"ops":["deploy","no-such-item"]}}`)
|
||||
env.writeLabelConfig(t, `["ops"]`)
|
||||
out, err := env.run(t)
|
||||
if err != nil {
|
||||
t.Fatalf("an unknown name must not fail the client sync: %v\n%s", err, out)
|
||||
}
|
||||
if !strings.Contains(out, `"no-such-item"`) {
|
||||
t.Errorf("sync must warn about the unknown name, got:\n%s", out)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
// Package labels parses the optional work-repository file that restricts
|
||||
// items to clients carrying a matching label.
|
||||
//
|
||||
// Semantics: an item that appears under no label is delivered to every
|
||||
// client; an item that appears under one or more labels is delivered to a
|
||||
// client that carries at least one of them. Entries are deployed item names
|
||||
// and match across types (a skill and a command of the same name are both
|
||||
// covered by one entry).
|
||||
package labels
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// FileName is the labels file at the work-repository root.
|
||||
const FileName = "agent-lib.labels.json"
|
||||
|
||||
// Version is the only file format version this binary understands.
|
||||
const Version = 1
|
||||
|
||||
var labelForm = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`)
|
||||
|
||||
// ValidLabel reports whether s has the required label form.
|
||||
func ValidLabel(s string) bool { return labelForm.MatchString(s) }
|
||||
|
||||
// File is a parsed labels file.
|
||||
type File struct {
|
||||
Version int `json:"version"`
|
||||
Labels map[string][]string `json:"labels"`
|
||||
|
||||
byItem map[string][]string
|
||||
}
|
||||
|
||||
// Parse decodes and validates a labels file strictly: unknown keys, an
|
||||
// unsupported version, malformed labels, empty lists and empty names are
|
||||
// errors. A file that does not validate must never be applied.
|
||||
func Parse(data []byte) (*File, error) {
|
||||
dec := json.NewDecoder(bytes.NewReader(data))
|
||||
dec.DisallowUnknownFields()
|
||||
var f File
|
||||
if err := dec.Decode(&f); err != nil {
|
||||
return nil, fmt.Errorf("%s is not valid: %w", FileName, err)
|
||||
}
|
||||
if dec.More() {
|
||||
return nil, fmt.Errorf("%s is not valid: trailing data after the JSON object", FileName)
|
||||
}
|
||||
if f.Version != Version {
|
||||
return nil, fmt.Errorf("%s: unsupported version %d (this binary understands version %d)", FileName, f.Version, Version)
|
||||
}
|
||||
if f.Labels == nil {
|
||||
return nil, fmt.Errorf("%s: \"labels\" is required (use {} for no restrictions)", FileName)
|
||||
}
|
||||
f.byItem = map[string][]string{}
|
||||
for _, label := range f.SortedLabels() {
|
||||
names := f.Labels[label]
|
||||
if !ValidLabel(label) {
|
||||
return nil, fmt.Errorf("%s: label %q must match %s", FileName, label, labelForm)
|
||||
}
|
||||
if len(names) == 0 {
|
||||
return nil, fmt.Errorf("%s: label %q has an empty item list (remove the label instead)", FileName, label)
|
||||
}
|
||||
for _, name := range names {
|
||||
if name == "" {
|
||||
return nil, fmt.Errorf("%s: label %q contains an empty item name", FileName, label)
|
||||
}
|
||||
if !contains(f.byItem[name], label) {
|
||||
f.byItem[name] = append(f.byItem[name], label)
|
||||
}
|
||||
}
|
||||
}
|
||||
return &f, nil
|
||||
}
|
||||
|
||||
// SortedLabels returns the declared labels in stable order.
|
||||
func (f *File) SortedLabels() []string {
|
||||
out := make([]string, 0, len(f.Labels))
|
||||
for l := range f.Labels {
|
||||
out = append(out, l)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// Names returns every item name the file mentions, sorted and unique.
|
||||
func (f *File) Names() []string {
|
||||
out := make([]string, 0, len(f.byItem))
|
||||
for n := range f.byItem {
|
||||
out = append(out, n)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// LabelsOf returns the labels an item carries (nil = unlabeled).
|
||||
func (f *File) LabelsOf(name string) []string {
|
||||
if f == nil {
|
||||
return nil
|
||||
}
|
||||
return f.byItem[name]
|
||||
}
|
||||
|
||||
// Selected reports whether an item goes to a client carrying clientLabels.
|
||||
// Unlabeled items always do; a nil file restricts nothing.
|
||||
func (f *File) Selected(name string, clientLabels []string) bool {
|
||||
itemLabels := f.LabelsOf(name)
|
||||
if len(itemLabels) == 0 {
|
||||
return true
|
||||
}
|
||||
for _, l := range itemLabels {
|
||||
if contains(clientLabels, l) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func contains(list []string, s string) bool {
|
||||
for _, v := range list {
|
||||
if v == s {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package labels
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseAndSelect(t *testing.T) {
|
||||
f, err := Parse([]byte(`{"version":1,"labels":{"sales":["crm","quote"],"finance":["model","crm"]}}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cases := []struct {
|
||||
item string
|
||||
client []string
|
||||
want bool
|
||||
}{
|
||||
{"unlabeled", nil, true},
|
||||
{"unlabeled", []string{}, true},
|
||||
{"crm", nil, false},
|
||||
{"crm", []string{"sales"}, true},
|
||||
{"crm", []string{"finance"}, true},
|
||||
{"quote", []string{"finance"}, false},
|
||||
{"quote", []string{"finance", "sales"}, true},
|
||||
{"model", []string{"other"}, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := f.Selected(c.item, c.client); got != c.want {
|
||||
t.Errorf("Selected(%q, %v) = %v, want %v", c.item, c.client, got, c.want)
|
||||
}
|
||||
}
|
||||
if got := strings.Join(f.Names(), ","); got != "crm,model,quote" {
|
||||
t.Errorf("Names() = %s", got)
|
||||
}
|
||||
if got := strings.Join(f.LabelsOf("crm"), ","); got != "finance,sales" {
|
||||
t.Errorf("LabelsOf(crm) = %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNilFileRestrictsNothing(t *testing.T) {
|
||||
var f *File
|
||||
if !f.Selected("anything", nil) {
|
||||
t.Error("a nil file must select every item")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyLabelsMapIsValid(t *testing.T) {
|
||||
f, err := Parse([]byte(`{"version":1,"labels":{}}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !f.Selected("x", nil) {
|
||||
t.Error("no labels declared means no restrictions")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRejects(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"not json": `{`,
|
||||
"unknown key": `{"version":1,"labels":{},"extra":true}`,
|
||||
"wrong version": `{"version":2,"labels":{}}`,
|
||||
"missing version": `{"labels":{}}`,
|
||||
"missing labels": `{"version":1}`,
|
||||
"upper label": `{"version":1,"labels":{"Sales":["a"]}}`,
|
||||
"space label": `{"version":1,"labels":{"sales team":["a"]}}`,
|
||||
"leading dash": `{"version":1,"labels":{"-sales":["a"]}}`,
|
||||
"empty list": `{"version":1,"labels":{"sales":[]}}`,
|
||||
"empty name": `{"version":1,"labels":{"sales":[""]}}`,
|
||||
"trailing data": `{"version":1,"labels":{}} {}`,
|
||||
}
|
||||
for name, data := range cases {
|
||||
if _, err := Parse([]byte(data)); err == nil {
|
||||
t.Errorf("%s: expected an error", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package vendor
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/m3tam3re/agent-lib/internal/lockfile"
|
||||
)
|
||||
|
||||
func labelsWorkDir(t *testing.T, labelsJSON string) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
write := func(rel, content string) {
|
||||
p := filepath.Join(dir, rel)
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(p, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
write("skills/alpha/SKILL.md", "---\nname: alpha\ndescription: a\n---\n")
|
||||
write("agents/beta.md", "---\ndescription: b\n---\n")
|
||||
write("mcp/websearch.yaml", "websearch: {}\n")
|
||||
if labelsJSON != "" {
|
||||
write("agent-lib.labels.json", labelsJSON)
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
func labelErrors(v Validation) []string {
|
||||
var out []string
|
||||
for _, e := range v.Errors {
|
||||
if e.Rule == "labels" {
|
||||
out = append(out, e.Message)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestValidateLabels(t *testing.T) {
|
||||
lf := lockfile.New()
|
||||
if errs := labelErrors(Validate(labelsWorkDir(t, ""), lf)); len(errs) != 0 {
|
||||
t.Errorf("no labels file is fine, got %v", errs)
|
||||
}
|
||||
ok := `{"version":1,"labels":{"sales":["alpha","websearch"],"dev":["beta"]}}`
|
||||
if errs := labelErrors(Validate(labelsWorkDir(t, ok), lf)); len(errs) != 0 {
|
||||
t.Errorf("valid file reported errors: %v", errs)
|
||||
}
|
||||
unknown := `{"version":1,"labels":{"sales":["alpha","gamma"]}}`
|
||||
errs := labelErrors(Validate(labelsWorkDir(t, unknown), lf))
|
||||
if len(errs) != 1 || !strings.Contains(errs[0], `"gamma"`) {
|
||||
t.Errorf("unknown name must be reported once, got %v", errs)
|
||||
}
|
||||
bad := `{"version":1,"labels":{"Sales":["alpha"]}}`
|
||||
if errs := labelErrors(Validate(labelsWorkDir(t, bad), lf)); len(errs) != 1 {
|
||||
t.Errorf("malformed label must be reported, got %v", errs)
|
||||
}
|
||||
}
|
||||
Vendored
+37
@@ -8,6 +8,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/m3tam3re/agent-lib/internal/discovery"
|
||||
"github.com/m3tam3re/agent-lib/internal/labels"
|
||||
"github.com/m3tam3re/agent-lib/internal/lockfile"
|
||||
)
|
||||
|
||||
@@ -34,6 +35,7 @@ func Validate(workDir string, lf *lockfile.Lockfile) Validation {
|
||||
v.checkExternalArea(workDir, name, src)
|
||||
}
|
||||
v.Errors = append(v.Errors, validateCollisions(workDir, lf)...)
|
||||
v.checkLabels(workDir, lf)
|
||||
sort.Slice(v.Errors, func(i, j int) bool {
|
||||
if v.Errors[i].Source != v.Errors[j].Source {
|
||||
return v.Errors[i].Source < v.Errors[j].Source
|
||||
@@ -44,6 +46,41 @@ func Validate(workDir string, lf *lockfile.Lockfile) Validation {
|
||||
return v
|
||||
}
|
||||
|
||||
// checkLabels validates the optional labels file: format rules (via the
|
||||
// labels parser) and that every name resolves to an item of any type —
|
||||
// own items, vendored items under their deployed names, MCP fragments.
|
||||
func (v *Validation) checkLabels(workDir string, lf *lockfile.Lockfile) {
|
||||
data, err := os.ReadFile(filepath.Join(workDir, labels.FileName))
|
||||
if err != nil {
|
||||
if !os.IsNotExist(err) {
|
||||
v.fail("", "labels", "reading %s: %v", labels.FileName, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
file, err := labels.Parse(data)
|
||||
if err != nil {
|
||||
v.fail("", "labels", "%v", err)
|
||||
return
|
||||
}
|
||||
own, err := ownDeployed(workDir)
|
||||
if err != nil {
|
||||
v.fail("", "labels", "scanning own items: %v", err)
|
||||
return
|
||||
}
|
||||
known := map[string]bool{}
|
||||
for _, m := range mergeIndex(own, lockfileDeployed(lf, "")) {
|
||||
for name := range m {
|
||||
known[name] = true
|
||||
}
|
||||
}
|
||||
for _, name := range file.Names() {
|
||||
if !known[name] {
|
||||
v.fail("", "labels", "%s: %q (labels %s) matches no item in the work repository",
|
||||
labels.FileName, name, strings.Join(file.LabelsOf(name), ", "))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (v *Validation) fail(source, rule, format string, args ...any) {
|
||||
v.Errors = append(v.Errors, ValidationError{
|
||||
Source: source,
|
||||
|
||||
Reference in new issue
Block a user