fix(client): harden label pinning and close review findings

- Resolve the Windows admin config via the ProgramData known folder
  instead of the user-controlled ProgramData variable, so a user cannot
  redirect the admin lookup and drop pinned labels
- vendor rename rewrites matching agent-lib.labels.json entries, so a
  renamed item keeps its labels instead of going to every client
- validate checks the labels file in repositories without a lockfile
- A kept modified copy of a deselected item is no longer drift in status,
  and the toast explains it as "no longer assigned to you"
- Labels parser rejects trailing data such as an extra closing brace
- Tests: admin pin wiring (config chain, --repo, admin as chosen config),
  reselect redeploy with byte-level no-op, status labels JSON, validate
  without lockfile, rename keeps labels
- README: document unreadable admin config, drift semantics, rename

Refs: agent_lib-fh4

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
m3ta-chironandClaude Opus 5.5 committed 2026-11-14 11:00:41 +01:00
1 parent 59735c3b24
commit 22458291d0
17 files changed
+296 -17

No files matched your search

+11 -5
View File
@@ -328,16 +328,22 @@ Clients opt in through `labels` in their config:
**Admin-pinned:** when the admin default config exists and sets `labels`,
that value applies no matter which config supplied `repo_url` — a user-level
config, `AGENT_LIB_CONFIG` or `--config` can neither widen nor drop it. An
admin config that exists but cannot be parsed aborts the run.
config, `AGENT_LIB_CONFIG` or `--config` can neither widen nor drop it. On
Windows the admin location is resolved through the ProgramData known folder,
not the user-controlled `ProgramData` variable. An admin config that exists
but cannot be read (including permission denied) or parsed aborts the run —
the admin's selection is unknown, so none is guessed.
Sync filters before planning. An item that is no longer selected follows
the upstream-deletion rules: unmodified copies are removed, locally modified
copies are kept with a warning (`--force` removes them); the reason reads
"not selected for this client's labels". A labels file that does not
"not selected for this client's labels". Such a kept copy blocks no
repository update and therefore does not count as drift in `status`. A labels file that does not
validate **aborts the sync before any change** — it never falls back to
delivering everything. Names that match no item only warn on the client;
`agent-lib validate` treats them as errors on the curator side.
delivering everything. Names that match no item only warn on clients that
carry labels; `agent-lib validate` treats them as errors on the curator side
(also in repositories without a lockfile). `vendor rename` rewrites matching
labels entries so a renamed item keeps its labels.
`sync` and `status` print the active selection
(`labels: sales (admin) — 12 item(s) not selected`); `status --json` adds a
+1 -1
View File
@@ -109,7 +109,7 @@ a separately authenticated repository.
unknown version) → **sync aborts before any change** with a clear
error. Never fall back to "deliver everything".
- A name that matches no item → warning on sync output and in
`status`, not fatal and no toast (the curator-side `validate` is the
`status` of labeled clients, not fatal and no toast (the curator-side `validate` is the
hard gate).
3. Drop items whose labels do not intersect the client labels before
hashing/planning (`internal/client/sync.go`, loop over
+1 -1
View File
@@ -6,6 +6,7 @@ require (
github.com/go-git/go-billy/v5 v5.9.1
github.com/go-git/go-git/v5 v5.19.2
github.com/spf13/cobra v1.10.2
golang.org/x/sys v0.46.0
)
require (
@@ -28,6 +29,5 @@ require (
github.com/xanzy/ssh-agent v0.3.3 // indirect
golang.org/x/crypto v0.53.0 // indirect
golang.org/x/net v0.56.0 // indirect
golang.org/x/sys v0.46.0 // indirect
gopkg.in/warnings.v0 v0.1.2 // indirect
)
+13 -1
View File
@@ -26,6 +26,18 @@ func loadLockfileOrFail(cmd *cobra.Command) *lockfile.Lockfile {
return lf
}
// loadLockfileForValidate is loadLockfileOrFail, except that a repository
// without a lockfile but with a labels file still gets its labels checked
// (own items only) instead of failing on the missing lockfile.
func loadLockfileForValidate(cmd *cobra.Command) *lockfile.Lockfile {
if _, err := os.Stat(filepath.Join(".", lockfile.FileName)); os.IsNotExist(err) {
if _, err := os.Stat(labels.FileName); err == nil {
return lockfile.New()
}
}
return loadLockfileOrFail(cmd)
}
func emitJSON(cmd *cobra.Command, v any) error {
enc := json.NewEncoder(cmd.OutOrStdout())
enc.SetIndent("", " ")
@@ -39,7 +51,7 @@ func newValidateCmd() *cobra.Command {
Short: "Check lockfile rules and external-area consistency offline",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
lf := loadLockfileOrFail(cmd)
lf := loadLockfileForValidate(cmd)
result := vendor.Validate(".", lf)
if asJSON {
return emitJSON(cmd, result)
+3 -5
View File
@@ -38,13 +38,11 @@ const (
)
// DefaultConfigPath returns the admin-protected config location per platform:
// ProgramData on Windows, /etc on Linux/macOS.
// the ProgramData known folder on Windows (resolved via the shell API, not
// the user-controlled environment variable), /etc on Linux/macOS.
func DefaultConfigPath() string {
if runtime.GOOS == "windows" {
if pd := os.Getenv("ProgramData"); pd != "" {
return filepath.Join(pd, "agent-lib", "config.json")
}
return `C:\ProgramData\agent-lib\config.json`
return filepath.Join(programDataDir(), "agent-lib", "config.json")
}
return "/etc/agent-lib/config.json"
}
+35
View File
@@ -263,3 +263,38 @@ func TestAdminConfigBrokenIsFatal(t *testing.T) {
t.Fatal("an unreadable admin config must abort: its label intent is unknown")
}
}
func TestResolveRunConfigAppliesAdminPin(t *testing.T) {
dir := t.TempDir()
admin := filepath.Join(dir, "admin.json")
writeRaw(t, admin, `{"repo_url":"r","labels":["finance"]}`)
orig := adminConfigPath
t.Cleanup(func() { adminConfigPath = orig })
adminConfigPath = func() string { return admin }
user := filepath.Join(dir, "user.json")
writeRaw(t, user, `{"repo_url":"r","labels":["sales","it"]}`)
cfg, err := resolveRunConfig(SyncOptions{ConfigPath: user})
if err != nil {
t.Fatal(err)
}
if cfg.LabelSource != "admin" || strings.Join(*cfg.Labels, ",") != "finance" {
t.Errorf("config-chain run: admin pin not applied, got %v (%s)", *cfg.Labels, cfg.LabelSource)
}
cfg, err = resolveRunConfig(SyncOptions{ConfigPath: user, RepoURL: "other"})
if err != nil {
t.Fatal(err)
}
if cfg.LabelSource != "admin" || strings.Join(*cfg.Labels, ",") != "finance" {
t.Errorf("--repo run: admin pin not applied, got %v (%s)", *cfg.Labels, cfg.LabelSource)
}
cfg, err = resolveRunConfig(SyncOptions{ConfigPath: admin})
if err != nil {
t.Fatal(err)
}
if cfg.LabelSource != "admin" {
t.Errorf("admin config as chosen config: source = %q", cfg.LabelSource)
}
}
+7
View File
@@ -35,6 +35,7 @@ type SyncReport struct {
func ExecutePlan(tree *gitsource.GitTree, plan []PlanEntry, manifest *Manifest, paths StatePaths, rev string, stdout io.Writer) (*SyncReport, error) {
report := &SyncReport{Revision: rev, Manifest: paths.Manifest}
var warnings []string
labelSkips := 0
for _, e := range plan {
key := manifestKey(e.Type, e.Name)
@@ -62,6 +63,9 @@ func ExecutePlan(tree *gitsource.GitTree, plan []PlanEntry, manifest *Manifest,
case ActSkip:
warnings = append(warnings, fmt.Sprintf("SKIP %s/%s: %s", e.Type, e.Name, e.Reason))
report.Skipped++
if IsLabelSkip(e) {
labelSkips++
}
case ActLeave:
warnings = append(warnings, fmt.Sprintf("LEAVE %s/%s: %s", e.Type, e.Name, e.Reason))
report.Left++
@@ -79,6 +83,9 @@ func ExecutePlan(tree *gitsource.GitTree, plan []PlanEntry, manifest *Manifest,
}
title := "agent-lib sync"
body := fmt.Sprintf("%d item(s) kept local: modifications blocked company updates. See the sync log for details.", report.Skipped+report.Left)
if labelSkips > 0 && labelSkips == report.Skipped && report.Left == 0 {
body = fmt.Sprintf("%d item(s) kept local: no longer assigned to you, but you modified them. See the sync log for details.", labelSkips)
}
if err := Notifier.Send(title, body); err != nil {
fmt.Fprintf(stdout, "warning: notification failed: %v\n", err)
}
+11 -1
View File
@@ -1,6 +1,9 @@
package client
import "sort"
import (
"sort"
"strings"
)
// Action is one step of a sync plan.
type Action string
@@ -20,6 +23,13 @@ const (
// ReasonNotSelected explains removals caused by the client's labels.
const ReasonNotSelected = "not selected for this client's labels"
// IsLabelSkip reports whether a skip keeps a modified copy of an item that
// is no longer selected for this client's labels. Such a copy blocks no
// repository update, so it is not drift.
func IsLabelSkip(e PlanEntry) bool {
return e.Action == ActSkip && strings.HasPrefix(e.Reason, ReasonNotSelected)
}
// PlanOptions tune planning. Force overwrites/removes locally modified
// managed items; Deselected holds manifest keys filtered out by labels.
type PlanOptions struct {
+6
View File
@@ -0,0 +1,6 @@
//go:build !windows
package client
// programDataDir is only meaningful on Windows.
func programDataDir() string { return "" }
+16
View File
@@ -0,0 +1,16 @@
//go:build windows
package client
import "golang.org/x/sys/windows"
// programDataDir resolves the ProgramData known folder through the shell
// API instead of the ProgramData environment variable: the variable is
// user-controlled, and the admin config pins labels — a user must not be
// able to point the admin lookup at a folder of their own.
func programDataDir() string {
if p, err := windows.KnownFolderPath(windows.FOLDERID_ProgramData, 0); err == nil && p != "" {
return p
}
return `C:\ProgramData`
}
+3
View File
@@ -51,6 +51,9 @@ func Status(opts SyncOptions) (*StatusReport, error) {
if rec := p.manifest.Items[manifestKey(e.Type, e.Name)]; rec != nil && rec.Hash == e.NewHash {
blocked = false
}
if IsLabelSkip(e) {
blocked = false
}
if blocked {
report.Drift = true
}
+6 -2
View File
@@ -37,6 +37,10 @@ type prepared struct {
labels *LabelSelection
}
// adminConfigPath locates the admin default config for label pinning;
// tests swap it to exercise the pin end to end.
var adminConfigPath = DefaultConfigPath
// 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.
@@ -171,7 +175,7 @@ func resolveRunConfig(opts SyncOptions) (*ClientConfig, error) {
return nil, err
}
cfg.FillTokenAuth()
if err := ApplyAdminLabels(cfg, DefaultConfigPath()); err != nil {
if err := ApplyAdminLabels(cfg, adminConfigPath()); err != nil {
return nil, err
}
return cfg, nil
@@ -188,7 +192,7 @@ func resolveRunConfig(opts SyncOptions) (*ClientConfig, error) {
cfg.Ref = opts.Ref
}
cfg.FillTokenAuth()
if err := ApplyAdminLabels(cfg, DefaultConfigPath()); err != nil {
if err := ApplyAdminLabels(cfg, adminConfigPath()); err != nil {
return nil, err
}
return cfg, nil
+100
View File
@@ -1,6 +1,7 @@
package e2e
import (
"encoding/json"
"os"
"path/filepath"
"strings"
@@ -164,3 +165,102 @@ func TestSyncLabelsUnknownNameWarns(t *testing.T) {
t.Errorf("sync must warn about the unknown name, got:\n%s", out)
}
}
func TestSyncLabelsReselectRedeploysAndIsByteStable(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"]}}`)
agent := filepath.Join(env.home, ".config/opencode/agents/helper.md")
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("helper is labeled dev and must not deploy for ops")
}
env.writeLabelConfig(t, `["ops","dev"]`)
if out, err := env.run(t); err != nil {
t.Fatalf("sync failed: %v\n%s", err, out)
}
if !exists(agent) {
t.Fatal("an item that becomes selected must deploy")
}
manifest := filepath.Join(env.stateDir, "manifest.json")
before, _ := os.ReadFile(manifest)
agentBefore, _ := os.ReadFile(agent)
if out, err := env.run(t); err != nil {
t.Fatalf("sync failed: %v\n%s", err, out)
}
after, _ := os.ReadFile(manifest)
agentAfter, _ := os.ReadFile(agent)
if string(before) != string(after) || string(agentBefore) != string(agentAfter) {
t.Error("a second run with labels must be a byte-level no-op")
}
}
func TestStatusLabelsJSONAndNoDriftForDeselectedCopy(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)
}
cmd := agentLibCmd("status", "--json", "--config", env.config)
cmd.Env = append(os.Environ(), "HOME="+env.home, "USERPROFILE="+env.home, "AGENT_LIB_STATE_DIR="+env.stateDir)
out, err := cmd.Output()
if err != nil {
t.Fatalf("a kept copy of a deselected item is not drift; status must exit 0: %v\n%s", err, out)
}
var report struct {
Drift bool `json:"problematic_drift"`
Labels *struct {
Client []string `json:"client"`
Source string `json:"source"`
File bool `json:"labels_file"`
NotSelected []string `json:"not_selected"`
} `json:"labels"`
}
if err := json.Unmarshal(out, &report); err != nil {
t.Fatalf("status --json not parseable: %v\n%s", err, out)
}
if report.Drift {
t.Error("deselected modified copy must not count as drift")
}
if report.Labels == nil || report.Labels.Source != "flag" || !report.Labels.File ||
strings.Join(report.Labels.Client, ",") != "ops" ||
strings.Join(report.Labels.NotSelected, ",") != "agents/helper" {
t.Errorf("unexpected labels object: %+v", report.Labels)
}
}
func TestValidateLabelsWithoutLockfile(t *testing.T) {
h := newHarness(t)
write := func(rel, content string) {
p := filepath.Join(h.workDir, rel)
os.MkdirAll(filepath.Dir(p), 0o755)
os.WriteFile(p, []byte(content), 0o644)
}
write("skills/alpha/SKILL.md", "---\nname: alpha\ndescription: a\n---\n")
write("agent-lib.labels.json", `{"version":1,"labels":{"dev":["alpha"]}}`)
if out, err := h.run(t, "validate"); err != nil || !strings.Contains(out, "agent-lib.labels.json valid") {
t.Fatalf("a repo without lockfile must still validate its labels: %v\n%s", err, out)
}
write("agent-lib.labels.json", `{"version":1,"labels":{"dev":["gamma"]}}`)
if out, err := h.run(t, "validate"); err == nil || !strings.Contains(out, `"gamma"`) {
t.Fatalf("an unknown name must fail validate: %v\n%s", err, out)
}
}
+2 -1
View File
@@ -12,6 +12,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"io"
"regexp"
"sort"
)
@@ -45,7 +46,7 @@ func Parse(data []byte) (*File, error) {
if err := dec.Decode(&f); err != nil {
return nil, fmt.Errorf("%s is not valid: %w", FileName, err)
}
if dec.More() {
if _, err := dec.Token(); err != io.EOF {
return nil, fmt.Errorf("%s is not valid: trailing data after the JSON object", FileName)
}
if f.Version != Version {
+1
View File
@@ -67,6 +67,7 @@ func TestParseRejects(t *testing.T) {
"empty list": `{"version":1,"labels":{"sales":[]}}`,
"empty name": `{"version":1,"labels":{"sales":[""]}}`,
"trailing data": `{"version":1,"labels":{}} {}`,
"trailing brace": `{"version":1,"labels":{}}}`,
}
for name, data := range cases {
if _, err := Parse([]byte(data)); err == nil {
+25
View File
@@ -0,0 +1,25 @@
package vendor
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestRenameLabelEntriesKeepsLabels(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "agent-lib.labels.json")
os.WriteFile(p, []byte(`{"version":1,"labels":{"sales":["old-name","other"],"dev":["old-name"]}}`), 0o644)
n, err := renameLabelEntries(dir, map[string]string{"old-name": "new-name"})
if err != nil || n != 2 {
t.Fatalf("want 2 entries renamed, got %d, %v", n, err)
}
data, _ := os.ReadFile(p)
if strings.Contains(string(data), "old-name") || strings.Count(string(data), "new-name") != 2 {
t.Errorf("entries not rewritten:\n%s", data)
}
if n, err := renameLabelEntries(t.TempDir(), map[string]string{"a": "b"}); err != nil || n != 0 {
t.Errorf("missing labels file must be a no-op, got %d, %v", n, err)
}
}
+55
View File
@@ -1,6 +1,7 @@
package vendor
import (
"encoding/json"
"fmt"
"io"
"os"
@@ -9,6 +10,7 @@ import (
"github.com/m3tam3re/agent-lib/internal/discovery"
"github.com/m3tam3re/agent-lib/internal/gitsource"
"github.com/m3tam3re/agent-lib/internal/labels"
"github.com/m3tam3re/agent-lib/internal/lockfile"
)
@@ -128,6 +130,17 @@ func Rename(workDir, name string, opts RenameOptions, stdout io.Writer) error {
if err := lf.Save(lockPath); err != nil {
return err
}
renamed := map[string]string{}
for _, id := range ids {
if before, after := deployedName(id, oldRenames), deployedName(id, newRenames); before != after {
renamed[before] = after
}
}
if n, err := renameLabelEntries(workDir, renamed); err != nil {
fmt.Fprintf(stdout, "warning: %s not updated: %v — fix the entries by hand\n", labels.FileName, err)
} else if n > 0 {
fmt.Fprintf(stdout, "%s: %d entries renamed so the items keep their labels\n", labels.FileName, n)
}
inSelection := idSet(selected)
fmt.Fprintf(stdout, "source %s: renames updated at pinned rev %s\n", name, short(src.Rev))
@@ -178,3 +191,45 @@ func boolSet(ids []string) map[string]bool {
}
return out
}
// renameLabelEntries rewrites labels-file entries from old to new deployed
// names. Without it a rename would silently drop an item's labels and widen
// its delivery to every client. Returns how many entries changed; a missing
// file is not an error.
func renameLabelEntries(workDir string, renamed map[string]string) (int, error) {
if len(renamed) == 0 {
return 0, nil
}
path := filepath.Join(workDir, labels.FileName)
data, err := os.ReadFile(path)
if os.IsNotExist(err) {
return 0, nil
}
if err != nil {
return 0, err
}
file, err := labels.Parse(data)
if err != nil {
return 0, err
}
changed := 0
for label, names := range file.Labels {
for i, n := range names {
if to, ok := renamed[n]; ok {
file.Labels[label][i] = to
changed++
}
}
}
if changed == 0 {
return 0, nil
}
out, err := json.MarshalIndent(struct {
Version int `json:"version"`
Labels map[string][]string `json:"labels"`
}{file.Version, file.Labels}, "", " ")
if err != nil {
return 0, err
}
return changed, os.WriteFile(path, append(out, '\n'), 0o644)
}