Compare commits
12
Commits
v0.1.0
...
ae316860e5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ae316860e5 | ||
|
|
59735c3b24 | ||
|
|
39952ceb02 | ||
|
|
d6821c6d7c | ||
|
|
f37c3dce5e | ||
|
|
0b91a8a2a7 | ||
|
|
e41ffa6a14 | ||
|
|
5e7d693699 | ||
|
|
a913baa496 | ||
|
|
0c779bc970 | ||
|
|
1ab97bff43 | ||
|
|
2017329015 |
No files matched your search
@@ -0,0 +1,80 @@
|
|||||||
|
---
|
||||||
|
name: beads
|
||||||
|
description: Use when working in a repository that uses bd or Beads for durable project task tracking, issue dependencies, blocker management, multi-session handoff, or shared work memory. Trigger when the user asks to find ready work, claim or close tasks, create follow-up work, inspect blockers, recover project context, or choose between local planning and persistent project tracking.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Beads
|
||||||
|
|
||||||
|
Use Beads as the shared project task system. Local plans, scratch files, and personal memories are useful, but they are not the durable source of truth for project work.
|
||||||
|
|
||||||
|
## First Step
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bd prime
|
||||||
|
```
|
||||||
|
|
||||||
|
If that prints nothing, check whether the repository has an active Beads workspace:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bd where
|
||||||
|
```
|
||||||
|
|
||||||
|
## Preferred Route
|
||||||
|
|
||||||
|
Use the `bd` CLI when shell access is available. It is the most compact and direct Beads interface.
|
||||||
|
|
||||||
|
## Core CLI Workflow
|
||||||
|
|
||||||
|
1. Find work:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bd ready
|
||||||
|
bd list --status=open
|
||||||
|
bd list --status=in_progress
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Inspect before editing:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bd show <id>
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Claim work atomically:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bd update <id> --claim
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Create durable follow-up work when implementation reveals new tasks:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bd create "Short title" --description="Why this exists and what needs to be done" --type=task --priority=2
|
||||||
|
```
|
||||||
|
|
||||||
|
5. Close completed work:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bd close <id> --reason="Completed"
|
||||||
|
```
|
||||||
|
|
||||||
|
## What Belongs In Beads
|
||||||
|
|
||||||
|
Use Beads for:
|
||||||
|
|
||||||
|
- shared project tasks
|
||||||
|
- blockers and dependencies
|
||||||
|
- discovered follow-up work
|
||||||
|
- work that must survive thread reset, compaction, or handoff
|
||||||
|
- status that another person or agent should be able to resume
|
||||||
|
|
||||||
|
Use agent-local planning tools only for the current turn's execution checklist. Do not treat them as shared project state.
|
||||||
|
|
||||||
|
## Rules
|
||||||
|
|
||||||
|
- Do not create markdown TODO files as the source of truth when Beads is available.
|
||||||
|
- Do not use `bd edit`; it opens an interactive editor. Use `bd update` flags instead.
|
||||||
|
- Prefer `--json` when parsing `bd` output programmatically.
|
||||||
|
- If hooks are installed, `bd prime` may already be injected. Run it manually when context is missing.
|
||||||
|
- Do not auto-close or mutate tasks unless the work is actually complete.
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
interface:
|
||||||
|
display_name: "Beads"
|
||||||
|
short_description: "Project task tracking with bd"
|
||||||
|
default_prompt: "Use $beads to inspect ready work and manage durable project tasks."
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"size":51360,"mtime_ns":1793863936779644645}
|
||||||
@@ -68,3 +68,10 @@ bd.db
|
|||||||
# They would override fork protection in .git/info/exclude.
|
# They would override fork protection in .git/info/exclude.
|
||||||
# Config files (metadata.json, config.yaml) are tracked by git by default
|
# Config files (metadata.json, config.yaml) are tracked by git by default
|
||||||
# since no pattern above ignores them.
|
# since no pattern above ignores them.
|
||||||
|
|
||||||
|
# Added by bd (missing required patterns)
|
||||||
|
*.gate.lock*
|
||||||
|
last_pull
|
||||||
|
proxieddb/
|
||||||
|
dolt-server-config.yaml
|
||||||
|
proxied_server_client_info.json
|
||||||
@@ -1 +1,5 @@
|
|||||||
no-git-ops: true
|
no-git-ops: true
|
||||||
|
sync:
|
||||||
|
remote: "git+ssh://gitea@code.m3ta.dev/m3tam3re/agent-lib.git"
|
||||||
|
export:
|
||||||
|
auto: true
|
||||||
Executable
+59
@@ -0,0 +1,59 @@
|
|||||||
|
#!/usr/bin/env sh
|
||||||
|
# --- BEGIN BEADS INTEGRATION v1.3.2 ---
|
||||||
|
# This section is managed by beads. Do not remove these markers.
|
||||||
|
if command -v bd >/dev/null 2>&1; then
|
||||||
|
export BD_GIT_HOOK=1
|
||||||
|
_bd_timeout=${BEADS_HOOK_TIMEOUT:-300}
|
||||||
|
case "$_bd_timeout" in
|
||||||
|
*[!0-9]*|'') _bd_timeout_invalid=1 ;;
|
||||||
|
*[1-9]*) _bd_timeout_invalid=0 ;;
|
||||||
|
*) _bd_timeout_invalid=1 ;;
|
||||||
|
esac
|
||||||
|
if [ "$_bd_timeout_invalid" -eq 1 ]; then
|
||||||
|
echo >&2 "beads: invalid BEADS_HOOK_TIMEOUT; using 300 seconds"
|
||||||
|
_bd_timeout=300
|
||||||
|
fi
|
||||||
|
_bd_timeout_backend=none
|
||||||
|
_bd_timeout_command=
|
||||||
|
for _bd_timeout_candidate in timeout gtimeout; do
|
||||||
|
if command -v "$_bd_timeout_candidate" >/dev/null 2>&1; then
|
||||||
|
if _bd_timeout_version="$("$_bd_timeout_candidate" --version 2>/dev/null)"; then
|
||||||
|
case "$_bd_timeout_version" in
|
||||||
|
"timeout (GNU coreutils) "*) _bd_timeout_command=$_bd_timeout_candidate; break ;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
if [ -n "$_bd_timeout_command" ]; then
|
||||||
|
_bd_timeout_backend=coreutils
|
||||||
|
if "$_bd_timeout_command" -- "$_bd_timeout" bd hooks run post-checkout "$@"; then
|
||||||
|
_bd_exit=0
|
||||||
|
else
|
||||||
|
_bd_exit=$?
|
||||||
|
fi
|
||||||
|
elif command -v perl >/dev/null 2>&1; then
|
||||||
|
_bd_timeout_backend=perl
|
||||||
|
if perl -e 'alarm shift; exec @ARGV' -- "$_bd_timeout" bd hooks run post-checkout "$@"; then
|
||||||
|
_bd_exit=0
|
||||||
|
else
|
||||||
|
_bd_exit=$?
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo >&2 "beads: hook 'post-checkout' running without timeout; install coreutils or perl to enable BEADS_HOOK_TIMEOUT"
|
||||||
|
if bd hooks run post-checkout "$@"; then
|
||||||
|
_bd_exit=0
|
||||||
|
else
|
||||||
|
_bd_exit=$?
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
if { [ "$_bd_timeout_backend" = coreutils ] && [ "$_bd_exit" -eq 124 ]; } || { [ "$_bd_timeout_backend" = perl ] && [ "$_bd_exit" -eq 142 ]; }; then
|
||||||
|
echo >&2 "beads: hook 'post-checkout' timed out after ${_bd_timeout}s — continuing without beads"
|
||||||
|
_bd_exit=0
|
||||||
|
fi
|
||||||
|
if [ "$_bd_exit" -eq 3 ]; then
|
||||||
|
echo >&2 "beads: database not initialized — skipping hook 'post-checkout'"
|
||||||
|
_bd_exit=0
|
||||||
|
fi
|
||||||
|
if [ "$_bd_exit" -ne 0 ]; then exit "$_bd_exit"; fi
|
||||||
|
fi
|
||||||
|
# --- END BEADS INTEGRATION v1.3.2 ---
|
||||||
Executable
+59
@@ -0,0 +1,59 @@
|
|||||||
|
#!/usr/bin/env sh
|
||||||
|
# --- BEGIN BEADS INTEGRATION v1.3.2 ---
|
||||||
|
# This section is managed by beads. Do not remove these markers.
|
||||||
|
if command -v bd >/dev/null 2>&1; then
|
||||||
|
export BD_GIT_HOOK=1
|
||||||
|
_bd_timeout=${BEADS_HOOK_TIMEOUT:-300}
|
||||||
|
case "$_bd_timeout" in
|
||||||
|
*[!0-9]*|'') _bd_timeout_invalid=1 ;;
|
||||||
|
*[1-9]*) _bd_timeout_invalid=0 ;;
|
||||||
|
*) _bd_timeout_invalid=1 ;;
|
||||||
|
esac
|
||||||
|
if [ "$_bd_timeout_invalid" -eq 1 ]; then
|
||||||
|
echo >&2 "beads: invalid BEADS_HOOK_TIMEOUT; using 300 seconds"
|
||||||
|
_bd_timeout=300
|
||||||
|
fi
|
||||||
|
_bd_timeout_backend=none
|
||||||
|
_bd_timeout_command=
|
||||||
|
for _bd_timeout_candidate in timeout gtimeout; do
|
||||||
|
if command -v "$_bd_timeout_candidate" >/dev/null 2>&1; then
|
||||||
|
if _bd_timeout_version="$("$_bd_timeout_candidate" --version 2>/dev/null)"; then
|
||||||
|
case "$_bd_timeout_version" in
|
||||||
|
"timeout (GNU coreutils) "*) _bd_timeout_command=$_bd_timeout_candidate; break ;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
if [ -n "$_bd_timeout_command" ]; then
|
||||||
|
_bd_timeout_backend=coreutils
|
||||||
|
if "$_bd_timeout_command" -- "$_bd_timeout" bd hooks run post-merge "$@"; then
|
||||||
|
_bd_exit=0
|
||||||
|
else
|
||||||
|
_bd_exit=$?
|
||||||
|
fi
|
||||||
|
elif command -v perl >/dev/null 2>&1; then
|
||||||
|
_bd_timeout_backend=perl
|
||||||
|
if perl -e 'alarm shift; exec @ARGV' -- "$_bd_timeout" bd hooks run post-merge "$@"; then
|
||||||
|
_bd_exit=0
|
||||||
|
else
|
||||||
|
_bd_exit=$?
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo >&2 "beads: hook 'post-merge' running without timeout; install coreutils or perl to enable BEADS_HOOK_TIMEOUT"
|
||||||
|
if bd hooks run post-merge "$@"; then
|
||||||
|
_bd_exit=0
|
||||||
|
else
|
||||||
|
_bd_exit=$?
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
if { [ "$_bd_timeout_backend" = coreutils ] && [ "$_bd_exit" -eq 124 ]; } || { [ "$_bd_timeout_backend" = perl ] && [ "$_bd_exit" -eq 142 ]; }; then
|
||||||
|
echo >&2 "beads: hook 'post-merge' timed out after ${_bd_timeout}s — continuing without beads"
|
||||||
|
_bd_exit=0
|
||||||
|
fi
|
||||||
|
if [ "$_bd_exit" -eq 3 ]; then
|
||||||
|
echo >&2 "beads: database not initialized — skipping hook 'post-merge'"
|
||||||
|
_bd_exit=0
|
||||||
|
fi
|
||||||
|
if [ "$_bd_exit" -ne 0 ]; then exit "$_bd_exit"; fi
|
||||||
|
fi
|
||||||
|
# --- END BEADS INTEGRATION v1.3.2 ---
|
||||||
Executable
+59
@@ -0,0 +1,59 @@
|
|||||||
|
#!/usr/bin/env sh
|
||||||
|
# --- BEGIN BEADS INTEGRATION v1.3.2 ---
|
||||||
|
# This section is managed by beads. Do not remove these markers.
|
||||||
|
if command -v bd >/dev/null 2>&1; then
|
||||||
|
export BD_GIT_HOOK=1
|
||||||
|
_bd_timeout=${BEADS_HOOK_TIMEOUT:-300}
|
||||||
|
case "$_bd_timeout" in
|
||||||
|
*[!0-9]*|'') _bd_timeout_invalid=1 ;;
|
||||||
|
*[1-9]*) _bd_timeout_invalid=0 ;;
|
||||||
|
*) _bd_timeout_invalid=1 ;;
|
||||||
|
esac
|
||||||
|
if [ "$_bd_timeout_invalid" -eq 1 ]; then
|
||||||
|
echo >&2 "beads: invalid BEADS_HOOK_TIMEOUT; using 300 seconds"
|
||||||
|
_bd_timeout=300
|
||||||
|
fi
|
||||||
|
_bd_timeout_backend=none
|
||||||
|
_bd_timeout_command=
|
||||||
|
for _bd_timeout_candidate in timeout gtimeout; do
|
||||||
|
if command -v "$_bd_timeout_candidate" >/dev/null 2>&1; then
|
||||||
|
if _bd_timeout_version="$("$_bd_timeout_candidate" --version 2>/dev/null)"; then
|
||||||
|
case "$_bd_timeout_version" in
|
||||||
|
"timeout (GNU coreutils) "*) _bd_timeout_command=$_bd_timeout_candidate; break ;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
if [ -n "$_bd_timeout_command" ]; then
|
||||||
|
_bd_timeout_backend=coreutils
|
||||||
|
if "$_bd_timeout_command" -- "$_bd_timeout" bd hooks run pre-commit "$@"; then
|
||||||
|
_bd_exit=0
|
||||||
|
else
|
||||||
|
_bd_exit=$?
|
||||||
|
fi
|
||||||
|
elif command -v perl >/dev/null 2>&1; then
|
||||||
|
_bd_timeout_backend=perl
|
||||||
|
if perl -e 'alarm shift; exec @ARGV' -- "$_bd_timeout" bd hooks run pre-commit "$@"; then
|
||||||
|
_bd_exit=0
|
||||||
|
else
|
||||||
|
_bd_exit=$?
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo >&2 "beads: hook 'pre-commit' running without timeout; install coreutils or perl to enable BEADS_HOOK_TIMEOUT"
|
||||||
|
if bd hooks run pre-commit "$@"; then
|
||||||
|
_bd_exit=0
|
||||||
|
else
|
||||||
|
_bd_exit=$?
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
if { [ "$_bd_timeout_backend" = coreutils ] && [ "$_bd_exit" -eq 124 ]; } || { [ "$_bd_timeout_backend" = perl ] && [ "$_bd_exit" -eq 142 ]; }; then
|
||||||
|
echo >&2 "beads: hook 'pre-commit' timed out after ${_bd_timeout}s — continuing without beads"
|
||||||
|
_bd_exit=0
|
||||||
|
fi
|
||||||
|
if [ "$_bd_exit" -eq 3 ]; then
|
||||||
|
echo >&2 "beads: database not initialized — skipping hook 'pre-commit'"
|
||||||
|
_bd_exit=0
|
||||||
|
fi
|
||||||
|
if [ "$_bd_exit" -ne 0 ]; then exit "$_bd_exit"; fi
|
||||||
|
fi
|
||||||
|
# --- END BEADS INTEGRATION v1.3.2 ---
|
||||||
Executable
+59
@@ -0,0 +1,59 @@
|
|||||||
|
#!/usr/bin/env sh
|
||||||
|
# --- BEGIN BEADS INTEGRATION v1.3.2 ---
|
||||||
|
# This section is managed by beads. Do not remove these markers.
|
||||||
|
if command -v bd >/dev/null 2>&1; then
|
||||||
|
export BD_GIT_HOOK=1
|
||||||
|
_bd_timeout=${BEADS_HOOK_TIMEOUT:-300}
|
||||||
|
case "$_bd_timeout" in
|
||||||
|
*[!0-9]*|'') _bd_timeout_invalid=1 ;;
|
||||||
|
*[1-9]*) _bd_timeout_invalid=0 ;;
|
||||||
|
*) _bd_timeout_invalid=1 ;;
|
||||||
|
esac
|
||||||
|
if [ "$_bd_timeout_invalid" -eq 1 ]; then
|
||||||
|
echo >&2 "beads: invalid BEADS_HOOK_TIMEOUT; using 300 seconds"
|
||||||
|
_bd_timeout=300
|
||||||
|
fi
|
||||||
|
_bd_timeout_backend=none
|
||||||
|
_bd_timeout_command=
|
||||||
|
for _bd_timeout_candidate in timeout gtimeout; do
|
||||||
|
if command -v "$_bd_timeout_candidate" >/dev/null 2>&1; then
|
||||||
|
if _bd_timeout_version="$("$_bd_timeout_candidate" --version 2>/dev/null)"; then
|
||||||
|
case "$_bd_timeout_version" in
|
||||||
|
"timeout (GNU coreutils) "*) _bd_timeout_command=$_bd_timeout_candidate; break ;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
if [ -n "$_bd_timeout_command" ]; then
|
||||||
|
_bd_timeout_backend=coreutils
|
||||||
|
if "$_bd_timeout_command" -- "$_bd_timeout" bd hooks run pre-push "$@"; then
|
||||||
|
_bd_exit=0
|
||||||
|
else
|
||||||
|
_bd_exit=$?
|
||||||
|
fi
|
||||||
|
elif command -v perl >/dev/null 2>&1; then
|
||||||
|
_bd_timeout_backend=perl
|
||||||
|
if perl -e 'alarm shift; exec @ARGV' -- "$_bd_timeout" bd hooks run pre-push "$@"; then
|
||||||
|
_bd_exit=0
|
||||||
|
else
|
||||||
|
_bd_exit=$?
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo >&2 "beads: hook 'pre-push' running without timeout; install coreutils or perl to enable BEADS_HOOK_TIMEOUT"
|
||||||
|
if bd hooks run pre-push "$@"; then
|
||||||
|
_bd_exit=0
|
||||||
|
else
|
||||||
|
_bd_exit=$?
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
if { [ "$_bd_timeout_backend" = coreutils ] && [ "$_bd_exit" -eq 124 ]; } || { [ "$_bd_timeout_backend" = perl ] && [ "$_bd_exit" -eq 142 ]; }; then
|
||||||
|
echo >&2 "beads: hook 'pre-push' timed out after ${_bd_timeout}s — continuing without beads"
|
||||||
|
_bd_exit=0
|
||||||
|
fi
|
||||||
|
if [ "$_bd_exit" -eq 3 ]; then
|
||||||
|
echo >&2 "beads: database not initialized — skipping hook 'pre-push'"
|
||||||
|
_bd_exit=0
|
||||||
|
fi
|
||||||
|
if [ "$_bd_exit" -ne 0 ]; then exit "$_bd_exit"; fi
|
||||||
|
fi
|
||||||
|
# --- END BEADS INTEGRATION v1.3.2 ---
|
||||||
Executable
+59
@@ -0,0 +1,59 @@
|
|||||||
|
#!/usr/bin/env sh
|
||||||
|
# --- BEGIN BEADS INTEGRATION v1.3.2 ---
|
||||||
|
# This section is managed by beads. Do not remove these markers.
|
||||||
|
if command -v bd >/dev/null 2>&1; then
|
||||||
|
export BD_GIT_HOOK=1
|
||||||
|
_bd_timeout=${BEADS_HOOK_TIMEOUT:-300}
|
||||||
|
case "$_bd_timeout" in
|
||||||
|
*[!0-9]*|'') _bd_timeout_invalid=1 ;;
|
||||||
|
*[1-9]*) _bd_timeout_invalid=0 ;;
|
||||||
|
*) _bd_timeout_invalid=1 ;;
|
||||||
|
esac
|
||||||
|
if [ "$_bd_timeout_invalid" -eq 1 ]; then
|
||||||
|
echo >&2 "beads: invalid BEADS_HOOK_TIMEOUT; using 300 seconds"
|
||||||
|
_bd_timeout=300
|
||||||
|
fi
|
||||||
|
_bd_timeout_backend=none
|
||||||
|
_bd_timeout_command=
|
||||||
|
for _bd_timeout_candidate in timeout gtimeout; do
|
||||||
|
if command -v "$_bd_timeout_candidate" >/dev/null 2>&1; then
|
||||||
|
if _bd_timeout_version="$("$_bd_timeout_candidate" --version 2>/dev/null)"; then
|
||||||
|
case "$_bd_timeout_version" in
|
||||||
|
"timeout (GNU coreutils) "*) _bd_timeout_command=$_bd_timeout_candidate; break ;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
if [ -n "$_bd_timeout_command" ]; then
|
||||||
|
_bd_timeout_backend=coreutils
|
||||||
|
if "$_bd_timeout_command" -- "$_bd_timeout" bd hooks run prepare-commit-msg "$@"; then
|
||||||
|
_bd_exit=0
|
||||||
|
else
|
||||||
|
_bd_exit=$?
|
||||||
|
fi
|
||||||
|
elif command -v perl >/dev/null 2>&1; then
|
||||||
|
_bd_timeout_backend=perl
|
||||||
|
if perl -e 'alarm shift; exec @ARGV' -- "$_bd_timeout" bd hooks run prepare-commit-msg "$@"; then
|
||||||
|
_bd_exit=0
|
||||||
|
else
|
||||||
|
_bd_exit=$?
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo >&2 "beads: hook 'prepare-commit-msg' running without timeout; install coreutils or perl to enable BEADS_HOOK_TIMEOUT"
|
||||||
|
if bd hooks run prepare-commit-msg "$@"; then
|
||||||
|
_bd_exit=0
|
||||||
|
else
|
||||||
|
_bd_exit=$?
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
if { [ "$_bd_timeout_backend" = coreutils ] && [ "$_bd_exit" -eq 124 ]; } || { [ "$_bd_timeout_backend" = perl ] && [ "$_bd_exit" -eq 142 ]; }; then
|
||||||
|
echo >&2 "beads: hook 'prepare-commit-msg' timed out after ${_bd_timeout}s — continuing without beads"
|
||||||
|
_bd_exit=0
|
||||||
|
fi
|
||||||
|
if [ "$_bd_exit" -eq 3 ]; then
|
||||||
|
echo >&2 "beads: database not initialized — skipping hook 'prepare-commit-msg'"
|
||||||
|
_bd_exit=0
|
||||||
|
fi
|
||||||
|
if [ "$_bd_exit" -ne 0 ]; then exit "$_bd_exit"; fi
|
||||||
|
fi
|
||||||
|
# --- END BEADS INTEGRATION v1.3.2 ---
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
{"_type":"issue","id":"agent_lib-fh4","title":"Client labels: deliver items only to clients with a matching label","description":"Design: docs/proposals/client-labels.md (proposed 14.11.2026).\n\nOptional repo file agent-lib.labels.json ({version:1, labels:{label:[item names]}}); unlabeled items go to everyone. Client config gains 'labels'; absent = no filtering, [] = only unlabeled. Admin default config's labels win over user/env config. Invalid labels file aborts sync before any disk change. Filter before planning (internal/client/sync.go loop over inv.Deployable()); deselected items reuse the upstream-deleted path with reason 'not selected for this client's labels'. status --json reports labels/source/filtered; validate checks the file (names resolve incl. MCP). Revises README non-goal 'client-side selection or profiles'.\n\nConsumer: az-agent-defaults (agent-lib.labels.json already prepared) + az-fleet agent_lib role.","acceptance_criteria":"Tests per proposal section 'Tests' green; README documents file format, config field, admin precedence; release tagged; second sync with labels is a byte-level no-op.","notes":"14.11.: implementiert auf Branch feat/client-labels (internal/labels, config labels + ApplyAdminLabels, Filter in prepare(), PlanOptions.Deselected, status/sync-Ausgabe, validate-Check, README/fleet-handoff). go test ./... grün, Windows-Build ok, echter Sync gegen az-agent-defaults geprüft. Offen: Review, Merge, Release-Tag. Nicht committet.","status":"in_progress","priority":2,"issue_type":"feature","assignee":"m3ta-chiron","owner":"m3ta-chiron@agentmail.to","created_at":"2026-11-14T09:11:57Z","created_by":"m3ta-chiron","updated_at":"2026-11-14T09:31:19Z","started_at":"2026-11-14T09:24:34Z","lease_expires_at":"2026-11-14T09:29:34Z","heartbeat_at":"2026-11-14T09:24:34Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||||
|
{"_type":"issue","id":"agent-lib-u5t","title":"vendor rename: Vendor-Skills nachträglich umbenennen","description":"Kuratoren sollen vendored Items nachträglich (nicht nur bei vendor add) benutzerfreundlich umbenennen können. Neuer Befehl vendor rename \u003csource\u003e up=new / --reset; umbenannte Skills bekommen den name: im SKILL.md-Frontmatter angepasst (OpenCode verlangt name == Ordnername).","status":"closed","priority":2,"issue_type":"feature","assignee":"m3ta-chiron","owner":"m3ta-chiron@agentmail.to","created_at":"2026-11-05T07:43:31Z","created_by":"m3ta-chiron","updated_at":"2026-11-05T07:45:14Z","started_at":"2026-11-05T07:43:50Z","closed_at":"2026-11-05T07:45:14Z","close_reason":"vendor rename implemented with SKILL.md name rewrite, tests + README","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||||
{"_type":"issue","id":"agent-lib-4wx.11","title":"Deliver end-to-end documentation and release gate","description":"Finish the MVP by documenting the full workflow and proving it through an offline end-to-end acceptance path. The slice should provide README content, quickstart, CLI reference, Home Manager examples, security/trust notes, troubleshooting, and a release gate that demonstrates init, Source add, inspect, snippet, Home Manager eval/render, target Manifests, and a green offline check.","acceptance_criteria":"- Documentation covers installation, quickstart, CLI reference, Home Manager configuration, Lockfile behavior, discovery conventions, security/trust model, troubleshooting, MVP scope, and non-goals\n- An offline end-to-end fixture workflow demonstrates initialization, Source discovery, selection, Pi and Opencode Rendered output, target Manifests, and no unmanaged overwrites\n- nix flake check is green without external network access and verifies the MVP acceptance criteria","notes":"E2E fixture check green. All steps verified: init creates lockfile, discover finds all items, lockfile has rev/narHash/HM-compatible schema, inspect/snippet/validate commands work, managed-file protection present. nix flake check passes.","status":"closed","priority":2,"issue_type":"feature","assignee":"m3ta-chiron","owner":"p@m3ta.dev","created_at":"2026-05-27T17:50:02Z","created_by":"m3tam3re","updated_at":"2026-05-28T08:13:15Z","started_at":"2026-05-28T07:46:50Z","closed_at":"2026-05-28T08:13:15Z","labels":["ready-for-agent"],"dependencies":[{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx","type":"parent-child","created_at":"2026-05-27T19:50:01Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.1","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.10","type":"blocks","created_at":"2026-05-27T19:50:03Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.2","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.3","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.4","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.5","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.6","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.7","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.8","type":"blocks","created_at":"2026-05-27T19:50:03Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.9","type":"blocks","created_at":"2026-05-27T19:50:03Z","created_by":"m3tam3re","metadata":"{}"}],"dependency_count":10,"dependent_count":0,"comment_count":0}
|
{"_type":"issue","id":"agent-lib-4wx.11","title":"Deliver end-to-end documentation and release gate","description":"Finish the MVP by documenting the full workflow and proving it through an offline end-to-end acceptance path. The slice should provide README content, quickstart, CLI reference, Home Manager examples, security/trust notes, troubleshooting, and a release gate that demonstrates init, Source add, inspect, snippet, Home Manager eval/render, target Manifests, and a green offline check.","acceptance_criteria":"- Documentation covers installation, quickstart, CLI reference, Home Manager configuration, Lockfile behavior, discovery conventions, security/trust model, troubleshooting, MVP scope, and non-goals\n- An offline end-to-end fixture workflow demonstrates initialization, Source discovery, selection, Pi and Opencode Rendered output, target Manifests, and no unmanaged overwrites\n- nix flake check is green without external network access and verifies the MVP acceptance criteria","notes":"E2E fixture check green. All steps verified: init creates lockfile, discover finds all items, lockfile has rev/narHash/HM-compatible schema, inspect/snippet/validate commands work, managed-file protection present. nix flake check passes.","status":"closed","priority":2,"issue_type":"feature","assignee":"m3ta-chiron","owner":"p@m3ta.dev","created_at":"2026-05-27T17:50:02Z","created_by":"m3tam3re","updated_at":"2026-05-28T08:13:15Z","started_at":"2026-05-28T07:46:50Z","closed_at":"2026-05-28T08:13:15Z","labels":["ready-for-agent"],"dependencies":[{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx","type":"parent-child","created_at":"2026-05-27T19:50:01Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.1","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.10","type":"blocks","created_at":"2026-05-27T19:50:03Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.2","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.3","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.4","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.5","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.6","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.7","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.8","type":"blocks","created_at":"2026-05-27T19:50:03Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.9","type":"blocks","created_at":"2026-05-27T19:50:03Z","created_by":"m3tam3re","metadata":"{}"}],"dependency_count":10,"dependent_count":0,"comment_count":0}
|
||||||
{"_type":"issue","id":"agent-lib-4wx.10","title":"Complete CLI operational workflows and snippets","description":"Complete the day-to-day CLI workflow around existing Sources, Profiles, and Targets. The slice should make update/review/switch workflows practical with added/removed Item reports, offline and fetch validation modes, minimal and full Nix snippets, JSON output, non-interactive defaults, and an optional interactive entry point without automatic Nix edits.","acceptance_criteria":"- source update and source update --all report added and removed Items without changing Home Manager selection\n- validate runs offline by default, validate --fetch performs explicit reachability checks, and list/inspect/validate support stable JSON output\n- snippet emits both minimal Profile include snippets and full example configuration, while the CLI remains non-interactive by default and never edits Nix files","status":"closed","priority":2,"issue_type":"feature","assignee":"m3ta-chiron","owner":"p@m3ta.dev","created_at":"2026-05-27T17:49:57Z","created_by":"m3tam3re","updated_at":"2026-05-28T07:46:28Z","started_at":"2026-05-28T07:39:36Z","closed_at":"2026-05-28T07:46:28Z","close_reason":"Closed","labels":["ready-for-agent"],"dependencies":[{"issue_id":"agent-lib-4wx.10","depends_on_id":"agent-lib-4wx","type":"parent-child","created_at":"2026-05-27T19:49:56Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.10","depends_on_id":"agent-lib-4wx.3","type":"blocks","created_at":"2026-05-27T19:49:57Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.10","depends_on_id":"agent-lib-4wx.5","type":"blocks","created_at":"2026-05-27T19:49:57Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.10","depends_on_id":"agent-lib-4wx.7","type":"blocks","created_at":"2026-05-27T19:49:57Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.10","depends_on_id":"agent-lib-4wx.8","type":"blocks","created_at":"2026-05-27T19:49:57Z","created_by":"m3tam3re","metadata":"{}"}],"dependency_count":4,"dependent_count":1,"comment_count":0}
|
{"_type":"issue","id":"agent-lib-4wx.10","title":"Complete CLI operational workflows and snippets","description":"Complete the day-to-day CLI workflow around existing Sources, Profiles, and Targets. The slice should make update/review/switch workflows practical with added/removed Item reports, offline and fetch validation modes, minimal and full Nix snippets, JSON output, non-interactive defaults, and an optional interactive entry point without automatic Nix edits.","acceptance_criteria":"- source update and source update --all report added and removed Items without changing Home Manager selection\n- validate runs offline by default, validate --fetch performs explicit reachability checks, and list/inspect/validate support stable JSON output\n- snippet emits both minimal Profile include snippets and full example configuration, while the CLI remains non-interactive by default and never edits Nix files","status":"closed","priority":2,"issue_type":"feature","assignee":"m3ta-chiron","owner":"p@m3ta.dev","created_at":"2026-05-27T17:49:57Z","created_by":"m3tam3re","updated_at":"2026-05-28T07:46:28Z","started_at":"2026-05-28T07:39:36Z","closed_at":"2026-05-28T07:46:28Z","close_reason":"Closed","labels":["ready-for-agent"],"dependencies":[{"issue_id":"agent-lib-4wx.10","depends_on_id":"agent-lib-4wx","type":"parent-child","created_at":"2026-05-27T19:49:56Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.10","depends_on_id":"agent-lib-4wx.3","type":"blocks","created_at":"2026-05-27T19:49:57Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.10","depends_on_id":"agent-lib-4wx.5","type":"blocks","created_at":"2026-05-27T19:49:57Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.10","depends_on_id":"agent-lib-4wx.7","type":"blocks","created_at":"2026-05-27T19:49:57Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.10","depends_on_id":"agent-lib-4wx.8","type":"blocks","created_at":"2026-05-27T19:49:57Z","created_by":"m3tam3re","metadata":"{}"}],"dependency_count":4,"dependent_count":1,"comment_count":0}
|
||||||
{"_type":"issue","id":"agent-lib-4wx.9","title":"Apply item-specific patches and deployment safety controls","description":"Add safety and customization controls around selected Items, including item-specific patches, target-specific overrides, targetName collision handling, editable-copy escape hatch, license propagation, and configurable incompatibility policy. The slice should prove that patches affect only copied Artifacts and never mutate original source content.","acceptance_criteria":"- Item-specific patches apply only to copied Artifacts, while original Canonical source content remains immutable and auditable\n- targetName overrides, target-specific enable/disable overrides, collision detection, and onIncompatible policies are enforced for both Pi and Opencode\n- License files, provenance headers for rendered Markdown, preserved file permissions, and editable-copy deployment mode are covered by tests","status":"closed","priority":2,"issue_type":"feature","assignee":"m3ta-chiron","owner":"p@m3ta.dev","created_at":"2026-05-27T17:49:51Z","created_by":"m3tam3re","updated_at":"2026-05-28T07:39:25Z","started_at":"2026-05-28T07:25:13Z","closed_at":"2026-05-28T07:39:25Z","close_reason":"Closed","labels":["ready-for-agent"],"dependencies":[{"issue_id":"agent-lib-4wx.9","depends_on_id":"agent-lib-4wx","type":"parent-child","created_at":"2026-05-27T19:49:51Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.9","depends_on_id":"agent-lib-4wx.7","type":"blocks","created_at":"2026-05-27T19:49:52Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.9","depends_on_id":"agent-lib-4wx.8","type":"blocks","created_at":"2026-05-27T19:49:52Z","created_by":"m3tam3re","metadata":"{}"}],"dependency_count":2,"dependent_count":1,"comment_count":0}
|
{"_type":"issue","id":"agent-lib-4wx.9","title":"Apply item-specific patches and deployment safety controls","description":"Add safety and customization controls around selected Items, including item-specific patches, target-specific overrides, targetName collision handling, editable-copy escape hatch, license propagation, and configurable incompatibility policy. The slice should prove that patches affect only copied Artifacts and never mutate original source content.","acceptance_criteria":"- Item-specific patches apply only to copied Artifacts, while original Canonical source content remains immutable and auditable\n- targetName overrides, target-specific enable/disable overrides, collision detection, and onIncompatible policies are enforced for both Pi and Opencode\n- License files, provenance headers for rendered Markdown, preserved file permissions, and editable-copy deployment mode are covered by tests","status":"closed","priority":2,"issue_type":"feature","assignee":"m3ta-chiron","owner":"p@m3ta.dev","created_at":"2026-05-27T17:49:51Z","created_by":"m3tam3re","updated_at":"2026-05-28T07:39:25Z","started_at":"2026-05-28T07:25:13Z","closed_at":"2026-05-28T07:39:25Z","close_reason":"Closed","labels":["ready-for-agent"],"dependencies":[{"issue_id":"agent-lib-4wx.9","depends_on_id":"agent-lib-4wx","type":"parent-child","created_at":"2026-05-27T19:49:51Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.9","depends_on_id":"agent-lib-4wx.7","type":"blocks","created_at":"2026-05-27T19:49:52Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.9","depends_on_id":"agent-lib-4wx.8","type":"blocks","created_at":"2026-05-27T19:49:52Z","created_by":"m3tam3re","metadata":"{}"}],"dependency_count":2,"dependent_count":1,"comment_count":0}
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"hooks": {
|
||||||
|
"SessionStart": [
|
||||||
|
{
|
||||||
|
"hooks": [
|
||||||
|
{
|
||||||
|
"command": "bd prime --hook-json",
|
||||||
|
"type": "command"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"matcher": ""
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
[features]
|
||||||
|
hooks = true
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
{
|
||||||
|
"hooks": {
|
||||||
|
"PostCompact": [
|
||||||
|
{
|
||||||
|
"hooks": [
|
||||||
|
{
|
||||||
|
"command": "bd codex-hook PostCompact",
|
||||||
|
"statusMessage": "Scheduling Beads context refresh",
|
||||||
|
"type": "command"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"matcher": "manual|auto"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"PreCompact": [
|
||||||
|
{
|
||||||
|
"hooks": [
|
||||||
|
{
|
||||||
|
"command": "bd codex-hook PreCompact",
|
||||||
|
"statusMessage": "Checking Beads context",
|
||||||
|
"type": "command"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"matcher": "manual|auto"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"SessionStart": [
|
||||||
|
{
|
||||||
|
"hooks": [
|
||||||
|
{
|
||||||
|
"command": "bd codex-hook SessionStart",
|
||||||
|
"statusMessage": "Loading Beads context",
|
||||||
|
"type": "command"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"matcher": "startup|resume|clear"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"UserPromptSubmit": [
|
||||||
|
{
|
||||||
|
"hooks": [
|
||||||
|
{
|
||||||
|
"command": "bd codex-hook UserPromptSubmit",
|
||||||
|
"statusMessage": "Refreshing Beads context",
|
||||||
|
"type": "command"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"hooks": {
|
||||||
|
"postToolUse": [
|
||||||
|
{
|
||||||
|
"command": "bd cursor-hook postToolUse"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"preCompact": [
|
||||||
|
{
|
||||||
|
"command": "bd cursor-hook preCompact"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"sessionStart": [
|
||||||
|
{
|
||||||
|
"command": "bd cursor-hook sessionStart"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"version": 1
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
---
|
||||||
|
alwaysApply: true
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- BEGIN BEADS INTEGRATION -->
|
||||||
|
<!-- Auto-generated by 'bd setup cursor'. Content between these markers is managed by bd. -->
|
||||||
|
|
||||||
|
# Beads Issue Tracking
|
||||||
|
|
||||||
|
This project uses [Beads (bd)](https://github.com/gastownhall/beads) for issue tracking.
|
||||||
|
|
||||||
|
## Core Rules
|
||||||
|
|
||||||
|
- Track ALL work in bd (never use markdown TODOs or comment-based task lists)
|
||||||
|
- Use `bd ready` to find available work
|
||||||
|
- Use `bd create` to track new issues/tasks/bugs
|
||||||
|
- Treat commit, push, and Dolt remote sync as policy-controlled handoff actions
|
||||||
|
- Run `bd prime` for complete workflow context (SSOT for operational commands)
|
||||||
|
- Default to conservative git authority: report status and proposed commands unless the user, orchestrator, or repository profile explicitly authorizes commit/sync/push
|
||||||
|
|
||||||
|
## Quick Reference
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bd prime # Load complete workflow context (SSOT)
|
||||||
|
bd ready # Show issues ready to work (no blockers)
|
||||||
|
bd list --status=open # List all open issues
|
||||||
|
bd create "title" -t task -p 2 # Create new issue
|
||||||
|
bd update <id> --claim # Claim work atomically
|
||||||
|
bd unclaim <id> # Release stuck issue (agent crashed)
|
||||||
|
bd close <id> # Mark complete
|
||||||
|
bd dep add <issue> <depends-on> # Add dependency
|
||||||
|
bd dolt push # Sync with remote when authorized
|
||||||
|
```
|
||||||
|
|
||||||
|
## Workflow
|
||||||
|
|
||||||
|
1. Check for ready work: `bd ready`
|
||||||
|
2. Claim an issue atomically: `bd update <id> --claim`
|
||||||
|
3. Do the work
|
||||||
|
4. Mark complete: `bd close <id>`
|
||||||
|
5. Handoff: report changed files, validation, issue status, and any proposed commit/sync/push commands
|
||||||
|
|
||||||
|
## Issue Types
|
||||||
|
|
||||||
|
- `bug` - Something broken
|
||||||
|
- `feature` - New functionality
|
||||||
|
- `task` - Work item (tests, docs, refactoring)
|
||||||
|
- `epic` - Large feature with subtasks
|
||||||
|
- `chore` - Maintenance (dependencies, tooling)
|
||||||
|
|
||||||
|
## Priorities
|
||||||
|
|
||||||
|
- `0` - Critical (security, data loss, broken builds)
|
||||||
|
- `1` - High (major features, important bugs)
|
||||||
|
- `2` - Medium (default, nice-to-have)
|
||||||
|
- `3` - Low (polish, optimization)
|
||||||
|
- `4` - Backlog (future ideas)
|
||||||
|
|
||||||
|
## Context Loading
|
||||||
|
|
||||||
|
Run `bd prime` to get complete workflow documentation in AI-optimized format.
|
||||||
|
`bd prime` is the single source of truth for operational commands and session workflow.
|
||||||
|
|
||||||
|
For detailed docs: see AGENTS.md, the beads quickstart
|
||||||
|
(https://github.com/gastownhall/beads/blob/main/docs/getting-started/quickstart.md), or run `bd --help`
|
||||||
|
|
||||||
|
<!-- END BEADS INTEGRATION -->
|
||||||
@@ -6,6 +6,7 @@
|
|||||||
# Go build artifacts
|
# Go build artifacts
|
||||||
agent-lib
|
agent-lib
|
||||||
agent-lib.exe
|
agent-lib.exe
|
||||||
|
agent-libw.exe
|
||||||
dist/
|
dist/
|
||||||
*.test
|
*.test
|
||||||
*.out
|
*.out
|
||||||
@@ -24,3 +25,7 @@ coverage.*
|
|||||||
# Local env overrides (never commit)
|
# Local env overrides (never commit)
|
||||||
.env
|
.env
|
||||||
.env.local
|
.env.local
|
||||||
|
|
||||||
|
# Beads / Dolt files (added by bd init)
|
||||||
|
.beads/proxieddb/
|
||||||
|
*.gate.lock*
|
||||||
+29
-9
@@ -3,10 +3,21 @@ version: 2
|
|||||||
project_name: agent-lib
|
project_name: agent-lib
|
||||||
|
|
||||||
# Releases gehen an die eigene Gitea-Instanz (NICHT GitHub):
|
# Releases gehen an die eigene Gitea-Instanz (NICHT GitHub):
|
||||||
# GITEA_URL=https://code.m3ta.dev
|
# GITEA_TOKEN=<token mit repository-write> als Umgebungsvariable
|
||||||
# GITEA_TOKEN=<token mit repository-write>
|
# Owner/Name sind explizit gesetzt, weil das SCP-Stil-Remote
|
||||||
# Repo/Owner werden aus dem origin-Remote abgeleitet
|
# (gitea@code.m3ta.dev:m3tam3re/agent-lib.git) fuer die automatische
|
||||||
# (gitea@code.m3ta.dev:m3tam3re/agent-lib.git).
|
# Ableitung unzuverlaessig ist.
|
||||||
|
gitea_urls:
|
||||||
|
api: https://code.m3ta.dev/api/v1
|
||||||
|
download: https://code.m3ta.dev
|
||||||
|
|
||||||
|
release:
|
||||||
|
draft: false
|
||||||
|
prerelease: auto
|
||||||
|
mode: append
|
||||||
|
gitea:
|
||||||
|
owner: m3tam3re
|
||||||
|
name: agent-lib
|
||||||
|
|
||||||
before:
|
before:
|
||||||
hooks:
|
hooks:
|
||||||
@@ -29,6 +40,18 @@ builds:
|
|||||||
ldflags:
|
ldflags:
|
||||||
- -s -w -X github.com/m3tam3re/agent-lib/internal/version.Version={{.Version}}
|
- -s -w -X github.com/m3tam3re/agent-lib/internal/version.Version={{.Version}}
|
||||||
binary: agent-lib
|
binary: agent-lib
|
||||||
|
# GUI-Subsystem-Variante fuer die Aufgabenplanung: oeffnet kein
|
||||||
|
# Konsolenfenster, dafuer auch keine Ausgabe auf stdout/stderr.
|
||||||
|
- id: agent-libw
|
||||||
|
env:
|
||||||
|
- CGO_ENABLED=0
|
||||||
|
goos:
|
||||||
|
- windows
|
||||||
|
goarch:
|
||||||
|
- amd64
|
||||||
|
ldflags:
|
||||||
|
- -s -w -H=windowsgui -X github.com/m3tam3re/agent-lib/internal/version.Version={{.Version}}
|
||||||
|
binary: agent-libw
|
||||||
|
|
||||||
checksum:
|
checksum:
|
||||||
name_template: "checksums.txt"
|
name_template: "checksums.txt"
|
||||||
@@ -42,11 +65,8 @@ archives:
|
|||||||
# Explizit stabil, damit Fleet-Download-URLs vorhersehbar bleiben:
|
# Explizit stabil, damit Fleet-Download-URLs vorhersehbar bleiben:
|
||||||
# .../releases/download/<tag>/agent-lib_<os>_<arch>.<ext>
|
# .../releases/download/<tag>/agent-lib_<os>_<arch>.<ext>
|
||||||
name_template: "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}"
|
name_template: "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}"
|
||||||
|
# Das Windows-Zip enthaelt zusaetzlich agent-libw.exe.
|
||||||
release:
|
allow_different_binary_count: true
|
||||||
draft: false
|
|
||||||
prerelease: auto
|
|
||||||
mode: append
|
|
||||||
|
|
||||||
changelog:
|
changelog:
|
||||||
sort: asc
|
sort: asc
|
||||||
|
|||||||
@@ -0,0 +1,128 @@
|
|||||||
|
# Agent Instructions
|
||||||
|
|
||||||
|
This project uses **bd** (beads) for issue tracking. Run `bd prime` for full workflow context.
|
||||||
|
|
||||||
|
> **Architecture in one line:** Issues live in a local Dolt database
|
||||||
|
> (`.beads/dolt/`); cross-machine sync uses `bd dolt push/pull` (a
|
||||||
|
> git-compatible protocol), stored under `refs/dolt/data` on your git
|
||||||
|
> remote — separate from `refs/heads/*` where your code lives.
|
||||||
|
> `.beads/issues.jsonl` is a passive export, not the wire protocol.
|
||||||
|
>
|
||||||
|
> See [sync-concepts](https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md)
|
||||||
|
> for the one-screen overview and anti-patterns (don't treat JSONL as the
|
||||||
|
> source of truth; don't `bd import` during normal operation; don't
|
||||||
|
> reach for third-party Dolt hosting before trying the default).
|
||||||
|
|
||||||
|
## Quick Reference
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bd ready # Find available work
|
||||||
|
bd show <id> # View issue details
|
||||||
|
bd update <id> --claim # Claim work atomically
|
||||||
|
bd close <id> # Complete work
|
||||||
|
bd dolt push # Push beads data to remote
|
||||||
|
```
|
||||||
|
|
||||||
|
## Non-Interactive Shell Commands
|
||||||
|
|
||||||
|
**ALWAYS use non-interactive flags** with file operations to avoid hanging on confirmation prompts.
|
||||||
|
|
||||||
|
Shell commands like `cp`, `mv`, and `rm` may be aliased to include `-i` (interactive) mode on some systems, causing the agent to hang indefinitely waiting for y/n input.
|
||||||
|
|
||||||
|
**Use these forms instead:**
|
||||||
|
```bash
|
||||||
|
# Force overwrite without prompting
|
||||||
|
cp -f source dest # NOT: cp source dest
|
||||||
|
mv -f source dest # NOT: mv source dest
|
||||||
|
rm -f file # NOT: rm file
|
||||||
|
|
||||||
|
# For recursive operations
|
||||||
|
rm -rf directory # NOT: rm -r directory
|
||||||
|
cp -rf source dest # NOT: cp -r source dest
|
||||||
|
```
|
||||||
|
|
||||||
|
**Other commands that may prompt:**
|
||||||
|
- `scp` - use `-o BatchMode=yes` for non-interactive
|
||||||
|
- `ssh` - use `-o BatchMode=yes` to fail instead of prompting
|
||||||
|
- `apt-get` - use `-y` flag
|
||||||
|
- `brew` - use `HOMEBREW_NO_AUTO_UPDATE=1` env var
|
||||||
|
|
||||||
|
<!-- BEGIN BEADS INTEGRATION v:1 profile:minimal hash:46cd31e7 -->
|
||||||
|
## Beads Issue Tracker
|
||||||
|
|
||||||
|
This project uses **bd (beads)** for issue tracking. Run `bd prime` to see full workflow context and commands.
|
||||||
|
|
||||||
|
### Quick Reference
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bd ready # Find available work
|
||||||
|
bd show <id> # View issue details
|
||||||
|
bd update <id> --claim # Claim work
|
||||||
|
bd close <id> # Complete work
|
||||||
|
```
|
||||||
|
|
||||||
|
### Rules
|
||||||
|
|
||||||
|
- Use `bd` for ALL task tracking — do NOT use TodoWrite, TaskCreate, or markdown TODO lists
|
||||||
|
- Run `bd prime` for detailed command reference and session close protocol
|
||||||
|
- Use `bd remember` for persistent knowledge — do NOT use MEMORY.md files
|
||||||
|
|
||||||
|
**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md for details and anti-patterns.
|
||||||
|
|
||||||
|
## Agent Context Profiles
|
||||||
|
|
||||||
|
The managed Beads block is task-tracking guidance, not permission to override repository, user, or orchestrator instructions.
|
||||||
|
|
||||||
|
- **Conservative (default)**: Use `bd` for task tracking. Do not run git commits, git pushes, or Dolt remote sync unless explicitly asked. At handoff, report changed files, validation, and suggested next commands.
|
||||||
|
- **Minimal**: Keep tool instruction files as pointers to `bd prime`; use the same conservative git policy unless active instructions say otherwise.
|
||||||
|
- **Team-maintainer**: Only when the repository explicitly opts in, agents may close beads, run quality gates, commit, and push as part of session close. A current "do not commit" or "do not push" instruction still wins.
|
||||||
|
|
||||||
|
## Session Completion
|
||||||
|
|
||||||
|
This protocol applies when ending a Beads implementation workflow. It is subordinate to explicit user, repository, and orchestrator instructions.
|
||||||
|
|
||||||
|
1. **File issues for remaining work** - Create beads for anything that needs follow-up
|
||||||
|
2. **Run quality gates** (if code changed) - Tests, linters, builds
|
||||||
|
3. **Update issue status** - Close finished work, update in-progress items
|
||||||
|
4. **Handle git/sync by active profile**:
|
||||||
|
```bash
|
||||||
|
# Conservative/minimal/default: report status and proposed commands; wait for approval.
|
||||||
|
git status
|
||||||
|
|
||||||
|
# Team-maintainer opt-in only, unless current instructions forbid it:
|
||||||
|
git pull --rebase
|
||||||
|
bd dolt push
|
||||||
|
git push
|
||||||
|
git status
|
||||||
|
```
|
||||||
|
5. **Hand off** - Summarize changes, validation, issue status, and any blocked sync/commit/push step
|
||||||
|
|
||||||
|
**Critical rules:**
|
||||||
|
- Explicit user or orchestrator instructions override this Beads block.
|
||||||
|
- Do not commit or push without clear authority from the active profile or the current user request.
|
||||||
|
- If a required sync or push is blocked, stop and report the exact command and error.
|
||||||
|
<!-- END BEADS INTEGRATION -->
|
||||||
|
|
||||||
|
<!-- BEGIN BEADS CODEX SETUP: generated by bd setup codex -->
|
||||||
|
## Beads Issue Tracker
|
||||||
|
|
||||||
|
Use Beads (`bd`) for durable task tracking in repositories that include it. Use the `beads` skill at `.agents/skills/beads/SKILL.md` (project install) or `~/.agents/skills/beads/SKILL.md` (global install) for Beads workflow guidance, then use the `bd` CLI for issue operations.
|
||||||
|
|
||||||
|
### Quick Reference
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bd ready # Find available work
|
||||||
|
bd show <id> # View issue details
|
||||||
|
bd update <id> --claim # Claim work
|
||||||
|
bd close <id> # Complete work
|
||||||
|
bd prime # Refresh Beads context
|
||||||
|
```
|
||||||
|
|
||||||
|
### Rules
|
||||||
|
|
||||||
|
- Use `bd` for all task tracking; do not create markdown TODO lists.
|
||||||
|
- Run `bd prime` when Beads context is missing or stale. Codex 0.129.0+ can load Beads context automatically through native hooks; use `/hooks` to inspect or toggle them.
|
||||||
|
- Keep persistent project memory in Beads via `bd remember`; do not create ad hoc memory files.
|
||||||
|
|
||||||
|
**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md for details and anti-patterns.
|
||||||
|
<!-- END BEADS CODEX SETUP -->
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
# Project Instructions for AI Agents
|
||||||
|
|
||||||
|
This file provides instructions and context for AI coding agents working on this project.
|
||||||
|
|
||||||
|
<!-- BEGIN BEADS INTEGRATION v:1 profile:minimal hash:1105d646 -->
|
||||||
|
## Beads Issue Tracker
|
||||||
|
|
||||||
|
This project uses **bd (beads)** for issue tracking. Run `bd prime` to see full workflow context and commands.
|
||||||
|
|
||||||
|
### Quick Reference
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bd ready # Find available work
|
||||||
|
bd show <id> # View issue details
|
||||||
|
bd update <id> --claim # Claim work
|
||||||
|
bd close <id> # Complete work
|
||||||
|
```
|
||||||
|
|
||||||
|
### Rules
|
||||||
|
|
||||||
|
- Use `bd` for ALL task tracking — do NOT use TodoWrite, TaskCreate, or markdown TODO lists
|
||||||
|
- Run `bd prime` for detailed command reference and session close protocol
|
||||||
|
- Use `bd remember` for persistent knowledge — do NOT use MEMORY.md files
|
||||||
|
|
||||||
|
**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md for details and anti-patterns.
|
||||||
|
|
||||||
|
## Agent Context Profiles
|
||||||
|
|
||||||
|
The managed Beads block is task-tracking guidance, not permission to override repository, user, or orchestrator instructions.
|
||||||
|
|
||||||
|
- **Conservative (default)**: Use `bd` for task tracking. Do not run git commits, git pushes, or Dolt remote sync unless explicitly asked. At handoff, report changed files, validation, and suggested next commands.
|
||||||
|
- **Minimal**: Keep tool instruction files as pointers to `bd prime`; use the same conservative git policy unless active instructions say otherwise.
|
||||||
|
- **Team-maintainer**: Only when the repository explicitly opts in, agents may close beads, run quality gates, commit, and push as part of session close. A current "do not commit" or "do not push" instruction still wins.
|
||||||
|
|
||||||
|
## Session Completion
|
||||||
|
|
||||||
|
This protocol applies when ending a Beads implementation workflow. It is subordinate to explicit user, repository, and orchestrator instructions.
|
||||||
|
|
||||||
|
1. **File issues for remaining work** - Create beads for anything that needs follow-up
|
||||||
|
2. **Run quality gates** (if code changed) - Tests, linters, builds
|
||||||
|
3. **Update issue status** - Close finished work, update in-progress items
|
||||||
|
4. **Handle git/sync by active profile**:
|
||||||
|
```bash
|
||||||
|
# Conservative/minimal/default: report status and proposed commands; wait for approval.
|
||||||
|
git status
|
||||||
|
|
||||||
|
# Team-maintainer opt-in only, unless current instructions forbid it:
|
||||||
|
git pull --rebase
|
||||||
|
git push
|
||||||
|
git status
|
||||||
|
```
|
||||||
|
5. **Hand off** - Summarize changes, validation, issue status, and any blocked sync/commit/push step
|
||||||
|
|
||||||
|
**Critical rules:**
|
||||||
|
- Explicit user or orchestrator instructions override this Beads block.
|
||||||
|
- Do not commit or push without clear authority from the active profile or the current user request.
|
||||||
|
- If a required sync or push is blocked, stop and report the exact command and error.
|
||||||
|
<!-- END BEADS INTEGRATION -->
|
||||||
|
|
||||||
|
|
||||||
|
## Build & Test
|
||||||
|
|
||||||
|
_Add your build and test commands here_
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Example:
|
||||||
|
# npm install
|
||||||
|
# npm test
|
||||||
|
```
|
||||||
|
|
||||||
|
## Architecture Overview
|
||||||
|
|
||||||
|
_Add a brief overview of your project architecture_
|
||||||
|
|
||||||
|
## Conventions & Patterns
|
||||||
|
|
||||||
|
_Add your project-specific conventions here_
|
||||||
@@ -45,6 +45,7 @@ agents/<id>.md own OpenCode agents
|
|||||||
mcp/<id>.yaml own MCP fragments (never deployed by the binary)
|
mcp/<id>.yaml own MCP fragments (never deployed by the binary)
|
||||||
external/<source>/<type>/ vendored content, mirrors the same four types
|
external/<source>/<type>/ vendored content, mirrors the same four types
|
||||||
agent-lib.lock.json lockfile v2 — pins every source
|
agent-lib.lock.json lockfile v2 — pins every source
|
||||||
|
agent-lib.labels.json optional — restricts items to labeled clients
|
||||||
```
|
```
|
||||||
|
|
||||||
This layout is **exactly** what OpenCode natively consumes — agent-lib is
|
This layout is **exactly** what OpenCode natively consumes — agent-lib is
|
||||||
@@ -89,11 +90,23 @@ executed.
|
|||||||
- Default: vendor **everything** (`mode: all`).
|
- Default: vendor **everything** (`mode: all`).
|
||||||
- `--include a,b,c` switches the source to **include mode**: only those ids
|
- `--include a,b,c` switches the source to **include mode**: only those ids
|
||||||
arrive, and new upstream items do **not** arrive automatically.
|
arrive, and new upstream items do **not** arrive automatically.
|
||||||
|
- `--exclude a,b,c` keeps **all mode** minus those ids — for taking the
|
||||||
|
majority of a source while dropping a few items.
|
||||||
|
- `--types skills,commands` (**allow-list**) and `--exclude-types agents,mcp`
|
||||||
|
(**deny-list**) filter whole content types. The filter is stored as
|
||||||
|
`exclude_types` in the lockfile and **survives updates**: new upstream items
|
||||||
|
of an excluded type never enter the work repository. `--types` covering all
|
||||||
|
four types normalizes to no filter; excluding all four fails at the
|
||||||
|
zero-selection guard.
|
||||||
- Hard errors, enforced by `vendor add`, `vendor update`, `vendor select`
|
- Hard errors, enforced by `vendor add`, `vendor update`, `vendor select`
|
||||||
and `validate`:
|
and `validate`:
|
||||||
- `all` combined with an include list → error
|
- `all` combined with an include list → error
|
||||||
- an exclude list without `all` → error (not supported in v2 selections)
|
- an exclude list without `all` → error (not supported in v2 selections)
|
||||||
- an include entry that no longer exists upstream → error naming the item
|
- an include or exclude entry that no longer exists upstream → error naming the item
|
||||||
|
- `--include` combined with `--exclude` → error
|
||||||
|
- `--types` combined with `--exclude-types` → error
|
||||||
|
- unknown type names → error listing `skills, commands, agents, mcp`
|
||||||
|
- an include entry belonging to a type the type filter excludes → error
|
||||||
|
|
||||||
(`vendor select` changes selections later — see
|
(`vendor select` changes selections later — see
|
||||||
[Changing your selection later](#changing-your-selection-later) below.)
|
[Changing your selection later](#changing-your-selection-later) below.)
|
||||||
@@ -107,6 +120,7 @@ advancing the pinned revision (that is `vendor update`'s job):
|
|||||||
agent-lib vendor select superpowers --add tdd,brainstorm # include mode: grow
|
agent-lib vendor select superpowers --add tdd,brainstorm # include mode: grow
|
||||||
agent-lib vendor select superpowers --remove review,debug # include mode: shrink
|
agent-lib vendor select superpowers --remove review,debug # include mode: shrink
|
||||||
agent-lib vendor select superpowers --remove review # all mode: move to exclude
|
agent-lib vendor select superpowers --remove review # all mode: move to exclude
|
||||||
|
agent-lib vendor select superpowers --types skills # replace the type filter
|
||||||
agent-lib vendor select superpowers --mode all # reset: take everything again
|
agent-lib vendor select superpowers --mode all # reset: take everything again
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -116,8 +130,11 @@ agent-lib vendor select superpowers --mode all # reset: take everyth
|
|||||||
- **all mode**: `--remove` moves ids onto the exclude list (lockfile v2
|
- **all mode**: `--remove` moves ids onto the exclude list (lockfile v2
|
||||||
supports exclude in all mode) and deletes their folders; `--add` is a hard
|
supports exclude in all mode) and deletes their folders; `--add` is a hard
|
||||||
error — everything is already selected.
|
error — everything is already selected.
|
||||||
- `--mode all` clears include/exclude and re-materializes the full pinned
|
- `--types` / `--exclude-types` **replace** the content-type filter
|
||||||
upstream, reporting what appeared.
|
(same semantics as on `vendor add`); when neither flag is passed, the
|
||||||
|
stored filter stays as-is.
|
||||||
|
- `--mode all` clears include/exclude **and the type filter** and
|
||||||
|
re-materializes the full pinned upstream, reporting what appeared.
|
||||||
|
|
||||||
Every select re-runs the collision checks and honors the lockfile rename map
|
Every select re-runs the collision checks and honors the lockfile rename map
|
||||||
— you can hand-add a rename for a not-yet-selected item, then `--add` it
|
— you can hand-add a rename for a not-yet-selected item, then `--add` it
|
||||||
@@ -137,6 +154,32 @@ agent-lib vendor add superpowers "$URL" --rename review=superpowers-review
|
|||||||
The on-disk folder always carries exactly the deployed name. Renaming onto
|
The on-disk folder always carries exactly the deployed name. Renaming onto
|
||||||
another collision is an error.
|
another collision is an error.
|
||||||
|
|
||||||
|
### Friendlier names for your users
|
||||||
|
|
||||||
|
Renames are not only for collisions — use them to give vendored items names
|
||||||
|
your colleagues recognize. `vendor rename` changes them at any time, without
|
||||||
|
moving the pinned revision or the selection:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
agent-lib vendor rename superpowers brainstorming=ideen-sammeln tdd=test-first
|
||||||
|
agent-lib vendor rename superpowers --reset tdd # back to the upstream id
|
||||||
|
agent-lib vendor rename superpowers # list current renames
|
||||||
|
```
|
||||||
|
|
||||||
|
- The rename map lives in the lockfile and survives `vendor update` and
|
||||||
|
`vendor select`.
|
||||||
|
- A renamed skill gets the `name:` in its `SKILL.md` frontmatter rewritten to
|
||||||
|
the new folder name (OpenCode requires both to match and shows that name).
|
||||||
|
Commands and agents are renamed via their file name only.
|
||||||
|
- Skill names must be 1–64 lowercase letters, digits and single hyphens
|
||||||
|
(`code-review`, not `Code Review`). No name of any type may contain path
|
||||||
|
separators or start with a dot.
|
||||||
|
- Renaming an id that is not selected yet is allowed; it applies once the
|
||||||
|
item is added via `vendor select --add`.
|
||||||
|
- On the next `agent-lib sync`, clients receive the item under the new name;
|
||||||
|
the old name is removed from their machine like any upstream deletion
|
||||||
|
(locally modified copies stay, as usual).
|
||||||
|
|
||||||
### The maintenance loop
|
### The maintenance loop
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@@ -196,8 +239,16 @@ repository, the local manifest and the on-disk content:
|
|||||||
- upstream deleted & unmodified → **remove**
|
- upstream deleted & unmodified → **remove**
|
||||||
- upstream deleted & modified → **skip + warn** — your version stays
|
- upstream deleted & modified → **skip + warn** — your version stays
|
||||||
|
|
||||||
|
With `--force` the two skip cases turn into **update** and **remove** —
|
||||||
|
the repository version wins over local modifications. Unmanaged items
|
||||||
|
(leave + warn) are never touched, even with `--force`; neither are paths
|
||||||
|
occupied by items agent-lib never deployed.
|
||||||
|
|
||||||
Sync is idempotent (a second run is a byte-level no-op) and fails cleanly:
|
Sync is idempotent (a second run is a byte-level no-op) and fails cleanly:
|
||||||
an unreachable repository never leaves a half-deployed machine.
|
an unreachable repository never leaves a half-deployed machine. The default
|
||||||
|
branch is resolved from the remote's advertised `HEAD`, so a sync without
|
||||||
|
`--ref` always tracks the server's current default branch — even after the
|
||||||
|
cache has been re-fetched many times.
|
||||||
|
|
||||||
### Configuration
|
### Configuration
|
||||||
|
|
||||||
@@ -241,6 +292,68 @@ agent-lib sync --repo https://github.com/you/your-agent-content.git
|
|||||||
The work repository must be a committed git repository (sync pulls it
|
The work repository must be a committed git repository (sync pulls it
|
||||||
read-only via go-git; local uncommitted state is ignored).
|
read-only via go-git; local uncommitted state is ignored).
|
||||||
|
|
||||||
|
### Client labels
|
||||||
|
|
||||||
|
Not every client needs every item. Restrict items to clients that carry a
|
||||||
|
matching label with an optional `agent-lib.labels.json` at the work
|
||||||
|
repository root:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"labels": {
|
||||||
|
"sales": ["crm-agent", "quote-writer"],
|
||||||
|
"finance": ["officecli-financial-model", "crm-agent"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Unlabeled items go to every client.** Only restricted items appear in
|
||||||
|
the file; a new item needs no entry to reach everyone.
|
||||||
|
- Entries are deployed item names (after renames) and match across types —
|
||||||
|
one entry covers a skill and a command of the same name. MCP fragment
|
||||||
|
names are allowed too (fleet tooling can scope MCP from the same file;
|
||||||
|
the binary never deploys MCP).
|
||||||
|
- An item under several labels reaches clients with any of them.
|
||||||
|
- Labels match `^[a-z0-9][a-z0-9-]*$`; lists must be non-empty; unknown
|
||||||
|
keys and unknown versions are errors.
|
||||||
|
|
||||||
|
Clients opt in through `labels` in their config:
|
||||||
|
|
||||||
|
| `labels` | Delivered |
|
||||||
|
|---|---|
|
||||||
|
| absent | everything — no filtering (default, backward compatible) |
|
||||||
|
| `[]` | unlabeled items only |
|
||||||
|
| `["sales", "lead"]` | unlabeled items plus items labeled `sales` or `lead` |
|
||||||
|
|
||||||
|
**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. 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". 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 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
|
||||||
|
`labels` object with `client`, `source`, `labels_file`, `not_selected` and
|
||||||
|
`unknown_names`.
|
||||||
|
|
||||||
|
Labels are a relevance filter, **not access control**: every client still
|
||||||
|
fetches the whole revision into its cache. Keep confidential material in a
|
||||||
|
separately authenticated repository.
|
||||||
|
|
||||||
### Notifications
|
### Notifications
|
||||||
|
|
||||||
On Windows, a toast fires when (and only when) a sync kept local
|
On Windows, a toast fires when (and only when) a sync kept local
|
||||||
@@ -272,10 +385,11 @@ flag that drives the non-zero exit code — suitable for headless drift checks.
|
|||||||
| `error: … include entry "x" not found upstream` | Typo, or the item was renamed/removed upstream. Fix the lockfile include list, or re-add with a corrected `--include`. |
|
| `error: … include entry "x" not found upstream` | Typo, or the item was renamed/removed upstream. Fix the lockfile include list, or re-add with a corrected `--include`. |
|
||||||
| `error: … collides with own skills "x"` | Deployed-name collision. Add `--rename <upstream>=<deployed>` (add) or fix the rename map (update). |
|
| `error: … collides with own skills "x"` | Deployed-name collision. Add `--rename <upstream>=<deployed>` (add) or fix the rename map (update). |
|
||||||
| `validate` reports tree/lockfile divergence | Someone edited `external/` by hand. Re-run `vendor update <source>` to restore the pinned state. |
|
| `validate` reports tree/lockfile divergence | Someone edited `external/` by hand. Re-run `vendor update <source>` to restore the pinned state. |
|
||||||
| Skill didn't update, `skipped (local modifications kept): 1` | Working as designed — you edited the deployed item. Restore the company version by deleting the local copy and re-syncing. |
|
| Skill didn't update, `skipped (local modifications kept): 1` | Working as designed — you edited the deployed item. Run `agent-lib sync --force` to overwrite local modifications with the repository version, or delete the local copy and re-sync. |
|
||||||
| `status` exits 1 | Local modifications block repository updates (or occupy names the repo needs). See `status` output for the item list. |
|
| `status` exits 1 | Local modifications block repository updates (or occupy names the repo needs). See `status` output for the item list. |
|
||||||
| Sync fails with clone/fetch error | Work repository unreachable, or token expired. Previous local state remains intact; fix config/network and re-run. |
|
| Sync fails with clone/fetch error | Work repository unreachable, or token expired. Previous local state remains intact; fix config/network and re-run. |
|
||||||
| No toast on Windows | Toasts need an interactive user session — the scheduled task must run as the logged-in user, not SYSTEM. |
|
| No toast on Windows | Toasts need an interactive user session — the scheduled task must run as the logged-in user, not SYSTEM. |
|
||||||
|
| Terminal window flashes on scheduled sync (Windows) | The task runs the console program `agent-lib.exe`. Point it at `agent-libw.exe sync` from the same zip: same commands, no window, no output. |
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
@@ -296,7 +410,10 @@ In scope: vendoring with selection/renames into any git work repository;
|
|||||||
OpenCode-only deployment with three-state protection; toast notifications;
|
OpenCode-only deployment with three-state protection; toast notifications;
|
||||||
goreleaser/GitHub release pipeline.
|
goreleaser/GitHub release pipeline.
|
||||||
|
|
||||||
Not in scope: client-side selection or profiles, additional targets (Pi,
|
Client-side selection is limited to label filtering (see Client labels) —
|
||||||
|
no per-client profiles, overrides or inheritance.
|
||||||
|
|
||||||
|
Not in scope: additional targets (Pi,
|
||||||
Hermes, Crush, Amp), MCP merge/vault (fleet-controller concern), binary
|
Hermes, Crush, Amp), MCP merge/vault (fleet-controller concern), binary
|
||||||
self-update, git submodule sources, migration tooling from the Python-era
|
self-update, git submodule sources, migration tooling from the Python-era
|
||||||
lockfile.
|
lockfile.
|
||||||
+14
-1
@@ -27,7 +27,8 @@ the external areas).
|
|||||||
|
|
||||||
- Source of truth: GitHub releases of `m3tam3re/agent-lib`.
|
- Source of truth: GitHub releases of `m3tam3re/agent-lib`.
|
||||||
- Artifacts: `agent-lib_{windows_amd64,linux_amd64,linux_arm64,darwin_amd64,darwin_arm64}`
|
- Artifacts: `agent-lib_{windows_amd64,linux_amd64,linux_arm64,darwin_amd64,darwin_arm64}`
|
||||||
plus `checksums.txt` (tar.gz archives; windows is a zip).
|
plus `checksums.txt` (tar.gz archives; windows is a zip containing
|
||||||
|
`agent-lib.exe` and the windowless `agent-libw.exe`).
|
||||||
- Fleet pins an exact release tag (installer-pin pattern already used for
|
- Fleet pins an exact release tag (installer-pin pattern already used for
|
||||||
other tools). **No self-update exists in the binary** — binary updates are
|
other tools). **No self-update exists in the binary** — binary updates are
|
||||||
exclusively fleet rollouts. Content updates are pulled by the binary itself.
|
exclusively fleet rollouts. Content updates are pulled by the binary itself.
|
||||||
@@ -55,6 +56,10 @@ root-owned, mode 0644).
|
|||||||
- Employees must be able to read the config (sync runs in their context) but
|
- Employees must be able to read the config (sync runs in their context) but
|
||||||
must not be able to alter it.
|
must not be able to alter it.
|
||||||
- Per-run overrides for testing: `--config <path>` or `AGENT_LIB_CONFIG`.
|
- Per-run overrides for testing: `--config <path>` or `AGENT_LIB_CONFIG`.
|
||||||
|
- Optional `"labels": ["<label>", ...]` selects labeled content for this
|
||||||
|
client (README, "Client labels"). Labels in this admin config are pinned:
|
||||||
|
user-level configs cannot override them. Omit the field to deliver
|
||||||
|
everything; `[]` delivers unlabeled items only.
|
||||||
|
|
||||||
Local state (manifest, cached bare repo, sync log) lives per-user:
|
Local state (manifest, cached bare repo, sync log) lives per-user:
|
||||||
`%LocalAppData%\agent-lib` on Windows, `~/.local/state/agent-lib` on Linux
|
`%LocalAppData%\agent-lib` on Windows, `~/.local/state/agent-lib` on Linux
|
||||||
@@ -68,6 +73,12 @@ Local state (manifest, cached bare repo, sync log) lives per-user:
|
|||||||
against the user's profile.
|
against the user's profile.
|
||||||
2. Windows toast notifications require an interactive user session. A task
|
2. Windows toast notifications require an interactive user session. A task
|
||||||
running as SYSTEM produces no visible toasts.
|
running as SYSTEM produces no visible toasts.
|
||||||
|
- On Windows, the task action must run `agent-libw.exe sync`, not
|
||||||
|
`agent-lib.exe sync`. `agent-lib.exe` is a console program, so Windows opens
|
||||||
|
a terminal window for it on every run. `agent-libw.exe` is the same program
|
||||||
|
without a console. It prints nothing, so check the task's last run result
|
||||||
|
(`0` = success, `1` = failed), and run `agent-lib.exe sync` by hand to see
|
||||||
|
the error.
|
||||||
- Suggested cadence: every 1–4 hours plus/except at logon. Sync is idempotent
|
- Suggested cadence: every 1–4 hours plus/except at logon. Sync is idempotent
|
||||||
and cheap when unchanged.
|
and cheap when unchanged.
|
||||||
- Optional companion: a drift check running `agent-lib status --json`
|
- Optional companion: a drift check running `agent-lib status --json`
|
||||||
@@ -132,6 +143,8 @@ Local state (manifest, cached bare repo, sync log) lives per-user:
|
|||||||
admins; token present.
|
admins; token present.
|
||||||
- [ ] Scheduled task runs as the logged-in user; toast appears when a
|
- [ ] Scheduled task runs as the logged-in user; toast appears when a
|
||||||
modified item is skipped (manual visual check on a Windows client).
|
modified item is skipped (manual visual check on a Windows client).
|
||||||
|
- [ ] Windows task action uses `agent-libw.exe`; no terminal window appears
|
||||||
|
when the task runs.
|
||||||
- [ ] `agent-lib status` exits 0 on a clean machine, non-zero after editing a
|
- [ ] `agent-lib status` exits 0 on a clean machine, non-zero after editing a
|
||||||
deployed file (self-test).
|
deployed file (self-test).
|
||||||
- [ ] Drift monitoring consumes `status --json` → `problematic_drift`.
|
- [ ] Drift monitoring consumes `status --json` → `problematic_drift`.
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
# Proposal: client labels — deliver content to a subset of clients
|
||||||
|
|
||||||
|
Status: implemented on branch feat/client-labels (14.11.2026) — user docs in the README, section "Client labels"
|
||||||
|
|
||||||
|
## Problem
|
||||||
|
|
||||||
|
A work repository serves every client the same content. Organisations with
|
||||||
|
teams want *relevant* content per team: finance needs finance skills, sales
|
||||||
|
needs sales agents, and nobody benefits from all of it. A long skill list
|
||||||
|
also hurts routing quality of small models.
|
||||||
|
|
||||||
|
Today the only way to split is one repository or one branch per team. Both
|
||||||
|
force shared content to be maintained N times (merges, drift) and cannot
|
||||||
|
serve a client that belongs to two teams — a client pulls exactly one ref.
|
||||||
|
|
||||||
|
## Decision in one sentence
|
||||||
|
|
||||||
|
Content items may carry **labels** in the work repository; clients carry
|
||||||
|
**labels** in their config; `sync` delivers an item when it is unlabeled or
|
||||||
|
shares at least one label with the client.
|
||||||
|
|
||||||
|
agent-lib stays generic: it knows "label" and "item", never "department",
|
||||||
|
"role" or any organisation's vocabulary. What a label means and who gets it
|
||||||
|
is decided outside agent-lib (curator: which item has which label; fleet
|
||||||
|
tooling: which client has which label).
|
||||||
|
|
||||||
|
This revises the v2 non-goal "client-side selection or profiles": labels are
|
||||||
|
a selection, but no profiles — there is no per-label content, overrides or
|
||||||
|
inheritance, only a filter over the one shared inventory.
|
||||||
|
|
||||||
|
## Repository side: `agent-lib.labels.json`
|
||||||
|
|
||||||
|
Optional file in the work repository root, next to `agent-lib.lock.json`.
|
||||||
|
JSON keeps the binary free of a YAML dependency (frontmatter is hand-parsed
|
||||||
|
today) and matches the lockfile and client config.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"labels": {
|
||||||
|
"sales": ["crm-agent", "quote-writer"],
|
||||||
|
"finance": ["officecli-financial-model", "invoice-check"],
|
||||||
|
"dev": ["grilling", "to-spec"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- **Unlabeled = everyone.** Only items that should be restricted appear in
|
||||||
|
the file. Adding an item to the repository without touching the file
|
||||||
|
delivers it to all clients — same as today.
|
||||||
|
- An item may appear under several labels (OR).
|
||||||
|
- Entries are **deployed item names** (after vendor renames), matched across
|
||||||
|
types: `foo` covers the skill `foo` and the command `foo` alike. Type-
|
||||||
|
qualified entries are not needed until a real collision appears.
|
||||||
|
- Label form `^[a-z0-9][a-z0-9-]*$`; lists must be non-empty.
|
||||||
|
- Names may also refer to MCP fragments. The binary never deploys MCP, but
|
||||||
|
fleet tooling can read the same file to scope MCP servers — one source of
|
||||||
|
truth for "who gets what".
|
||||||
|
- Unknown top-level keys are an error (typo protection); `version` is
|
||||||
|
required.
|
||||||
|
|
||||||
|
## Client side: `labels` in the client config
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"repo_url": "https://git.example.com/company/agent-content.git",
|
||||||
|
"ref": "main",
|
||||||
|
"labels": ["sales", "leadership"]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| `labels` | Effect |
|
||||||
|
|---|---|
|
||||||
|
| field absent | **no filtering** — every item, as today (backward compatible) |
|
||||||
|
| `[]` | only unlabeled items |
|
||||||
|
| `["a","b"]` | unlabeled items plus items labeled `a` or `b` |
|
||||||
|
|
||||||
|
Client labels that no item uses are fine (no warning): a client may be
|
||||||
|
labeled ahead of content.
|
||||||
|
|
||||||
|
### Admin-pinned labels
|
||||||
|
|
||||||
|
Today the first config found wins as a whole, and the user-level config
|
||||||
|
precedes the admin default. For labels that would let a user widen their
|
||||||
|
own selection. Rule:
|
||||||
|
|
||||||
|
> If the admin default config exists and contains `labels`, that value
|
||||||
|
> applies — whichever config supplied `repo_url`. User-level and env
|
||||||
|
> configs cannot set or override `labels` while an admin value exists.
|
||||||
|
> Without an admin value, `labels` from the chosen config applies
|
||||||
|
> (personal machines keep full control).
|
||||||
|
|
||||||
|
`--labels a,b` as a flag is deliberately not offered for sync; for testing
|
||||||
|
use `--config` with a file that has no admin counterpart, i.e. on a machine
|
||||||
|
without an admin default.
|
||||||
|
|
||||||
|
Labels are a **relevance filter, not access control**: the whole repository
|
||||||
|
revision is still fetched into the local cache. Confidential content needs
|
||||||
|
a separately authenticated repository.
|
||||||
|
|
||||||
|
## Sync behaviour
|
||||||
|
|
||||||
|
1. Build the inventory as today.
|
||||||
|
2. Read `agent-lib.labels.json` from the **same revision**.
|
||||||
|
- Absent → no filtering.
|
||||||
|
- Invalid (parse error, bad label form, empty list, unknown key,
|
||||||
|
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` 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
|
||||||
|
`inv.Deployable()`).
|
||||||
|
4. Planning is unchanged. A previously deployed item that is no longer
|
||||||
|
selected is handled exactly like an upstream deletion: unmodified →
|
||||||
|
remove; locally modified → skip + warn (`--force` removes). The plan
|
||||||
|
reason and toast text say **"not selected for this client's labels"**
|
||||||
|
instead of "upstream deleted" so users understand why.
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
`status --json` gains:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"labels": {
|
||||||
|
"client": ["sales"], "source": "admin", "labels_file": true,
|
||||||
|
"not_selected": ["skills/officecli-financial-model"],
|
||||||
|
"unknown_names": []
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The object is omitted when the client has no labels. `source` is `admin`
|
||||||
|
| `user` | `env` | `flag`. Human output prints one line:
|
||||||
|
`labels: sales (admin) — 12 item(s) not selected`.
|
||||||
|
|
||||||
|
## Curator side
|
||||||
|
|
||||||
|
`agent-lib validate` checks `agent-lib.labels.json` when present:
|
||||||
|
schema/version, label form, non-empty lists, every name resolves to an
|
||||||
|
inventory item (own or external, any type including MCP). Errors are
|
||||||
|
fatal, so a broken file never reaches clients through CI.
|
||||||
|
|
||||||
|
No new curator command is required; the file is edited by hand. A later
|
||||||
|
`agent-lib labels list` (item → labels table) is a nice-to-have.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
- planner/sync: absent field, `[]`, single/multi label, item under two
|
||||||
|
labels, label removed from client → remove unmodified / keep modified,
|
||||||
|
`--force`.
|
||||||
|
- config: admin labels beat user labels; user labels apply without admin
|
||||||
|
value; absent everywhere → no filtering.
|
||||||
|
- labels file: absent, invalid variants (abort, no disk change), unknown
|
||||||
|
name (warning).
|
||||||
|
- validate: each error class.
|
||||||
|
- e2e: second run is a byte-level no-op with labels active.
|
||||||
|
|
||||||
|
## Rollout
|
||||||
|
|
||||||
|
Additive and backward compatible: old clients ignore the file, new
|
||||||
|
clients without `labels` ignore the file. Fleet tooling adds the field
|
||||||
|
after pinning the release that understands it.
|
||||||
@@ -6,6 +6,7 @@ require (
|
|||||||
github.com/go-git/go-billy/v5 v5.9.1
|
github.com/go-git/go-billy/v5 v5.9.1
|
||||||
github.com/go-git/go-git/v5 v5.19.2
|
github.com/go-git/go-git/v5 v5.19.2
|
||||||
github.com/spf13/cobra v1.10.2
|
github.com/spf13/cobra v1.10.2
|
||||||
|
golang.org/x/sys v0.46.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
@@ -28,6 +29,5 @@ require (
|
|||||||
github.com/xanzy/ssh-agent v0.3.3 // indirect
|
github.com/xanzy/ssh-agent v0.3.3 // indirect
|
||||||
golang.org/x/crypto v0.53.0 // indirect
|
golang.org/x/crypto v0.53.0 // indirect
|
||||||
golang.org/x/net v0.56.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
|
gopkg.in/warnings.v0 v0.1.2 // indirect
|
||||||
)
|
)
|
||||||
+17
-1
@@ -8,6 +8,7 @@ import (
|
|||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
|
"github.com/m3tam3re/agent-lib/internal/labels"
|
||||||
"github.com/m3tam3re/agent-lib/internal/lockfile"
|
"github.com/m3tam3re/agent-lib/internal/lockfile"
|
||||||
"github.com/m3tam3re/agent-lib/internal/vendor"
|
"github.com/m3tam3re/agent-lib/internal/vendor"
|
||||||
)
|
)
|
||||||
@@ -25,6 +26,18 @@ func loadLockfileOrFail(cmd *cobra.Command) *lockfile.Lockfile {
|
|||||||
return lf
|
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 {
|
func emitJSON(cmd *cobra.Command, v any) error {
|
||||||
enc := json.NewEncoder(cmd.OutOrStdout())
|
enc := json.NewEncoder(cmd.OutOrStdout())
|
||||||
enc.SetIndent("", " ")
|
enc.SetIndent("", " ")
|
||||||
@@ -38,7 +51,7 @@ func newValidateCmd() *cobra.Command {
|
|||||||
Short: "Check lockfile rules and external-area consistency offline",
|
Short: "Check lockfile rules and external-area consistency offline",
|
||||||
Args: cobra.NoArgs,
|
Args: cobra.NoArgs,
|
||||||
RunE: func(cmd *cobra.Command, args []string) error {
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
lf := loadLockfileOrFail(cmd)
|
lf := loadLockfileForValidate(cmd)
|
||||||
result := vendor.Validate(".", lf)
|
result := vendor.Validate(".", lf)
|
||||||
if asJSON {
|
if asJSON {
|
||||||
return emitJSON(cmd, result)
|
return emitJSON(cmd, result)
|
||||||
@@ -46,6 +59,9 @@ func newValidateCmd() *cobra.Command {
|
|||||||
w := cmd.OutOrStdout()
|
w := cmd.OutOrStdout()
|
||||||
if result.Valid {
|
if result.Valid {
|
||||||
fmt.Fprintf(w, "lockfile valid (%d sources)\n", len(lf.Sources))
|
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
|
return nil
|
||||||
}
|
}
|
||||||
for _, e := range result.Errors {
|
for _, e := range result.Errors {
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
|
|
||||||
func newSyncCmd() *cobra.Command {
|
func newSyncCmd() *cobra.Command {
|
||||||
var configPath, repoURL, ref string
|
var configPath, repoURL, ref string
|
||||||
|
var force bool
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
Use: "sync",
|
Use: "sync",
|
||||||
Short: "Pull the work repository and deploy its content to OpenCode",
|
Short: "Pull the work repository and deploy its content to OpenCode",
|
||||||
@@ -17,10 +18,13 @@ func newSyncCmd() *cobra.Command {
|
|||||||
"into the OpenCode runtime paths. The repository comes from --repo, " +
|
"into the OpenCode runtime paths. The repository comes from --repo, " +
|
||||||
"or from the config chain: --config, " + client.ConfigEnv + " env, the " +
|
"or from the config chain: --config, " + client.ConfigEnv + " env, the " +
|
||||||
"user-level config, or the admin-protected platform default. " +
|
"user-level config, or the admin-protected platform default. " +
|
||||||
"Idempotent: re-running changes nothing when content and disk match.",
|
"Idempotent: re-running changes nothing when content and disk match. " +
|
||||||
|
"Locally modified managed items are kept by default (skip + warn); " +
|
||||||
|
"--force overwrites them with the repository version and removes " +
|
||||||
|
"them after upstream deletion. Unmanaged items are never touched.",
|
||||||
Args: cobra.NoArgs,
|
Args: cobra.NoArgs,
|
||||||
RunE: func(cmd *cobra.Command, args []string) error {
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
opts := client.SyncOptions{ConfigPath: configPath, RepoURL: repoURL, Ref: ref}
|
opts := client.SyncOptions{ConfigPath: configPath, RepoURL: repoURL, Ref: ref, Force: force}
|
||||||
if _, err := client.Sync(opts, cmd.OutOrStdout()); err != nil {
|
if _, err := client.Sync(opts, cmd.OutOrStdout()); err != nil {
|
||||||
return fmt.Errorf("sync: %w", err)
|
return fmt.Errorf("sync: %w", err)
|
||||||
}
|
}
|
||||||
@@ -30,5 +34,6 @@ func newSyncCmd() *cobra.Command {
|
|||||||
cmd.Flags().StringVar(&configPath, "config", "", "client config path (default: "+client.ConfigEnv+" env, user config, or platform default)")
|
cmd.Flags().StringVar(&configPath, "config", "", "client config path (default: "+client.ConfigEnv+" env, user config, or platform default)")
|
||||||
cmd.Flags().StringVar(&repoURL, "repo", "", "work repository URL or path — overrides any config, works without one")
|
cmd.Flags().StringVar(&repoURL, "repo", "", "work repository URL or path — overrides any config, works without one")
|
||||||
cmd.Flags().StringVar(&ref, "ref", "", "branch or tag to pull (requires --repo)")
|
cmd.Flags().StringVar(&ref, "ref", "", "branch or tag to pull (requires --repo)")
|
||||||
|
cmd.Flags().BoolVar(&force, "force", false, "overwrite locally modified managed items with the repository version; unmanaged items are never touched")
|
||||||
return cmd
|
return cmd
|
||||||
}
|
}
|
||||||
+65
-14
@@ -16,6 +16,7 @@ func newVendorCmd() *cobra.Command {
|
|||||||
}
|
}
|
||||||
cmd.AddCommand(newVendorAddCmd())
|
cmd.AddCommand(newVendorAddCmd())
|
||||||
cmd.AddCommand(newVendorSelectCmd())
|
cmd.AddCommand(newVendorSelectCmd())
|
||||||
|
cmd.AddCommand(newVendorRenameCmd())
|
||||||
cmd.AddCommand(newVendorListCmd())
|
cmd.AddCommand(newVendorListCmd())
|
||||||
cmd.AddCommand(newVendorInspectCmd())
|
cmd.AddCommand(newVendorInspectCmd())
|
||||||
cmd.AddCommand(newVendorUpdateCmd())
|
cmd.AddCommand(newVendorUpdateCmd())
|
||||||
@@ -26,7 +27,7 @@ func newVendorCmd() *cobra.Command {
|
|||||||
|
|
||||||
func newVendorAddCmd() *cobra.Command {
|
func newVendorAddCmd() *cobra.Command {
|
||||||
var ref string
|
var ref string
|
||||||
var include []string
|
var include, exclude, onlyTypes, excludeTypes []string
|
||||||
var renames []string
|
var renames []string
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
Use: "add <name> <url>",
|
Use: "add <name> <url>",
|
||||||
@@ -34,7 +35,10 @@ func newVendorAddCmd() *cobra.Command {
|
|||||||
Long: "Clones the source (in-process, via go-git), discovers skills, commands,\n" +
|
Long: "Clones the source (in-process, via go-git), discovers skills, commands,\n" +
|
||||||
"agents and MCP fragments, materializes the selection under external/<name>/\n" +
|
"agents and MCP fragments, materializes the selection under external/<name>/\n" +
|
||||||
"and pins URL, ref, revision, selection and renames in the lockfile.\n" +
|
"and pins URL, ref, revision, selection and renames in the lockfile.\n" +
|
||||||
"Default selection is everything; --include switches to an explicit list.\n" +
|
"Default selection is everything; --include switches to an explicit list,\n" +
|
||||||
|
"--exclude keeps everything except the listed ids. --types (allow-list) and\n" +
|
||||||
|
"--exclude-types (deny-list) filter whole content types and survive updates:\n" +
|
||||||
|
"new upstream items of an excluded type never enter the work repository.\n" +
|
||||||
"Collisions abort with a hard error; resolve them with --rename upstream=deployed.",
|
"Collisions abort with a hard error; resolve them with --rename upstream=deployed.",
|
||||||
Args: cobra.ExactArgs(2),
|
Args: cobra.ExactArgs(2),
|
||||||
RunE: func(cmd *cobra.Command, args []string) error {
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
@@ -43,11 +47,14 @@ func newVendorAddCmd() *cobra.Command {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
opts := vendor.AddOptions{
|
opts := vendor.AddOptions{
|
||||||
Name: args[0],
|
Name: args[0],
|
||||||
URL: args[1],
|
URL: args[1],
|
||||||
Ref: ref,
|
Ref: ref,
|
||||||
Include: splitList(include),
|
Include: splitList(include),
|
||||||
Renames: renameMap,
|
Exclude: splitList(exclude),
|
||||||
|
OnlyTypes: splitList(onlyTypes),
|
||||||
|
ExcludeTypes: splitList(excludeTypes),
|
||||||
|
Renames: renameMap,
|
||||||
}
|
}
|
||||||
if err := vendor.Add(".", opts, cmd.OutOrStdout()); err != nil {
|
if err := vendor.Add(".", opts, cmd.OutOrStdout()); err != nil {
|
||||||
return fmt.Errorf("vendor add: %w", err)
|
return fmt.Errorf("vendor add: %w", err)
|
||||||
@@ -57,10 +64,47 @@ func newVendorAddCmd() *cobra.Command {
|
|||||||
}
|
}
|
||||||
cmd.Flags().StringVar(&ref, "ref", "", "branch or tag to track (default: the source's default branch)")
|
cmd.Flags().StringVar(&ref, "ref", "", "branch or tag to track (default: the source's default branch)")
|
||||||
cmd.Flags().StringSliceVar(&include, "include", nil, "comma-separated item ids to vendor (switches selection to include mode)")
|
cmd.Flags().StringSliceVar(&include, "include", nil, "comma-separated item ids to vendor (switches selection to include mode)")
|
||||||
|
cmd.Flags().StringSliceVar(&exclude, "exclude", nil, "comma-separated item ids to skip (keeps all mode, drops these ids)")
|
||||||
|
cmd.Flags().StringSliceVar(&onlyTypes, "types", nil, "comma-separated content types to take: skills, commands, agents, mcp (allow-list)")
|
||||||
|
cmd.Flags().StringSliceVar(&excludeTypes, "exclude-types", nil, "comma-separated content types to skip: skills, commands, agents, mcp (deny-list)")
|
||||||
cmd.Flags().StringSliceVar(&renames, "rename", nil, "deployed-name override upstream-id=deployed-name (repeatable)")
|
cmd.Flags().StringSliceVar(&renames, "rename", nil, "deployed-name override upstream-id=deployed-name (repeatable)")
|
||||||
return cmd
|
return cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func newVendorRenameCmd() *cobra.Command {
|
||||||
|
var reset []string
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "rename <name> [upstream-id=deployed-name ...]",
|
||||||
|
Short: "Give vendored items user-friendly deployed names",
|
||||||
|
Long: "Sets or resets deployed-name overrides for a vendored source after\n" +
|
||||||
|
"vendor add. The rename map is pinned in the lockfile and survives\n" +
|
||||||
|
"vendor update and vendor select. Renamed skills get their SKILL.md\n" +
|
||||||
|
"frontmatter name rewritten to the new folder name, so OpenCode lists\n" +
|
||||||
|
"them under the new name. Skill names must be lowercase letters, digits\n" +
|
||||||
|
"and single hyphens (e.g. code-review). The pinned revision and the\n" +
|
||||||
|
"selection never change; collisions re-run before anything is written.\n" +
|
||||||
|
"Without arguments the current renames are listed.\n\n" +
|
||||||
|
"Examples:\n" +
|
||||||
|
" agent-lib vendor rename superpowers brainstorming=ideen-sammeln\n" +
|
||||||
|
" agent-lib vendor rename superpowers --reset brainstorming\n" +
|
||||||
|
" agent-lib vendor rename superpowers",
|
||||||
|
Args: cobra.MinimumNArgs(1),
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
set, err := vendor.ParseRenames(args[1:])
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
opts := vendor.RenameOptions{Set: set, Reset: splitList(reset)}
|
||||||
|
if err := vendor.Rename(".", args[0], opts, cmd.OutOrStdout()); err != nil {
|
||||||
|
return fmt.Errorf("vendor rename: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().StringSliceVar(&reset, "reset", nil, "comma-separated upstream ids whose rename is dropped (deploy under the upstream id again)")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
func splitList(in []string) []string {
|
func splitList(in []string) []string {
|
||||||
var out []string
|
var out []string
|
||||||
for _, s := range in {
|
for _, s := range in {
|
||||||
@@ -75,6 +119,7 @@ func splitList(in []string) []string {
|
|||||||
|
|
||||||
func newVendorSelectCmd() *cobra.Command {
|
func newVendorSelectCmd() *cobra.Command {
|
||||||
var add, remove []string
|
var add, remove []string
|
||||||
|
var onlyTypes, excludeTypes []string
|
||||||
var mode string
|
var mode string
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
Use: "select <name>",
|
Use: "select <name>",
|
||||||
@@ -83,9 +128,11 @@ func newVendorSelectCmd() *cobra.Command {
|
|||||||
"Include mode: --add appends ids (validated against the pinned upstream),\n" +
|
"Include mode: --add appends ids (validated against the pinned upstream),\n" +
|
||||||
"--remove drops ids and deletes their folders. All mode: --remove moves ids\n" +
|
"--remove drops ids and deletes their folders. All mode: --remove moves ids\n" +
|
||||||
"onto the exclude list; --add is an error (everything is selected already).\n" +
|
"onto the exclude list; --add is an error (everything is selected already).\n" +
|
||||||
"--mode all resets to everything: include/exclude lists are cleared and the\n" +
|
"--types/--exclude-types replace the content-type filter (skills, commands,\n" +
|
||||||
"full pinned upstream is re-materialized. Collisions re-run on every change;\n" +
|
"agents, mcp); absent flags keep it as-is. --mode all resets to everything:\n" +
|
||||||
"renames from the lockfile are honored. The revision never moves — that is\n" +
|
"include/exclude lists and the type filter are cleared and the full pinned\n" +
|
||||||
|
"upstream is re-materialized. Collisions re-run on every change; renames\n" +
|
||||||
|
"from the lockfile are honored. The revision never moves — that is\n" +
|
||||||
"vendor update's job.",
|
"vendor update's job.",
|
||||||
Args: cobra.ExactArgs(1),
|
Args: cobra.ExactArgs(1),
|
||||||
RunE: func(cmd *cobra.Command, args []string) error {
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
@@ -93,9 +140,11 @@ func newVendorSelectCmd() *cobra.Command {
|
|||||||
return fmt.Errorf("--mode accepts only \"all\" (got %q)", mode)
|
return fmt.Errorf("--mode accepts only \"all\" (got %q)", mode)
|
||||||
}
|
}
|
||||||
opts := vendor.SelectOptions{
|
opts := vendor.SelectOptions{
|
||||||
Add: splitList(add),
|
Add: splitList(add),
|
||||||
Remove: splitList(remove),
|
Remove: splitList(remove),
|
||||||
ModeAll: mode == "all",
|
ModeAll: mode == "all",
|
||||||
|
OnlyTypes: splitList(onlyTypes),
|
||||||
|
ExcludeTypes: splitList(excludeTypes),
|
||||||
}
|
}
|
||||||
if _, err := vendor.Select(".", args[0], opts, cmd.OutOrStdout()); err != nil {
|
if _, err := vendor.Select(".", args[0], opts, cmd.OutOrStdout()); err != nil {
|
||||||
return fmt.Errorf("vendor select: %w", err)
|
return fmt.Errorf("vendor select: %w", err)
|
||||||
@@ -105,6 +154,8 @@ func newVendorSelectCmd() *cobra.Command {
|
|||||||
}
|
}
|
||||||
cmd.Flags().StringSliceVar(&add, "add", nil, "comma-separated upstream ids to add to the selection")
|
cmd.Flags().StringSliceVar(&add, "add", nil, "comma-separated upstream ids to add to the selection")
|
||||||
cmd.Flags().StringSliceVar(&remove, "remove", nil, "comma-separated upstream ids to remove from the selection")
|
cmd.Flags().StringSliceVar(&remove, "remove", nil, "comma-separated upstream ids to remove from the selection")
|
||||||
cmd.Flags().StringVar(&mode, "mode", "", "switch selection mode (only \"all\": clear include/exclude, take everything)")
|
cmd.Flags().StringSliceVar(&onlyTypes, "types", nil, "content types to take: skills, commands, agents, mcp (allow-list; replaces the type filter)")
|
||||||
|
cmd.Flags().StringSliceVar(&excludeTypes, "exclude-types", nil, "content types to skip: skills, commands, agents, mcp (deny-list; replaces the type filter)")
|
||||||
|
cmd.Flags().StringVar(&mode, "mode", "", "switch selection mode (only \"all\": clear include/exclude and the type filter, take everything)")
|
||||||
return cmd
|
return cmd
|
||||||
}
|
}
|
||||||
+81
-15
@@ -11,6 +11,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/m3tam3re/agent-lib/internal/gitsource"
|
"github.com/m3tam3re/agent-lib/internal/gitsource"
|
||||||
|
"github.com/m3tam3re/agent-lib/internal/labels"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ClientConfig is the client configuration for sync: fleet-provided or
|
// ClientConfig is the client configuration for sync: fleet-provided or
|
||||||
@@ -20,6 +21,14 @@ type ClientConfig struct {
|
|||||||
Ref string `json:"ref,omitempty"`
|
Ref string `json:"ref,omitempty"`
|
||||||
Token string `json:"token,omitempty"`
|
Token string `json:"token,omitempty"`
|
||||||
TokenUser string `json:"token_user,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.
|
// ConfigEnv names the override environment variables.
|
||||||
@@ -29,13 +38,11 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// DefaultConfigPath returns the admin-protected config location per platform:
|
// 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 {
|
func DefaultConfigPath() string {
|
||||||
if runtime.GOOS == "windows" {
|
if runtime.GOOS == "windows" {
|
||||||
if pd := os.Getenv("ProgramData"); pd != "" {
|
return filepath.Join(programDataDir(), "agent-lib", "config.json")
|
||||||
return filepath.Join(pd, "agent-lib", "config.json")
|
|
||||||
}
|
|
||||||
return `C:\ProgramData\agent-lib\config.json`
|
|
||||||
}
|
}
|
||||||
return "/etc/agent-lib/config.json"
|
return "/etc/agent-lib/config.json"
|
||||||
}
|
}
|
||||||
@@ -115,50 +122,102 @@ func (e *MissingConfigError) Error() string {
|
|||||||
// default — first existing file wins. Explicit flag/env paths that do not
|
// default — first existing file wins. Explicit flag/env paths that do not
|
||||||
// exist are hard errors; a completely empty chain yields *MissingConfigError.
|
// exist are hard errors; a completely empty chain yields *MissingConfigError.
|
||||||
func LoadClientConfig(flagPath string) (*ClientConfig, error) {
|
func LoadClientConfig(flagPath string) (*ClientConfig, error) {
|
||||||
path, ok, err := resolveConfigPath(flagPath)
|
path, desc, ok, err := resolveConfigPath(flagPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, &MissingConfigError{Chain: ConfigSearchChain(flagPath)}
|
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)
|
// LoadOptionalConfig behaves like LoadClientConfig but returns (nil, nil)
|
||||||
// when no config exists anywhere — for runs that carry their own --repo.
|
// when no config exists anywhere — for runs that carry their own --repo.
|
||||||
// Malformed existing configs are still hard errors.
|
// Malformed existing configs are still hard errors.
|
||||||
func LoadOptionalConfig(flagPath string) (*ClientConfig, error) {
|
func LoadOptionalConfig(flagPath string) (*ClientConfig, error) {
|
||||||
path, ok, err := resolveConfigPath(flagPath)
|
path, desc, ok, err := resolveConfigPath(flagPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, nil
|
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.
|
// 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
|
// The flag and env legs must exist when set (explicit intent); the user and
|
||||||
// admin legs are skipped when absent.
|
// 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 != "" {
|
if flagPath != "" {
|
||||||
return flagPath, true, nil
|
return flagPath, "flag", true, nil
|
||||||
}
|
}
|
||||||
if envPath := os.Getenv(ConfigEnv); envPath != "" {
|
if envPath := os.Getenv(ConfigEnv); envPath != "" {
|
||||||
return envPath, true, nil
|
return envPath, "env", true, nil
|
||||||
}
|
}
|
||||||
if p := UserConfigPath(); p != "" {
|
if p := UserConfigPath(); p != "" {
|
||||||
if _, statErr := os.Stat(p); statErr == nil {
|
if _, statErr := os.Stat(p); statErr == nil {
|
||||||
return p, true, nil
|
return p, "user", true, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
admin := DefaultConfigPath()
|
admin := DefaultConfigPath()
|
||||||
if _, statErr := os.Stat(admin); statErr == nil {
|
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) {
|
func readClientConfig(path string) (*ClientConfig, error) {
|
||||||
@@ -173,6 +232,13 @@ func readClientConfig(path string) (*ClientConfig, error) {
|
|||||||
if cfg.RepoURL == "" {
|
if cfg.RepoURL == "" {
|
||||||
return nil, fmt.Errorf("client config %s: repo_url is required", path)
|
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
|
return &cfg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -163,3 +163,138 @@ func TestFillTokenAuthEnvOnlyFillsEmptyToken(t *testing.T) {
|
|||||||
t.Errorf("env must never override a config token: %+v", configured)
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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) {
|
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}
|
report := &SyncReport{Revision: rev, Manifest: paths.Manifest}
|
||||||
var warnings []string
|
var warnings []string
|
||||||
|
labelSkips := 0
|
||||||
|
|
||||||
for _, e := range plan {
|
for _, e := range plan {
|
||||||
key := manifestKey(e.Type, e.Name)
|
key := manifestKey(e.Type, e.Name)
|
||||||
@@ -62,6 +63,9 @@ func ExecutePlan(tree *gitsource.GitTree, plan []PlanEntry, manifest *Manifest,
|
|||||||
case ActSkip:
|
case ActSkip:
|
||||||
warnings = append(warnings, fmt.Sprintf("SKIP %s/%s: %s", e.Type, e.Name, e.Reason))
|
warnings = append(warnings, fmt.Sprintf("SKIP %s/%s: %s", e.Type, e.Name, e.Reason))
|
||||||
report.Skipped++
|
report.Skipped++
|
||||||
|
if IsLabelSkip(e) {
|
||||||
|
labelSkips++
|
||||||
|
}
|
||||||
case ActLeave:
|
case ActLeave:
|
||||||
warnings = append(warnings, fmt.Sprintf("LEAVE %s/%s: %s", e.Type, e.Name, e.Reason))
|
warnings = append(warnings, fmt.Sprintf("LEAVE %s/%s: %s", e.Type, e.Name, e.Reason))
|
||||||
report.Left++
|
report.Left++
|
||||||
@@ -79,6 +83,9 @@ func ExecutePlan(tree *gitsource.GitTree, plan []PlanEntry, manifest *Manifest,
|
|||||||
}
|
}
|
||||||
title := "agent-lib sync"
|
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)
|
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 {
|
if err := Notifier.Send(title, body); err != nil {
|
||||||
fmt.Fprintf(stdout, "warning: notification failed: %v\n", err)
|
fmt.Fprintf(stdout, "warning: notification failed: %v\n", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
package client
|
package client
|
||||||
|
|
||||||
import "sort"
|
import (
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
// Action is one step of a sync plan.
|
// Action is one step of a sync plan.
|
||||||
type Action string
|
type Action string
|
||||||
@@ -17,6 +20,23 @@ const (
|
|||||||
ActKeep Action = "keep"
|
ActKeep Action = "keep"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// 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 {
|
||||||
|
Force bool
|
||||||
|
Deselected map[string]bool
|
||||||
|
}
|
||||||
|
|
||||||
// PlannedItem is one deployable inventory item with its repo-side hash.
|
// PlannedItem is one deployable inventory item with its repo-side hash.
|
||||||
type PlannedItem struct {
|
type PlannedItem struct {
|
||||||
Type string
|
Type string
|
||||||
@@ -47,8 +67,16 @@ type PlanEntry struct {
|
|||||||
// Plan is a pure function from (inventory, manifest, on-disk facts) to an
|
// Plan is a pure function from (inventory, manifest, on-disk facts) to an
|
||||||
// action plan. pathFor injects the target path mapping so the planner never
|
// action plan. pathFor injects the target path mapping so the planner never
|
||||||
// touches the filesystem or the environment. The plan is sorted by
|
// touches the filesystem or the environment. The plan is sorted by
|
||||||
// (type, name) for deterministic execution and reporting.
|
// (type, name) for deterministic execution and reporting. With force set,
|
||||||
func Plan(items []PlannedItem, manifest *Manifest, disk map[string]DiskFact, pathFor func(typ, name string) string) []PlanEntry {
|
// 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.
|
||||||
|
//
|
||||||
|
// 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{}
|
invByKey := map[string]PlannedItem{}
|
||||||
for _, it := range items {
|
for _, it := range items {
|
||||||
invByKey[manifestKey(it.Type, it.Name)] = it
|
invByKey[manifestKey(it.Type, it.Name)] = it
|
||||||
@@ -84,6 +112,10 @@ func Plan(items []PlannedItem, manifest *Manifest, disk map[string]DiskFact, pat
|
|||||||
it, inInv := invByKey[key]
|
it, inInv := invByKey[key]
|
||||||
rec := manifest.Items[key]
|
rec := manifest.Items[key]
|
||||||
fact := disk[key]
|
fact := disk[key]
|
||||||
|
gone := "upstream deleted"
|
||||||
|
if opts.Deselected[key] {
|
||||||
|
gone = ReasonNotSelected
|
||||||
|
}
|
||||||
|
|
||||||
switch {
|
switch {
|
||||||
case inInv && rec == nil:
|
case inInv && rec == nil:
|
||||||
@@ -93,16 +125,18 @@ func Plan(items []PlannedItem, manifest *Manifest, disk map[string]DiskFact, pat
|
|||||||
emit(ActDeploy, it, "")
|
emit(ActDeploy, it, "")
|
||||||
}
|
}
|
||||||
case inInv && it.Hash == rec.Hash:
|
case inInv && it.Hash == rec.Hash:
|
||||||
decideAgainstDisk(it, rec, fact, emit, "unchanged")
|
decideAgainstDisk(it, rec, fact, emit, "unchanged", force)
|
||||||
case inInv:
|
case inInv:
|
||||||
decideAgainstDisk(it, rec, fact, emit, "changed")
|
decideAgainstDisk(it, rec, fact, emit, "changed", force)
|
||||||
case rec != nil && !fact.Exists:
|
case rec != nil && !fact.Exists:
|
||||||
emit(ActRemove, PlannedItem{Type: rec.Type, Name: rec.Name, Origin: rec.Origin}, "already gone from disk; dropping manifest record")
|
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:
|
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}, gone+"; forced removal of the locally modified copy")
|
||||||
case rec != nil:
|
case rec != nil:
|
||||||
emit(ActSkip, PlannedItem{Type: rec.Type, Name: rec.Name, Origin: rec.Origin},
|
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:
|
default:
|
||||||
emit(ActLeave, PlannedItem{Type: typeOfKey(key), Name: nameOfKey(key)},
|
emit(ActLeave, PlannedItem{Type: typeOfKey(key), Name: nameOfKey(key)},
|
||||||
"unmanaged local item; left untouched")
|
"unmanaged local item; left untouched")
|
||||||
@@ -111,7 +145,7 @@ func Plan(items []PlannedItem, manifest *Manifest, disk map[string]DiskFact, pat
|
|||||||
return plan
|
return plan
|
||||||
}
|
}
|
||||||
|
|
||||||
func decideAgainstDisk(it PlannedItem, rec *ManifestItem, fact DiskFact, emit func(Action, PlannedItem, string), upstreamState string) {
|
func decideAgainstDisk(it PlannedItem, rec *ManifestItem, fact DiskFact, emit func(Action, PlannedItem, string), upstreamState string, force bool) {
|
||||||
switch {
|
switch {
|
||||||
case !fact.Exists:
|
case !fact.Exists:
|
||||||
emit(ActUpdate, it, "managed item missing on disk; restoring")
|
emit(ActUpdate, it, "managed item missing on disk; restoring")
|
||||||
@@ -121,6 +155,8 @@ func decideAgainstDisk(it PlannedItem, rec *ManifestItem, fact DiskFact, emit fu
|
|||||||
} else {
|
} else {
|
||||||
emit(ActUpdate, it, "")
|
emit(ActUpdate, it, "")
|
||||||
}
|
}
|
||||||
|
case force:
|
||||||
|
emit(ActUpdate, it, "forced: locally modified copy overwritten")
|
||||||
default:
|
default:
|
||||||
emit(ActSkip, it, "locally modified; keeping the local version (upstream "+upstreamState+")")
|
emit(ActSkip, it, "locally modified; keeping the local version (upstream "+upstreamState+")")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -98,7 +98,7 @@ func TestPlanMatrix(t *testing.T) {
|
|||||||
diskFacts[key] = DiskFact{Exists: true, Hash: hashMod}
|
diskFacts[key] = DiskFact{Exists: true, Hash: hashMod}
|
||||||
}
|
}
|
||||||
|
|
||||||
plan := Plan(items, manifest, diskFacts, testPathFor)
|
plan := Plan(items, manifest, diskFacts, testPathFor, PlanOptions{})
|
||||||
if tc.disk == diskNone && tc.up == upAbsent {
|
if tc.disk == diskNone && tc.up == upAbsent {
|
||||||
if len(plan) != 0 {
|
if len(plan) != 0 {
|
||||||
t.Fatalf("a key present nowhere must produce no entry, got %+v", plan)
|
t.Fatalf("a key present nowhere must produce no entry, got %+v", plan)
|
||||||
@@ -123,6 +123,54 @@ func TestPlanMatrix(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestPlanForceMatrix asserts how --force changes the skip cases: locally
|
||||||
|
// modified managed items become updates (or removes after upstream
|
||||||
|
// deletion), while never-managed occupancies stay skipped even with force.
|
||||||
|
func TestPlanForceMatrix(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
up string // "changed", "unchanged", "gone"
|
||||||
|
want Action
|
||||||
|
}{
|
||||||
|
{"modified/changed", "changed", ActUpdate},
|
||||||
|
{"modified/unchanged", "unchanged", ActUpdate},
|
||||||
|
{"modified/gone", "gone", ActRemove},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
key := manifestKey("skills", "alpha")
|
||||||
|
var items []PlannedItem
|
||||||
|
manifest := NewManifest()
|
||||||
|
manifest.Items[key] = &ManifestItem{Name: "alpha", Type: "skills", Hash: hashV1}
|
||||||
|
if tc.up != "gone" {
|
||||||
|
hash := hashV2
|
||||||
|
if tc.up == "unchanged" {
|
||||||
|
hash = hashV1
|
||||||
|
}
|
||||||
|
items = append(items, PlannedItem{Type: "skills", Name: "alpha", RelPath: "skills/alpha", Hash: hash})
|
||||||
|
}
|
||||||
|
disk := map[string]DiskFact{key: {Exists: true, Hash: hashMod}}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
if plan[0].Action != tc.want {
|
||||||
|
t.Errorf("action = %s, want %s (reason: %s)", plan[0].Action, tc.want, plan[0].Reason)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
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, PlanOptions{Force: true})
|
||||||
|
if len(plan) != 1 || plan[0].Action != ActSkip {
|
||||||
|
t.Fatalf("force must not deploy over a never-managed item: %+v", plan)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
// TestPlanMixedFixture combines several states in one plan and asserts the
|
// TestPlanMixedFixture combines several states in one plan and asserts the
|
||||||
// full deterministic output.
|
// full deterministic output.
|
||||||
func TestPlanMixedFixture(t *testing.T) {
|
func TestPlanMixedFixture(t *testing.T) {
|
||||||
@@ -151,7 +199,7 @@ func TestPlanMixedFixture(t *testing.T) {
|
|||||||
"agents/helper": {Exists: true, Hash: hashV1}, // unmodified × unchanged
|
"agents/helper": {Exists: true, Hash: hashV1}, // unmodified × unchanged
|
||||||
}
|
}
|
||||||
|
|
||||||
plan := Plan(items, manifest, disk, testPathFor)
|
plan := Plan(items, manifest, disk, testPathFor, PlanOptions{})
|
||||||
got := map[string]Action{}
|
got := map[string]Action{}
|
||||||
for _, e := range plan {
|
for _, e := range plan {
|
||||||
got[e.Type+"/"+e.Name] = e.Action
|
got[e.Type+"/"+e.Name] = e.Action
|
||||||
@@ -195,8 +243,8 @@ func TestPlanPureGuarantee(t *testing.T) {
|
|||||||
manifest := manifestWith(map[string]*ManifestItem{"skills/b": {Name: "b", Type: "skills", Hash: hashV1}})
|
manifest := manifestWith(map[string]*ManifestItem{"skills/b": {Name: "b", Type: "skills", Hash: hashV1}})
|
||||||
disk := map[string]DiskFact{"skills/b": {Exists: true, Hash: hashV1}}
|
disk := map[string]DiskFact{"skills/b": {Exists: true, Hash: hashV1}}
|
||||||
|
|
||||||
p1 := Plan(items, manifest, disk, testPathFor)
|
p1 := Plan(items, manifest, disk, testPathFor, PlanOptions{})
|
||||||
p2 := Plan(items, manifest, disk, testPathFor)
|
p2 := Plan(items, manifest, disk, testPathFor, PlanOptions{})
|
||||||
if len(p1) != len(p2) {
|
if len(p1) != len(p2) {
|
||||||
t.Fatal("same inputs must yield same plan length")
|
t.Fatal("same inputs must yield same plan length")
|
||||||
}
|
}
|
||||||
@@ -209,3 +257,31 @@ func TestPlanPureGuarantee(t *testing.T) {
|
|||||||
t.Error("planner must not mutate its inputs")
|
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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
//go:build !windows
|
||||||
|
|
||||||
|
package client
|
||||||
|
|
||||||
|
// programDataDir is only meaningful on Windows.
|
||||||
|
func programDataDir() string { return "" }
|
||||||
@@ -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`
|
||||||
|
}
|
||||||
+46
-1
@@ -31,7 +31,15 @@ func Pull(cacheDir, url, ref, token, tokenUser string) (*PullResult, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
hash, err := resolveRemoteRef(repo, ref)
|
var hash plumbing.Hash
|
||||||
|
if ref == "" {
|
||||||
|
// The cached bare clone's HEAD is frozen at clone time (fetch never
|
||||||
|
// updates refs/heads/*), so the default branch must be asked from the
|
||||||
|
// remote directly — never resolved through local refs.
|
||||||
|
hash, err = resolveDefaultBranch(repo, auth)
|
||||||
|
} else {
|
||||||
|
hash, err = resolveRemoteRef(repo, ref)
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("resolving %q in %s: %w", refLabel(ref), gitsource.RedactURL(url), err)
|
return nil, fmt.Errorf("resolving %q in %s: %w", refLabel(ref), gitsource.RedactURL(url), err)
|
||||||
}
|
}
|
||||||
@@ -86,6 +94,43 @@ func openOrCreate(cacheDir, url, ref string, auth gittransport.AuthMethod) (*git
|
|||||||
return repo, nil
|
return repo, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// resolveDefaultBranch asks the remote for its advertised HEAD — the only
|
||||||
|
// source of truth for the default branch tip. HEAD may be advertised as a
|
||||||
|
// plain hash or as a symbolic reference to one of the advertised refs; both
|
||||||
|
// are handled. Local refs are never consulted: the cached bare clone's HEAD
|
||||||
|
// is frozen at clone time because fetch updates only refs/remotes/*.
|
||||||
|
func resolveDefaultBranch(repo *git.Repository, auth gittransport.AuthMethod) (plumbing.Hash, error) {
|
||||||
|
remote, err := repo.Remote(git.DefaultRemoteName)
|
||||||
|
if err != nil {
|
||||||
|
return plumbing.ZeroHash, fmt.Errorf("reading remote: %w", err)
|
||||||
|
}
|
||||||
|
refs, err := remote.List(&git.ListOptions{Auth: auth})
|
||||||
|
if err != nil {
|
||||||
|
return plumbing.ZeroHash, fmt.Errorf("listing remote refs: %w", err)
|
||||||
|
}
|
||||||
|
hashes := map[string]plumbing.Hash{}
|
||||||
|
var head *plumbing.Reference
|
||||||
|
for _, ref := range refs {
|
||||||
|
if ref.Name() == plumbing.HEAD {
|
||||||
|
head = ref
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ref.Type() == plumbing.HashReference {
|
||||||
|
hashes[ref.Name().String()] = ref.Hash()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if head == nil {
|
||||||
|
return plumbing.ZeroHash, errors.New("remote advertises no HEAD")
|
||||||
|
}
|
||||||
|
if head.Type() == plumbing.HashReference {
|
||||||
|
return head.Hash(), nil
|
||||||
|
}
|
||||||
|
if h, ok := hashes[head.Target().String()]; ok {
|
||||||
|
return h, nil
|
||||||
|
}
|
||||||
|
return plumbing.ZeroHash, fmt.Errorf("advertised HEAD points at %s, which was not advertised", head.Target())
|
||||||
|
}
|
||||||
|
|
||||||
// repointRemote aligns the cached origin with the configured URL so a fleet
|
// repointRemote aligns the cached origin with the configured URL so a fleet
|
||||||
// re-point takes effect on the next sync.
|
// re-point takes effect on the next sync.
|
||||||
func repointRemote(repo *git.Repository, url string) error {
|
func repointRemote(repo *git.Repository, url string) error {
|
||||||
|
|||||||
@@ -15,14 +15,15 @@ type StatusEntry struct {
|
|||||||
|
|
||||||
// StatusReport is the machine-readable local-state report.
|
// StatusReport is the machine-readable local-state report.
|
||||||
type StatusReport struct {
|
type StatusReport struct {
|
||||||
Version string `json:"agent_lib_version"`
|
Version string `json:"agent_lib_version"`
|
||||||
DeployedRev string `json:"deployed_revision"`
|
DeployedRev string `json:"deployed_revision"`
|
||||||
RepoRev string `json:"repository_revision"`
|
RepoRev string `json:"repository_revision"`
|
||||||
InSync bool `json:"in_sync"`
|
InSync bool `json:"in_sync"`
|
||||||
Drift bool `json:"problematic_drift"`
|
Drift bool `json:"problematic_drift"`
|
||||||
Pending []StatusEntry `json:"pending_changes,omitempty"`
|
Pending []StatusEntry `json:"pending_changes,omitempty"`
|
||||||
Skipped []StatusEntry `json:"skipped_items,omitempty"`
|
Skipped []StatusEntry `json:"skipped_items,omitempty"`
|
||||||
Unrecognized []StatusEntry `json:"unrecognized_items,omitempty"`
|
Unrecognized []StatusEntry `json:"unrecognized_items,omitempty"`
|
||||||
|
Labels *LabelSelection `json:"labels,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Status reports the local state without mutating anything. Drift is true
|
// Status reports the local state without mutating anything. Drift is true
|
||||||
@@ -38,6 +39,7 @@ func Status(opts SyncOptions) (*StatusReport, error) {
|
|||||||
Version: version.Version,
|
Version: version.Version,
|
||||||
DeployedRev: p.manifest.Revision,
|
DeployedRev: p.manifest.Revision,
|
||||||
RepoRev: p.pull.Rev,
|
RepoRev: p.pull.Rev,
|
||||||
|
Labels: p.labels,
|
||||||
}
|
}
|
||||||
for _, e := range p.plan {
|
for _, e := range p.plan {
|
||||||
item := e.Type + "/" + e.Name
|
item := e.Type + "/" + e.Name
|
||||||
@@ -49,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 {
|
if rec := p.manifest.Items[manifestKey(e.Type, e.Name)]; rec != nil && rec.Hash == e.NewHash {
|
||||||
blocked = false
|
blocked = false
|
||||||
}
|
}
|
||||||
|
if IsLabelSkip(e) {
|
||||||
|
blocked = false
|
||||||
|
}
|
||||||
if blocked {
|
if blocked {
|
||||||
report.Drift = true
|
report.Drift = true
|
||||||
}
|
}
|
||||||
@@ -85,6 +90,12 @@ func PrintStatus(w io.Writer, r *StatusReport) bool {
|
|||||||
fmt.Fprintln(w)
|
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("pending changes", r.Pending)
|
||||||
printSection("skipped (local modifications)", r.Skipped)
|
printSection("skipped (local modifications)", r.Skipped)
|
||||||
printSection("unrecognized local items", r.Unrecognized)
|
printSection("unrecognized local items", r.Unrecognized)
|
||||||
|
|||||||
+110
-3
@@ -1,22 +1,29 @@
|
|||||||
package client
|
package client
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"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"
|
"github.com/m3tam3re/agent-lib/internal/target"
|
||||||
)
|
)
|
||||||
|
|
||||||
// SyncOptions parameterize a client sync run. RepoURL (with optional Ref)
|
// SyncOptions parameterize a client sync run. RepoURL (with optional Ref)
|
||||||
// is the inline --repo override: it works without any config file and beats
|
// is the inline --repo override: it works without any config file and beats
|
||||||
// a repo_url discovered in the config chain.
|
// a repo_url discovered in the config chain. Force switches the planner
|
||||||
|
// from skip+warn to overwrite for locally modified managed items.
|
||||||
type SyncOptions struct {
|
type SyncOptions struct {
|
||||||
ConfigPath string
|
ConfigPath string
|
||||||
RepoURL string
|
RepoURL string
|
||||||
Ref string
|
Ref string
|
||||||
|
Force bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// prepared is everything sync and status share: the pulled repository, the
|
// prepared is everything sync and status share: the pulled repository, the
|
||||||
@@ -27,6 +34,22 @@ type prepared struct {
|
|||||||
manifest *Manifest
|
manifest *Manifest
|
||||||
items []PlannedItem
|
items []PlannedItem
|
||||||
plan []PlanEntry
|
plan []PlanEntry
|
||||||
|
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.
|
||||||
|
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
|
// prepare pulls, inventories, hashes and plans — the complete read-only
|
||||||
@@ -64,11 +87,29 @@ func prepare(opts SyncOptions) (*prepared, error) {
|
|||||||
return nil, err
|
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))
|
items := make([]PlannedItem, 0, len(inv.Items))
|
||||||
|
deselected := map[string]bool{}
|
||||||
for _, it := range inv.Deployable() {
|
for _, it := range inv.Deployable() {
|
||||||
if _, ok := oc.DeployPath(it.Type, it.Name); !ok {
|
if _, ok := oc.DeployPath(it.Type, it.Name); !ok {
|
||||||
continue
|
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)
|
hash, err := HashItem(pull.Tree, it)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("hashing %s/%s: %w", it.Type, it.Name, err)
|
return nil, fmt.Errorf("hashing %s/%s: %w", it.Type, it.Name, err)
|
||||||
@@ -80,13 +121,48 @@ func prepare(opts SyncOptions) (*prepared, error) {
|
|||||||
path, _ := oc.DeployPath(typ, name)
|
path, _ := oc.DeployPath(typ, name)
|
||||||
return path
|
return path
|
||||||
}
|
}
|
||||||
plan := Plan(items, manifest, diskFacts(oc, manifest, items), pathFor)
|
plan := Plan(items, manifest, diskFacts(oc, manifest, items), pathFor, PlanOptions{Force: opts.Force, Deselected: deselected})
|
||||||
for _, e := range plan {
|
for _, e := range plan {
|
||||||
if !safePath(e.DstPath) {
|
if !safePath(e.DstPath) {
|
||||||
return nil, fmt.Errorf("refusing unsafe deploy path %q", 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:
|
// resolveRunConfig applies the --repo inline override to the config chain:
|
||||||
@@ -99,6 +175,9 @@ func resolveRunConfig(opts SyncOptions) (*ClientConfig, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
cfg.FillTokenAuth()
|
cfg.FillTokenAuth()
|
||||||
|
if err := ApplyAdminLabels(cfg, adminConfigPath()); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
return cfg, nil
|
return cfg, nil
|
||||||
}
|
}
|
||||||
cfg, err := LoadOptionalConfig(opts.ConfigPath)
|
cfg, err := LoadOptionalConfig(opts.ConfigPath)
|
||||||
@@ -113,6 +192,9 @@ func resolveRunConfig(opts SyncOptions) (*ClientConfig, error) {
|
|||||||
cfg.Ref = opts.Ref
|
cfg.Ref = opts.Ref
|
||||||
}
|
}
|
||||||
cfg.FillTokenAuth()
|
cfg.FillTokenAuth()
|
||||||
|
if err := ApplyAdminLabels(cfg, adminConfigPath()); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
return cfg, nil
|
return cfg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -125,6 +207,7 @@ func Sync(opts SyncOptions, stdout io.Writer) (*SyncReport, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
printLabelSelection(stdout, p.labels)
|
||||||
return ExecutePlan(p.pull.Tree, p.plan, p.manifest, p.paths, p.pull.Rev, stdout)
|
return ExecutePlan(p.pull.Tree, p.plan, p.manifest, p.paths, p.pull.Rev, stdout)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,3 +226,27 @@ func safePath(dst string) bool {
|
|||||||
}
|
}
|
||||||
return rel != ".." && rel != "." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
|
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,266 @@
|
|||||||
|
package e2e
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
package e2e
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestVendorRenameAfterAdd(t *testing.T) {
|
||||||
|
h := newHarness(t)
|
||||||
|
standardFixture(h, t)
|
||||||
|
h.mustRun(t, "vendor", "add", "superpowers", h.upstreamDir)
|
||||||
|
|
||||||
|
out := h.mustRun(t, "vendor", "rename", "superpowers", "good-skill=gute-skill", "review=pruefen")
|
||||||
|
for _, want := range []string{"good-skill → gute-skill", "review → pruefen"} {
|
||||||
|
if !contains(out, want) {
|
||||||
|
t.Errorf("report must contain %q:\n%s", want, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
skill := readFile(t, filepath.Join(h.workDir, "external/superpowers/skills/gute-skill/SKILL.md"))
|
||||||
|
if !contains(skill, "name: gute-skill\n") || !contains(skill, "description: works") {
|
||||||
|
t.Errorf("renamed skill must carry the new frontmatter name and keep the rest:\n%s", skill)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(h.workDir, "external/superpowers/skills/gute-skill/helper.py")); err != nil {
|
||||||
|
t.Error("skill artifacts must move with the rename")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(h.workDir, "external/superpowers/skills/good-skill")); err == nil {
|
||||||
|
t.Error("old skill folder must be gone")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(h.workDir, "external/superpowers/commands/pruefen.md")); err != nil {
|
||||||
|
t.Error("renamed command must exist under the new name")
|
||||||
|
}
|
||||||
|
lock := readLock(t, h.workDir)
|
||||||
|
if got := lock.Sources["superpowers"].Renames["good-skill"]; got != "gute-skill" {
|
||||||
|
t.Errorf("lockfile rename = %q", got)
|
||||||
|
}
|
||||||
|
h.mustRun(t, "validate")
|
||||||
|
|
||||||
|
// Listing.
|
||||||
|
if out := h.mustRun(t, "vendor", "rename", "superpowers"); !contains(out, "good-skill → gute-skill") {
|
||||||
|
t.Errorf("listing must show renames:\n%s", out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Survives update with new upstream content.
|
||||||
|
h.write(t, "skills/good-skill/SKILL.md", "---\nname: Good Skill\ndescription: v2\n---\n# Good v2\n")
|
||||||
|
h.commitUpstream(t, "v2")
|
||||||
|
h.mustRun(t, "vendor", "update", "superpowers")
|
||||||
|
skill = readFile(t, filepath.Join(h.workDir, "external/superpowers/skills/gute-skill/SKILL.md"))
|
||||||
|
if !contains(skill, "name: gute-skill\n") || !contains(skill, "description: v2") {
|
||||||
|
t.Errorf("update must keep the rename and frontmatter rewrite:\n%s", skill)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset.
|
||||||
|
h.mustRun(t, "vendor", "rename", "superpowers", "--reset", "good-skill")
|
||||||
|
if _, err := os.Stat(filepath.Join(h.workDir, "external/superpowers/skills/good-skill/SKILL.md")); err != nil {
|
||||||
|
t.Error("reset must restore the upstream folder name")
|
||||||
|
}
|
||||||
|
if got := readLock(t, h.workDir).Sources["superpowers"].Renames["good-skill"]; got != "" {
|
||||||
|
t.Errorf("reset must drop the rename, got %q", got)
|
||||||
|
}
|
||||||
|
h.mustRun(t, "validate")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestVendorRenameRejectsBadInput(t *testing.T) {
|
||||||
|
h := newHarness(t)
|
||||||
|
ownSkillFixture(h, t) // own skills/good-skill
|
||||||
|
standardFixture(h, t)
|
||||||
|
h.mustRun(t, "vendor", "add", "superpowers", h.upstreamDir, "--rename", "good-skill=sp-good")
|
||||||
|
before := readFile(t, filepath.Join(h.workDir, "agent-lib.lock.json"))
|
||||||
|
|
||||||
|
for _, args := range [][]string{
|
||||||
|
{"broken-skill=good-skill"}, // collides with own skill
|
||||||
|
{"good-skill=Gute Skill"}, // invalid skill name
|
||||||
|
{"does-not-exist=whatever"}, // unknown upstream id
|
||||||
|
{"--reset", "broken-skill"}, // nothing to reset
|
||||||
|
} {
|
||||||
|
out, err := h.run(t, append([]string{"vendor", "rename", "superpowers"}, args...)...)
|
||||||
|
if err == nil {
|
||||||
|
t.Errorf("rename %v must fail:\n%s", args, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if after := readFile(t, filepath.Join(h.workDir, "agent-lib.lock.json")); after != before {
|
||||||
|
t.Error("failed renames must not touch the lockfile")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(h.workDir, "external/superpowers/skills/sp-good")); err != nil {
|
||||||
|
t.Error("failed renames must not touch the external area")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package e2e
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestSyncDefaultBranchStaysFresh pins the fix for the stale-cache bug: with
|
||||||
|
// no ref configured, sync must resolve the default branch from the remote
|
||||||
|
// advertisement, never from the cached bare clone's frozen refs/heads ref.
|
||||||
|
func TestSyncDefaultBranchStaysFresh(t *testing.T) {
|
||||||
|
h := newHarness(t)
|
||||||
|
env := newSyncEnv(t, h)
|
||||||
|
buildWorkRepo(t, h, env.workRepo)
|
||||||
|
|
||||||
|
// config without "ref": the default-branch resolution path
|
||||||
|
env.config = filepath.Join(env.configDir, "config.json")
|
||||||
|
os.WriteFile(env.config, []byte(`{"repo_url": "`+env.workRepo+`"}`), 0o600)
|
||||||
|
|
||||||
|
if _, err := env.run(t); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// upstream change on the default branch
|
||||||
|
p := filepath.Join(env.workRepo, "commands/deploy.md")
|
||||||
|
os.WriteFile(p, []byte("---\nname: Deploy\ndescription: updated\n---\nfresh body\n"), 0o644)
|
||||||
|
h.git(t, env.workRepo, "add", "-A")
|
||||||
|
h.git(t, env.workRepo, "commit", "-m", "update command on default branch")
|
||||||
|
|
||||||
|
out, err := env.run(t)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("second sync (default branch) failed: %v\n%s", err, out)
|
||||||
|
}
|
||||||
|
if !contains(out, "updated: 1") {
|
||||||
|
t.Errorf("default-branch sync must pick up the upstream change:\n%s", out)
|
||||||
|
}
|
||||||
|
deployed := readFile(t, filepath.Join(env.home, ".config/opencode/commands/deploy.md"))
|
||||||
|
if !contains(deployed, "fresh body") {
|
||||||
|
t.Error("default-branch sync must deploy the fresh content, not the clone-time revision")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package e2e
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestSyncForceOverwritesLocallyModified pins the --force escape hatch:
|
||||||
|
// locally modified managed items are overwritten with the repository
|
||||||
|
// version, upstream-deleted modified items are removed, and unmanaged
|
||||||
|
// local items are never touched.
|
||||||
|
func TestSyncForceOverwritesLocallyModified(t *testing.T) {
|
||||||
|
h := newHarness(t)
|
||||||
|
env := newSyncEnv(t, h)
|
||||||
|
buildWorkRepo(t, h, env.workRepo)
|
||||||
|
env.writeConfig(t, env.workRepo, "")
|
||||||
|
env.run(t)
|
||||||
|
|
||||||
|
// local drift on a managed item + upstream change to the same item
|
||||||
|
deployed := filepath.Join(env.home, ".config/opencode/commands/deploy.md")
|
||||||
|
os.WriteFile(deployed, []byte("---\nname: Deploy\n---\nlocal drift\n"), 0o644)
|
||||||
|
upstream := filepath.Join(env.workRepo, "commands/deploy.md")
|
||||||
|
os.WriteFile(upstream, []byte("---\nname: Deploy\ndescription: updated\n---\nnew body\n"), 0o644)
|
||||||
|
|
||||||
|
// an unmanaged local item that must survive --force untouched
|
||||||
|
unmanaged := filepath.Join(env.home, ".config/opencode/commands/mine.md")
|
||||||
|
os.MkdirAll(filepath.Dir(unmanaged), 0o755)
|
||||||
|
os.WriteFile(unmanaged, []byte("---\nname: Mine\n---\nprecious\n"), 0o644)
|
||||||
|
|
||||||
|
h.git(t, env.workRepo, "add", "-A")
|
||||||
|
h.git(t, env.workRepo, "commit", "-m", "update deploy command")
|
||||||
|
|
||||||
|
out, err := env.run(t)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("sync failed: %v\n%s", err, out)
|
||||||
|
}
|
||||||
|
if !contains(out, "skipped (local modifications kept): 1") {
|
||||||
|
t.Errorf("default sync must keep the local modification:\n%s", out)
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err = env.run(t, "--force")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("sync --force failed: %v\n%s", err, out)
|
||||||
|
}
|
||||||
|
if !contains(out, "updated: 1") {
|
||||||
|
t.Errorf("force must update the locally modified item:\n%s", out)
|
||||||
|
}
|
||||||
|
if got := readFile(t, deployed); !contains(got, "new body") {
|
||||||
|
t.Error("force must overwrite the local drift with the repository version")
|
||||||
|
}
|
||||||
|
if got := readFile(t, unmanaged); !contains(got, "precious") {
|
||||||
|
t.Error("force must never touch unmanaged local items")
|
||||||
|
}
|
||||||
|
|
||||||
|
// upstream deletion of a locally modified item: force removes it
|
||||||
|
os.WriteFile(deployed, []byte("---\nname: Deploy\n---\nmore drift\n"), 0o644)
|
||||||
|
os.Remove(upstream)
|
||||||
|
h.git(t, env.workRepo, "add", "-A")
|
||||||
|
h.git(t, env.workRepo, "commit", "-m", "delete deploy command")
|
||||||
|
|
||||||
|
out, err = env.run(t)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("sync failed: %v\n%s", err, out)
|
||||||
|
}
|
||||||
|
if !contains(out, "skipped (local modifications kept): 1") {
|
||||||
|
t.Errorf("default sync must keep the modified item after upstream deletion:\n%s", out)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(deployed); err != nil {
|
||||||
|
t.Fatal("item must still exist before force")
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err = env.run(t, "--force")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("sync --force failed: %v\n%s", err, out)
|
||||||
|
}
|
||||||
|
if !contains(out, "removed: 1") {
|
||||||
|
t.Errorf("force must remove the locally modified item after upstream deletion:\n%s", out)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(deployed); !os.IsNotExist(err) {
|
||||||
|
t.Error("forced removal must delete the deployed file")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package e2e
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestVendorAddExcludeMode pins --exclude: all mode minus the listed ids,
|
||||||
|
// materialized and recorded in the lockfile as mode "all" with an exclude
|
||||||
|
// list.
|
||||||
|
func TestVendorAddExcludeMode(t *testing.T) {
|
||||||
|
h := newHarness(t)
|
||||||
|
standardFixture(h, t)
|
||||||
|
|
||||||
|
h.mustRun(t, "vendor", "add", "curated", h.upstreamDir, "--exclude", "broken-skill,scout")
|
||||||
|
|
||||||
|
for _, p := range []string{
|
||||||
|
"external/curated/skills/good-skill/SKILL.md",
|
||||||
|
"external/curated/commands/review.md",
|
||||||
|
"external/curated/mcp/search.yaml",
|
||||||
|
} {
|
||||||
|
if _, err := os.Stat(filepath.Join(h.workDir, p)); err != nil {
|
||||||
|
t.Errorf("non-excluded item must be materialized: %s", p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, p := range []string{
|
||||||
|
"external/curated/skills/broken-skill/SKILL.md",
|
||||||
|
"external/curated/agents/scout.md",
|
||||||
|
} {
|
||||||
|
if _, err := os.Stat(filepath.Join(h.workDir, p)); err == nil {
|
||||||
|
t.Errorf("excluded item must NOT be materialized: %s", p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lock := readFile(t, filepath.Join(h.workDir, "agent-lib.lock.json"))
|
||||||
|
if !contains(lock, `"mode": "all"`) {
|
||||||
|
t.Errorf("exclude keeps all mode:\n%s", lock)
|
||||||
|
}
|
||||||
|
if !contains(lock, `"exclude": [`) {
|
||||||
|
t.Errorf("exclude list must be recorded:\n%s", lock)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestVendorAddExcludeTypoFailsClean pins the typo protection for --exclude.
|
||||||
|
func TestVendorAddExcludeTypoFailsClean(t *testing.T) {
|
||||||
|
h := newHarness(t)
|
||||||
|
standardFixture(h, t)
|
||||||
|
|
||||||
|
out, err := h.run(t, "vendor", "add", "curated", h.upstreamDir, "--exclude", "good-skill,nope")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("typo in exclude list must fail:\n%s", out)
|
||||||
|
}
|
||||||
|
if !contains(out, "exclude entry") && !contains(out, "not found upstream") {
|
||||||
|
t.Errorf("error must name the unknown exclude entry:\n%s", out)
|
||||||
|
}
|
||||||
|
if _, statErr := os.Stat(filepath.Join(h.workDir, "external/curated")); statErr == nil {
|
||||||
|
t.Error("failed add must not leave an external area behind")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestVendorAddIncludeAndExcludeConflict pins the mutual exclusion.
|
||||||
|
func TestVendorAddIncludeAndExcludeConflict(t *testing.T) {
|
||||||
|
h := newHarness(t)
|
||||||
|
standardFixture(h, t)
|
||||||
|
|
||||||
|
out, err := h.run(t, "vendor", "add", "curated", h.upstreamDir,
|
||||||
|
"--include", "good-skill", "--exclude", "scout")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("--include and --exclude together must fail:\n%s", out)
|
||||||
|
}
|
||||||
|
if !contains(out, "--include and --exclude cannot be combined") {
|
||||||
|
t.Errorf("error must explain the conflict:\n%s", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
package e2e
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestVendorAddTypesAllowList pins --types: only the listed content types
|
||||||
|
// enter the work repository, recorded as the canonical exclude_types
|
||||||
|
// complement.
|
||||||
|
func TestVendorAddTypesAllowList(t *testing.T) {
|
||||||
|
h := newHarness(t)
|
||||||
|
standardFixture(h, t)
|
||||||
|
|
||||||
|
h.mustRun(t, "vendor", "add", "curated", h.upstreamDir, "--types", "skills,commands")
|
||||||
|
|
||||||
|
if _, err := os.Stat(filepath.Join(h.workDir, "external/curated/skills/good-skill/SKILL.md")); err != nil {
|
||||||
|
t.Error("allowed skill must be materialized")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(h.workDir, "external/curated/commands/review.md")); err != nil {
|
||||||
|
t.Error("allowed command must be materialized")
|
||||||
|
}
|
||||||
|
for _, p := range []string{
|
||||||
|
"external/curated/agents/scout.md",
|
||||||
|
"external/curated/mcp/search.yaml",
|
||||||
|
} {
|
||||||
|
if _, err := os.Stat(filepath.Join(h.workDir, p)); err == nil {
|
||||||
|
t.Errorf("item of a non-allowed type must NOT be materialized: %s", p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lock := readFile(t, filepath.Join(h.workDir, "agent-lib.lock.json"))
|
||||||
|
if !contains(lock, `"exclude_types": [`) {
|
||||||
|
t.Errorf("type filter must be recorded as exclude_types:\n%s", lock)
|
||||||
|
}
|
||||||
|
if !contains(lock, `"agents"`) || !contains(lock, `"mcp"`) {
|
||||||
|
t.Errorf("exclude_types must hold the complement (agents, mcp):\n%s", lock)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestVendorAddExcludeTypesDenyList pins --exclude-types and its unknown-type
|
||||||
|
// validation.
|
||||||
|
func TestVendorAddExcludeTypesDenyList(t *testing.T) {
|
||||||
|
h := newHarness(t)
|
||||||
|
standardFixture(h, t)
|
||||||
|
|
||||||
|
h.mustRun(t, "vendor", "add", "curated", h.upstreamDir, "--exclude-types", "agents,mcp")
|
||||||
|
|
||||||
|
if _, err := os.Stat(filepath.Join(h.workDir, "external/curated/skills/good-skill/SKILL.md")); err != nil {
|
||||||
|
t.Error("skill must be materialized")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(h.workDir, "external/curated/agents/scout.md")); err == nil {
|
||||||
|
t.Error("agent of an excluded type must NOT be materialized")
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err := h.run(t, "vendor", "add", "other", h.upstreamDir, "--exclude-types", "skillz")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("unknown type must fail:\n%s", out)
|
||||||
|
}
|
||||||
|
if !contains(out, "unknown content type") || !contains(out, "skills, commands, agents, mcp") {
|
||||||
|
t.Errorf("error must list the valid type names:\n%s", out)
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err = h.run(t, "vendor", "add", "other", h.upstreamDir, "--types", "skills", "--exclude-types", "mcp")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("--types and --exclude-types together must fail:\n%s", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestVendorTypesSurviveUpdate pins the whole point of exclude_types: items
|
||||||
|
// of an excluded type that appear upstream later must not slip back in on
|
||||||
|
// vendor update.
|
||||||
|
func TestVendorTypesSurviveUpdate(t *testing.T) {
|
||||||
|
h := newHarness(t)
|
||||||
|
standardFixture(h, t)
|
||||||
|
h.mustRun(t, "vendor", "add", "curated", h.upstreamDir, "--types", "skills")
|
||||||
|
|
||||||
|
// upstream gains a new agent and a new skill
|
||||||
|
h.write(t, "agents/latecomer.md", "---\nname: Latecomer\n---\nbody\n")
|
||||||
|
h.write(t, "skills/new-skill/SKILL.md", "---\nname: New Skill\ndescription: fresh\n---\n# New\n")
|
||||||
|
h.commitUpstream(t, "add latecomer agent and new skill")
|
||||||
|
|
||||||
|
h.mustRun(t, "vendor", "update", "curated")
|
||||||
|
|
||||||
|
if _, err := os.Stat(filepath.Join(h.workDir, "external/curated/skills/new-skill/SKILL.md")); err != nil {
|
||||||
|
t.Error("new skill of an allowed type must be vendored by update")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(h.workDir, "external/curated/agents/latecomer.md")); err == nil {
|
||||||
|
t.Error("new agent of an excluded type must NOT re-enter on update")
|
||||||
|
}
|
||||||
|
lock := readFile(t, filepath.Join(h.workDir, "agent-lib.lock.json"))
|
||||||
|
if !contains(lock, `"exclude_types": [`) {
|
||||||
|
t.Errorf("type filter must survive the update:\n%s", lock)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestVendorSelectTypeFilter pins vendor select parity: --exclude-types /
|
||||||
|
// --types replace the filter, absent flags keep it, --mode all clears it.
|
||||||
|
func TestVendorSelectTypeFilter(t *testing.T) {
|
||||||
|
h := newHarness(t)
|
||||||
|
standardFixture(h, t)
|
||||||
|
h.mustRun(t, "vendor", "add", "curated", h.upstreamDir, "--types", "skills")
|
||||||
|
|
||||||
|
// replacing the filter via --types
|
||||||
|
h.mustRun(t, "vendor", "select", "curated", "--types", "commands")
|
||||||
|
if _, err := os.Stat(filepath.Join(h.workDir, "external/curated/skills/good-skill/SKILL.md")); err == nil {
|
||||||
|
t.Error("skill must be dropped after narrowing the type filter")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(h.workDir, "external/curated/commands/review.md")); err != nil {
|
||||||
|
t.Error("command must be materialized after widening the type filter")
|
||||||
|
}
|
||||||
|
|
||||||
|
// an id-only change keeps the type filter
|
||||||
|
h.mustRun(t, "vendor", "select", "curated", "--remove", "review")
|
||||||
|
if _, err := os.Stat(filepath.Join(h.workDir, "external/curated/commands/review.md")); err == nil {
|
||||||
|
t.Error("excluded command must be gone")
|
||||||
|
}
|
||||||
|
lock := readFile(t, filepath.Join(h.workDir, "agent-lib.lock.json"))
|
||||||
|
if !contains(lock, `"exclude_types": [`) || !contains(lock, `"skills"`) {
|
||||||
|
t.Errorf("type filter must survive an id-only select:\n%s", lock)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --mode all clears everything, including the type filter
|
||||||
|
h.mustRun(t, "vendor", "select", "curated", "--mode", "all")
|
||||||
|
for _, p := range []string{
|
||||||
|
"external/curated/skills/good-skill/SKILL.md",
|
||||||
|
"external/curated/commands/review.md",
|
||||||
|
"external/curated/agents/scout.md",
|
||||||
|
"external/curated/mcp/search.yaml",
|
||||||
|
} {
|
||||||
|
if _, err := os.Stat(filepath.Join(h.workDir, p)); err != nil {
|
||||||
|
t.Errorf("--mode all must re-materialize everything: %s", p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lock = readFile(t, filepath.Join(h.workDir, "agent-lib.lock.json"))
|
||||||
|
if contains(lock, `"exclude_types": [`) {
|
||||||
|
t.Errorf("--mode all must clear the type filter:\n%s", lock)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --mode all combined with type flags stays an error
|
||||||
|
out, err := h.run(t, "vendor", "select", "curated", "--mode", "all", "--types", "skills")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("--mode all with --types must fail:\n%s", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestVendorAddIncludeVsTypeFilter pins the explicit conflict error when an
|
||||||
|
// include id belongs to a type the filter excludes.
|
||||||
|
func TestVendorAddIncludeVsTypeFilter(t *testing.T) {
|
||||||
|
h := newHarness(t)
|
||||||
|
standardFixture(h, t)
|
||||||
|
|
||||||
|
out, err := h.run(t, "vendor", "add", "curated", h.upstreamDir,
|
||||||
|
"--include", "scout", "--exclude-types", "agents")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("include id of an excluded type must fail:\n%s", out)
|
||||||
|
}
|
||||||
|
if !contains(out, "type filter excludes") {
|
||||||
|
t.Errorf("error must explain the conflict:\n%s", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
// 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"
|
||||||
|
"io"
|
||||||
|
"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 _, 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 {
|
||||||
|
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,77 @@
|
|||||||
|
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":{}} {}`,
|
||||||
|
"trailing brace": `{"version":1,"labels":{}}}`,
|
||||||
|
}
|
||||||
|
for name, data := range cases {
|
||||||
|
if _, err := Parse([]byte(data)); err == nil {
|
||||||
|
t.Errorf("%s: expected an error", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -68,11 +68,15 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Selection expresses what enters the work repository: everything minus
|
// Selection expresses what enters the work repository: everything minus
|
||||||
// Exclude (mode all), or exactly Include (mode include).
|
// Exclude (mode all), or exactly Include (mode include). ExcludeTypes
|
||||||
|
// filters whole content types (skills, commands, agents, mcp) on top of
|
||||||
|
// either mode and survives updates: new upstream items of an excluded
|
||||||
|
// type never enter the work repository.
|
||||||
type Selection struct {
|
type Selection struct {
|
||||||
Mode SelectionMode `json:"mode"`
|
Mode SelectionMode `json:"mode"`
|
||||||
Exclude []string `json:"exclude,omitempty"`
|
Exclude []string `json:"exclude,omitempty"`
|
||||||
Include []string `json:"include,omitempty"`
|
Include []string `json:"include,omitempty"`
|
||||||
|
ExcludeTypes []string `json:"exclude_types,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Source pins one vendored git source.
|
// Source pins one vendored git source.
|
||||||
@@ -140,6 +144,7 @@ func (l *Lockfile) Save(path string) error {
|
|||||||
for _, src := range l.Sources {
|
for _, src := range l.Sources {
|
||||||
sort.Strings(src.Selection.Exclude)
|
sort.Strings(src.Selection.Exclude)
|
||||||
sort.Strings(src.Selection.Include)
|
sort.Strings(src.Selection.Include)
|
||||||
|
sort.Strings(src.Selection.ExcludeTypes)
|
||||||
sort.Strings(src.Warnings)
|
sort.Strings(src.Warnings)
|
||||||
for _, items := range src.Inventory {
|
for _, items := range src.Inventory {
|
||||||
sort.Strings(items)
|
sort.Strings(items)
|
||||||
|
|||||||
@@ -6,8 +6,12 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"strings"
|
"strings"
|
||||||
|
"syscall"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// createNoWindow is the Win32 CREATE_NO_WINDOW process creation flag.
|
||||||
|
const createNoWindow = 0x08000000
|
||||||
|
|
||||||
// PowerShellToast raises a Windows toast notification by invoking
|
// PowerShellToast raises a Windows toast notification by invoking
|
||||||
// PowerShell with an AppId-tagged script — the same mechanism go-toast
|
// PowerShell with an AppId-tagged script — the same mechanism go-toast
|
||||||
// uses, without the dependency.
|
// uses, without the dependency.
|
||||||
@@ -36,6 +40,8 @@ func (p PowerShellToast) Send(title, body string) error {
|
|||||||
}
|
}
|
||||||
script := fmt.Sprintf(toastScript, escape(appID), escape(title), escape(body))
|
script := fmt.Sprintf(toastScript, escape(appID), escape(title), escape(body))
|
||||||
cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", script)
|
cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", script)
|
||||||
|
// agent-libw has no console to inherit, so PowerShell would open its own.
|
||||||
|
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: createNoWindow}
|
||||||
if out, err := cmd.CombinedOutput(); err != nil {
|
if out, err := cmd.CombinedOutput(); err != nil {
|
||||||
return fmt.Errorf("toast failed: %v: %s", err, strings.TrimSpace(string(out)))
|
return fmt.Errorf("toast failed: %v: %s", err, strings.TrimSpace(string(out)))
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+120
-12
@@ -21,11 +21,14 @@ const externalDir = "external"
|
|||||||
|
|
||||||
// AddOptions parameterize vendor add.
|
// AddOptions parameterize vendor add.
|
||||||
type AddOptions struct {
|
type AddOptions struct {
|
||||||
Name string
|
Name string
|
||||||
URL string
|
URL string
|
||||||
Ref string
|
Ref string
|
||||||
Include []string
|
Include []string
|
||||||
Renames map[string]string
|
Exclude []string
|
||||||
|
OnlyTypes []string
|
||||||
|
ExcludeTypes []string
|
||||||
|
Renames map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add vendors a new source into the work repository at workDir: it clones,
|
// Add vendors a new source into the work repository at workDir: it clones,
|
||||||
@@ -68,12 +71,29 @@ func Add(workDir string, opts AddOptions, stdout io.Writer) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
sel := lockfile.Selection{Mode: lockfile.ModeAll}
|
if len(opts.Include) > 0 && len(opts.Exclude) > 0 {
|
||||||
if len(opts.Include) > 0 {
|
return fmt.Errorf("--include and --exclude cannot be combined (a v2 selection is either include mode or all mode minus excludes)")
|
||||||
sel = lockfile.Selection{Mode: lockfile.ModeInclude, Include: opts.Include}
|
}
|
||||||
if err := checkIncludeEntries(items, opts.Include, opts.Name); err != nil {
|
excludeTypes, err := TypeFilter(opts.OnlyTypes, opts.ExcludeTypes)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
sel := lockfile.Selection{Mode: lockfile.ModeAll, ExcludeTypes: excludeTypes}
|
||||||
|
switch {
|
||||||
|
case len(opts.Include) > 0:
|
||||||
|
sel = lockfile.Selection{Mode: lockfile.ModeInclude, Include: opts.Include, ExcludeTypes: excludeTypes}
|
||||||
|
if err := checkIDEntries(items, opts.Include, opts.Name, "include"); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
case len(opts.Exclude) > 0:
|
||||||
|
sel.Exclude = opts.Exclude
|
||||||
|
if err := checkIDEntries(items, opts.Exclude, opts.Name, "exclude"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := checkIncludeVsTypes(items, sel, opts.Name); err != nil {
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
selected := applySelection(items, sel)
|
selected := applySelection(items, sel)
|
||||||
@@ -147,21 +167,96 @@ func discoveryFromTreeRoot(root string) lockfile.Discovery {
|
|||||||
return d
|
return d
|
||||||
}
|
}
|
||||||
|
|
||||||
func checkIncludeEntries(items []discovery.Item, include []string, name string) error {
|
// checkIDEntries fails when any id is not available upstream (not discovered
|
||||||
|
// or skipped) — typo protection for include and exclude lists alike.
|
||||||
|
func checkIDEntries(items []discovery.Item, ids []string, name, flag string) error {
|
||||||
available := map[string]bool{}
|
available := map[string]bool{}
|
||||||
for _, it := range items {
|
for _, it := range items {
|
||||||
if !it.Skipped {
|
if !it.Skipped {
|
||||||
available[it.UpstreamID] = true
|
available[it.UpstreamID] = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, want := range include {
|
for _, want := range ids {
|
||||||
if !available[want] {
|
if !available[want] {
|
||||||
return fmt.Errorf("source %q: include entry %q not found upstream (available: %s)", name, want, strings.Join(sortedKeys(available), ", "))
|
return fmt.Errorf("source %q: %s entry %q not found upstream (available: %s)", name, flag, want, strings.Join(sortedKeys(available), ", "))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// checkIncludeVsTypes fails when an include id belongs to a type excluded by
|
||||||
|
// the type filter — silently dropping it would betray the explicit include.
|
||||||
|
func checkIncludeVsTypes(items []discovery.Item, sel lockfile.Selection, name string) error {
|
||||||
|
if sel.Mode != lockfile.ModeInclude || len(sel.ExcludeTypes) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
excluded := map[string]bool{}
|
||||||
|
for _, t := range sel.ExcludeTypes {
|
||||||
|
excluded[t] = true
|
||||||
|
}
|
||||||
|
for _, it := range items {
|
||||||
|
if it.Skipped || !excluded[it.Type] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, id := range sel.Include {
|
||||||
|
if id == it.UpstreamID {
|
||||||
|
return fmt.Errorf("source %q: include entry %q belongs to type %s, which the type filter excludes", name, id, it.Type)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TypeFilter translates --types (allow-list) and --exclude-types (deny-list)
|
||||||
|
// into the canonical exclude_types list: the complement of the allow-list,
|
||||||
|
// or the deny-list verbatim. Both empty means no filter (nil). A filter that
|
||||||
|
// would exclude nothing normalizes to nil; a filter excluding everything is
|
||||||
|
// returned as-is and fails later at the zero-selection guard.
|
||||||
|
func TypeFilter(only, exclude []string) ([]string, error) {
|
||||||
|
if len(only) > 0 && len(exclude) > 0 {
|
||||||
|
return nil, fmt.Errorf("--types and --exclude-types cannot be combined")
|
||||||
|
}
|
||||||
|
if len(only) == 0 && len(exclude) == 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
names := only
|
||||||
|
if len(names) == 0 {
|
||||||
|
names = exclude
|
||||||
|
}
|
||||||
|
valid := map[string]bool{}
|
||||||
|
for _, t := range lockfile.Types {
|
||||||
|
valid[t] = true
|
||||||
|
}
|
||||||
|
var unknown []string
|
||||||
|
for _, t := range names {
|
||||||
|
if !valid[t] {
|
||||||
|
unknown = append(unknown, t)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(unknown) > 0 {
|
||||||
|
return nil, fmt.Errorf("unknown content type(s) %s (valid: %s)", strings.Join(unknown, ", "), strings.Join(lockfile.Types, ", "))
|
||||||
|
}
|
||||||
|
if len(exclude) > 0 {
|
||||||
|
out := append([]string{}, exclude...)
|
||||||
|
sort.Strings(out)
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
allowed := map[string]bool{}
|
||||||
|
for _, t := range only {
|
||||||
|
allowed[t] = true
|
||||||
|
}
|
||||||
|
var out []string
|
||||||
|
for _, t := range lockfile.Types {
|
||||||
|
if !allowed[t] {
|
||||||
|
out = append(out, t)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(out) == 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
func applySelection(items []discovery.Item, sel lockfile.Selection) []discovery.Item {
|
func applySelection(items []discovery.Item, sel lockfile.Selection) []discovery.Item {
|
||||||
exclude := map[string]bool{}
|
exclude := map[string]bool{}
|
||||||
for _, e := range sel.Exclude {
|
for _, e := range sel.Exclude {
|
||||||
@@ -171,11 +266,18 @@ func applySelection(items []discovery.Item, sel lockfile.Selection) []discovery.
|
|||||||
for _, i := range sel.Include {
|
for _, i := range sel.Include {
|
||||||
include[i] = true
|
include[i] = true
|
||||||
}
|
}
|
||||||
|
excludedTypes := map[string]bool{}
|
||||||
|
for _, t := range sel.ExcludeTypes {
|
||||||
|
excludedTypes[t] = true
|
||||||
|
}
|
||||||
var out []discovery.Item
|
var out []discovery.Item
|
||||||
for _, it := range items {
|
for _, it := range items {
|
||||||
if it.Skipped {
|
if it.Skipped {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if excludedTypes[it.Type] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
switch sel.Mode {
|
switch sel.Mode {
|
||||||
case lockfile.ModeInclude:
|
case lockfile.ModeInclude:
|
||||||
if include[it.UpstreamID] {
|
if include[it.UpstreamID] {
|
||||||
@@ -208,6 +310,9 @@ func materialize(workDir, name string, tree discovery.Tree, selected []discovery
|
|||||||
case lockfile.TypeSkill:
|
case lockfile.TypeSkill:
|
||||||
dst = filepath.Join(base, dep)
|
dst = filepath.Join(base, dep)
|
||||||
err = deploy.Dir(tree, it.RelPath, dst)
|
err = deploy.Dir(tree, it.RelPath, dst)
|
||||||
|
if err == nil && dep != it.UpstreamID {
|
||||||
|
err = rewriteSkillName(dst, dep)
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
dst = filepath.Join(base, dep+filepath.Ext(it.RelPath))
|
dst = filepath.Join(base, dep+filepath.Ext(it.RelPath))
|
||||||
err = deploy.File(tree, it.RelPath, dst)
|
err = deploy.File(tree, it.RelPath, dst)
|
||||||
@@ -251,6 +356,9 @@ func reportAdd(w io.Writer, name string, src *lockfile.Source, discovered, selec
|
|||||||
fmt.Fprintf(w, " rev: %s\n", src.Rev)
|
fmt.Fprintf(w, " rev: %s\n", src.Rev)
|
||||||
fmt.Fprintf(w, "discovered %d items (%s)\n", real, counts(discovered))
|
fmt.Fprintf(w, "discovered %d items (%s)\n", real, counts(discovered))
|
||||||
fmt.Fprintf(w, "selected %d items (%s)\n", len(selected), counts(selected))
|
fmt.Fprintf(w, "selected %d items (%s)\n", len(selected), counts(selected))
|
||||||
|
if len(src.Selection.ExcludeTypes) > 0 {
|
||||||
|
fmt.Fprintf(w, "type filter: excluding %s\n", strings.Join(src.Selection.ExcludeTypes, ", "))
|
||||||
|
}
|
||||||
fmt.Fprintf(w, "materialized under %s/\n", filepath.Join(externalDir, name))
|
fmt.Fprintf(w, "materialized under %s/\n", filepath.Join(externalDir, name))
|
||||||
if len(src.Warnings) > 0 {
|
if len(src.Warnings) > 0 {
|
||||||
fmt.Fprintf(w, "warnings:\n")
|
fmt.Fprintf(w, "warnings:\n")
|
||||||
|
|||||||
Vendored
+4
-2
@@ -103,8 +103,10 @@ func checkCollisions(workDir string, lf *lockfile.Lockfile, source string, selec
|
|||||||
seen := map[string]string{}
|
seen := map[string]string{}
|
||||||
for _, it := range selected {
|
for _, it := range selected {
|
||||||
deployed := deployedName(it.UpstreamID, renames)
|
deployed := deployedName(it.UpstreamID, renames)
|
||||||
if deployed == "" {
|
if deployed != it.UpstreamID {
|
||||||
return fmt.Errorf("source %q: rename of %q maps to an empty name", source, it.UpstreamID)
|
if err := validateRenameTarget(it.Type, it.UpstreamID, deployed); err != nil {
|
||||||
|
return fmt.Errorf("source %q: %w", source, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if prev, dup := seen[deployed]; dup {
|
if prev, dup := seen[deployed]; dup {
|
||||||
return &CollisionError{
|
return &CollisionError{
|
||||||
|
|||||||
+25
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
+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"
|
"strings"
|
||||||
|
|
||||||
"github.com/m3tam3re/agent-lib/internal/discovery"
|
"github.com/m3tam3re/agent-lib/internal/discovery"
|
||||||
|
"github.com/m3tam3re/agent-lib/internal/labels"
|
||||||
"github.com/m3tam3re/agent-lib/internal/lockfile"
|
"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.checkExternalArea(workDir, name, src)
|
||||||
}
|
}
|
||||||
v.Errors = append(v.Errors, validateCollisions(workDir, lf)...)
|
v.Errors = append(v.Errors, validateCollisions(workDir, lf)...)
|
||||||
|
v.checkLabels(workDir, lf)
|
||||||
sort.Slice(v.Errors, func(i, j int) bool {
|
sort.Slice(v.Errors, func(i, j int) bool {
|
||||||
if v.Errors[i].Source != v.Errors[j].Source {
|
if v.Errors[i].Source != v.Errors[j].Source {
|
||||||
return 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
|
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) {
|
func (v *Validation) fail(source, rule, format string, args ...any) {
|
||||||
v.Errors = append(v.Errors, ValidationError{
|
v.Errors = append(v.Errors, ValidationError{
|
||||||
Source: source,
|
Source: source,
|
||||||
|
|||||||
Vendored
+235
@@ -0,0 +1,235 @@
|
|||||||
|
package vendor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
|
||||||
|
"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"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RenameOptions parameterize vendor rename.
|
||||||
|
type RenameOptions struct {
|
||||||
|
// Set maps upstream ids to new deployed names. Mapping an id onto itself
|
||||||
|
// is the same as resetting it.
|
||||||
|
Set map[string]string
|
||||||
|
// Reset drops existing renames so the items deploy under their upstream id.
|
||||||
|
Reset []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rename changes the deployed names of a vendored source's items after the
|
||||||
|
// fact — without advancing the pinned revision or touching the selection.
|
||||||
|
// Ids are validated against the pinned upstream, collisions re-run, and the
|
||||||
|
// external area is rewritten atomically. With no options it only lists the
|
||||||
|
// current renames.
|
||||||
|
func Rename(workDir, name string, opts RenameOptions, stdout io.Writer) error {
|
||||||
|
lockPath := filepath.Join(workDir, lockfile.FileName)
|
||||||
|
lf, err := lockfile.Load(lockPath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
src, ok := lf.Sources[name]
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("source %q is not in the lockfile", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(opts.Set) == 0 && len(opts.Reset) == 0 {
|
||||||
|
printRenames(stdout, name, src.Renames)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
newRenames := map[string]string{}
|
||||||
|
for k, v := range src.Renames {
|
||||||
|
newRenames[k] = v
|
||||||
|
}
|
||||||
|
for _, id := range opts.Reset {
|
||||||
|
if _, ok := newRenames[id]; !ok {
|
||||||
|
return fmt.Errorf("source %q: --reset %q has no rename to reset", name, id)
|
||||||
|
}
|
||||||
|
delete(newRenames, id)
|
||||||
|
}
|
||||||
|
for up, dep := range opts.Set {
|
||||||
|
if up == dep {
|
||||||
|
delete(newRenames, up)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
newRenames[up] = dep
|
||||||
|
}
|
||||||
|
|
||||||
|
repo, err := gitsource.Clone(src.URL, src.Ref)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
pinned, err := repo.Pin(src.Rev)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("%w — run vendor update to re-pin", err)
|
||||||
|
}
|
||||||
|
tree, err := pinned.Tree()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
items, err := discovery.Scan(tree, discovery.FromLockfileDiscovery(derefDiscovery(src)))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
ids := append(sortedKeys(boolSet(keysOf(opts.Set))), opts.Reset...)
|
||||||
|
if err := checkIDEntries(items, ids, name, "rename"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
types := map[string]string{}
|
||||||
|
for _, it := range items {
|
||||||
|
if !it.Skipped {
|
||||||
|
types[it.UpstreamID] = it.Type
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for up, dep := range opts.Set {
|
||||||
|
if up == dep {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := validateRenameTarget(types[up], up, dep); err != nil {
|
||||||
|
return fmt.Errorf("source %q: %w", name, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
selected := applySelection(items, src.Selection)
|
||||||
|
if err := checkCollisions(workDir, lf, name, selected, newRenames); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanupStaleStaging(workDir)
|
||||||
|
staging := filepath.Join(workDir, externalDir, ".staging-"+name)
|
||||||
|
if err := os.RemoveAll(staging); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := materializeTree(tree, selected, newRenames, staging); err != nil {
|
||||||
|
os.RemoveAll(staging)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
oldDir := filepath.Join(workDir, externalDir, name)
|
||||||
|
if err := os.RemoveAll(oldDir); err != nil {
|
||||||
|
return fmt.Errorf("replacing %s: %w", oldDir, err)
|
||||||
|
}
|
||||||
|
if err := os.Rename(staging, oldDir); err != nil {
|
||||||
|
return fmt.Errorf("swapping in new external area: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
oldRenames := src.Renames
|
||||||
|
if len(newRenames) == 0 {
|
||||||
|
newRenames = nil
|
||||||
|
}
|
||||||
|
src.Renames = newRenames
|
||||||
|
src.Inventory = inventoryOf(selected)
|
||||||
|
src.Warnings = dedupe(warningsOf(items))
|
||||||
|
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))
|
||||||
|
for _, id := range ids {
|
||||||
|
before := deployedName(id, oldRenames)
|
||||||
|
after := deployedName(id, newRenames)
|
||||||
|
note := ""
|
||||||
|
if !inSelection[types[id]][id] {
|
||||||
|
note = " (not selected — applies once added)"
|
||||||
|
}
|
||||||
|
if before == after {
|
||||||
|
fmt.Fprintf(stdout, " %s %s: unchanged (%s)%s\n", types[id], id, after, note)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, " %s %s: %s → %s%s\n", types[id], id, before, after, note)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func printRenames(w io.Writer, name string, renames map[string]string) {
|
||||||
|
if len(renames) == 0 {
|
||||||
|
fmt.Fprintf(w, "source %s: no renames\n", name)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "source %s renames (upstream → deployed):\n", name)
|
||||||
|
ups := make([]string, 0, len(renames))
|
||||||
|
for up := range renames {
|
||||||
|
ups = append(ups, up)
|
||||||
|
}
|
||||||
|
sort.Strings(ups)
|
||||||
|
for _, up := range ups {
|
||||||
|
fmt.Fprintf(w, " %s → %s\n", up, renames[up])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func keysOf(m map[string]string) []string {
|
||||||
|
out := make([]string, 0, len(m))
|
||||||
|
for k := range m {
|
||||||
|
out = append(out, k)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func boolSet(ids []string) map[string]bool {
|
||||||
|
out := map[string]bool{}
|
||||||
|
for _, id := range ids {
|
||||||
|
out[id] = true
|
||||||
|
}
|
||||||
|
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)
|
||||||
|
}
|
||||||
Vendored
+37
-16
@@ -15,9 +15,11 @@ import (
|
|||||||
|
|
||||||
// SelectOptions parameterize vendor select.
|
// SelectOptions parameterize vendor select.
|
||||||
type SelectOptions struct {
|
type SelectOptions struct {
|
||||||
Add []string
|
Add []string
|
||||||
Remove []string
|
Remove []string
|
||||||
ModeAll bool
|
ModeAll bool
|
||||||
|
OnlyTypes []string
|
||||||
|
ExcludeTypes []string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Select changes what a vendored source contributes — without advancing the
|
// Select changes what a vendored source contributes — without advancing the
|
||||||
@@ -60,6 +62,9 @@ func Select(workDir, name string, opts SelectOptions, stdout io.Writer) (*Change
|
|||||||
if err := validateSelectIDs(items, src, opts, name); err != nil {
|
if err := validateSelectIDs(items, src, opts, name); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if err := checkIncludeVsTypes(items, newSel, name); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
selected := applySelection(items, newSel)
|
selected := applySelection(items, newSel)
|
||||||
if err := checkCollisions(workDir, lf, name, selected, src.Renames); err != nil {
|
if err := checkCollisions(workDir, lf, name, selected, src.Renames); err != nil {
|
||||||
@@ -99,6 +104,9 @@ func Select(workDir, name string, opts SelectOptions, stdout io.Writer) (*Change
|
|||||||
}
|
}
|
||||||
|
|
||||||
fmt.Fprintf(stdout, "source %s: selection updated at pinned rev %s (mode %s)\n", name, short(src.Rev), newSel.Mode)
|
fmt.Fprintf(stdout, "source %s: selection updated at pinned rev %s (mode %s)\n", name, short(src.Rev), newSel.Mode)
|
||||||
|
if len(newSel.ExcludeTypes) > 0 {
|
||||||
|
fmt.Fprintf(stdout, " type filter: excluding %s\n", strings.Join(newSel.ExcludeTypes, ", "))
|
||||||
|
}
|
||||||
printChangeReport(stdout, report)
|
printChangeReport(stdout, report)
|
||||||
return report, nil
|
return report, nil
|
||||||
}
|
}
|
||||||
@@ -106,30 +114,43 @@ func Select(workDir, name string, opts SelectOptions, stdout io.Writer) (*Change
|
|||||||
// planSelection derives the new selection from the flags — pure, before any
|
// planSelection derives the new selection from the flags — pure, before any
|
||||||
// upstream contact: --mode all resets to everything; include mode grows and
|
// upstream contact: --mode all resets to everything; include mode grows and
|
||||||
// shrinks the include list; all mode --remove moves ids onto the exclude
|
// shrinks the include list; all mode --remove moves ids onto the exclude
|
||||||
// list.
|
// list. --types/--exclude-types replace the type filter (absent flags keep
|
||||||
|
// it; --mode all clears it along with include/exclude).
|
||||||
func planSelection(src *lockfile.Source, opts SelectOptions, name string) (lockfile.Selection, error) {
|
func planSelection(src *lockfile.Source, opts SelectOptions, name string) (lockfile.Selection, error) {
|
||||||
|
typeFilter, err := TypeFilter(opts.OnlyTypes, opts.ExcludeTypes)
|
||||||
|
if err != nil {
|
||||||
|
return lockfile.Selection{}, err
|
||||||
|
}
|
||||||
if opts.ModeAll {
|
if opts.ModeAll {
|
||||||
if len(opts.Add) > 0 || len(opts.Remove) > 0 {
|
if len(opts.Add) > 0 || len(opts.Remove) > 0 || typeFilter != nil {
|
||||||
return lockfile.Selection{}, fmt.Errorf("--mode all cannot be combined with --add or --remove")
|
return lockfile.Selection{}, fmt.Errorf("--mode all cannot be combined with --add, --remove, --types or --exclude-types")
|
||||||
}
|
}
|
||||||
return lockfile.Selection{Mode: lockfile.ModeAll}, nil
|
return lockfile.Selection{Mode: lockfile.ModeAll}, nil
|
||||||
}
|
}
|
||||||
if len(opts.Add) == 0 && len(opts.Remove) == 0 {
|
if len(opts.Add) == 0 && len(opts.Remove) == 0 && typeFilter == nil {
|
||||||
return lockfile.Selection{}, fmt.Errorf("nothing to do: pass --add <ids>, --remove <ids> or --mode all")
|
return lockfile.Selection{}, fmt.Errorf("nothing to do: pass --add <ids>, --remove <ids>, --types/--exclude-types or --mode all")
|
||||||
}
|
}
|
||||||
|
var newSel lockfile.Selection
|
||||||
if src.Selection.Mode == lockfile.ModeAll {
|
if src.Selection.Mode == lockfile.ModeAll {
|
||||||
if len(opts.Add) > 0 {
|
if len(opts.Add) > 0 {
|
||||||
return lockfile.Selection{}, fmt.Errorf("source %q: everything is already selected in all mode; use --remove <ids> to exclude items", name)
|
return lockfile.Selection{}, fmt.Errorf("source %q: everything is already selected in all mode; use --remove <ids> to exclude items", name)
|
||||||
}
|
}
|
||||||
return lockfile.Selection{
|
newSel = lockfile.Selection{
|
||||||
Mode: lockfile.ModeAll,
|
Mode: lockfile.ModeAll,
|
||||||
Exclude: unionIDs(src.Selection.Exclude, opts.Remove),
|
Exclude: unionIDs(src.Selection.Exclude, opts.Remove),
|
||||||
}, nil
|
}
|
||||||
|
} else {
|
||||||
|
newSel = lockfile.Selection{
|
||||||
|
Mode: lockfile.ModeInclude,
|
||||||
|
Include: unionIDs(minusIDs(src.Selection.Include, opts.Remove), opts.Add),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return lockfile.Selection{
|
if typeFilter != nil {
|
||||||
Mode: lockfile.ModeInclude,
|
newSel.ExcludeTypes = typeFilter
|
||||||
Include: unionIDs(minusIDs(src.Selection.Include, opts.Remove), opts.Add),
|
} else {
|
||||||
}, nil
|
newSel.ExcludeTypes = src.Selection.ExcludeTypes
|
||||||
|
}
|
||||||
|
return newSel, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// validateSelectIDs checks flag ids against the pinned upstream (and, for
|
// validateSelectIDs checks flag ids against the pinned upstream (and, for
|
||||||
@@ -137,7 +158,7 @@ func planSelection(src *lockfile.Source, opts SelectOptions, name string) (lockf
|
|||||||
// before anything is mutated.
|
// before anything is mutated.
|
||||||
func validateSelectIDs(items []discovery.Item, src *lockfile.Source, opts SelectOptions, name string) error {
|
func validateSelectIDs(items []discovery.Item, src *lockfile.Source, opts SelectOptions, name string) error {
|
||||||
if len(opts.Add) > 0 {
|
if len(opts.Add) > 0 {
|
||||||
if err := checkIncludeEntries(items, opts.Add, name); err != nil {
|
if err := checkIDEntries(items, opts.Add, name, "include"); err != nil {
|
||||||
return fmt.Errorf("--add: %w", err)
|
return fmt.Errorf("--add: %w", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -153,7 +174,7 @@ func validateSelectIDs(items []discovery.Item, src *lockfile.Source, opts Select
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(opts.Remove) > 0 && src.Selection.Mode == lockfile.ModeAll {
|
if len(opts.Remove) > 0 && src.Selection.Mode == lockfile.ModeAll {
|
||||||
if err := checkIncludeEntries(items, opts.Remove, name); err != nil {
|
if err := checkIDEntries(items, opts.Remove, name, "exclude"); err != nil {
|
||||||
return fmt.Errorf("--remove: %w", err)
|
return fmt.Errorf("--remove: %w", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+91
@@ -0,0 +1,91 @@
|
|||||||
|
package vendor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/m3tam3re/agent-lib/internal/lockfile"
|
||||||
|
)
|
||||||
|
|
||||||
|
// skillNameRe is the OpenCode / Agent Skills naming rule: lowercase
|
||||||
|
// alphanumerics with single hyphen separators. OpenCode additionally requires
|
||||||
|
// the SKILL.md frontmatter name to equal the folder name.
|
||||||
|
var skillNameRe = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*$`)
|
||||||
|
|
||||||
|
const maxSkillNameLen = 64
|
||||||
|
|
||||||
|
// validateRenameTarget checks a deployed-name override before it becomes a
|
||||||
|
// path segment. Every type rejects path separators and dot-names; skills must
|
||||||
|
// additionally follow the OpenCode skill naming rule so the renamed skill
|
||||||
|
// still loads.
|
||||||
|
func validateRenameTarget(typ, upstreamID, deployed string) error {
|
||||||
|
if deployed == "" {
|
||||||
|
return fmt.Errorf("rename of %q maps to an empty name", upstreamID)
|
||||||
|
}
|
||||||
|
if strings.ContainsAny(deployed, `/\`) || strings.HasPrefix(deployed, ".") || strings.TrimSpace(deployed) != deployed {
|
||||||
|
return fmt.Errorf("rename of %q to %q: name must be a single path segment without leading dot or surrounding whitespace", upstreamID, deployed)
|
||||||
|
}
|
||||||
|
if typ == lockfile.TypeSkill {
|
||||||
|
if len(deployed) > maxSkillNameLen || !skillNameRe.MatchString(deployed) {
|
||||||
|
return fmt.Errorf("rename of skill %q to %q: skill names must be 1-%d lowercase letters, digits and single hyphens (e.g. \"code-review\")", upstreamID, deployed, maxSkillNameLen)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// rewriteSkillName sets the frontmatter `name:` of dir/SKILL.md to name so a
|
||||||
|
// renamed skill matches its folder (OpenCode loads skills by that pairing and
|
||||||
|
// shows the frontmatter name to the user). A missing name key is inserted, a
|
||||||
|
// missing frontmatter block is created. Everything else stays byte-identical.
|
||||||
|
func rewriteSkillName(dir, name string) error {
|
||||||
|
path := filepath.Join(dir, "SKILL.md")
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out := setFrontmatterName(string(data), name)
|
||||||
|
if out == string(data) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
tmp := path + ".agent-lib-tmp"
|
||||||
|
if err := os.WriteFile(tmp, []byte(out), info.Mode().Perm()); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.Rename(tmp, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
func setFrontmatterName(content, name string) string {
|
||||||
|
lines := strings.SplitAfter(content, "\n")
|
||||||
|
if len(lines) == 0 || strings.TrimRight(lines[0], "\r\n") != "---" {
|
||||||
|
return "---\nname: " + name + "\n---\n" + content
|
||||||
|
}
|
||||||
|
eol := "\n"
|
||||||
|
if strings.HasSuffix(lines[0], "\r\n") {
|
||||||
|
eol = "\r\n"
|
||||||
|
}
|
||||||
|
for i := 1; i < len(lines); i++ {
|
||||||
|
bare := strings.TrimRight(lines[i], "\r\n")
|
||||||
|
if bare == "---" {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if bare == "" || bare[0] == ' ' || bare[0] == '\t' {
|
||||||
|
continue // nested/continuation lines never carry the top-level name
|
||||||
|
}
|
||||||
|
key, _, ok := strings.Cut(bare, ":")
|
||||||
|
if ok && strings.EqualFold(strings.TrimSpace(key), "name") {
|
||||||
|
lineEOL := lines[i][len(bare):]
|
||||||
|
lines[i] = "name: " + name + lineEOL
|
||||||
|
return strings.Join(lines, "")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// No name key: insert one right after the opening fence.
|
||||||
|
rest := strings.Join(lines[1:], "")
|
||||||
|
return lines[0] + "name: " + name + eol + rest
|
||||||
|
}
|
||||||
Vendored
+39
@@ -0,0 +1,39 @@
|
|||||||
|
package vendor
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestSetFrontmatterName(t *testing.T) {
|
||||||
|
cases := []struct{ name, in, want string }{
|
||||||
|
{"replace", "---\nname: Good Skill\ndescription: d\n---\nbody\n", "---\nname: ideen\ndescription: d\n---\nbody\n"},
|
||||||
|
{"crlf", "---\r\nname: x\r\n---\r\nb", "---\r\nname: ideen\r\n---\r\nb"},
|
||||||
|
{"insert", "---\ndescription: d\n---\n", "---\nname: ideen\ndescription: d\n---\n"},
|
||||||
|
{"no frontmatter", "# Title\n", "---\nname: ideen\n---\n# Title\n"},
|
||||||
|
{"nested name untouched", "---\nmeta:\n name: inner\n---\n", "---\nname: ideen\nmeta:\n name: inner\n---\n"},
|
||||||
|
{"name in body untouched", "---\ndescription: d\n---\nname: body\n", "---\nname: ideen\ndescription: d\n---\nname: body\n"},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
if got := setFrontmatterName(c.in, "ideen"); got != c.want {
|
||||||
|
t.Errorf("%s:\n got %q\nwant %q", c.name, got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateRenameTarget(t *testing.T) {
|
||||||
|
ok := []struct{ typ, dep string }{
|
||||||
|
{"skills", "code-review"}, {"skills", "a1"}, {"commands", "Review_Things"},
|
||||||
|
}
|
||||||
|
for _, c := range ok {
|
||||||
|
if err := validateRenameTarget(c.typ, "up", c.dep); err != nil {
|
||||||
|
t.Errorf("%s %q should be valid: %v", c.typ, c.dep, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bad := []struct{ typ, dep string }{
|
||||||
|
{"skills", "Code Review"}, {"skills", "code--review"}, {"skills", "-x"}, {"skills", "Gross"},
|
||||||
|
{"commands", "../x"}, {"agents", "a/b"}, {"commands", ".hidden"}, {"skills", ""},
|
||||||
|
}
|
||||||
|
for _, c := range bad {
|
||||||
|
if err := validateRenameTarget(c.typ, "up", c.dep); err == nil {
|
||||||
|
t.Errorf("%s %q should be rejected", c.typ, c.dep)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+9
-1
@@ -197,7 +197,7 @@ func computeUpdate(workDir string, lf *lockfile.Lockfile, name string, withColli
|
|||||||
}
|
}
|
||||||
|
|
||||||
if src.Selection.Mode == lockfile.ModeInclude {
|
if src.Selection.Mode == lockfile.ModeInclude {
|
||||||
if err := checkIncludeEntries(items, src.Selection.Include, name); err != nil {
|
if err := checkIDEntries(items, src.Selection.Include, name, "include"); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -250,6 +250,11 @@ func cleanupStaleStaging(workDir string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func materializeTree(tree discovery.Tree, selected []discovery.Item, renames map[string]string, dst string) error {
|
func materializeTree(tree discovery.Tree, selected []discovery.Item, renames map[string]string, dst string) error {
|
||||||
|
// Create dst even for an empty selection: the caller swaps it in with a
|
||||||
|
// rename, which fails when nothing materialized the directory.
|
||||||
|
if err := os.MkdirAll(dst, 0o755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
for _, it := range selected {
|
for _, it := range selected {
|
||||||
dep := deployedName(it.UpstreamID, renames)
|
dep := deployedName(it.UpstreamID, renames)
|
||||||
base := filepath.Join(dst, it.Type)
|
base := filepath.Join(dst, it.Type)
|
||||||
@@ -259,6 +264,9 @@ func materializeTree(tree discovery.Tree, selected []discovery.Item, renames map
|
|||||||
case lockfile.TypeSkill:
|
case lockfile.TypeSkill:
|
||||||
target = filepath.Join(base, dep)
|
target = filepath.Join(base, dep)
|
||||||
err = deploy.Dir(tree, it.RelPath, target)
|
err = deploy.Dir(tree, it.RelPath, target)
|
||||||
|
if err == nil && dep != it.UpstreamID {
|
||||||
|
err = rewriteSkillName(target, dep)
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
target = filepath.Join(base, dep+filepath.Ext(it.RelPath))
|
target = filepath.Join(base, dep+filepath.Ext(it.RelPath))
|
||||||
err = deploy.File(tree, it.RelPath, target)
|
err = deploy.File(tree, it.RelPath, target)
|
||||||
|
|||||||
@@ -81,6 +81,26 @@ assert_no_file "$WR3/external" "no partial external area"
|
|||||||
assert_file "$WR3/external/sp/skills/sp-good/SKILL.md" "renamed folder carries deployed name"
|
assert_file "$WR3/external/sp/skills/sp-good/SKILL.md" "renamed folder carries deployed name"
|
||||||
assert_no_file "$WR3/external/sp/skills/good-skill" "upstream name absent after rename"
|
assert_no_file "$WR3/external/sp/skills/good-skill" "upstream name absent after rename"
|
||||||
|
|
||||||
|
step "vendor add selection flags (--exclude, --types)"
|
||||||
|
WR4="$WORK/work-repo-4"
|
||||||
|
mkdir -p "$WR4"
|
||||||
|
(cd "$WR4" && "$BIN" vendor add cur "$UP" --exclude broken-skill) > "$WORK/exclude.log" 2>&1
|
||||||
|
assert_exit_zero $? "add --exclude succeeds"
|
||||||
|
assert_no_file "$WR4/external/cur/skills/broken-skill" "excluded skill absent"
|
||||||
|
assert_file "$WR4/external/cur/skills/good-skill/SKILL.md" "non-excluded skill present"
|
||||||
|
assert_contains "$WR4/agent-lib.lock.json" '"exclude": [' "exclude list pinned"
|
||||||
|
WR5="$WORK/work-repo-5"
|
||||||
|
mkdir -p "$WR5"
|
||||||
|
(cd "$WR5" && "$BIN" vendor add typed "$UP" --types skills,commands) > "$WORK/types.log" 2>&1
|
||||||
|
assert_exit_zero $? "add --types succeeds"
|
||||||
|
assert_no_file "$WR5/external/typed/agents" "agent type filtered out"
|
||||||
|
assert_no_file "$WR5/external/typed/mcp" "mcp type filtered out"
|
||||||
|
assert_contains "$WR5/agent-lib.lock.json" '"exclude_types": [' "type filter pinned"
|
||||||
|
set +e
|
||||||
|
(cd "$WR5" && "$BIN" vendor add bad "$UP" --include good-skill --exclude broken-skill) > "$WORK/flagconflict.log" 2>&1; RCX=$?
|
||||||
|
set -e
|
||||||
|
assert_exit_nonzero "$RCX" "--include + --exclude rejected"
|
||||||
|
|
||||||
step "validate / list / inspect"
|
step "validate / list / inspect"
|
||||||
(cd "$WR" && "$BIN" validate) > "$WORK/validate.log" 2>&1
|
(cd "$WR" && "$BIN" validate) > "$WORK/validate.log" 2>&1
|
||||||
assert_exit_zero $? "healthy state validates"
|
assert_exit_zero $? "healthy state validates"
|
||||||
@@ -114,6 +134,15 @@ assert_no_file "$WR/external/superpowers" "remove leaves no residue"
|
|||||||
(cd "$WR" && "$BIN" vendor add superpowers "$UP") >/dev/null 2>&1
|
(cd "$WR" && "$BIN" vendor add superpowers "$UP") >/dev/null 2>&1
|
||||||
git -C "$WR" add -A && git -C "$WR" commit -qm "vendor superpowers (publication = commit && push)"
|
git -C "$WR" add -A && git -C "$WR" commit -qm "vendor superpowers (publication = commit && push)"
|
||||||
|
|
||||||
|
step "vendor select type filter parity"
|
||||||
|
(cd "$WR5" && "$BIN" vendor select typed --exclude-types skills) > "$WORK/types-select.log" 2>&1
|
||||||
|
assert_exit_zero $? "select --exclude-types succeeds"
|
||||||
|
assert_no_file "$WR5/external/typed/skills" "skills dropped after narrowing the filter"
|
||||||
|
assert_contains "$WORK/types-select.log" "type filter" "select reports the type filter"
|
||||||
|
(cd "$WR5" && "$BIN" vendor select typed --mode all) > "$WORK/types-reset.log" 2>&1
|
||||||
|
assert_exit_zero $? "select --mode all clears the filter"
|
||||||
|
assert_file "$WR5/external/typed/skills/good-skill/SKILL.md" "skills restored after --mode all"
|
||||||
|
|
||||||
step "employee sync"
|
step "employee sync"
|
||||||
HOME_DIR="$WORK/employee-home"
|
HOME_DIR="$WORK/employee-home"
|
||||||
STATE="$WORK/employee-state"
|
STATE="$WORK/employee-state"
|
||||||
@@ -142,6 +171,31 @@ assert_exit_zero "$RC2" "second sync succeeds"
|
|||||||
printf '%s' "$OUT2" > "$WORK/sync2.log"
|
printf '%s' "$OUT2" > "$WORK/sync2.log"
|
||||||
assert_contains "$WORK/sync2.log" "kept:" "second run keeps everything"
|
assert_contains "$WORK/sync2.log" "kept:" "second run keeps everything"
|
||||||
|
|
||||||
|
step "default branch stays fresh without ref"
|
||||||
|
DB="$WORK/db-repo"
|
||||||
|
mkdir -p "$DB/skills/db-skill"
|
||||||
|
git -C "$DB" init -q -b main
|
||||||
|
printf -- '---\nname: DB\n---\n# v1\n' > "$DB/skills/db-skill/SKILL.md"
|
||||||
|
git -C "$DB" add -A && git -C "$DB" commit -qm "db v1"
|
||||||
|
DBCFG="$WORK/db-config.json"
|
||||||
|
printf '{"repo_url":"%s"}\n' "$DB" > "$DBCFG"
|
||||||
|
DBHOME="$WORK/db-home"; DBSTATE="$WORK/db-state"
|
||||||
|
mkdir -p "$DBHOME" "$DBSTATE"
|
||||||
|
set +e
|
||||||
|
HOME="$DBHOME" USERPROFILE="$DBHOME" AGENT_LIB_STATE_DIR="$DBSTATE" \
|
||||||
|
"$BIN" sync --config "$DBCFG" >/dev/null 2>&1; RCDB=$?
|
||||||
|
set -e
|
||||||
|
assert_exit_zero "$RCDB" "first default-branch sync (clone)"
|
||||||
|
printf -- '---\nname: DB\n---\n# v2\n' > "$DB/skills/db-skill/SKILL.md"
|
||||||
|
git -C "$DB" add -A && git -C "$DB" commit -qm "db v2"
|
||||||
|
set +e
|
||||||
|
HOME="$DBHOME" USERPROFILE="$DBHOME" AGENT_LIB_STATE_DIR="$DBSTATE" \
|
||||||
|
"$BIN" sync --config "$DBCFG" > "$WORK/db2.log" 2>&1; RCDB2=$?
|
||||||
|
set -e
|
||||||
|
assert_exit_zero "$RCDB2" "second default-branch sync (fetch)"
|
||||||
|
assert_contains "$WORK/db2.log" "updated: 1" "default branch advanced past the clone-time revision"
|
||||||
|
grep -q "# v2" "$DBHOME/.agents/skills/db-skill/SKILL.md" && ok "fresh content deployed" || fail "stale clone-time content served"
|
||||||
|
|
||||||
step "protected sync: local modification wins"
|
step "protected sync: local modification wins"
|
||||||
printf -- '---\nname: Own Skill\n---\n# MY EDITS\n' > "$HOME_DIR/.agents/skills/own-skill/SKILL.md"
|
printf -- '---\nname: Own Skill\n---\n# MY EDITS\n' > "$HOME_DIR/.agents/skills/own-skill/SKILL.md"
|
||||||
printf -- '---\nname: Own Skill\ndescription: v2\n---\n# Upstream v2\n' > "$WR/skills/own-skill/SKILL.md"
|
printf -- '---\nname: Own Skill\ndescription: v2\n---\n# Upstream v2\n' > "$WR/skills/own-skill/SKILL.md"
|
||||||
@@ -153,6 +207,18 @@ assert_contains "$WORK/sync3.log" "skipped (local modifications kept): 1" "modif
|
|||||||
grep -q "MY EDITS" "$HOME_DIR/.agents/skills/own-skill/SKILL.md" && ok "local version kept" || fail "local version overwritten"
|
grep -q "MY EDITS" "$HOME_DIR/.agents/skills/own-skill/SKILL.md" && ok "local version kept" || fail "local version overwritten"
|
||||||
assert_contains "$STATE/sync.log" "SKIP skills/own-skill" "warning logged with item and reason"
|
assert_contains "$STATE/sync.log" "SKIP skills/own-skill" "warning logged with item and reason"
|
||||||
|
|
||||||
|
step "forced sync: repository version wins"
|
||||||
|
set +e
|
||||||
|
OUTF="$(HOME="$HOME_DIR" USERPROFILE="$HOME_DIR" AGENT_LIB_STATE_DIR="$STATE" \
|
||||||
|
"$BIN" sync --config "$CFG" --force 2>&1)"; RCF=$?
|
||||||
|
set -e
|
||||||
|
assert_exit_zero "$RCF" "sync --force succeeds"
|
||||||
|
printf '%s' "$OUTF" > "$WORK/syncf.log"
|
||||||
|
assert_contains "$WORK/syncf.log" "updated:" "forced overwrite reported as update"
|
||||||
|
grep -q "Upstream v2" "$HOME_DIR/.agents/skills/own-skill/SKILL.md" && ok "repository version restored" || fail "local modification survived --force"
|
||||||
|
# re-introduce drift so the upstream-deletion walk below has a modified copy
|
||||||
|
printf -- '---\nname: Own Skill\n---\n# MY EDITS\n' > "$HOME_DIR/.agents/skills/own-skill/SKILL.md"
|
||||||
|
|
||||||
step "self-created item survives"
|
step "self-created item survives"
|
||||||
MINE="$HOME_DIR/.agents/skills/my-private-skill"
|
MINE="$HOME_DIR/.agents/skills/my-private-skill"
|
||||||
mkdir -p "$MINE" && printf -- '---\nname: Mine\n---\n' > "$MINE/SKILL.md"
|
mkdir -p "$MINE" && printf -- '---\nname: Mine\n---\n' > "$MINE/SKILL.md"
|
||||||
@@ -189,6 +255,18 @@ set +e; OUTSJ="$(HOME="$HOME_DIR" USERPROFILE="$HOME_DIR" AGENT_LIB_STATE_DIR="$
|
|||||||
assert_exit_nonzero "$RCSJ" "status --json keeps drift exit code"
|
assert_exit_nonzero "$RCSJ" "status --json keeps drift exit code"
|
||||||
printf '%s' "$OUTSJ" | grep -q '"problematic_drift": true' && ok "json drift flag set" || fail "json drift flag missing"
|
printf '%s' "$OUTSJ" | grep -q '"problematic_drift": true' && ok "json drift flag set" || fail "json drift flag missing"
|
||||||
|
|
||||||
|
step "forced sync after upstream deletion removes modified copies"
|
||||||
|
set +e
|
||||||
|
OUTR="$(HOME="$HOME_DIR" USERPROFILE="$HOME_DIR" AGENT_LIB_STATE_DIR="$STATE" \
|
||||||
|
"$BIN" sync --config "$CFG" --force 2>&1)"; RCR=$?
|
||||||
|
set -e
|
||||||
|
assert_exit_zero "$RCR" "sync --force after deletion succeeds"
|
||||||
|
printf '%s' "$OUTR" > "$WORK/syncr.log"
|
||||||
|
assert_contains "$WORK/syncr.log" "removed:" "forced removals reported"
|
||||||
|
assert_no_file "$HOME_DIR/.agents/skills/own-skill" "modified skill removed by force"
|
||||||
|
assert_no_file "$HOME_DIR/.config/opencode/agents/scout.md" "modified agent removed by force"
|
||||||
|
assert_file "$MINE/SKILL.md" "unmanaged item survives --force untouched"
|
||||||
|
|
||||||
step "unreachable repository keeps state"
|
step "unreachable repository keeps state"
|
||||||
BEFORE="$(cat "$HOME_DIR/.agents/skills/fresh-skill/SKILL.md")"
|
BEFORE="$(cat "$HOME_DIR/.agents/skills/fresh-skill/SKILL.md")"
|
||||||
printf '{"repo_url":"%s","ref":"main"}\n' "$WORK/nonexistent-repo" > "$CFG"
|
printf '{"repo_url":"%s","ref":"main"}\n' "$WORK/nonexistent-repo" > "$CFG"
|
||||||
|
|||||||
Reference in new issue
Block a user