Author SHA1 Message Date
m3ta-chiron 01ab8227fb dolt remote info 2026-11-14 11:04:11 +01:00
90 changed files with 7 additions and 10251 deletions

No files matched your search

-80
View File
@@ -1,80 +0,0 @@
---
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.
-4
View File
@@ -1,4 +0,0 @@
interface:
display_name: "Beads"
short_description: "Project task tracking with bd"
default_prompt: "Use $beads to inspect ready work and manage durable project tasks."
-1
View File
@@ -1 +0,0 @@
{"size":51360,"mtime_ns":1793863936779644645}
-77
View File
@@ -1,77 +0,0 @@
# Dolt database (managed by Dolt, not git)
dolt/
embeddeddolt/
# Runtime files
bd.sock
bd.sock.startlock
sync-state.json
last-touched
.exclusive-lock
# Daemon runtime (lock, log, pid)
daemon.*
# Push state (runtime, per-machine)
push-state.json
# Lock files (various runtime locks)
*.lock
# Credential key (encryption key for federation peer auth — never commit)
.beads-credential-key
# Local version tracking (prevents upgrade notification spam after git ops)
.local_version
# Worktree redirect file (contains relative path to main repo's .beads/)
# Must not be committed as paths would be wrong in other clones
redirect
# Sync state (local-only, per-machine)
# These files are machine-specific and should not be shared across clones
.sync.lock
export-state/
export-state.json
# Ephemeral store (SQLite - wisps/molecules, intentionally not versioned)
ephemeral.sqlite3
ephemeral.sqlite3-journal
ephemeral.sqlite3-wal
ephemeral.sqlite3-shm
# Dolt server management (auto-started by bd)
dolt-server.pid
dolt-server.log
dolt-server.lock
dolt-server.port
dolt-server.activity
# Corrupt backup directories (created by bd doctor --fix recovery)
*.corrupt.backup/
# Backup data (auto-exported JSONL, local-only)
backup/
# Per-project environment file (Dolt connection config, GH#2520)
.env
# Legacy files (from pre-Dolt versions)
*.db
*.db?*
*.db-journal
*.db-wal
*.db-shm
db.sqlite
bd.db
# NOTE: Do NOT add negation patterns here.
# They would override fork protection in .git/info/exclude.
# Config files (metadata.json, config.yaml) are tracked by git by default
# 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
-81
View File
@@ -1,81 +0,0 @@
# Beads - AI-Native Issue Tracking
Welcome to Beads! This repository uses **Beads** for issue tracking - a modern, AI-native tool designed to live directly in your codebase alongside your code.
## What is Beads?
Beads is issue tracking that lives in your repo, making it perfect for AI coding agents and developers who want their issues close to their code. No web UI required - everything works through the CLI and integrates seamlessly with git.
**Learn more:** [github.com/steveyegge/beads](https://github.com/steveyegge/beads)
## Quick Start
### Essential Commands
```bash
# Create new issues
bd create "Add user authentication"
# View all issues
bd list
# View issue details
bd show <issue-id>
# Update issue status
bd update <issue-id> --claim
bd update <issue-id> --status done
# Sync with Dolt remote
bd dolt push
```
### Working with Issues
Issues in Beads are:
- **Git-native**: Stored in Dolt database with version control and branching
- **AI-friendly**: CLI-first design works perfectly with AI coding agents
- **Branch-aware**: Issues can follow your branch workflow
- **Always in sync**: Auto-syncs with your commits
## Why Beads?
✨ **AI-Native Design**
- Built specifically for AI-assisted development workflows
- CLI-first interface works seamlessly with AI coding agents
- No context switching to web UIs
🚀 **Developer Focused**
- Issues live in your repo, right next to your code
- Works offline, syncs when you push
- Fast, lightweight, and stays out of your way
🔧 **Git Integration**
- Automatic sync with git commits
- Branch-aware issue tracking
- Dolt-native three-way merge resolution
## Get Started with Beads
Try Beads in your own projects:
```bash
# Install Beads
curl -sSL https://raw.githubusercontent.com/steveyegge/beads/main/scripts/install.sh | bash
# Initialize in your repo
bd init
# Create your first issue
bd create "Try out Beads"
```
## Learn More
- **Documentation**: [github.com/steveyegge/beads/docs](https://github.com/steveyegge/beads/tree/main/docs)
- **Quick Start Guide**: Run `bd quickstart`
- **Examples**: [github.com/steveyegge/beads/examples](https://github.com/steveyegge/beads/tree/main/examples)
---
*Beads: Issue tracking that moves at the speed of thought* ⚡
-5
View File
@@ -1,5 +0,0 @@
no-git-ops: true
sync:
remote: "git+ssh://gitea@code.m3ta.dev/m3tam3re/agent-lib.git"
export:
auto: true
-59
View File
@@ -1,59 +0,0 @@
#!/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 ---
-59
View File
@@ -1,59 +0,0 @@
#!/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 ---
-59
View File
@@ -1,59 +0,0 @@
#!/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 ---
-59
View File
@@ -1,59 +0,0 @@
#!/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 ---
-59
View File
@@ -1,59 +0,0 @@
#!/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 ---
-30
View File
@@ -1,30 +0,0 @@
{"id":"int-58dc40ee","kind":"field_change","created_at":"2026-05-28T06:40:53.266160436Z","actor":"m3ta-chiron","issue_id":"agent-lib-4wx.1","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}}
{"id":"int-c96014b1","kind":"field_change","created_at":"2026-05-28T06:51:57.995522933Z","actor":"m3ta-chiron","issue_id":"agent-lib-4wx.2","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}}
{"id":"int-8ec2fe7f","kind":"field_change","created_at":"2026-05-28T06:57:14.054839388Z","actor":"m3ta-chiron","issue_id":"agent-lib-4wx.3","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}}
{"id":"int-5ef02067","kind":"field_change","created_at":"2026-05-28T07:00:18.483464037Z","actor":"m3ta-chiron","issue_id":"agent-lib-4wx.4","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}}
{"id":"int-b12d010f","kind":"field_change","created_at":"2026-05-28T07:15:22.597226799Z","actor":"m3ta-chiron","issue_id":"agent-lib-4wx.5","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}}
{"id":"int-4608df17","kind":"field_change","created_at":"2026-05-28T07:20:45.404215963Z","actor":"m3ta-chiron","issue_id":"agent-lib-4wx.6","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}}
{"id":"int-8a35ddbf","kind":"field_change","created_at":"2026-05-28T07:23:24.229234781Z","actor":"m3ta-chiron","issue_id":"agent-lib-4wx.7","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}}
{"id":"int-af8bd7ce","kind":"field_change","created_at":"2026-05-28T07:24:47.032378976Z","actor":"m3ta-chiron","issue_id":"agent-lib-4wx.8","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}}
{"id":"int-e6245ea7","kind":"field_change","created_at":"2026-05-28T07:39:25.408163902Z","actor":"m3ta-chiron","issue_id":"agent-lib-4wx.9","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}}
{"id":"int-3d420466","kind":"field_change","created_at":"2026-05-28T07:46:27.577138032Z","actor":"m3ta-chiron","issue_id":"agent-lib-4wx.10","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}}
{"id":"int-f444e5d1","kind":"field_change","created_at":"2026-05-28T08:13:14.820734703Z","actor":"m3ta-chiron","issue_id":"agent-lib-4wx.11","extra":{"field":"status","new_value":"closed","old_value":"in_progress"}}
{"id":"int-b1779011c451e8aecfac8a15e2c332b8","kind":"field_change","created_at":"2026-06-13T07:55:57.404556723Z","actor":"m3ta-chiron","issue_id":"agent-lib-j6b","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Architecture review report written and opened: /tmp/architecture-review-20260613-075521.html"}}
{"id":"int-eaab83169be77c1e6a853e502b70362f","kind":"field_change","created_at":"2026-06-13T08:17:27.20786458Z","actor":"m3ta-chiron","issue_id":"agent-lib-feu","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Babysitter Deployment Plan exploration completed. Artifact: .a5c/deployment-plan-exploration.md. Run: 01KV00D3F73F6KY5Q8W4TFER5X"}}
{"id":"int-4d5bf5dc890a6963a0e1110a8fb71635","kind":"field_change","created_at":"2026-08-22T19:43:28.592284059Z","actor":"m3ta-chiron","issue_id":"agent-lib-j2w.1","extra":{"field":"status","new_value":"closed","old_value":"open"}}
{"id":"int-090714c2a2d985183cc965b11b5c53d8","kind":"field_change","created_at":"2026-08-22T19:52:30.546382863Z","actor":"m3ta-chiron","issue_id":"agent-lib-j2w.10","extra":{"field":"status","new_value":"closed","old_value":"in_progress"}}
{"id":"int-c5834aa5e95b421826d076fd129d7a1a","kind":"field_change","created_at":"2026-08-22T19:54:32.168882535Z","actor":"m3ta-chiron","issue_id":"agent-lib-j2w.2","extra":{"field":"status","new_value":"closed","old_value":"in_progress"}}
{"id":"int-b7efd31fd41bbb5acd082eb3c2f34dbd","kind":"field_change","created_at":"2026-08-22T19:56:21.734777976Z","actor":"m3ta-chiron","issue_id":"agent-lib-j2w.3","extra":{"field":"status","new_value":"closed","old_value":"in_progress"}}
{"id":"int-d0f6b2e3946129f47ed8f071902a5c78","kind":"field_change","created_at":"2026-08-22T20:01:15.960626197Z","actor":"m3ta-chiron","issue_id":"agent-lib-j2w.4","extra":{"field":"status","new_value":"closed","old_value":"in_progress"}}
{"id":"int-baf99558287967cfd7c3aeb9c0e6354c","kind":"field_change","created_at":"2026-08-23T08:31:08.602480836Z","actor":"m3ta-chiron","issue_id":"agent-lib-j2w.5","extra":{"field":"status","new_value":"closed","old_value":"in_progress"}}
{"id":"int-41040467e9dbadf410d0563d3775e728","kind":"field_change","created_at":"2026-08-23T08:36:53.924991634Z","actor":"m3ta-chiron","issue_id":"agent-lib-j2w.6","extra":{"field":"status","new_value":"closed","old_value":"in_progress"}}
{"id":"int-06e7ec6923aa26fc3a5eb446c5aa001c","kind":"field_change","created_at":"2026-08-23T08:40:34.06547132Z","actor":"m3ta-chiron","issue_id":"agent-lib-j2w.7","extra":{"field":"status","new_value":"closed","old_value":"in_progress"}}
{"id":"int-b75bf2027708c976d3772b28e613cd65","kind":"field_change","created_at":"2026-08-23T08:47:26.764431384Z","actor":"m3ta-chiron","issue_id":"agent-lib-j2w.8","extra":{"field":"status","new_value":"closed","old_value":"in_progress"}}
{"id":"int-cebf102ccf1bf8528c4fec36a8f42cc7","kind":"field_change","created_at":"2026-08-23T08:47:26.967094464Z","actor":"m3ta-chiron","issue_id":"agent-lib-j2w","extra":{"field":"status","new_value":"closed","old_value":"open"}}
{"id":"int-bd14ae37b3379485b36911ca7a2bbe15","kind":"field_change","created_at":"2026-08-23T08:47:27.131938505Z","actor":"m3ta-chiron","issue_id":"agent-lib-4wx","extra":{"field":"status","new_value":"closed","old_value":"open"}}
{"id":"int-9a5615ca0f4de20c5fe9fafb139cd3b2","kind":"field_change","created_at":"2026-08-23T13:03:54.908000849Z","actor":"m3ta-chiron","issue_id":"agent-lib-9o8","extra":{"field":"status","new_value":"in_progress","old_value":"open"}}
{"id":"int-005ddaf8341eee855d7ef445384c1eb2","kind":"field_change","created_at":"2026-08-23T13:08:31.340775217Z","actor":"m3ta-chiron","issue_id":"agent-lib-cd3","extra":{"field":"status","new_value":"in_progress","old_value":"open"}}
{"id":"int-6a3ffee4df39714f0a8a1cefdf51368a","kind":"field_change","created_at":"2026-08-23T13:08:55.524996787Z","actor":"m3ta-chiron","issue_id":"agent-lib-9o8","extra":{"field":"status","new_value":"closed","old_value":"in_progress"}}
{"id":"int-4e8b40d542411129531fce3d50d010d3","kind":"field_change","created_at":"2026-08-23T13:13:54.796811925Z","actor":"m3ta-chiron","issue_id":"agent-lib-cd3","extra":{"field":"status","new_value":"closed","old_value":"in_progress"}}
{"id":"int-ef6081b577d921a381ae9c71cc12ba08","kind":"field_change","created_at":"2026-08-23T13:15:45.502686945Z","actor":"m3ta-chiron","issue_id":"agent-lib-2n7","extra":{"field":"status","new_value":"in_progress","old_value":"open"}}
{"id":"int-4db074ab41df585e161f9113a52af827","kind":"field_change","created_at":"2026-08-23T13:17:57.282225246Z","actor":"m3ta-chiron","issue_id":"agent-lib-2n7","extra":{"field":"status","new_value":"closed","old_value":"in_progress"}}
-13
View File
@@ -1,13 +0,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.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.8","title":"Deploy selected Items to the Pi Target","description":"Create the first Rendered output path for Pi, from selected Canonical Artifacts through the Pi Adapter into a target Manifest and deployable Linux/XDG target structure. The slice should support Skills, Prompts, and Agent Definitions as far as the verified Pi contract allows, while failing on incompatible Items.","acceptance_criteria":"- A selected Skill, Prompt, and Agent Definition can be rendered or deployed to the Pi Target according to the verified Adapter contract\n- The Pi Manifest records Source, Item identifier, content type, targetName, rev, narHash, and adapterVersion for every deployed Item\n- The deployment path is read-only/symlink-oriented by default, includes provenance for rendered files, and never overwrites unmanaged files","status":"closed","priority":2,"issue_type":"feature","assignee":"m3ta-chiron","owner":"p@m3ta.dev","created_at":"2026-05-27T17:49:47Z","created_by":"m3tam3re","updated_at":"2026-05-28T07:24:47Z","started_at":"2026-05-28T07:23:38Z","closed_at":"2026-05-28T07:24:47Z","close_reason":"Closed","labels":["ready-for-agent"],"dependencies":[{"issue_id":"agent-lib-4wx.8","depends_on_id":"agent-lib-4wx","type":"parent-child","created_at":"2026-05-27T19:49:46Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.8","depends_on_id":"agent-lib-4wx.4","type":"blocks","created_at":"2026-05-27T19:49:47Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.8","depends_on_id":"agent-lib-4wx.6","type":"blocks","created_at":"2026-05-27T19:49:47Z","created_by":"m3tam3re","metadata":"{}"}],"dependency_count":2,"dependent_count":3,"comment_count":0}
{"_type":"issue","id":"agent-lib-4wx.7","title":"Deploy selected Items to the Opencode Target","description":"Create the first Rendered output path for Opencode, from selected Canonical Artifacts through the Opencode Adapter into a target Manifest and deployable Linux/XDG target structure. The slice should support Skills, Prompts, and Agent Definitions as far as the verified Opencode contract allows, while failing on incompatible Items.","acceptance_criteria":"- A selected Skill, Prompt, and Agent Definition can be rendered or deployed to the Opencode Target according to the verified Adapter contract\n- The Opencode Manifest records Source, Item identifier, content type, targetName, rev, narHash, and adapterVersion for every deployed Item\n- The deployment path is read-only/symlink-oriented by default, includes provenance for rendered files, and never overwrites unmanaged files","status":"closed","priority":2,"issue_type":"feature","assignee":"m3ta-chiron","owner":"p@m3ta.dev","created_at":"2026-05-27T17:49:42Z","created_by":"m3tam3re","updated_at":"2026-05-28T07:23:24Z","started_at":"2026-05-28T07:21:06Z","closed_at":"2026-05-28T07:23:24Z","close_reason":"Closed","labels":["ready-for-agent"],"dependencies":[{"issue_id":"agent-lib-4wx.7","depends_on_id":"agent-lib-4wx","type":"parent-child","created_at":"2026-05-27T19:49:41Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.7","depends_on_id":"agent-lib-4wx.4","type":"blocks","created_at":"2026-05-27T19:49:42Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.7","depends_on_id":"agent-lib-4wx.6","type":"blocks","created_at":"2026-05-27T19:49:42Z","created_by":"m3tam3re","metadata":"{}"}],"dependency_count":2,"dependent_count":3,"comment_count":0}
{"_type":"issue","id":"agent-lib-4wx.6","title":"Verify Target Adapter contracts and scaffold the registry","description":"Establish the Target Adapter Registry and verify the native Target contracts for Pi and Opencode before rendering any real output. The slice should encode supported content types, adapterVersion, Linux/XDG default paths, compatibility rules, and scaffold Crush/Amp as known but not implemented Targets.","acceptance_criteria":"- Pi and Opencode Target conventions are researched, documented in the implementation, and represented as Adapter metadata with adapterVersion\n- Crush and Amp are represented in the registry as scaffolded Targets that fail explicitly if enabled before implementation\n- Adapter compatibility and unsupported Target behavior are tested independently from the Home Manager deployment pipeline","status":"closed","priority":2,"issue_type":"feature","assignee":"m3ta-chiron","owner":"p@m3ta.dev","created_at":"2026-05-27T17:49:37Z","created_by":"m3tam3re","updated_at":"2026-05-28T07:20:45Z","started_at":"2026-05-28T07:15:42Z","closed_at":"2026-05-28T07:20:45Z","close_reason":"Closed","labels":["ready-for-agent"],"dependencies":[{"issue_id":"agent-lib-4wx.6","depends_on_id":"agent-lib-4wx","type":"parent-child","created_at":"2026-05-27T19:49:37Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.6","depends_on_id":"agent-lib-4wx.1","type":"blocks","created_at":"2026-05-27T19:49:37Z","created_by":"m3tam3re","metadata":"{}"}],"dependency_count":1,"dependent_count":3,"comment_count":0}
{"_type":"issue","id":"agent-lib-4wx.5","title":"Support all/include/exclude and Profile merge validation","description":"Extend the Selection Model to cover all supported selection semantics across multiple Profiles. The slice should normalize all/include/exclude, merge Profiles by union, reject ambiguous or conflicting selections, and expose the same fail-fast behavior through Home Manager evaluation and CLI validation where applicable.","acceptance_criteria":"- all, include, and exclude are normalized per Source and content type, with all=true plus include rejected and exclude allowed only with all=true\n- Multiple Profiles merge by union when compatible and fail when the same Item has conflicting overrides\n- Validation errors are precise and tested for unknown Sources, unknown Items, include/exclude conflicts, and incompatible selection semantics","status":"closed","priority":2,"issue_type":"feature","assignee":"m3ta-chiron","owner":"p@m3ta.dev","created_at":"2026-05-27T17:49:32Z","created_by":"m3tam3re","updated_at":"2026-05-28T07:15:23Z","started_at":"2026-05-28T07:07:23Z","closed_at":"2026-05-28T07:15:23Z","close_reason":"Closed","labels":["ready-for-agent"],"dependencies":[{"issue_id":"agent-lib-4wx.5","depends_on_id":"agent-lib-4wx","type":"parent-child","created_at":"2026-05-27T19:49:32Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.5","depends_on_id":"agent-lib-4wx.4","type":"blocks","created_at":"2026-05-27T19:49:32Z","created_by":"m3tam3re","metadata":"{}"}],"dependency_count":1,"dependent_count":2,"comment_count":0}
{"_type":"issue","id":"agent-lib-4wx.4","title":"Select one explicit Item into Canonical output","description":"Implement the first selected-Item path from Lockfile inventory through Profile include configuration into Canonical output. The slice should prove that explicit selection is required, unknown Sources/Items fail fast, target override data is preserved, and the selected Artifact remains a whole folder in Canonical output.","acceptance_criteria":"- A Profile can explicitly include one Item from a Source and produce a Canonical output Artifact for it\n- No Item is selected by default, and unknown Source or Item references fail with errors that include Source, type, Item, and Profile context\n- The Canonical output preserves the whole Artifact folder, including references and permissions, without target-specific rendering","status":"closed","priority":2,"issue_type":"feature","assignee":"m3ta-chiron","owner":"p@m3ta.dev","created_at":"2026-05-27T17:49:27Z","created_by":"m3tam3re","updated_at":"2026-05-28T07:00:18Z","started_at":"2026-05-28T06:57:29Z","closed_at":"2026-05-28T07:00:18Z","close_reason":"Closed","labels":["ready-for-agent"],"dependencies":[{"issue_id":"agent-lib-4wx.4","depends_on_id":"agent-lib-4wx","type":"parent-child","created_at":"2026-05-27T19:49:27Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.4","depends_on_id":"agent-lib-4wx.2","type":"blocks","created_at":"2026-05-27T19:49:27Z","created_by":"m3tam3re","metadata":"{}"}],"dependency_count":1,"dependent_count":4,"comment_count":0}
{"_type":"issue","id":"agent-lib-4wx.3","title":"Add and update reproducible Git Sources","description":"Add the first reproducible Git Source workflow, from provider-neutral and known Web tree URLs through the Source Resolver into pinned Lockfile entries. The slice should resolve refs to rev/narHash, run Discovery, support update/remove/list/inspect/update-all, and report added/removed Items using local Git fixtures rather than external network tests.","acceptance_criteria":"- source add resolves a Git Source ref to rev and narHash, normalizes supported Web tree URLs, runs Discovery, and writes a deterministic Lockfile\n- source update, source update --all, source remove, source list, and source inspect preserve reproducibility and report Item inventory changes\n- Private repository credentials are never stored in the Lockfile, submodules are unsupported, and default tests use temporary local Git repositories","status":"closed","priority":2,"issue_type":"feature","assignee":"m3ta-chiron","owner":"p@m3ta.dev","created_at":"2026-05-27T17:49:22Z","created_by":"m3tam3re","updated_at":"2026-05-28T06:57:14Z","started_at":"2026-05-28T06:52:15Z","closed_at":"2026-05-28T06:57:14Z","close_reason":"Closed","labels":["ready-for-agent"],"dependencies":[{"issue_id":"agent-lib-4wx.3","depends_on_id":"agent-lib-4wx","type":"parent-child","created_at":"2026-05-27T19:49:22Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.3","depends_on_id":"agent-lib-4wx.1","type":"blocks","created_at":"2026-05-27T19:49:22Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.3","depends_on_id":"agent-lib-4wx.2","type":"blocks","created_at":"2026-05-27T19:49:22Z","created_by":"m3tam3re","metadata":"{}"}],"dependency_count":2,"dependent_count":2,"comment_count":0}
{"_type":"issue","id":"agent-lib-4wx.2","title":"Discover a local fixture Source into a Lockfile inventory","description":"Create the first content-bearing path from a local fixture Source through the Discovery Engine into the Lockfile inventory. The slice should discover Skills, Prompts, Agent Definitions, and Tool Manifests as whole Artifacts with Entry files, Metadata, warnings, and license hints, then expose the result through CLI inspect/validate output and Home Manager inventory validation.","acceptance_criteria":"- A local fixture Source produces Lockfile Items for Skills, Prompts, Agent Definitions, and Tool Manifests, including nested Item identifiers\n- Discovery records Entry file, Artifact path, Metadata, warnings, and license file hints without executing any source content\n- CLI inspect and validate expose the discovered inventory in human-readable and JSON output, and tests run offline against fixtures","status":"closed","priority":2,"issue_type":"feature","assignee":"m3ta-chiron","owner":"p@m3ta.dev","created_at":"2026-05-27T17:49:17Z","created_by":"m3tam3re","updated_at":"2026-05-28T06:51:58Z","started_at":"2026-05-28T06:41:02Z","closed_at":"2026-05-28T06:51:58Z","close_reason":"Closed","labels":["ready-for-agent"],"dependencies":[{"issue_id":"agent-lib-4wx.2","depends_on_id":"agent-lib-4wx","type":"parent-child","created_at":"2026-05-27T19:49:17Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.2","depends_on_id":"agent-lib-4wx.1","type":"blocks","created_at":"2026-05-27T19:49:17Z","created_by":"m3tam3re","metadata":"{}"}],"dependency_count":1,"dependent_count":3,"comment_count":0}
{"_type":"issue","id":"agent-lib-4wx.1","title":"Bootstrap the empty agent-lib installation path","description":"Establish the first demoable path through the empty project: a Nix flake, development shell, CLI entry point, empty Lockfile initialization, importable Home Manager module, fixture skeleton, and a green baseline check. This slice should prove that agent-lib can be installed, initialized, and validated without any real Source content yet.","acceptance_criteria":"- agent-lib init creates a deterministic empty Lockfile with the expected schema version and no active Items\n- The Home Manager module can be imported and evaluated with agent-lib disabled and enabled against an empty Lockfile\n- The project quality gate runs offline and covers the baseline CLI, Nix, formatting, and fixture skeleton","status":"closed","priority":2,"issue_type":"feature","assignee":"m3ta-chiron","owner":"p@m3ta.dev","created_at":"2026-05-27T17:49:11Z","created_by":"m3tam3re","updated_at":"2026-05-28T06:40:53Z","started_at":"2026-05-27T18:00:14Z","closed_at":"2026-05-28T06:40:53Z","close_reason":"Closed","labels":["ready-for-agent"],"dependencies":[{"issue_id":"agent-lib-4wx.1","depends_on_id":"agent-lib-4wx","type":"parent-child","created_at":"2026-05-27T19:49:11Z","created_by":"m3tam3re","metadata":"{}"}],"dependency_count":0,"dependent_count":4,"comment_count":0}
{"_type":"issue","id":"agent-lib-4wx","title":"agent-lib PRD v1.0","description":"Product Requirements Document for agent-lib: an agent-independent library infrastructure built on Nix flakes and Home Manager. See docs/prd.md for the full document.","notes":"# agent-lib: Product Requirements Document\n\n**Status:** Draft \n**Version:** 1.0\n\n---\n\n## Problem Statement\n\nUsers who rely on multiple AI agent runtimes — such as Pi, Opencode, Crush, and Amp — face a fragmented and manually maintained experience when it comes to managing skills, prompts, and agent definitions. Existing approaches are agent-specific: configurations are copied, modified, and versioned separately for each runtime. This makes it difficult to:\n\n- Share and reuse skills across different agent runtimes\n- Reproduce a consistent agent environment across machines and systems\n- Import content from external repositories in a controlled, reproducible way\n- Manage which content is active on which target platform\n\nThere is no unified, agent-independent abstraction layer that allows a user to manage a canonical library of skills, prompts, and agent definitions — and then deploy precisely selected subsets to specific runtime targets in a deterministic, declarative way.\n\n---\n\n## Solution\n\n**agent-lib** is an agent-independent library infrastructure built on Nix flakes and Home Manager. It provides:\n\n1. A **canonical model** for skills, prompts, agent definitions, and tool manifests — stored as structured artifacts, not agent-specific configs\n2. A **Python CLI** for managing source repositories, discovering items, and producing configuration snippets — without ever editing Nix files automatically\n3. A **Home Manager module** that consumes a versioned lockfile and declarative profile selections to produce target-specific deployment artifacts\n4. **Target adapters** for supported runtimes (Pi and Opencode in MVP; Crush and Amp scaffolded)\n5. A **provenance-aware deployment pipeline** that keeps original artifacts immutable and renders target-specific outputs separately\n\nThe result: a single declarative source of truth for your agent library, deployed reproducibly to any supported target.\n\n---\n\n## User Stories\n\n### Source Management\n\n1. As a user, I want to add an external Git repository as a source, so that I can import skills and other content from shared libraries.\n2. As a user, I want the CLI to automatically pin the current commit (rev) and narHash when adding a source, so that my library is reproducible.\n3. As a user, I want to optionally specify a branch or tag (ref) when adding a source, so that I can target a specific release line.\n4. As a user, I want the CLI to resolve the default branch when no ref is specified, so that I do not have to know the branch name in advance.\n5. As a user, I want the CLI to normalize GitHub/GitLab/Web tree URLs (e.g., `https://github.com/org/repo/tree/main/skills`) into provider-neutral git URLs, so that I can paste URLs directly from browser tabs.\n6. As a user, I want to update a source to the latest version of its ref, so that I can pull in upstream changes.\n7. As a user, I want `source update` to update both the rev/narHash and the full discovery inventory, so that pins and artifacts stay in sync.\n8. As a user, I want to update all sources at once with `source update --all`, so that I can refresh my entire library efficiently.\n9. As a user, I want to remove a source from the lockfile, so that I can clean up deprecated or unwanted repositories.\n10. As a user, I want the CLI to warn when a source is still referenced in my Home Manager configuration after removal, so that I am not surprised by Nix eval failures.\n11. As a user, I want to list all configured sources with their current rev and item counts, so that I can review my library at a glance.\n12. As a user, I want to inspect a specific source in detail, so that I can see what skills, prompts, agents, and tool manifests are available.\n13. As a user, I want the CLI to detect and report when a source already exists, so that I am not accidentally overwriting configurations.\n14. As a user, I want to force-add a source with `--force`, so that I can intentionally replace an existing source configuration.\n15. As a user, I want private Git repositories to work via external SSH/HTTPS credentials, so that I am not blocked from using proprietary or internal libraries.\n16. As a user, I want the CLI to never store secrets in the lockfile, so that my credentials are not leaked into version-controlled files.\n17. As a user, I want the CLI to not support submodules in the MVP, so that the implementation remains simple and predictable.\n\n### Discovery\n\n18. As a user, I want items to be discovered automatically by convention, so that I do not have to manually specify every file.\n19. As a user, I want skills to be discovered in `skills/\u003cid\u003e/SKILL.md`, prompts in `prompts/\u003cid\u003e/PROMPT.md`, and agent Line truncated
-7
View File
@@ -1,7 +0,0 @@
{
"database": "dolt",
"backend": "dolt",
"dolt_mode": "embedded",
"dolt_database": "agent_lib",
"project_id": "379983ee-9720-40e7-a662-3872246af82f"
}
-15
View File
@@ -1,15 +0,0 @@
{
"hooks": {
"SessionStart": [
{
"hooks": [
{
"command": "bd prime --hook-json",
"type": "command"
}
],
"matcher": ""
}
]
}
}
-2
View File
@@ -1,2 +0,0 @@
[features]
hooks = true
-51
View File
@@ -1,51 +0,0 @@
{
"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"
}
]
}
]
}
}
-20
View File
@@ -1,20 +0,0 @@
{
"hooks": {
"postToolUse": [
{
"command": "bd cursor-hook postToolUse"
}
],
"preCompact": [
{
"command": "bd cursor-hook preCompact"
}
],
"sessionStart": [
{
"command": "bd cursor-hook sessionStart"
}
]
},
"version": 1
}
-67
View File
@@ -1,67 +0,0 @@
---
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 -->
-31
View File
@@ -1,31 +0,0 @@
# Beads / Dolt files (added by bd init)
.dolt/
*.db
.beads-credential-key
# Go build artifacts
agent-lib
agent-lib.exe
agent-libw.exe
dist/
*.test
*.out
coverage.*
# Editor/IDE
*.swp
*.swo
*~
.fuse_hidden*
.DS_Store
.idea/
.vscode/
*.code-workspace
# Local env overrides (never commit)
.env
.env.local
# Beads / Dolt files (added by bd init)
.beads/proxieddb/
*.gate.lock*
-79
View File
@@ -1,79 +0,0 @@
version: 2
project_name: agent-lib
# Releases gehen an die eigene Gitea-Instanz (NICHT GitHub):
# GITEA_TOKEN=<token mit repository-write> als Umgebungsvariable
# Owner/Name sind explizit gesetzt, weil das SCP-Stil-Remote
# (gitea@code.m3ta.dev:m3tam3re/agent-lib.git) fuer die automatische
# 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:
hooks:
- go mod tidy
builds:
- id: agent-lib
env:
- CGO_ENABLED=0
goos:
- windows
- linux
- darwin
goarch:
- amd64
- arm64
ignore:
- goos: windows
goarch: arm64
ldflags:
- -s -w -X github.com/m3tam3re/agent-lib/internal/version.Version={{.Version}}
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:
name_template: "checksums.txt"
archives:
- id: agent-lib
formats: [tar.gz]
format_overrides:
- goos: windows
formats: [zip]
# Explizit stabil, damit Fleet-Download-URLs vorhersehbar bleiben:
# .../releases/download/<tag>/agent-lib_<os>_<arch>.<ext>
name_template: "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}"
# Das Windows-Zip enthaelt zusaetzlich agent-libw.exe.
allow_different_binary_count: true
changelog:
sort: asc
filters:
exclude:
- "^docs:"
- "^test:"
- "^chore:"
- Merge pull request
- Merge branch
-128
View File
@@ -1,128 +0,0 @@
# 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 -->
-77
View File
@@ -1,77 +0,0 @@
# 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_
+7
View File
@@ -0,0 +1,7 @@
This repository is being used as a Dolt remote.
ref=refs/dolt/data
head=ab55cb150ef6f28d7cb73b87d61dd6ce47e77674
timestamp=2026-11-14T10:04:11Z
-26
View File
@@ -1,26 +0,0 @@
BINARY := agent-lib
VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
LDFLAGS := -s -w -X github.com/m3tam3re/agent-lib/internal/version.Version=$(VERSION)
.PHONY: build test vet lint fmt fmt-check clean
build:
go build -ldflags '$(LDFLAGS)' -o $(BINARY) .
test:
go test ./...
vet:
go vet ./...
fmt:
gofmt -w .
fmt-check:
@out=$$(gofmt -l .); if [ -n "$$out" ]; then \
echo "gofmt required on:"; echo "$$out"; exit 1; fi
lint: vet fmt-check
clean:
rm -rf $(BINARY) dist/
-353
View File
@@ -1,353 +0,0 @@
# agent-lib
One Go binary, two roles: **curator** and **client**.
- **Curator side** — `agent-lib vendor …` pulls external git repositories into a
plain work repository under `external/<source>/<type>/`, pinned by revision,
with per-source selection and collision-safe naming. Publication is nothing
more than `git commit && git push`.
- **Client side** — `agent-lib sync` pulls the work repository and deploys its
content into the OpenCode runtime paths. Local modifications win over
company updates, self-created items are never touched, and Windows toast
notifications tell employees when their edits blocked an update.
No Nix, no Python, no git subprocess at runtime — a single static binary for
windows/amd64, linux/amd64, linux/arm64, darwin/amd64 and darwin/arm64.
## Installation
Download the binary for your platform from the
[GitHub releases](https://github.com/m3tam3re/agent-lib/releases), verify the
checksum, and put it on your `PATH`:
```sh
curl -fsSLO https://github.com/m3tam3re/agent-lib/releases/latest/download/agent-lib_linux_amd64.tar.gz
tar xzf agent-lib_linux_amd64.tar.gz
sha256sum -c checksums.txt --ignore-missing
install -m 0755 agent-lib /usr/local/bin/
agent-lib version
```
Fleet-managed machines receive the binary via a pinned rollout — see
[docs/fleet-handoff.md](docs/fleet-handoff.md). There is no self-update.
From source: `go build .` (version is baked in via ldflags; `make build` uses
the git description).
## Curator guide
The work repository layout:
```
skills/<id>/SKILL.md own skills (folder artifacts)
commands/<id>.md own OpenCode commands
agents/<id>.md own OpenCode agents
mcp/<id>.yaml own MCP fragments (never deployed by the binary)
external/<source>/<type>/ vendored content, mirrors the same four types
agent-lib.lock.json lockfile v2 — pins every source
```
This layout is **exactly** what OpenCode natively consumes — agent-lib is
deliberately on the opencode standard, no conversion layer:
| Type | Canonical form |
|---|---|
| skills | `<id>/SKILL.md` folder (any depth, category nesting ok) |
| commands | flat `commands/<id>.md` |
| agents | flat `agents/<id>.md` |
| mcp | flat `mcp/<id>.yaml` (inventoried, never deployed) |
**Migrating from folder-style agent repos** (e.g. `agents/<id>/AGENT.md`
layouts): flatten `agents/<id>/AGENT.md` → `agents/<id>.md`, and move
documentation and manifests (`SCHEMA.md`, `agents.json`, `README.md`) out of
the typed directories. No folder support for agents/commands is planned —
adapting the source repo to the standard beats shipping a renderer.
### Vendoring a source
```sh
agent-lib vendor add superpowers https://github.com/obra/superpowers/tree/main/skills
```
Pasted GitHub/GitLab web-tree URLs are normalized automatically. A URL
pointing directly at a type directory (e.g. `…/tree/main/skills`) selects
that directory as the skills root. `--ref <branch-or-tag>` pins a ref; the
resolved revision is pinned in the lockfile. Discovery understands the four
standard directories (`skills/`, `commands/`, `agents/`, `mcp/`); skills are
folders containing `SKILL.md` — found at **any depth**, so category-nested
layouts (`skills/engineering/tdd/SKILL.md`) work too, with the folder's base
name as the skill id — commands and agents are flat `.md` files, MCP
fragments are `.yaml`. A flat `.md` under `commands/` or `agents/` whose
frontmatter contains none of the definition keys (`name`, `description`,
`mode`, `agent`, `model`, `argument-hint`, `temperature`, `permission`) is
treated as dropped documentation: skipped with a recorded warning, never an
inventory entry. Everything is read-only scanned — upstream code is never
executed.
### Selection rules
- Default: vendor **everything** (`mode: all`).
- `--include a,b,c` switches the source to **include mode**: only those ids
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`
and `validate`:
- `all` combined with an include list → error
- an exclude list without `all` → error (not supported in v2 selections)
- 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
[Changing your selection later](#changing-your-selection-later) below.)
### Changing your selection later
`vendor select` manages the selection after the initial add — without ever
advancing the pinned revision (that is `vendor update`'s job):
```sh
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 # 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
```
- **include mode**: `--add` appends ids (validated against the pinned
upstream — typos abort with the list of available ids), `--remove` drops
ids and deletes their folders from `external/`.
- **all mode**: `--remove` moves ids onto the exclude list (lockfile v2
supports exclude in all mode) and deletes their folders; `--add` is a hard
error — everything is already selected.
- `--types` / `--exclude-types` **replace** the content-type filter
(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
— you can hand-add a rename for a not-yet-selected item, then `--add` it
under its deployed name. Failed selects mutate nothing.
### Collisions and renames
Every item deploys into a flat per-type namespace. If a vendored id collides
with one of your own items (or with another source's item), the operation
aborts with a hard error naming both parties — before anything is written.
Resolve it with an explicit, reviewable rename:
```sh
agent-lib vendor add superpowers "$URL" --rename review=superpowers-review
```
The on-disk folder always carries exactly the deployed name. Renaming onto
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
```sh
agent-lib vendor diff superpowers # read-only preview: new/changed/deleted vs selection
agent-lib vendor update superpowers # fetch latest of the pinned ref, rewrite, report
agent-lib vendor update --all # every source, reported per source
agent-lib vendor remove superpowers # delete external area + lockfile entry
```
In `all` mode new upstream items arrive automatically (and appear in the
update report); in include mode they deliberately do not — `vendor diff`
surfaces them as `available upstream, not selected`. Every update re-runs the
collision checks and honors the rename map.
### Auditing
```sh
agent-lib validate # offline: rules + tree/lockfile consistency
agent-lib vendor list # sources with pin, mode, item counts
agent-lib vendor inspect <name> # full inventory with metadata + warnings
```
All three accept `--json`. The lockfile is deterministic JSON (sorted keys,
fixed indentation) — identical reruns produce identical bytes, so git diffs
stay clean.
## Client guide
Employees run two commands:
```sh
agent-lib sync # pull the work repository and deploy
agent-lib status # report local state; exit 1 when updates are blocked
```
Both accept `--repo <url>` / `--ref <ref>` for config-free personal use —
see [Configuration](#configuration) below.
Deployment mapping (OpenCode target):
| Type | Destination |
|---|---|
| skills | `~/.agents/skills/<id>/` (whole artifact folders) |
| commands | `~/.config/opencode/commands/<id>.md` |
| agents | `~/.config/opencode/agents/<id>.md` |
| mcp | **never deployed** — stays under fleet-controller merge |
### Sync semantics (three-state)
Sync plans before it mutates. For every item the planner compares the
repository, the local manifest and the on-disk content:
- new item → **deploy**
- managed & unmodified, upstream changed → **update**
- managed & locally modified → **skip + warn** — your version stays
- on disk but never deployed by us → **leave + warn** — self-created items are safe by construction
- upstream deleted & unmodified → **remove**
- 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:
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
The repository to pull comes from the first source that provides one:
1. `--repo <url>` flag (works with **no config file at all**)
2. `--config <path>` flag
3. `AGENT_LIB_CONFIG` env
4. user-level config (personal machines)
5. admin-protected platform default (fleet rollout)
| Source | Linux / macOS | Windows |
|---|---|---|
| user-level config | `$XDG_CONFIG_HOME/agent-lib/config.json` (default `~/.config/agent-lib/config.json`) | `%AppData%\agent-lib\config.json` |
| admin default | `/etc/agent-lib/config.json` | `%ProgramData%\agent-lib\config.json` |
`--repo` overrides a `repo_url` from any discovered config; `--ref` narrows it
to a branch or tag. When no config exists anywhere, the error lists every
searched location, a minimal working example, and the `--repo` shortcut.
```json
{
"repo_url": "https://git.example.com/company/agent-content.git",
"ref": "main",
"token": "<read-only deploy token>",
"token_user": "oauth2"
}
```
The token is used for basic auth only. It never appears in the lockfile, the
manifest, logs or error messages. On `--repo` runs (or when the discovered
config carries no token) `AGENT_LIB_GIT_TOKEN` / `AGENT_LIB_GIT_USER` supply
credentials instead — env never overrides a configured token.
**Personal quickstart (no fleet, no config):**
```sh
agent-lib sync --repo https://github.com/you/your-agent-content.git
```
The work repository must be a committed git repository (sync pulls it
read-only via go-git; local uncommitted state is ignored).
### Notifications
On Windows, a toast fires when (and only when) a sync kept local
modifications or discovered unmanaged items — never for routine syncs. The
same warnings are appended to the sync log
(`~/.local/state/agent-lib/sync.log` on Linux, `%LocalAppData%\agent-lib`
on Windows) and surfaced by `status`. Linux/macOS notification is a no-op.
`status --json` is machine-readable: deployed revision, repository revision,
pending changes, skipped and unrecognized items, and a `problematic_drift`
flag that drives the non-zero exit code — suitable for headless drift checks.
## Security / trust model
- External sources are **untrusted**. Discovery and vendoring never execute
upstream code; only file contents are read.
- The shared read-only token limits blast radius; rotation is a single fleet
run (see the handoff doc).
- MCP fragments from vendored sources are **never activated** by the binary;
merging and vault substitution remain an explicit fleet-controller decision.
- Binary updates happen exclusively via pinned fleet rollouts — there is no
self-update path to abuse.
## Troubleshooting
| Symptom | Cause / fix |
|---|---|
| `error: … no client config found. Searched (in order): …` | No config anywhere. Create one where the error suggests, or skip it: `agent-lib sync --repo <url>`. |
| `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). |
| `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. 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. |
| 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. |
| 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
```sh
make build # build with version ldflags
make test # unit + black-box e2e (fully offline, local fixture git repos)
make lint # go vet + gofmt check
./scripts/e2e-acceptance.sh # full spec walk: 60+ assertions, offline
```
Release: `goreleaser release` on a tagged commit builds all five targets with
checksums and publishes to GitHub releases. Verify with
`goreleaser release --snapshot --clean` or a tagged `--skip=publish` dry run.
## Scope and non-goals (v2)
In scope: vendoring with selection/renames into any git work repository;
OpenCode-only deployment with three-state protection; toast notifications;
goreleaser/GitHub release pipeline.
Not in scope: client-side selection or profiles, additional targets (Pi,
Hermes, Crush, Amp), MCP merge/vault (fleet-controller concern), binary
self-update, git submodule sources, migration tooling from the Python-era
lockfile.
-146
View File
@@ -1,146 +0,0 @@
# Fleet handoff — agent-lib v2 rollout
What az-fleet must roll out, and why. This document is written so the fleet
team can implement their role from this file alone.
## What the binary does (and does not do)
`agent-lib` is one static Go binary with two roles:
- **Curator** (maintainer machine): `vendor add/update/diff/remove/list/inspect`
plus `validate` — manages external content inside the company work
repository. Publication = `git commit && git push` by the maintainer.
- **Client** (employee machine): `sync` + `status` — pulls the work repository
and deploys skills/commands/agents into the OpenCode paths. Deploys with
three-state protection: user-modified managed items are skipped with a
warning (never steamrolled), self-created items are never touched,
unmodified items update/remove silently.
The binary handles all content transport itself. It never deploys or merges
MCP fragments — `mcp/` and `external/*/mcp/` stay under controller-side merge
and vault substitution (clone the work repository as before, now including
the external areas).
## Rollout components
### 1. Binary via pinned GitHub release
- Source of truth: GitHub releases of `m3tam3re/agent-lib`.
- Artifacts: `agent-lib_{windows_amd64,linux_amd64,linux_arm64,darwin_amd64,darwin_arm64}`
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
other tools). **No self-update exists in the binary** — binary updates are
exclusively fleet rollouts. Content updates are pulled by the binary itself.
- Verify the checksum during rollout; install to a fixed path
(e.g. `C:\Program Files\agent-lib\agent-lib.exe` / `/usr/local/bin/agent-lib`).
### 2. Admin-protected client config
Path: `C:\ProgramData\agent-lib\config.json` (Windows, ACL restricted to
Administrators + read for Users) or `/etc/agent-lib/config.json` (Linux,
root-owned, mode 0644).
```json
{
"repo_url": "https://git.example.com/company/agent-content.git",
"ref": "main",
"token": "<read-only deploy token>",
"token_user": "oauth2"
}
```
- The token is a **shared read-only** deploy token scoped to the work
repository. It is used for HTTP basic auth only and never appears in the
lockfile, the manifest, logs, or error output.
- Employees must be able to read the config (sync runs in their context) but
must not be able to alter it.
- Per-run overrides for testing: `--config <path>` or `AGENT_LIB_CONFIG`.
Local state (manifest, cached bare repo, sync log) lives per-user:
`%LocalAppData%\agent-lib` on Windows, `~/.local/state/agent-lib` on Linux
(override with `AGENT_LIB_STATE_DIR`).
### 3. Scheduled task — logged-in user context (required)
- Schedule `agent-lib sync` per user, **running as the logged-in user, not
SYSTEM**. Two reasons:
1. Deployment targets (`~/.agents/skills`, `~/.config/opencode/...`) resolve
against the user's profile.
2. Windows toast notifications require an interactive user session. A task
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
and cheap when unchanged.
- Optional companion: a drift check running `agent-lib status --json`
headless; its non-zero exit (`problematic_drift: true`) means a user's local
modifications are blocking company updates — feed it into monitoring.
## Token rotation procedure
1. Create/rotate the read-only deploy token on the git host.
2. Update `token` in the admin-protected config via the fleet (single run;
config is fleet-managed, so this is one playbook task).
3. No client-side action: the next scheduled sync picks up the new token
(config is read on every run). The old token can be revoked once the
fleet run completed.
4. A failed sync never damages local state — a revoked token mid-rotation
only means "no updates until the config arrives".
## ADR draft — superseding the "exact mirror" doctrine
> # ADR-000X: agent-lib three-state sync supersedes exact-mirror deletion
>
> ## Status
> Proposed (supersedes ADR-0006 "exact mirror including deletion")
>
> ## Context
> The previous fleet doctrine required employee machines to be an exact
> mirror of the company content repository, including deletions. This
> steamrolled legitimate local work: employees' own skills and their local
> adjustments to company skills were destroyed by routine syncs.
>
> agent-lib v2 replaces the mirror sync with a **manifest-based three-state
> sync**: a local manifest records every item agent-lib deployed (name, type,
> origin, revision, content hash), and the planner compares repository,
> manifest and on-disk content per item.
>
> ## Decision
> 1. Managed items that the user modified locally are **skipped** — the local
> version wins, a warning is logged and (on Windows) toasted.
> 2. Items on disk that agent-lib never deployed are **unmanaged** — left
> untouched, reported by `status` as unrecognized.
> 3. Upstream deletions remove only the **unmodified** managed copies;
> modified copies are kept and warned about.
> 4. Everything else (new, changed-unmodified) updates silently; sync is
> idempotent and safe to schedule.
>
> ## Consequences
> - Employee machines are no longer exact mirrors by design; drift is
> visible (`status`, exit code) instead of silently destroyed.
> - "What's in the repo is what I have" holds for everything the user never
> touched.
> - Remediation for blocked updates is a human decision (restore the company
> version by deleting the local copy and re-syncing), not a forced
> overwrite.
> - The controller-side MCP merge is unaffected: it clones the work
> repository (now including `external/*/mcp/`) and continues to own
> activation, merging and vault substitution.
## Verification checklist for the fleet team
- [ ] Pinned binary installed, `agent-lib version` prints the release version.
- [ ] Config at the admin-protected path, readable by users, writable only by
admins; token present.
- [ ] Scheduled task runs as the logged-in user; toast appears when a
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
deployed file (self-test).
- [ ] Drift monitoring consumes `status --json` → `problematic_drift`.
-33
View File
@@ -1,33 +0,0 @@
module github.com/m3tam3re/agent-lib
go 1.26.5
require (
github.com/go-git/go-billy/v5 v5.9.1
github.com/go-git/go-git/v5 v5.19.2
github.com/spf13/cobra v1.10.2
)
require (
dario.cat/mergo v1.0.0 // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/ProtonMail/go-crypto v1.1.6 // indirect
github.com/cloudflare/circl v1.6.3 // indirect
github.com/cyphar/filepath-securejoin v0.6.1 // indirect
github.com/emirpasic/gods v1.18.1 // indirect
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
github.com/kevinburke/ssh_config v1.2.0 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/pjbgf/sha1cd v0.6.0 // indirect
github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 // indirect
github.com/skeema/knownhosts v1.3.1 // indirect
github.com/spf13/pflag v1.0.9 // indirect
github.com/xanzy/ssh-agent v0.3.3 // indirect
golang.org/x/crypto v0.53.0 // indirect
golang.org/x/net v0.56.0 // indirect
golang.org/x/sys v0.46.0 // indirect
gopkg.in/warnings.v0 v0.1.2 // indirect
)
-113
View File
@@ -1,113 +0,0 @@
dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk=
dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk=
github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/ProtonMail/go-crypto v1.1.6 h1:ZcV+Ropw6Qn0AX9brlQLAUXfqLBc7Bl+f/DmNxpLfdw=
github.com/ProtonMail/go-crypto v1.1.6/go.mod h1:rA3QumHc/FZ8pAHreoekgiAbzpNsfQAosU5td4SnOrE=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8=
github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/cyphar/filepath-securejoin v0.6.1 h1:5CeZ1jPXEiYt3+Z6zqprSAgSWiggmpVyciv8syjIpVE=
github.com/cyphar/filepath-securejoin v0.6.1/go.mod h1:A8hd4EnAeyujCJRrICiOWqjS1AX0a9kM5XL+NwKoYSc=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/elazarl/goproxy v1.7.2 h1:Y2o6urb7Eule09PjlhQRGNsqRfPmYI3KKQLFpCAV3+o=
github.com/elazarl/goproxy v1.7.2/go.mod h1:82vkLNir0ALaW14Rc399OTTjyNREgmdL2cVoIbS6XaE=
github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c=
github.com/gliderlabs/ssh v0.3.8/go.mod h1:xYoytBv1sV0aL3CavoDuJIQNURXkkfPA/wxQ1pL1fAU=
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI=
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376/go.mod h1:an3vInlBmSxCcxctByoQdvwPiA7DTK7jaaFDBTtu0ic=
github.com/go-git/go-billy/v5 v5.9.1 h1:8U73XiOTfINdItHVa6z4Gv7ToObcZ6grkqQbLryLCdA=
github.com/go-git/go-billy/v5 v5.9.1/go.mod h1:ExsU+jcGwXTBOnyilvAnEM1wug1IxHr4yP2ZXsNRtV0=
github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399 h1:eMje31YglSBqCdIqdhKBW8lokaMrL3uTkpGYlE2OOT4=
github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399/go.mod h1:1OCfN199q1Jm3HZlxleg+Dw/mwps2Wbk9frAWm+4FII=
github.com/go-git/go-git/v5 v5.19.2 h1:wkfn7vOlUBu8ivAWKBWisTiwJK4jYHzTF8Ndv1LyGqY=
github.com/go-git/go-git/v5 v5.19.2/go.mod h1:QqCBE1EFN5ddFmrliLQ3/ntRCUjZU3EJuwuB/jWEHjk=
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ=
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A=
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo=
github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4gf13a4=
github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/onsi/gomega v1.34.1 h1:EUMJIKUjM8sKjYbtxQI9A4z2o+rruxnzNvpknOXie6k=
github.com/onsi/gomega v1.34.1/go.mod h1:kU1QgUvBDLXBJq618Xvm2LUX6rSAfRaFRTcdOeDLwwY=
github.com/pjbgf/sha1cd v0.6.0 h1:3WJ8Wz8gvDz29quX1OcEmkAlUg9diU4GxJHqs0/XiwU=
github.com/pjbgf/sha1cd v0.6.0/go.mod h1:lhpGlyHLpQZoxMv8HcgXvZEhcGs0PG/vsZnEJ7H0iCM=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 h1:n661drycOFuPLCN3Uc8sB6B/s6Z4t2xvBgU1htSHuq8=
github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/skeema/knownhosts v1.3.1 h1:X2osQ+RAjK76shCbvhHHHVl3ZlgDm8apHEHFqRjnBY8=
github.com/skeema/knownhosts v1.3.1/go.mod h1:r7KTdC8l4uxWRyK2TpQZ/1o5HaSzh06ePQNxPwTcfiY=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM=
github.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM=
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=
golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME=
gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
-157
View File
@@ -1,157 +0,0 @@
package cli
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/spf13/cobra"
"github.com/m3tam3re/agent-lib/internal/lockfile"
"github.com/m3tam3re/agent-lib/internal/vendor"
)
func loadLockfileOrFail(cmd *cobra.Command) *lockfile.Lockfile {
lf, err := lockfile.Load(filepath.Join(".", lockfile.FileName))
if err != nil {
if err == lockfile.ErrNotExist {
fmt.Fprintln(os.Stderr, "error: no lockfile found — run `agent-lib vendor add` first")
} else {
fmt.Fprintln(os.Stderr, "error:", err)
}
os.Exit(1)
}
return lf
}
func emitJSON(cmd *cobra.Command, v any) error {
enc := json.NewEncoder(cmd.OutOrStdout())
enc.SetIndent("", " ")
return enc.Encode(v)
}
func newValidateCmd() *cobra.Command {
var asJSON bool
cmd := &cobra.Command{
Use: "validate",
Short: "Check lockfile rules and external-area consistency offline",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
lf := loadLockfileOrFail(cmd)
result := vendor.Validate(".", lf)
if asJSON {
return emitJSON(cmd, result)
}
w := cmd.OutOrStdout()
if result.Valid {
fmt.Fprintf(w, "lockfile valid (%d sources)\n", len(lf.Sources))
return nil
}
for _, e := range result.Errors {
fmt.Fprintf(w, "%s: %s\n", e.Rule, e.Message)
}
cmd.SilenceErrors = true
os.Exit(1)
return nil
},
}
cmd.Flags().BoolVar(&asJSON, "json", false, "machine-readable output")
return cmd
}
func newVendorListCmd() *cobra.Command {
var asJSON bool
cmd := &cobra.Command{
Use: "list",
Short: "List all vendored sources with pin, mode and item counts",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
lf := loadLockfileOrFail(cmd)
rows := vendor.List(lf)
if asJSON {
return emitJSON(cmd, map[string]any{"sources": rows})
}
w := cmd.OutOrStdout()
if len(rows) == 0 {
fmt.Fprintln(w, "no sources vendored yet")
return nil
}
fmt.Fprintf(w, "%-16s %-6s %-9s %-8s %s\n", "SOURCE", "REF", "REV", "MODE", "URL")
for _, r := range rows {
rev := r.Rev
if len(rev) > 8 {
rev = rev[:8]
}
fmt.Fprintf(w, "%-16s %-6s %-9s %-8s %s\n", r.Name, r.Ref, rev, r.Mode, r.URL)
fmt.Fprintf(w, "%16s %s\n", "", countsLine(r.Counts))
}
return nil
},
}
cmd.Flags().BoolVar(&asJSON, "json", false, "machine-readable output")
return cmd
}
func countsLine(counts map[string]int) string {
line := ""
total := 0
for _, t := range lockfile.Types {
if n, ok := counts[t]; ok {
if line != "" {
line += ", "
}
line += fmt.Sprintf("%d %s", n, t)
total += n
}
}
return fmt.Sprintf("%d items: %s", total, line)
}
func newVendorInspectCmd() *cobra.Command {
var asJSON bool
cmd := &cobra.Command{
Use: "inspect <name>",
Short: "Show one source's full item inventory with metadata and warnings",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
lf := loadLockfileOrFail(cmd)
report, err := vendor.Inspect(".", args[0], lf)
if err != nil {
return err
}
if asJSON {
return emitJSON(cmd, report)
}
w := cmd.OutOrStdout()
fmt.Fprintf(w, "source %s\n", report.Name)
fmt.Fprintf(w, " url: %s\n", report.URL)
fmt.Fprintf(w, " ref: %s\n", report.Ref)
fmt.Fprintf(w, " rev: %s\n", report.Rev)
fmt.Fprintf(w, " mode: %s\n", report.Mode)
for _, t := range lockfile.Types {
items := report.Items[t]
if len(items) == 0 {
continue
}
fmt.Fprintf(w, " %s:\n", t)
for _, it := range items {
fmt.Fprintf(w, " %s", it.DeployedID)
if it.DeployedID != it.UpstreamID {
fmt.Fprintf(w, " (upstream: %s)", it.UpstreamID)
}
if it.Name != "" {
fmt.Fprintf(w, " name=%s", it.Name)
}
fmt.Fprintln(w)
for _, warn := range it.Warnings {
fmt.Fprintf(w, " warning: %s\n", warn)
}
}
}
return nil
},
}
cmd.Flags().BoolVar(&asJSON, "json", false, "machine-readable output")
return cmd
}
-53
View File
@@ -1,53 +0,0 @@
// Package cli wires the agent-lib command tree: vendor (curator side),
// sync/status (client side) and version.
package cli
import (
"fmt"
"io"
"os"
"runtime"
"github.com/spf13/cobra"
"github.com/m3tam3re/agent-lib/internal/version"
)
func NewRootCmd() *cobra.Command {
root := &cobra.Command{
Use: "agent-lib",
Short: "Curated agent content: vendor external sources, sync to OpenCode",
SilenceUsage: true,
SilenceErrors: true,
}
root.AddCommand(newVersionCmd())
root.AddCommand(newVendorCmd())
root.AddCommand(newValidateCmd())
root.AddCommand(newSyncCmd())
root.AddCommand(newStatusCmd())
return root
}
func newVersionCmd() *cobra.Command {
return &cobra.Command{
Use: "version",
Short: "Print the agent-lib version",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return printVersion(cmd.OutOrStdout())
},
}
}
func printVersion(w io.Writer) error {
_, err := fmt.Fprintf(w, "agent-lib %s (%s/%s)\n", version.Version, runtime.GOOS, runtime.GOARCH)
return err
}
func Execute() error {
if err := NewRootCmd().Execute(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
return err
}
return nil
}
-46
View File
@@ -1,46 +0,0 @@
package cli
import (
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/m3tam3re/agent-lib/internal/client"
)
func newStatusCmd() *cobra.Command {
var configPath, repoURL, ref string
var asJSON bool
cmd := &cobra.Command{
Use: "status",
Short: "Report deployed revision, pending changes, skips and unrecognized items",
Long: "Read-only local state report. Exits non-zero when local modifications " +
"block repository updates — suitable for headless drift checks. " +
"agent-lib version is included in the report.",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
opts := client.SyncOptions{ConfigPath: configPath, RepoURL: repoURL, Ref: ref}
report, err := client.Status(opts)
if err != nil {
return fmt.Errorf("status: %w", err)
}
if asJSON {
if err := emitJSON(cmd, report); err != nil {
return err
}
} else {
client.PrintStatus(cmd.OutOrStdout(), report)
}
if report.Drift {
os.Exit(1)
}
return nil
},
}
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(&ref, "ref", "", "branch or tag to pull (requires --repo)")
cmd.Flags().BoolVar(&asJSON, "json", false, "machine-readable output")
return cmd
}
-39
View File
@@ -1,39 +0,0 @@
package cli
import (
"fmt"
"github.com/spf13/cobra"
"github.com/m3tam3re/agent-lib/internal/client"
)
func newSyncCmd() *cobra.Command {
var configPath, repoURL, ref string
var force bool
cmd := &cobra.Command{
Use: "sync",
Short: "Pull the work repository and deploy its content to OpenCode",
Long: "Pulls the work repository and deploys skills, commands and agents " +
"into the OpenCode runtime paths. The repository comes from --repo, " +
"or from the config chain: --config, " + client.ConfigEnv + " env, the " +
"user-level config, or the admin-protected platform default. " +
"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,
RunE: func(cmd *cobra.Command, args []string) error {
opts := client.SyncOptions{ConfigPath: configPath, RepoURL: repoURL, Ref: ref, Force: force}
if _, err := client.Sync(opts, cmd.OutOrStdout()); err != nil {
return fmt.Errorf("sync: %w", err)
}
return nil
},
}
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(&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
}
-66
View File
@@ -1,66 +0,0 @@
package cli
import (
"fmt"
"github.com/spf13/cobra"
"github.com/m3tam3re/agent-lib/internal/vendor"
)
func newVendorUpdateCmd() *cobra.Command {
var all bool
cmd := &cobra.Command{
Use: "update [<name>]",
Short: "Fetch the latest revision of the pinned ref and rewrite the external area",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if all {
if len(args) != 0 {
return fmt.Errorf("--all takes no source name")
}
if err := vendor.UpdateAll(".", cmd.OutOrStdout()); err != nil {
return fmt.Errorf("vendor update: %w", err)
}
return nil
}
if len(args) != 1 {
return fmt.Errorf("specify a source name or --all")
}
if _, err := vendor.Update(".", args[0], cmd.OutOrStdout()); err != nil {
return fmt.Errorf("vendor update: %w", err)
}
return nil
},
}
cmd.Flags().BoolVar(&all, "all", false, "update every source and report per source")
return cmd
}
func newVendorDiffCmd() *cobra.Command {
return &cobra.Command{
Use: "diff <name>",
Short: "Compare upstream against the current selection without modifying anything",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if _, err := vendor.Diff(".", args[0], cmd.OutOrStdout()); err != nil {
return fmt.Errorf("vendor diff: %w", err)
}
return nil
},
}
}
func newVendorRemoveCmd() *cobra.Command {
return &cobra.Command{
Use: "remove <name>",
Short: "Delete a source's external area and lockfile entry",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if err := vendor.Remove(".", args[0], cmd.OutOrStdout()); err != nil {
return fmt.Errorf("vendor remove: %w", err)
}
return nil
},
}
}
-161
View File
@@ -1,161 +0,0 @@
package cli
import (
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/m3tam3re/agent-lib/internal/vendor"
)
func newVendorCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "vendor",
Short: "Curate external sources into this work repository",
}
cmd.AddCommand(newVendorAddCmd())
cmd.AddCommand(newVendorSelectCmd())
cmd.AddCommand(newVendorRenameCmd())
cmd.AddCommand(newVendorListCmd())
cmd.AddCommand(newVendorInspectCmd())
cmd.AddCommand(newVendorUpdateCmd())
cmd.AddCommand(newVendorDiffCmd())
cmd.AddCommand(newVendorRemoveCmd())
return cmd
}
func newVendorAddCmd() *cobra.Command {
var ref string
var include, exclude, onlyTypes, excludeTypes []string
var renames []string
cmd := &cobra.Command{
Use: "add <name> <url>",
Short: "Vendor a new external git source",
Long: "Clones the source (in-process, via go-git), discovers skills, commands,\n" +
"agents and MCP fragments, materializes the selection under external/<name>/\n" +
"and pins URL, ref, revision, selection and renames in the lockfile.\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.",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
renameMap, err := vendor.ParseRenames(renames)
if err != nil {
return err
}
opts := vendor.AddOptions{
Name: args[0],
URL: args[1],
Ref: ref,
Include: splitList(include),
Exclude: splitList(exclude),
OnlyTypes: splitList(onlyTypes),
ExcludeTypes: splitList(excludeTypes),
Renames: renameMap,
}
if err := vendor.Add(".", opts, cmd.OutOrStdout()); err != nil {
return fmt.Errorf("vendor add: %w", err)
}
return nil
},
}
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(&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)")
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 {
var out []string
for _, s := range in {
for _, part := range strings.Split(s, ",") {
if t := strings.TrimSpace(part); t != "" {
out = append(out, t)
}
}
}
return out
}
func newVendorSelectCmd() *cobra.Command {
var add, remove []string
var onlyTypes, excludeTypes []string
var mode string
cmd := &cobra.Command{
Use: "select <name>",
Short: "Change a source's selection without advancing the pinned revision",
Long: "Manages include/exclude selection after the initial vendor add.\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" +
"onto the exclude list; --add is an error (everything is selected already).\n" +
"--types/--exclude-types replace the content-type filter (skills, commands,\n" +
"agents, mcp); absent flags keep it as-is. --mode all resets to everything:\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.",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if mode != "" && mode != "all" {
return fmt.Errorf("--mode accepts only \"all\" (got %q)", mode)
}
opts := vendor.SelectOptions{
Add: splitList(add),
Remove: splitList(remove),
ModeAll: mode == "all",
OnlyTypes: splitList(onlyTypes),
ExcludeTypes: splitList(excludeTypes),
}
if _, err := vendor.Select(".", args[0], opts, cmd.OutOrStdout()); err != nil {
return fmt.Errorf("vendor select: %w", err)
}
return nil
},
}
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(&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
}
-234
View File
@@ -1,234 +0,0 @@
// Package client implements the employee side: config loading, work-repo
// pull, inventory, manifest and deployment into the OpenCode target.
package client
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/m3tam3re/agent-lib/internal/gitsource"
)
// ClientConfig is the client configuration for sync: fleet-provided or
// personal, discovered via the search chain or overridden inline.
type ClientConfig struct {
RepoURL string `json:"repo_url"`
Ref string `json:"ref,omitempty"`
Token string `json:"token,omitempty"`
TokenUser string `json:"token_user,omitempty"`
}
// ConfigEnv names the override environment variables.
const (
ConfigEnv = "AGENT_LIB_CONFIG"
StateDirEnv = "AGENT_LIB_STATE_DIR"
)
// DefaultConfigPath returns the admin-protected config location per platform:
// ProgramData on Windows, /etc on Linux/macOS.
func DefaultConfigPath() string {
if runtime.GOOS == "windows" {
if pd := os.Getenv("ProgramData"); pd != "" {
return filepath.Join(pd, "agent-lib", "config.json")
}
return `C:\ProgramData\agent-lib\config.json`
}
return "/etc/agent-lib/config.json"
}
// UserConfigPath returns the user-level config location per platform:
// XDG_CONFIG_HOME or ~/.config on Linux/macOS, AppData on Windows.
func UserConfigPath() string {
if runtime.GOOS == "windows" {
if ad := os.Getenv("AppData"); ad != "" {
return filepath.Join(ad, "agent-lib", "config.json")
}
if home, err := os.UserHomeDir(); err == nil {
return filepath.Join(home, "AppData", "Roaming", "agent-lib", "config.json")
}
return ""
}
if xdg := os.Getenv("XDG_CONFIG_HOME"); xdg != "" {
return filepath.Join(xdg, "agent-lib", "config.json")
}
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return filepath.Join(home, ".config", "agent-lib", "config.json")
}
// configCandidate is one link in the config search chain.
type configCandidate struct {
path string
desc string
}
// ConfigSearchChain returns the ordered locations a client config is looked
// up in: the --config flag, the AGENT_LIB_CONFIG env, the user-level config
// and the admin-protected platform default. The flag and env entries are
// only included when actually set.
func ConfigSearchChain(flagPath string) []configCandidate {
chain := make([]configCandidate, 0, 4)
if flagPath != "" {
chain = append(chain, configCandidate{path: flagPath, desc: "--config flag"})
}
if envPath := os.Getenv(ConfigEnv); envPath != "" {
chain = append(chain, configCandidate{path: envPath, desc: ConfigEnv + " env"})
}
if p := UserConfigPath(); p != "" {
chain = append(chain, configCandidate{path: p, desc: "user config"})
}
chain = append(chain, configCandidate{path: DefaultConfigPath(), desc: "admin default"})
return chain
}
// MissingConfigError reports that no client config exists anywhere in the
// search chain — carrying the searched locations and the way out.
type MissingConfigError struct {
Chain []configCandidate
}
func (e *MissingConfigError) Error() string {
var b strings.Builder
b.WriteString("no client config found. Searched (in order):\n")
for _, c := range e.Chain {
fmt.Fprintf(&b, " - %s (%s)\n", c.path, c.desc)
}
b.WriteString("\nCreate one — minimal working example:\n\n")
b.WriteString(` {"repo_url": "https://git.example.com/company/agent-content.git", "ref": "main"}` + "\n")
if p := UserConfigPath(); p != "" {
fmt.Fprintf(&b, "\nat %s (personal) or %s (fleet rollout).\n", p, DefaultConfigPath())
} else {
fmt.Fprintf(&b, "\nat %s (fleet rollout).\n", DefaultConfigPath())
}
b.WriteString("\nOr skip the config entirely:\n\n agent-lib sync --repo <url> [--ref <ref>]\n")
return b.String()
}
// LoadClientConfig resolves and reads the client config via the search
// chain: --config flag, AGENT_LIB_CONFIG env, user-level config, admin
// default — first existing file wins. Explicit flag/env paths that do not
// exist are hard errors; a completely empty chain yields *MissingConfigError.
func LoadClientConfig(flagPath string) (*ClientConfig, error) {
path, ok, err := resolveConfigPath(flagPath)
if err != nil {
return nil, err
}
if !ok {
return nil, &MissingConfigError{Chain: ConfigSearchChain(flagPath)}
}
return readClientConfig(path)
}
// LoadOptionalConfig behaves like LoadClientConfig but returns (nil, nil)
// when no config exists anywhere — for runs that carry their own --repo.
// Malformed existing configs are still hard errors.
func LoadOptionalConfig(flagPath string) (*ClientConfig, error) {
path, ok, err := resolveConfigPath(flagPath)
if err != nil {
return nil, err
}
if !ok {
return nil, nil
}
return readClientConfig(path)
}
// resolveConfigPath walks the search chain and returns the config to read.
// The flag and env legs must exist when set (explicit intent); the user and
// admin legs are skipped when absent.
func resolveConfigPath(flagPath string) (path string, found bool, err error) {
if flagPath != "" {
return flagPath, true, nil
}
if envPath := os.Getenv(ConfigEnv); envPath != "" {
return envPath, true, nil
}
if p := UserConfigPath(); p != "" {
if _, statErr := os.Stat(p); statErr == nil {
return p, true, nil
}
}
admin := DefaultConfigPath()
if _, statErr := os.Stat(admin); statErr == nil {
return admin, true, nil
}
return "", false, nil
}
func readClientConfig(path string) (*ClientConfig, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("reading client config %s: %w", path, err)
}
var cfg ClientConfig
if err := json.Unmarshal(data, &cfg); err != nil {
return nil, fmt.Errorf("client config %s is not valid JSON: %w", path, err)
}
if cfg.RepoURL == "" {
return nil, fmt.Errorf("client config %s: repo_url is required", path)
}
return &cfg, nil
}
// FillTokenAuth completes the config's credentials from the environment:
// AGENT_LIB_GIT_TOKEN / AGENT_LIB_GIT_USER are only consulted when the
// discovered config carries no token — env never overrides a config token.
func (c *ClientConfig) FillTokenAuth() {
if c == nil || c.Token != "" {
return
}
if token := os.Getenv(gitsource.TokenEnv); token != "" {
c.Token = token
c.TokenUser = os.Getenv(gitsource.UserEnv)
}
}
// StateDir returns the client state directory: the override env, then the
// platform default (LocalAppData on Windows, XDG state elsewhere).
func StateDir() (string, error) {
if d := os.Getenv(StateDirEnv); d != "" {
return d, nil
}
if runtime.GOOS == "windows" {
base := os.Getenv("LocalAppData")
if base == "" {
return "", fmt.Errorf("LocalAppData is not set")
}
return filepath.Join(base, "agent-lib"), nil
}
if xdg := os.Getenv("XDG_STATE_HOME"); xdg != "" {
return filepath.Join(xdg, "agent-lib"), nil
}
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, ".local", "state", "agent-lib"), nil
}
// StatePaths bundles the well-known files inside the state dir.
type StatePaths struct {
Root string
CacheDir string
Manifest string
LogFile string
}
func ResolveStatePaths() (StatePaths, error) {
root, err := StateDir()
if err != nil {
return StatePaths{}, err
}
return StatePaths{
Root: root,
CacheDir: filepath.Join(root, "work-repo"),
Manifest: filepath.Join(root, "manifest.json"),
LogFile: filepath.Join(root, "sync.log"),
}, nil
}
-165
View File
@@ -1,165 +0,0 @@
package client
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
func writeConfigFile(t *testing.T, path, repoURL string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
data, err := json.Marshal(map[string]string{"repo_url": repoURL, "ref": "main"})
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, data, 0o600); err != nil {
t.Fatal(err)
}
}
// runIsolated points HOME/XDG at empty temp dirs and clears the override env
// so chain tests never see the real machine's config.
func runIsolated(t *testing.T, fn func()) {
t.Helper()
base := t.TempDir()
home := filepath.Join(base, "home")
xdg := filepath.Join(base, "xdg-config")
for _, d := range []string{home, xdg} {
if err := os.MkdirAll(d, 0o755); err != nil {
t.Fatal(err)
}
}
t.Setenv("HOME", home)
t.Setenv("XDG_CONFIG_HOME", xdg)
t.Setenv(ConfigEnv, "")
fn()
}
func TestUserConfigPathHonorsXDG(t *testing.T) {
runIsolated(t, func() {
base := t.TempDir()
t.Setenv("XDG_CONFIG_HOME", base)
want := filepath.Join(base, "agent-lib", "config.json")
if got := UserConfigPath(); got != want {
t.Errorf("UserConfigPath() = %q, want %q", got, want)
}
})
}
func TestLoadClientConfigChainOrder(t *testing.T) {
runIsolated(t, func() {
base := t.TempDir()
flagCfg := filepath.Join(base, "flag.json")
envCfg := filepath.Join(base, "env.json")
userCfg := filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "agent-lib", "config.json")
writeConfigFile(t, flagCfg, "https://flag.example/repo")
writeConfigFile(t, envCfg, "https://env.example/repo")
writeConfigFile(t, userCfg, "https://user.example/repo")
assertRepo := func(name, got, want string) {
t.Helper()
if got != want {
t.Errorf("%s: repo_url = %q, want %q", name, got, want)
}
}
cfg, err := LoadClientConfig(flagCfg)
if err != nil {
t.Fatal(err)
}
assertRepo("flag beats env and user", cfg.RepoURL, "https://flag.example/repo")
t.Setenv(ConfigEnv, envCfg)
cfg, err = LoadClientConfig("")
if err != nil {
t.Fatal(err)
}
assertRepo("env beats user", cfg.RepoURL, "https://env.example/repo")
t.Setenv(ConfigEnv, "")
cfg, err = LoadClientConfig("")
if err != nil {
t.Fatal(err)
}
assertRepo("user picked up without flags", cfg.RepoURL, "https://user.example/repo")
})
}
func TestLoadClientConfigMissingIsActionable(t *testing.T) {
runIsolated(t, func() {
_, err := LoadClientConfig("")
if err == nil {
t.Fatal("empty chain must fail")
}
var missing *MissingConfigError
if e, ok := err.(*MissingConfigError); !ok {
t.Fatalf("error must be MissingConfigError, got %T: %v", err, err)
} else {
missing = e
}
msg := missing.Error()
userPath := UserConfigPath()
for _, want := range []string{
"no client config found",
userPath,
DefaultConfigPath(),
`"repo_url"`,
"--repo",
} {
if !strings.Contains(msg, want) {
t.Errorf("error message must mention %q:\n%s", want, msg)
}
}
})
}
func TestLoadOptionalConfigNilWhenEmpty(t *testing.T) {
runIsolated(t, func() {
cfg, err := LoadOptionalConfig("")
if err != nil {
t.Fatalf("empty chain must be (nil, nil), got %v", err)
}
if cfg != nil {
t.Errorf("cfg must be nil, got %+v", cfg)
}
})
}
func TestLoadOptionalConfigMalformedStillFails(t *testing.T) {
runIsolated(t, func() {
userCfg := filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "agent-lib", "config.json")
writeConfigFile(t, userCfg, "")
if _, err := LoadOptionalConfig(""); err == nil {
t.Error("user config with empty repo_url must fail even in optional mode")
}
})
}
func TestLoadClientConfigExplicitFlagMustExist(t *testing.T) {
runIsolated(t, func() {
_, err := LoadClientConfig(filepath.Join(t.TempDir(), "nope.json"))
if err == nil || !strings.Contains(err.Error(), "nope.json") {
t.Errorf("explicit --config pointing nowhere must name the path, got %v", err)
}
})
}
func TestFillTokenAuthEnvOnlyFillsEmptyToken(t *testing.T) {
t.Setenv("AGENT_LIB_GIT_TOKEN", "env-token")
t.Setenv("AGENT_LIB_GIT_USER", "env-user")
fromEnv := &ClientConfig{}
fromEnv.FillTokenAuth()
if fromEnv.Token != "env-token" || fromEnv.TokenUser != "env-user" {
t.Errorf("empty token must be filled from env: %+v", fromEnv)
}
configured := &ClientConfig{Token: "config-token", TokenUser: "config-user"}
configured.FillTokenAuth()
if configured.Token != "config-token" || configured.TokenUser != "config-user" {
t.Errorf("env must never override a config token: %+v", configured)
}
}
-173
View File
@@ -1,173 +0,0 @@
package client
import (
"fmt"
"io"
"os"
"time"
"github.com/m3tam3re/agent-lib/internal/deploy"
"github.com/m3tam3re/agent-lib/internal/gitsource"
"github.com/m3tam3re/agent-lib/internal/lockfile"
"github.com/m3tam3re/agent-lib/internal/notify"
"github.com/m3tam3re/agent-lib/internal/target"
)
// Notifier delivers user-facing notifications; swap it in tests. Failures
// never fail the sync (fail-open, logged to stdout).
var Notifier notify.Sender = notify.Platform()
// SyncReport summarizes one planner-driven sync run.
type SyncReport struct {
Revision string
Deployed int
Updated int
Kept int
Removed int
Skipped int
Left int
Manifest string
}
// ExecutePlan applies a plan item by item: deploys and removes are atomic
// per item, every skip+warn and leave+warn is appended to the warning log
// with item name and reason, and the manifest is rewritten once at the end.
func ExecutePlan(tree *gitsource.GitTree, plan []PlanEntry, manifest *Manifest, paths StatePaths, rev string, stdout io.Writer) (*SyncReport, error) {
report := &SyncReport{Revision: rev, Manifest: paths.Manifest}
var warnings []string
for _, e := range plan {
key := manifestKey(e.Type, e.Name)
switch e.Action {
case ActDeploy, ActUpdate:
if err := deployEntry(tree, e); err != nil {
return nil, fmt.Errorf("%s %s/%s: %w", e.Action, e.Type, e.Name, err)
}
manifest.Items[key] = &ManifestItem{
Name: e.Name, Type: e.Type, Origin: e.Origin, Revision: rev, Hash: e.NewHash,
}
if e.Action == ActDeploy {
report.Deployed++
} else {
report.Updated++
}
case ActKeep:
report.Kept++
case ActRemove:
if err := os.RemoveAll(e.DstPath); err != nil {
return nil, fmt.Errorf("removing %s/%s: %w", e.Type, e.Name, err)
}
delete(manifest.Items, key)
report.Removed++
case ActSkip:
warnings = append(warnings, fmt.Sprintf("SKIP %s/%s: %s", e.Type, e.Name, e.Reason))
report.Skipped++
case ActLeave:
warnings = append(warnings, fmt.Sprintf("LEAVE %s/%s: %s", e.Type, e.Name, e.Reason))
report.Left++
}
}
manifest.Version = ManifestVersion
manifest.Revision = rev
if err := manifest.Save(paths.Manifest); err != nil {
return nil, err
}
if len(warnings) > 0 {
if err := appendWarnings(paths.LogFile, warnings); err != nil {
fmt.Fprintf(stdout, "warning: could not write sync log: %v\n", err)
}
title := "agent-lib sync"
body := fmt.Sprintf("%d item(s) kept local: modifications blocked company updates. See the sync log for details.", report.Skipped+report.Left)
if err := Notifier.Send(title, body); err != nil {
fmt.Fprintf(stdout, "warning: notification failed: %v\n", err)
}
}
printPlannedSyncReport(stdout, report)
return report, nil
}
func deployEntry(tree *gitsource.GitTree, e PlanEntry) error {
if e.Type == lockfile.TypeSkill {
return deploy.Dir(tree, e.RelPath, e.DstPath)
}
return deploy.File(tree, e.RelPath, e.DstPath)
}
// appendWarnings adds timestamped warning lines to the sync log.
func appendWarnings(logPath string, warnings []string) error {
f, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
return err
}
defer f.Close()
stamp := time.Now().UTC().Format(time.RFC3339)
for _, w := range warnings {
if _, err := fmt.Fprintf(f, "%s %s\n", stamp, w); err != nil {
return err
}
}
return nil
}
// diskFacts observes every deployed path the planner can care about:
// manifest items, current inventory items, and unmanaged occupants of the
// target directories.
func diskFacts(oc *target.OpenCode, manifest *Manifest, items []PlannedItem) map[string]DiskFact {
facts := map[string]DiskFact{}
observe := func(typ, name string) {
key := manifestKey(typ, name)
if _, seen := facts[key]; seen {
return
}
path, ok := oc.DeployPath(typ, name)
if !ok {
return
}
if _, err := os.Stat(path); err != nil {
facts[key] = DiskFact{}
return
}
hash, err := HashDiskPath(typ, path)
if err != nil {
hash = ""
}
facts[key] = DiskFact{Exists: true, Hash: hash}
}
for _, rec := range manifest.Items {
observe(rec.Type, rec.Name)
}
for _, it := range items {
observe(it.Type, it.Name)
}
for key := range oc.ScanTargetDirs() {
if _, seen := facts[key]; !seen {
facts[key] = DiskFact{Exists: true}
}
}
return facts
}
func printPlannedSyncReport(w io.Writer, r *SyncReport) {
fmt.Fprintf(w, "synced to revision %s\n", shortRev(r.Revision))
fmt.Fprintf(w, " deployed: %d\n", r.Deployed)
fmt.Fprintf(w, " updated: %d\n", r.Updated)
fmt.Fprintf(w, " kept: %d\n", r.Kept)
fmt.Fprintf(w, " removed: %d\n", r.Removed)
if r.Skipped > 0 {
fmt.Fprintf(w, " skipped (local modifications kept): %d\n", r.Skipped)
}
if r.Left > 0 {
fmt.Fprintf(w, " unmanaged items left untouched: %d\n", r.Left)
}
fmt.Fprintf(w, " manifest: %s\n", r.Manifest)
}
func shortRev(rev string) string {
if len(rev) > 12 {
return rev[:12]
}
return rev
}
-93
View File
@@ -1,93 +0,0 @@
package client
import (
"fmt"
"sort"
"github.com/m3tam3re/agent-lib/internal/discovery"
"github.com/m3tam3re/agent-lib/internal/gitsource"
"github.com/m3tam3re/agent-lib/internal/lockfile"
)
// InventoryItem is one deployable item found in the work repository.
type InventoryItem struct {
Type string
Name string
Origin string
RelPath string
Hash string
Warnings []string
}
// Inventory is the full content of a work-repo revision: own contributions
// plus every external area. MCP fragments are inventoried but filtered at
// deployment time.
type Inventory struct {
Revision string
Items []InventoryItem
}
// BuildInventory reads the work repository tree and the lockfile (when
// present) and resolves the flat deployed namespace.
func BuildInventory(tree *gitsource.GitTree, rev string) (*Inventory, error) {
inv := &Inventory{Revision: rev}
own, err := discovery.Scan(tree, discovery.Config{})
if err != nil {
return nil, fmt.Errorf("scanning own items: %w", err)
}
for _, it := range own {
inv.Items = append(inv.Items, InventoryItem{
Type: it.Type, Name: it.UpstreamID, Origin: "own", RelPath: it.RelPath,
})
}
var lf *lockfile.Lockfile
if data, err := tree.ReadFile(lockfile.FileName); err == nil {
lf, err = lockfile.ParseBytes(data)
if err != nil {
return nil, fmt.Errorf("work repository lockfile is invalid: %w", err)
}
} else {
lf = lockfile.New()
}
sources := make([]string, 0, len(lf.Sources))
for name := range lf.Sources {
sources = append(sources, name)
}
sort.Strings(sources)
for _, name := range sources {
sub := &discovery.PrefixTree{Tree: tree, Prefix: "external/" + name}
items, err := discovery.Scan(sub, discovery.Config{})
if err != nil {
return nil, fmt.Errorf("scanning external area of %q: %w", name, err)
}
for _, it := range items {
inv.Items = append(inv.Items, InventoryItem{
Type: it.Type, Name: it.UpstreamID, Origin: name, RelPath: "external/" + name + "/" + it.RelPath,
Warnings: it.Warnings,
})
}
}
sort.Slice(inv.Items, func(i, j int) bool {
if inv.Items[i].Type != inv.Items[j].Type {
return inv.Items[i].Type < inv.Items[j].Type
}
return inv.Items[i].Name < inv.Items[j].Name
})
return inv, nil
}
// Deployable filters the inventory down to the types the target deploys.
func (inv *Inventory) Deployable() []InventoryItem {
var out []InventoryItem
for _, it := range inv.Items {
if it.Type == lockfile.TypeMcp {
continue
}
out = append(out, it)
}
return out
}
-157
View File
@@ -1,157 +0,0 @@
package client
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"github.com/m3tam3re/agent-lib/internal/gitsource"
"github.com/m3tam3re/agent-lib/internal/lockfile"
)
// ManifestVersion is the local manifest schema version.
const ManifestVersion = 1
// ManifestItem records one deployed item: name, type, origin, the work-repo
// revision it came from, and the content hash at deploy time.
type ManifestItem struct {
Name string `json:"name"`
Type string `json:"type"`
Origin string `json:"origin"`
Revision string `json:"revision"`
Hash string `json:"hash"`
}
// Manifest is the local record of everything agent-lib deployed.
type Manifest struct {
Version int `json:"version"`
Revision string `json:"revision"`
Items map[string]*ManifestItem `json:"items"`
}
// NewManifest returns an empty manifest v1.
func NewManifest() *Manifest {
return &Manifest{Version: ManifestVersion, Items: map[string]*ManifestItem{}}
}
// LoadManifest reads the manifest at path; a missing file yields an empty
// manifest, not an error (first sync).
func LoadManifest(path string) (*Manifest, error) {
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return NewManifest(), nil
}
return nil, err
}
var m Manifest
if err := json.Unmarshal(data, &m); err != nil {
return nil, fmt.Errorf("manifest %s is not valid JSON: %w", path, err)
}
if m.Items == nil {
m.Items = map[string]*ManifestItem{}
}
return &m, nil
}
// Save writes the manifest deterministically (sorted item keys, two-space
// indent, trailing newline).
func (m *Manifest) Save(path string) error {
data, err := marshalManifest(m)
if err != nil {
return err
}
return os.WriteFile(path, data, 0o644)
}
func marshalManifest(m *Manifest) ([]byte, error) {
data, err := json.MarshalIndent(m, "", " ")
if err != nil {
return nil, err
}
return append(data, '\n'), nil
}
// Key identifies an item in the manifest: "<type>/<name>".
func manifestKey(typ, name string) string {
return typ + "/" + name
}
// HashItem computes the content hash of an inventory item from its git tree:
// single files hash their bytes; folders hash "relpath 0x00 hash" lines over
// all contained files, sorted.
func HashItem(tree *gitsource.GitTree, item InventoryItem) (string, error) {
if item.Type != lockfile.TypeSkill {
data, err := tree.ReadFile(item.RelPath)
if err != nil {
return "", err
}
sum := sha256.Sum256(data)
return "sha256:" + hex.EncodeToString(sum[:]), nil
}
files, err := tree.FilesUnder(item.RelPath)
if err != nil {
return "", err
}
prefix := strings.TrimSuffix(item.RelPath, "/") + "/"
h := sha256.New()
for _, f := range files {
data, err := tree.ReadFile(f)
if err != nil {
return "", err
}
fsum := sha256.Sum256(data)
fmt.Fprintf(h, "%s\x00%s\n", strings.TrimPrefix(f, prefix), hex.EncodeToString(fsum[:]))
}
return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil
}
// HashDiskPath computes the same content hash for a deployed path on disk.
func HashDiskPath(typ, path string) (string, error) {
info, err := os.Stat(path)
if err != nil {
return "", err
}
if !info.IsDir() {
data, err := os.ReadFile(path)
if err != nil {
return "", err
}
sum := sha256.Sum256(data)
return "sha256:" + hex.EncodeToString(sum[:]), nil
}
var lines []string
err = filepath.WalkDir(path, func(p string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
rel, err := filepath.Rel(path, p)
if err != nil {
return err
}
data, err := os.ReadFile(p)
if err != nil {
return err
}
fsum := sha256.Sum256(data)
lines = append(lines, fmt.Sprintf("%s\x00%s", filepath.ToSlash(rel), hex.EncodeToString(fsum[:])))
return nil
})
if err != nil {
return "", err
}
sort.Strings(lines)
h := sha256.New()
for _, l := range lines {
fmt.Fprintf(h, "%s\n", l)
}
return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil
}
-105
View File
@@ -1,105 +0,0 @@
package client
import (
"errors"
"os"
"path/filepath"
"testing"
"github.com/m3tam3re/agent-lib/internal/gitsource"
"github.com/m3tam3re/agent-lib/internal/lockfile"
)
type countingNotifier struct {
calls int
titles []string
failWith error
}
func (c *countingNotifier) Send(title, body string) error {
c.calls++
c.titles = append(c.titles, title)
return c.failWith
}
func skipPlanEntry(t *testing.T) PlanEntry {
return PlanEntry{
Action: ActSkip, Type: "skills", Name: "alpha",
RelPath: "skills/alpha", DstPath: filepath.Join(t.TempDir(), "skills", "alpha"),
NewHash: "sha256:x", Reason: "locally modified; keeping the local version (upstream changed)",
}
}
func executeForTest(t *testing.T, plan []PlanEntry) (*SyncReport, error) {
t.Helper()
dir := t.TempDir()
paths := StatePaths{Root: dir, Manifest: filepath.Join(dir, "manifest.json"), LogFile: filepath.Join(dir, "sync.log")}
manifest := manifestWith(map[string]*ManifestItem{
"skills/alpha": {Name: "alpha", Type: "skills", Hash: "sha256:old"},
})
var tree *gitsource.GitTree
return ExecutePlan(tree, plan, manifest, paths, "rev123", os.Stdout)
}
func TestToastFiredOnceForWarnings(t *testing.T) {
orig := Notifier
t.Cleanup(func() { Notifier = orig })
fake := &countingNotifier{}
Notifier = fake
_, err := executeForTest(t, []PlanEntry{skipPlanEntry(t), {
Action: ActLeave, Type: "skills", Name: "mine", Reason: "unmanaged local item; left untouched",
}})
if err != nil {
t.Fatal(err)
}
if fake.calls != 1 {
t.Errorf("exactly one toast per sync with warnings, got %d", fake.calls)
}
if len(fake.titles) != 1 || fake.titles[0] != "agent-lib sync" {
t.Errorf("unexpected toast titles: %v", fake.titles)
}
}
func TestNoToastForRoutineSync(t *testing.T) {
orig := Notifier
t.Cleanup(func() { Notifier = orig })
fake := &countingNotifier{}
Notifier = fake
_, err := executeForTest(t, []PlanEntry{{
Action: ActKeep, Type: "skills", Name: "alpha",
RelPath: "skills/alpha", DstPath: filepath.Join(t.TempDir(), "skills", "alpha"),
NewHash: "sha256:x",
}})
if err != nil {
t.Fatal(err)
}
if fake.calls != 0 {
t.Errorf("routine sync must stay silent, got %d toasts", fake.calls)
}
}
func TestToastFailureNeverFailsSync(t *testing.T) {
orig := Notifier
t.Cleanup(func() { Notifier = orig })
Notifier = &countingNotifier{failWith: errors.New("no interactive session")}
report, err := executeForTest(t, []PlanEntry{skipPlanEntry(t)})
if err != nil {
t.Fatalf("toast failure must not fail the sync: %v", err)
}
if report.Skipped != 1 {
t.Errorf("skip must still be applied: %+v", report)
}
if _, err := os.Stat(filepath.Join(t.TempDir())); err != nil {
t.Fatal(err)
}
}
func TestPlanEntryFieldCoverage(t *testing.T) {
e := skipPlanEntry(t)
if e.Action != ActSkip || e.Type != lockfile.TypeSkill || e.Reason == "" {
t.Fatalf("plan entry incomplete: %+v", e)
}
}
-152
View File
@@ -1,152 +0,0 @@
package client
import "sort"
// Action is one step of a sync plan.
type Action string
// The six sync actions. skip warns about managed items with local
// modifications; leave warns about self-created items agent-lib never
// managed; remove only ever touches unmodified managed copies.
const (
ActDeploy Action = "deploy"
ActUpdate Action = "update"
ActSkip Action = "skip+warn"
ActLeave Action = "leave+warn"
ActRemove Action = "remove"
ActKeep Action = "keep"
)
// PlannedItem is one deployable inventory item with its repo-side hash.
type PlannedItem struct {
Type string
Name string
Origin string
RelPath string
Hash string
}
// DiskFact is the observed on-disk state of one deployed path.
type DiskFact struct {
Exists bool
Hash string
}
// PlanEntry is one decided action with everything the executor needs.
type PlanEntry struct {
Action Action
Type string
Name string
Origin string
RelPath string
DstPath string
NewHash string
Reason string
}
// 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
// touches the filesystem or the environment. The plan is sorted by
// (type, name) for deterministic execution and reporting. With force set,
// locally modified managed items are overwritten with the upstream version
// (and removed after upstream deletion) instead of being skipped; items
// agent-lib never managed are never touched, even with force.
func Plan(items []PlannedItem, manifest *Manifest, disk map[string]DiskFact, pathFor func(typ, name string) string, force bool) []PlanEntry {
invByKey := map[string]PlannedItem{}
for _, it := range items {
invByKey[manifestKey(it.Type, it.Name)] = it
}
var plan []PlanEntry
emit := func(a Action, it PlannedItem, reason string) {
e := PlanEntry{Action: a, Reason: reason, NewHash: it.Hash}
e.Type, e.Name, e.Origin, e.RelPath = it.Type, it.Name, it.Origin, it.RelPath
e.DstPath = pathFor(e.Type, e.Name)
plan = append(plan, e)
}
keys := map[string]bool{}
for key := range invByKey {
keys[key] = true
}
for key := range manifest.Items {
keys[key] = true
}
for key, fact := range disk {
if fact.Exists {
keys[key] = true
}
}
sorted := make([]string, 0, len(keys))
for key := range keys {
sorted = append(sorted, key)
}
sort.Strings(sorted)
for _, key := range sorted {
it, inInv := invByKey[key]
rec := manifest.Items[key]
fact := disk[key]
switch {
case inInv && rec == nil:
if fact.Exists {
emit(ActSkip, it, "path occupied by a local item agent-lib never deployed; deploy blocked")
} else {
emit(ActDeploy, it, "")
}
case inInv && it.Hash == rec.Hash:
decideAgainstDisk(it, rec, fact, emit, "unchanged", force)
case inInv:
decideAgainstDisk(it, rec, fact, emit, "changed", force)
case rec != nil && !fact.Exists:
emit(ActRemove, PlannedItem{Type: rec.Type, Name: rec.Name, Origin: rec.Origin}, "already gone from disk; dropping manifest record")
case rec != nil && fact.Hash == rec.Hash:
emit(ActRemove, PlannedItem{Type: rec.Type, Name: rec.Name, Origin: rec.Origin}, "upstream deleted")
case rec != nil && force:
emit(ActRemove, PlannedItem{Type: rec.Type, Name: rec.Name, Origin: rec.Origin}, "upstream deleted; forced removal of the locally modified copy")
case rec != nil:
emit(ActSkip, PlannedItem{Type: rec.Type, Name: rec.Name, Origin: rec.Origin},
"upstream deleted but the local copy was modified; keeping it")
default:
emit(ActLeave, PlannedItem{Type: typeOfKey(key), Name: nameOfKey(key)},
"unmanaged local item; left untouched")
}
}
return plan
}
func decideAgainstDisk(it PlannedItem, rec *ManifestItem, fact DiskFact, emit func(Action, PlannedItem, string), upstreamState string, force bool) {
switch {
case !fact.Exists:
emit(ActUpdate, it, "managed item missing on disk; restoring")
case fact.Hash == rec.Hash:
if upstreamState == "unchanged" {
emit(ActKeep, it, "")
} else {
emit(ActUpdate, it, "")
}
case force:
emit(ActUpdate, it, "forced: locally modified copy overwritten")
default:
emit(ActSkip, it, "locally modified; keeping the local version (upstream "+upstreamState+")")
}
}
func typeOfKey(key string) string {
for i := len(key) - 1; i >= 0; i-- {
if key[i] == '/' {
return key[:i]
}
}
return key
}
func nameOfKey(key string) string {
for i := len(key) - 1; i >= 0; i-- {
if key[i] == '/' {
return key[i+1:]
}
}
return key
}
-259
View File
@@ -1,259 +0,0 @@
package client
import "testing"
const (
hashV1 = "sha256:aaa"
hashV2 = "sha256:bbb"
hashMod = "sha256:localmod"
)
func testPathFor(typ, name string) string { return "/home/u/target/" + typ + "/" + name }
func manifestWith(entries map[string]*ManifestItem) *Manifest {
m := NewManifest()
for k, v := range entries {
m.Items[k] = v
}
return m
}
// TestPlanMatrix walks the complete three-state matrix (disk × upstream)
// plus the missing-disk restore cases, asserting the single planned action.
func TestPlanMatrix(t *testing.T) {
type disk string
const (
diskNone disk = "missing"
diskClean disk = "unmodified"
diskMod disk = "user-modified"
diskForeign disk = "never-managed"
)
type upstream string
const (
upAdded upstream = "added"
upChanged upstream = "changed"
upSame upstream = "unchanged"
upGone upstream = "removed"
upAbsent upstream = "not-in-repo"
)
cases := []struct {
disk disk
up upstream
want Action
}{
{diskNone, upAdded, ActDeploy},
{diskClean, upAdded, ActSkip},
{diskMod, upAdded, ActSkip},
{diskForeign, upAdded, ActSkip},
{diskNone, upChanged, ActUpdate},
{diskClean, upChanged, ActUpdate},
{diskMod, upChanged, ActSkip},
{diskForeign, upChanged, ActSkip},
{diskNone, upSame, ActUpdate},
{diskClean, upSame, ActKeep},
{diskMod, upSame, ActSkip},
{diskForeign, upSame, ActSkip},
{diskNone, upGone, ActRemove},
{diskClean, upGone, ActRemove},
{diskMod, upGone, ActSkip},
{diskForeign, upGone, ActSkip},
{diskClean, upAbsent, ActLeave},
{diskNone, upAbsent, ActKeep}, // marker for "no plan entry at all"
}
for _, tc := range cases {
name := string(tc.disk) + "/" + string(tc.up)
t.Run(name, func(t *testing.T) {
key := manifestKey("skills", "alpha")
var items []PlannedItem
manifest := NewManifest()
diskFacts := map[string]DiskFact{}
switch tc.up {
case upAdded:
items = append(items, PlannedItem{Type: "skills", Name: "alpha", RelPath: "skills/alpha", Hash: hashV1})
case upChanged, upSame:
hash := hashV2
if tc.up == upSame {
hash = hashV1
}
items = append(items, PlannedItem{Type: "skills", Name: "alpha", RelPath: "skills/alpha", Hash: hash})
manifest.Items[key] = &ManifestItem{Name: "alpha", Type: "skills", Hash: hashV1}
case upGone:
manifest.Items[key] = &ManifestItem{Name: "alpha", Type: "skills", Hash: hashV1}
case upAbsent:
// neither inventory nor manifest
}
switch tc.disk {
case diskNone:
case diskClean:
diskFacts[key] = DiskFact{Exists: true, Hash: hashV1}
case diskMod, diskForeign:
diskFacts[key] = DiskFact{Exists: true, Hash: hashMod}
}
plan := Plan(items, manifest, diskFacts, testPathFor, false)
if tc.disk == diskNone && tc.up == upAbsent {
if len(plan) != 0 {
t.Fatalf("a key present nowhere must produce no entry, got %+v", plan)
}
return
}
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)
}
if plan[0].DstPath != testPathFor("skills", "alpha") {
t.Errorf("DstPath not mapped: %q", plan[0].DstPath)
}
if tc.want == ActSkip || tc.want == ActLeave {
if plan[0].Reason == "" {
t.Error("skip/leave entries must carry a reason")
}
}
})
}
}
// 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, 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, 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
// full deterministic output.
func TestPlanMixedFixture(t *testing.T) {
items := []PlannedItem{
{Type: "commands", Name: "deploy", RelPath: "commands/deploy.md", Hash: hashV1},
{Type: "skills", Name: "fresh", RelPath: "skills/fresh", Hash: hashV1},
{Type: "skills", Name: "tweaked", RelPath: "skills/tweaked", Hash: hashV2},
{Type: "skills", Name: "keeper", RelPath: "skills/keeper", Hash: hashV1},
{Type: "agents", Name: "helper", RelPath: "agents/helper.md", Hash: hashV1},
}
manifest := manifestWith(map[string]*ManifestItem{
"skills/tweaked": {Name: "tweaked", Type: "skills", Hash: hashV1},
"skills/goner": {Name: "goner", Type: "skills", Hash: hashV1},
"skills/keeper": {Name: "keeper", Type: "skills", Hash: hashV1},
"skills/blocked": {Name: "blocked", Type: "skills", Hash: hashV1},
"agents/helper": {Name: "helper", Type: "agents", Hash: hashV1},
})
disk := map[string]DiskFact{
"skills/fresh": {Exists: true, Hash: hashMod}, // never-managed × added
"skills/tweaked": {Exists: true, Hash: hashMod}, // user-modified × changed
"skills/goner": {Exists: true, Hash: hashV1}, // unmodified × removed
"skills/keeper": {Exists: true, Hash: hashV1}, // unmodified × unchanged
"skills/blocked": {Exists: true, Hash: hashMod}, // user-modified × removed
"skills/mine": {Exists: true}, // never-managed × absent
"commands/deploy": {}, // missing × added
"agents/helper": {Exists: true, Hash: hashV1}, // unmodified × unchanged
}
plan := Plan(items, manifest, disk, testPathFor, false)
got := map[string]Action{}
for _, e := range plan {
got[e.Type+"/"+e.Name] = e.Action
}
want := map[string]Action{
"commands/deploy": ActDeploy,
"skills/fresh": ActSkip,
"skills/tweaked": ActSkip,
"agents/helper": ActKeep,
"skills/goner": ActRemove,
"skills/keeper": ActKeep,
"skills/blocked": ActSkip,
"skills/mine": ActLeave,
}
if len(got) != len(want) {
t.Fatalf("plan has %d entries, want %d: %+v", len(got), len(want), plan)
}
for key, action := range want {
if got[key] != action {
t.Errorf("%s: action = %s, want %s", key, got[key], action)
}
}
sorted := true
for i := 1; i < len(plan); i++ {
prev := plan[i-1].Type + "/" + plan[i-1].Name
curr := plan[i].Type + "/" + plan[i].Name
if prev > curr {
sorted = false
}
}
if !sorted {
t.Error("plan must be deterministically sorted by type/name")
}
}
// TestPlanPureGuarantee compiles the purity contract: planning identical
// inputs twice yields identical plans, and no input is mutated.
func TestPlanPureGuarantee(t *testing.T) {
items := []PlannedItem{{Type: "skills", Name: "a", RelPath: "skills/a", 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}}
p1 := Plan(items, manifest, disk, testPathFor, false)
p2 := Plan(items, manifest, disk, testPathFor, false)
if len(p1) != len(p2) {
t.Fatal("same inputs must yield same plan length")
}
for i := range p1 {
if p1[i] != p2[i] {
t.Fatalf("plan not deterministic at %d: %+v vs %+v", i, p1[i], p2[i])
}
}
if manifest.Items["skills/b"] == nil || len(items) != 1 {
t.Error("planner must not mutate its inputs")
}
}
-184
View File
@@ -1,184 +0,0 @@
package client
import (
"errors"
"fmt"
"os"
"path/filepath"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing"
gittransport "github.com/go-git/go-git/v5/plumbing/transport"
"github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/m3tam3re/agent-lib/internal/gitsource"
)
// PullResult is one successful work-repo pull: the resolved revision plus
// read access to its commit tree.
type PullResult struct {
Rev string
Tree *gitsource.GitTree
}
// Pull fetches the work repository into the cache dir (bare clone, then
// fetch) and resolves ref — the default branch when empty. An unreachable
// repository yields a clean error before any deployment state is touched.
func Pull(cacheDir, url, ref, token, tokenUser string) (*PullResult, error) {
auth := basicAuth(token, tokenUser)
repo, err := openOrCreate(cacheDir, url, ref, auth)
if err != nil {
return nil, err
}
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 {
return nil, fmt.Errorf("resolving %q in %s: %w", refLabel(ref), gitsource.RedactURL(url), err)
}
commit, err := repo.CommitObject(hash)
if err != nil {
return nil, fmt.Errorf("reading commit %s: %w", hash, err)
}
tree, err := commit.Tree()
if err != nil {
return nil, fmt.Errorf("reading tree of %s: %w", hash, err)
}
return &PullResult{Rev: hash.String(), Tree: gitsource.NewGitTree(tree)}, nil
}
func basicAuth(token, tokenUser string) gittransport.AuthMethod {
if token == "" {
return nil
}
user := tokenUser
if user == "" {
user = "agent-lib"
}
return &http.BasicAuth{Username: user, Password: token}
}
func openOrCreate(cacheDir, url, ref string, auth gittransport.AuthMethod) (*git.Repository, error) {
if _, err := os.Stat(filepath.Join(cacheDir, "HEAD")); err == nil {
repo, err := git.PlainOpen(cacheDir)
if err != nil {
return nil, fmt.Errorf("opening cached work repo: %w", err)
}
if err := repointRemote(repo, url); err != nil {
return nil, err
}
if err := repo.Fetch(&git.FetchOptions{Auth: auth}); err != nil && !errors.Is(err, git.NoErrAlreadyUpToDate) {
return nil, fmt.Errorf("fetching %s: %w", gitsource.RedactURL(url), err)
}
return repo, nil
}
if err := os.MkdirAll(filepath.Dir(cacheDir), 0o755); err != nil {
return nil, err
}
opts := &git.CloneOptions{URL: url, Auth: auth, NoCheckout: true}
if ref != "" {
opts.ReferenceName = plumbing.NewBranchReferenceName(ref)
}
repo, err := git.PlainClone(cacheDir, true, opts)
if err != nil {
os.RemoveAll(cacheDir)
return nil, fmt.Errorf("cloning %s: %w", gitsource.RedactURL(url), err)
}
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
// re-point takes effect on the next sync.
func repointRemote(repo *git.Repository, url string) error {
remote, err := repo.Remote(git.DefaultRemoteName)
if err != nil {
return fmt.Errorf("reading cached remote: %w", err)
}
if len(remote.Config().URLs) == 0 || remote.Config().URLs[0] == url {
return nil
}
if err := repo.DeleteRemote(git.DefaultRemoteName); err != nil {
return fmt.Errorf("replacing cached remote: %w", err)
}
_, err = repo.CreateRemote(&config.RemoteConfig{
Name: git.DefaultRemoteName,
URLs: []string{url},
Fetch: []config.RefSpec{
config.RefSpec("+refs/heads/*:refs/remotes/origin/*"),
},
})
return err
}
func resolveRemoteRef(repo *git.Repository, ref string) (plumbing.Hash, error) {
candidates := remoteRefCandidates(ref)
for _, name := range candidates {
if h, err := repo.ResolveRevision(plumbing.Revision(name)); err == nil {
return *h, nil
}
}
return plumbing.ZeroHash, fmt.Errorf("reference not found (tried %v)", candidates)
}
func remoteRefCandidates(ref string) []string {
if ref == "" {
return []string{"refs/remotes/origin/HEAD", "HEAD"}
}
return []string{
"refs/remotes/origin/" + ref,
"refs/tags/" + ref,
"refs/heads/" + ref,
ref,
}
}
func refLabel(ref string) string {
if ref == "" {
return "default branch"
}
return ref
}
-102
View File
@@ -1,102 +0,0 @@
package client
import (
"fmt"
"io"
"github.com/m3tam3re/agent-lib/internal/version"
)
// StatusEntry names one item in a status section.
type StatusEntry struct {
Item string `json:"item"`
Reason string `json:"reason,omitempty"`
}
// StatusReport is the machine-readable local-state report.
type StatusReport struct {
Version string `json:"agent_lib_version"`
DeployedRev string `json:"deployed_revision"`
RepoRev string `json:"repository_revision"`
InSync bool `json:"in_sync"`
Drift bool `json:"problematic_drift"`
Pending []StatusEntry `json:"pending_changes,omitempty"`
Skipped []StatusEntry `json:"skipped_items,omitempty"`
Unrecognized []StatusEntry `json:"unrecognized_items,omitempty"`
}
// Status reports the local state without mutating anything. Drift is true
// when local modifications block repository updates (or occupy names the
// repository needs) — the state headless drift checks flag with a non-zero
// exit code.
func Status(opts SyncOptions) (*StatusReport, error) {
p, err := prepare(opts)
if err != nil {
return nil, err
}
report := &StatusReport{
Version: version.Version,
DeployedRev: p.manifest.Revision,
RepoRev: p.pull.Rev,
}
for _, e := range p.plan {
item := e.Type + "/" + e.Name
switch e.Action {
case ActDeploy, ActUpdate, ActRemove:
report.Pending = append(report.Pending, StatusEntry{Item: item, Reason: string(e.Action)})
case ActSkip:
blocked := true
if rec := p.manifest.Items[manifestKey(e.Type, e.Name)]; rec != nil && rec.Hash == e.NewHash {
blocked = false
}
if blocked {
report.Drift = true
}
report.Skipped = append(report.Skipped, StatusEntry{Item: item, Reason: e.Reason})
case ActLeave:
report.Unrecognized = append(report.Unrecognized, StatusEntry{Item: item, Reason: e.Reason})
}
}
report.InSync = report.DeployedRev == report.RepoRev && len(report.Pending) == 0
return report, nil
}
// PrintStatus renders the human-readable report and returns the drift
// verdict so the caller can set the exit code.
func PrintStatus(w io.Writer, r *StatusReport) bool {
fmt.Fprintf(w, "agent-lib %s\n", r.Version)
fmt.Fprintf(w, "deployed revision: %s\n", revOrNone(r.DeployedRev))
fmt.Fprintf(w, "repository revision: %s\n", revOrNone(r.RepoRev))
if r.InSync {
fmt.Fprintln(w, "state: in sync")
} else {
fmt.Fprintln(w, "state: out of sync")
}
printSection := func(title string, entries []StatusEntry) {
if len(entries) == 0 {
return
}
fmt.Fprintf(w, "%s:\n", title)
for _, e := range entries {
fmt.Fprintf(w, " %s", e.Item)
if e.Reason != "" {
fmt.Fprintf(w, " — %s", e.Reason)
}
fmt.Fprintln(w)
}
}
printSection("pending changes", r.Pending)
printSection("skipped (local modifications)", r.Skipped)
printSection("unrecognized local items", r.Unrecognized)
if r.Drift {
fmt.Fprintln(w, "drift: local modifications block repository updates")
}
return r.Drift
}
func revOrNone(rev string) string {
if rev == "" {
return "(never synced)"
}
return rev
}
-147
View File
@@ -1,147 +0,0 @@
package client
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/m3tam3re/agent-lib/internal/target"
)
// SyncOptions parameterize a client sync run. RepoURL (with optional Ref)
// is the inline --repo override: it works without any config file and beats
// 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 {
ConfigPath string
RepoURL string
Ref string
Force bool
}
// prepared is everything sync and status share: the pulled repository, the
// planned action list, and the local state — before any mutation.
type prepared struct {
paths StatePaths
pull *PullResult
manifest *Manifest
items []PlannedItem
plan []PlanEntry
}
// prepare pulls, inventories, hashes and plans — the complete read-only
// front half of a client run.
func prepare(opts SyncOptions) (*prepared, error) {
if opts.RepoURL == "" && opts.Ref != "" {
return nil, fmt.Errorf("--ref requires --repo (it only overrides the repository to pull)")
}
cfg, err := resolveRunConfig(opts)
if err != nil {
return nil, err
}
paths, err := ResolveStatePaths()
if err != nil {
return nil, err
}
if err := os.MkdirAll(paths.Root, 0o755); err != nil {
return nil, err
}
pull, err := Pull(paths.CacheDir, cfg.RepoURL, cfg.Ref, cfg.Token, cfg.TokenUser)
if err != nil {
return nil, err
}
inv, err := BuildInventory(pull.Tree, pull.Rev)
if err != nil {
return nil, err
}
oc, err := target.NewOpenCode()
if err != nil {
return nil, err
}
manifest, err := LoadManifest(paths.Manifest)
if err != nil {
return nil, err
}
items := make([]PlannedItem, 0, len(inv.Items))
for _, it := range inv.Deployable() {
if _, ok := oc.DeployPath(it.Type, it.Name); !ok {
continue
}
hash, err := HashItem(pull.Tree, it)
if err != nil {
return nil, fmt.Errorf("hashing %s/%s: %w", it.Type, it.Name, err)
}
items = append(items, PlannedItem{Type: it.Type, Name: it.Name, Origin: it.Origin, RelPath: it.RelPath, Hash: hash})
}
pathFor := func(typ, name string) string {
path, _ := oc.DeployPath(typ, name)
return path
}
plan := Plan(items, manifest, diskFacts(oc, manifest, items), pathFor, opts.Force)
for _, e := range plan {
if !safePath(e.DstPath) {
return nil, fmt.Errorf("refusing unsafe deploy path %q", e.DstPath)
}
}
return &prepared{paths: paths, pull: pull, manifest: manifest, items: items, plan: plan}, nil
}
// resolveRunConfig applies the --repo inline override to the config chain:
// with --repo, any discovered config only contributes auth (and ref, unless
// --ref is also given); without --repo, a config with a repo_url is required.
func resolveRunConfig(opts SyncOptions) (*ClientConfig, error) {
if opts.RepoURL == "" {
cfg, err := LoadClientConfig(opts.ConfigPath)
if err != nil {
return nil, err
}
cfg.FillTokenAuth()
return cfg, nil
}
cfg, err := LoadOptionalConfig(opts.ConfigPath)
if err != nil {
return nil, err
}
if cfg == nil {
cfg = &ClientConfig{}
}
cfg.RepoURL = opts.RepoURL
if opts.Ref != "" {
cfg.Ref = opts.Ref
}
cfg.FillTokenAuth()
return cfg, nil
}
// Sync pulls the work repository, plans the sync as a pure function over
// (inventory, manifest, disk facts) and executes the plan. Validation and
// hashing happen before the first mutation; unreachable repositories fail
// cleanly with the previous state intact.
func Sync(opts SyncOptions, stdout io.Writer) (*SyncReport, error) {
p, err := prepare(opts)
if err != nil {
return nil, err
}
return ExecutePlan(p.pull.Tree, p.plan, p.manifest, p.paths, p.pull.Rev, stdout)
}
// safePath rejects destinations that escape the user's home directory.
func safePath(dst string) bool {
home, err := os.UserHomeDir()
if err != nil {
return false
}
if dst == home {
return false
}
rel, err := filepath.Rel(home, dst)
if err != nil {
return false
}
return rel != ".." && rel != "." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
}
-79
View File
@@ -1,79 +0,0 @@
// Package deploy copies items from a discovery.Tree onto the filesystem,
// preserving executable bits and writing atomically (temp + rename).
package deploy
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/m3tam3re/agent-lib/internal/discovery"
)
// Dir copies a folder item (e.g. one skill) from the tree into dst,
// replacing whatever occupied dst before.
func Dir(tree discovery.Tree, srcRel, dst string) error {
lister, ok := tree.(interface {
FilesUnder(prefix string) ([]string, error)
})
if !ok {
return fmt.Errorf("tree does not support directory copy")
}
files, err := lister.FilesUnder(srcRel)
if err != nil {
return err
}
if len(files) == 0 {
return fmt.Errorf("no files under %s", srcRel)
}
parent := filepath.Dir(dst)
if err := os.MkdirAll(parent, 0o755); err != nil {
return err
}
tmp, err := os.MkdirTemp(parent, ".agent-lib-tmp-")
if err != nil {
return err
}
defer os.RemoveAll(tmp)
prefix := strings.TrimSuffix(srcRel, "/") + "/"
for _, f := range files {
relInside := strings.TrimPrefix(f, prefix)
target := filepath.Join(tmp, filepath.FromSlash(relInside))
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
return err
}
if err := File(tree, f, target); err != nil {
return err
}
}
if err := os.RemoveAll(dst); err != nil {
return err
}
return os.Rename(tmp, dst)
}
// File copies a single file from the tree to dst via temp file + rename.
func File(tree discovery.Tree, srcRel, dst string) error {
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
return err
}
if mt, ok := tree.(interface {
MaterializeFile(rel, dst string) error
}); ok {
tmp := dst + ".agent-lib-tmp"
if err := mt.MaterializeFile(srcRel, tmp); err != nil {
return err
}
return os.Rename(tmp, dst)
}
data, err := tree.ReadFile(srcRel)
if err != nil {
return err
}
tmp := dst + ".agent-lib-tmp"
if err := os.WriteFile(tmp, data, 0o644); err != nil {
return err
}
return os.Rename(tmp, dst)
}
-222
View File
@@ -1,222 +0,0 @@
package discovery
import (
"fmt"
"sort"
"strings"
"github.com/m3tam3re/agent-lib/internal/lockfile"
)
// Tree abstracts a readable content tree: a git commit tree or a filesystem
// root. Paths are slash-separated and relative to the tree root.
type Tree interface {
Walk(fn func(rel string, isDir bool) error) error
ReadFile(rel string) ([]byte, error)
}
// Config directs Scan; zero values select the standard layout.
type Config struct {
Root string
SkillsDir string
CommandsDir string
AgentsDir string
McpDir string
}
func FromLockfileDiscovery(d lockfile.Discovery) Config {
r := d.Resolve()
return Config{Root: r.Root, SkillsDir: r.SkillsDir, CommandsDir: r.CommandsDir, AgentsDir: r.AgentsDir, McpDir: r.McpDir}
}
// Item is one discovered deployable artifact.
type Item struct {
Type string
UpstreamID string
RelPath string
Frontmatter *Frontmatter
Warnings []string
// Skipped marks a file discovery recognized but deliberately excluded —
// e.g. a documentation .md under agents/ or commands/ without definition
// frontmatter. Skipped items carry warnings but must never enter a
// selection, inventory or availability listing.
Skipped bool
}
// Scan discovers items of all four content types under cfg. Discovery is a
// read-only scan; it never evaluates content beyond reading files.
func Scan(tree Tree, cfg Config) ([]Item, error) {
dirs := lockfile.Discovery{
Root: cfg.Root, SkillsDir: cfg.SkillsDir, CommandsDir: cfg.CommandsDir,
AgentsDir: cfg.AgentsDir, McpDir: cfg.McpDir,
}.Resolve()
skillRoot := join(dirs.Root, dirs.SkillsDir)
commandRoot := join(dirs.Root, dirs.CommandsDir)
agentRoot := join(dirs.Root, dirs.AgentsDir)
mcpRoot := join(dirs.Root, dirs.McpDir)
dirEntries := map[string]map[string]bool{}
fileEntries := map[string]map[string]bool{}
for _, d := range []string{skillRoot, commandRoot, agentRoot, mcpRoot} {
dirEntries[d] = map[string]bool{}
fileEntries[d] = map[string]bool{}
}
var skillDescendants []string
err := tree.Walk(func(rel string, isDir bool) error {
parent, base := splitPath(rel)
if isDir {
if set, ok := dirEntries[parent]; ok {
set[base] = true
}
if skillRoot != "" && (parent == skillRoot || strings.HasPrefix(parent, skillRoot+"/")) {
skillDescendants = append(skillDescendants, rel)
}
return nil
}
if set, ok := fileEntries[parent]; ok {
set[base] = true
}
return nil
})
if err != nil {
return nil, fmt.Errorf("walking source tree: %w", err)
}
var items []Item
for _, it := range scanSkills(tree, skillRoot, skillDescendants) {
items = append(items, it)
}
items = append(items, scanFlatFiles(tree, fileEntries, commandRoot, lockfile.TypeCommand)...)
items = append(items, scanFlatFiles(tree, fileEntries, agentRoot, lockfile.TypeAgent)...)
items = append(items, scanMcpFiles(tree, fileEntries, mcpRoot)...)
sort.Slice(items, func(i, j int) bool {
if items[i].Type != items[j].Type {
return typeRank(items[i].Type) < typeRank(items[j].Type)
}
return items[i].UpstreamID < items[j].UpstreamID
})
return items, nil
}
// scanSkills finds skill folders at any depth under skillRoot (flat layouts
// and category-nested layouts alike). The upstream id is the folder's base
// name; a directory that is itself a skill wins over anything nested inside
// it, and same-basename folders collide at the vendor layer.
func scanSkills(tree Tree, skillRoot string, descendants []string) []Item {
if skillRoot == "" {
return nil
}
sorted := append([]string(nil), descendants...)
sort.Strings(sorted)
withSkillMd := map[string]bool{}
for _, d := range sorted {
if _, err := tree.ReadFile(join(d, "SKILL.md")); err == nil {
withSkillMd[d] = true
}
}
var items []Item
for _, d := range sorted {
if !withSkillMd[d] {
continue
}
nested := false
for other := range withSkillMd {
if other != d && strings.HasPrefix(d, other+"/") {
nested = true
break
}
}
if nested {
continue
}
data, err := tree.ReadFile(join(d, "SKILL.md"))
if err != nil {
continue
}
name := d[strings.LastIndex(d, "/")+1:]
it := Item{Type: lockfile.TypeSkill, UpstreamID: name, RelPath: d}
fm, warnings := ParseFrontmatter(data)
it.Frontmatter = &fm
for _, w := range warnings {
it.Warnings = append(it.Warnings, fmt.Sprintf("skills/%s: %s", name, w))
}
items = append(items, it)
}
return items
}
func scanFlatFiles(tree Tree, fileEntries map[string]map[string]bool, root, typ string) []Item {
var items []Item
for base := range fileEntries[root] {
if !strings.HasSuffix(base, ".md") {
continue
}
id := strings.TrimSuffix(base, ".md")
rel := join(root, base)
data, err := tree.ReadFile(rel)
if err != nil {
continue
}
it := Item{Type: typ, UpstreamID: id, RelPath: rel}
if !HasDefinitionFrontmatter(data) {
it.Skipped = true
it.Warnings = append(it.Warnings, fmt.Sprintf("%s: no %s frontmatter, skipped", rel, strings.TrimSuffix(typ, "s")))
items = append(items, it)
continue
}
fm, warnings := ParseFrontmatter(data)
it.Frontmatter = &fm
for _, w := range warnings {
it.Warnings = append(it.Warnings, fmt.Sprintf("%s/%s: %s", typ, id, w))
}
items = append(items, it)
}
return items
}
func scanMcpFiles(tree Tree, fileEntries map[string]map[string]bool, root string) []Item {
var items []Item
for base := range fileEntries[root] {
var id string
switch {
case strings.HasSuffix(base, ".yaml"):
id = strings.TrimSuffix(base, ".yaml")
case strings.HasSuffix(base, ".yml"):
id = strings.TrimSuffix(base, ".yml")
default:
continue
}
items = append(items, Item{Type: lockfile.TypeMcp, UpstreamID: id, RelPath: join(root, base)})
}
return items
}
func typeRank(t string) int {
for i, tt := range lockfile.Types {
if tt == t {
return i
}
}
return len(lockfile.Types)
}
func join(parts ...string) string {
var nonEmpty []string
for _, p := range parts {
if p != "" {
nonEmpty = append(nonEmpty, p)
}
}
return strings.Join(nonEmpty, "/")
}
func splitPath(rel string) (parent, base string) {
i := strings.LastIndex(rel, "/")
if i < 0 {
return "", rel
}
return rel[:i], rel[i+1:]
}
-114
View File
@@ -1,114 +0,0 @@
package discovery
import (
"strings"
)
// Frontmatter holds the leniently parsed leading YAML block of an item.
type Frontmatter struct {
Name string
Description string
Tags []string
Requires []string
}
// ParseFrontmatter extracts name, description, tags and requires from a
// leading `---` fenced block. Parsing is deliberately lenient: a block that
// opens but never closes, or contains lines without a colon, yields warnings
// instead of failures; the parseable prefix still wins. Files without a
// leading fence have no frontmatter and no warning.
func ParseFrontmatter(data []byte) (Frontmatter, []string) {
var fm Frontmatter
var warnings []string
lines, fenced, closed := parseFence(data)
if !fenced {
return fm, nil
}
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if trimmed == "" {
continue
}
key, value, ok := strings.Cut(trimmed, ":")
if !ok {
warnings = append(warnings, "malformed frontmatter line (missing colon): "+trimmed)
continue
}
key = strings.TrimSpace(key)
value = strings.TrimSpace(value)
switch strings.ToLower(key) {
case "name":
fm.Name = value
case "description":
fm.Description = value
case "tags":
fm.Tags = splitList(value)
case "requires":
fm.Requires = splitList(value)
}
}
if !closed {
warnings = append(warnings, "frontmatter block not closed")
}
return fm, warnings
}
// definitionKeys mark a flat .md under agents/ or commands/ as an intentional
// agent/command definition rather than dropped documentation.
var definitionKeys = map[string]bool{
"name": true,
"description": true,
"mode": true,
"agent": true,
"model": true,
"argument-hint": true,
"temperature": true,
"permission": true,
}
// HasDefinitionFrontmatter reports whether data's leading frontmatter block
// contains any key that marks a flat .md as an agent/command definition.
func HasDefinitionFrontmatter(data []byte) bool {
lines, fenced, _ := parseFence(data)
if !fenced {
return false
}
for _, line := range lines {
key, _, ok := strings.Cut(strings.TrimSpace(line), ":")
if ok && definitionKeys[strings.ToLower(strings.TrimSpace(key))] {
return true
}
}
return false
}
// parseFence returns the lines between the leading `---` fences: the block
// lines, whether the file is fenced at all, and whether the fence closes.
func parseFence(data []byte) (lines []string, fenced, closed bool) {
all := strings.Split(strings.ReplaceAll(string(data), "\r\n", "\n"), "\n")
if len(all) == 0 || strings.TrimSpace(all[0]) != "---" {
return nil, false, false
}
fenced = true
for _, line := range all[1:] {
if strings.TrimSpace(line) == "---" {
return lines, fenced, true
}
lines = append(lines, line)
}
return lines, fenced, false
}
func splitList(v string) []string {
if v == "" {
return nil
}
parts := strings.Split(v, ",")
var out []string
for _, p := range parts {
if t := strings.TrimSpace(p); t != "" {
out = append(out, t)
}
}
return out
}
-54
View File
@@ -1,54 +0,0 @@
package discovery
import "testing"
func TestParseFrontmatter(t *testing.T) {
cases := []struct {
name string
in string
want Frontmatter
warnLen int
}{
{
name: "complete block",
in: "---\nname: Test Skill\ndescription: does things\ntags: a, b\nrequires: c,d\n---\nbody\n",
want: Frontmatter{Name: "Test Skill", Description: "does things", Tags: []string{"a", "b"}, Requires: []string{"c", "d"}},
},
{
name: "no frontmatter",
in: "# Just a file\nbody\n",
want: Frontmatter{},
},
{
name: "unclosed block",
in: "---\nname: Broken\ndescription: never closed\n",
want: Frontmatter{Name: "Broken", Description: "never closed"},
warnLen: 1,
},
{
name: "line missing colon",
in: "---\nname: X\nbroken line without colon\n---\n",
want: Frontmatter{Name: "X"},
warnLen: 1,
},
{
name: "crlf line endings",
in: "---\r\nname: Win\r\ndescription: windows author\r\n---\r\n",
want: Frontmatter{Name: "Win", Description: "windows author"},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
fm, warnings := ParseFrontmatter([]byte(tc.in))
if fm.Name != tc.want.Name || fm.Description != tc.want.Description {
t.Errorf("got %+v, want %+v", fm, tc.want)
}
if len(fm.Tags) != len(tc.want.Tags) || len(fm.Requires) != len(tc.want.Requires) {
t.Errorf("tags/requires mismatch: got %+v want %+v", fm, tc.want)
}
if len(warnings) != tc.warnLen {
t.Errorf("warnings = %v (len %d), want len %d", warnings, len(warnings), tc.warnLen)
}
})
}
}
-55
View File
@@ -1,55 +0,0 @@
package discovery
import (
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
)
// FsTree adapts a filesystem root to the Tree interface (used for scanning
// the work repository's own items).
type FsTree struct {
Root string
}
func (f *FsTree) Walk(fn func(rel string, isDir bool) error) error {
var paths []string
err := filepath.WalkDir(f.Root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if p == f.Root {
return nil
}
paths = append(paths, p)
return nil
})
if err != nil {
return err
}
sort.Strings(paths)
for _, p := range paths {
rel, err := filepath.Rel(f.Root, p)
if err != nil {
return err
}
info, err := os.Stat(p)
if err != nil {
return err
}
if err := fn(filepath.ToSlash(rel), info.IsDir()); err != nil {
return err
}
}
return nil
}
func (f *FsTree) ReadFile(rel string) ([]byte, error) {
clean := filepath.FromSlash(rel)
if strings.Contains(clean, "..") {
return nil, os.ErrNotExist
}
return os.ReadFile(filepath.Join(f.Root, clean))
}
-73
View File
@@ -1,73 +0,0 @@
package discovery
import (
"os"
"path/filepath"
"testing"
)
func writeTree(t *testing.T, root string, files map[string]string) {
t.Helper()
for rel, content := range files {
p := filepath.Join(root, filepath.FromSlash(rel))
os.MkdirAll(filepath.Dir(p), 0o755)
os.WriteFile(p, []byte(content), 0o644)
}
}
func TestScanNestedSkillCategories(t *testing.T) {
dir := t.TempDir()
writeTree(t, dir, map[string]string{
"skills/flat-skill/SKILL.md": "---\nname: Flat\n---\n",
"skills/engineering/tdd/SKILL.md": "---\nname: TDD\n---\n",
"skills/productivity/grill-me/SKILL.md": "---\nname: Grill Me\n---\n",
"skills/engineering/tdd/reference.md": "extra artifact",
"skills/deprecated/old/README.md": "no skill here",
"commands/deploy.md": "---\nname: Deploy\n---\n",
})
items, err := Scan(&FsTree{Root: dir}, Config{})
if err != nil {
t.Fatal(err)
}
got := map[string]Item{}
for _, it := range items {
got[it.UpstreamID] = it
}
for _, want := range []string{"flat-skill", "tdd", "grill-me"} {
it, ok := got[want]
if !ok {
t.Fatalf("skill %q not discovered (items: %+v)", want, items)
}
if it.Type != "skills" {
t.Errorf("%q type = %q", want, it.Type)
}
}
if _, ok := got["old"]; ok {
t.Error("folder without SKILL.md must not be a skill")
}
tdd := got["tdd"]
if tdd.RelPath != "skills/engineering/tdd" {
t.Errorf("tdd RelPath = %q", tdd.RelPath)
}
if got["deploy"].Type != "commands" {
t.Error("flat command types must still be discovered")
}
}
func TestScanOuterSkillWinsOverNested(t *testing.T) {
dir := t.TempDir()
writeTree(t, dir, map[string]string{
"skills/bundle/SKILL.md": "---\nname: Bundle\n---\n",
"skills/bundle/inner/SKILL.md": "---\nname: Inner\n---\n",
"skills/bundle/inner/deep/SKILL.md": "---\nname: Deep\n---\n",
})
items, err := Scan(&FsTree{Root: dir}, Config{})
if err != nil {
t.Fatal(err)
}
if len(items) != 1 || items[0].UpstreamID != "bundle" {
t.Fatalf("outermost skill must win, got %+v", items)
}
}
-66
View File
@@ -1,66 +0,0 @@
package discovery
import (
"os"
"strings"
)
// PrefixTree narrows a Tree to the subtree below Prefix; paths passed in and
// reported back are relative to that subtree.
type PrefixTree struct {
Tree Tree
Prefix string
}
func (p *PrefixTree) Walk(fn func(rel string, isDir bool) error) error {
prefix := strings.TrimSuffix(p.Prefix, "/") + "/"
return p.Tree.Walk(func(rel string, isDir bool) error {
if rel == p.Prefix || strings.HasPrefix(rel, prefix) {
sub := strings.TrimPrefix(rel, prefix)
if sub == "" {
return nil
}
return fn(sub, isDir)
}
return nil
})
}
func (p *PrefixTree) ReadFile(rel string) ([]byte, error) {
return p.Tree.ReadFile(p.Prefix + "/" + rel)
}
// FilesUnder delegates to the underlying tree with the prefix reapplied.
func (p *PrefixTree) FilesUnder(prefix string) ([]string, error) {
lister, ok := p.Tree.(interface {
FilesUnder(prefix string) ([]string, error)
})
if !ok {
return nil, os.ErrNotExist
}
full := prefix
if p.Prefix != "" {
full = p.Prefix + "/" + strings.TrimSuffix(prefix, "/")
}
files, err := lister.FilesUnder(full)
if err != nil {
return nil, err
}
trim := p.Prefix + "/"
out := make([]string, 0, len(files))
for _, f := range files {
out = append(out, strings.TrimPrefix(f, trim))
}
return out, nil
}
// MaterializeFile delegates to the underlying tree with the prefix reapplied.
func (p *PrefixTree) MaterializeFile(rel, dst string) error {
mt, ok := p.Tree.(interface {
MaterializeFile(rel, dst string) error
})
if !ok {
return os.ErrNotExist
}
return mt.MaterializeFile(p.Prefix+"/"+rel, dst)
}
-81
View File
@@ -1,81 +0,0 @@
package discovery
import (
"strings"
"testing"
)
func TestHasDefinitionFrontmatter(t *testing.T) {
cases := []struct {
name string
in string
want bool
}{
{name: "no frontmatter at all", in: "# Schema docs\nplain documentation\n", want: false},
{name: "empty fence", in: "---\n---\nbody\n", want: false},
{name: "only unknown keys", in: "---\ntitle: Schema\nlayout: docs\n---\n", want: false},
{name: "name key", in: "---\nname: Scout\n---\nbody\n", want: true},
{name: "description key", in: "---\ndescription: scouts things\n---\n", want: true},
{name: "mode key", in: "---\nmode: primary\n---\n", want: true},
{name: "model key", in: "---\nmodel: sonnet\n---\n", want: true},
{name: "argument-hint key", in: "---\nargument-hint: [msg]\n---\n", want: true},
{name: "temperature key", in: "---\ntemperature: 0.2\n---\n", want: true},
{name: "permission key", in: "---\npermission: edit\n---\n", want: true},
{name: "mixed unknown and known", in: "---\ntitle: X\ndescription: real agent\n---\n", want: true},
{name: "unclosed block still counts keys", in: "---\nname: Broken\n", want: true},
{name: "case-insensitive keys", in: "---\nDescription: Y\n---\n", want: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := HasDefinitionFrontmatter([]byte(tc.in)); got != tc.want {
t.Errorf("HasDefinitionFrontmatter(%q) = %v, want %v", tc.in, got, tc.want)
}
})
}
}
func TestScanSkipsDocMarkdownInFlatDirs(t *testing.T) {
dir := t.TempDir()
writeTree(t, dir, map[string]string{
"agents/scout.md": "---\ndescription: a real agent\n---\nbody\n",
"agents/SCHEMA.md": "# Schema\npure documentation, no frontmatter\n",
"commands/review.md": "---\nargument-hint: [files]\n---\nbody\n",
"commands/README.md": "Documentation for the commands directory.\n",
"commands/notes.md": "---\ntitle: Notes\n---\nunknown keys only\n",
"skills/good/SKILL.md": "---\nname: Good\n---\n# Good\n",
})
items, err := Scan(&FsTree{Root: dir}, Config{})
if err != nil {
t.Fatal(err)
}
got := map[string]bool{}
skippedWarnings := []string{}
for _, it := range items {
if it.Skipped {
skippedWarnings = append(skippedWarnings, it.Warnings...)
continue
}
got[it.Type+"/"+it.UpstreamID] = true
}
for _, want := range []string{"agents/scout", "commands/review", "skills/good"} {
if !got[want] {
t.Errorf("%s must still be discovered; got %v", want, got)
}
}
for _, doc := range []string{"agents/SCHEMA", "commands/README", "commands/notes"} {
if got[doc] {
t.Errorf("%s is documentation and must be skipped; got %v", doc, got)
}
}
joined := strings.Join(skippedWarnings, "\n")
for _, want := range []string{
"agents/SCHEMA.md: no agent frontmatter, skipped",
"commands/README.md: no command frontmatter, skipped",
"commands/notes.md: no command frontmatter, skipped",
} {
if !strings.Contains(joined, want) {
t.Errorf("skip warning %q missing; got %v", want, skippedWarnings)
}
}
}
-121
View File
@@ -1,121 +0,0 @@
package e2e
import (
"os"
"path/filepath"
"testing"
"github.com/m3tam3re/agent-lib/internal/lockfile"
)
func ownSkillFixture(h *harness, t *testing.T) {
t.Helper()
dir := filepath.Join(h.workDir, "skills", "good-skill")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("---\nname: Own Good\n---\n"), 0o644)
}
func TestCollisionOwnVsVendored(t *testing.T) {
h := newHarness(t)
ownSkillFixture(h, t)
standardFixture(h, t)
out, err := h.run(t, "vendor", "add", "superpowers", h.upstreamDir)
if err == nil {
t.Fatalf("own-vs-vendored collision must fail:\n%s", out)
}
for _, want := range []string{"collides", "own", "good-skill"} {
if !contains(out, want) {
t.Errorf("error must contain %q:\n%s", want, out)
}
}
if _, err := os.Stat(filepath.Join(h.workDir, "external")); err == nil {
t.Error("collision must abort before any tree mutation")
}
if _, err := os.Stat(filepath.Join(h.workDir, lockfile.FileName)); err == nil {
t.Error("collision must not write a lockfile")
}
}
func TestCollisionVendoredVsVendored(t *testing.T) {
h := newHarness(t)
standardFixture(h, t)
h.mustRun(t, "vendor", "add", "first", h.upstreamDir)
out, err := h.run(t, "vendor", "add", "second", h.upstreamDir)
if err == nil {
t.Fatalf("vendored-vs-vendored collision must fail:\n%s", out)
}
for _, want := range []string{"collides", "first"} {
if !contains(out, want) {
t.Errorf("error must name both parties (%q missing):\n%s", want, out)
}
}
}
func TestCollisionResolvedByRename(t *testing.T) {
h := newHarness(t)
ownSkillFixture(h, t)
standardFixture(h, t)
out := h.mustRun(t, "vendor", "add", "superpowers", h.upstreamDir,
"--rename", "good-skill=superpowers-good-skill")
if !contains(out, "renamed") && !contains(out, "materialized") {
t.Errorf("rename resolution should report success:\n%s", out)
}
renamed := filepath.Join(h.workDir, "external/superpowers/skills/superpowers-good-skill/SKILL.md")
if _, err := os.Stat(renamed); err != nil {
t.Fatal("renamed folder must carry the deployed name")
}
original := filepath.Join(h.workDir, "external/superpowers/skills/good-skill")
if _, err := os.Stat(original); err == nil {
t.Error("upstream folder name must not appear after rename")
}
lock := readFile(t, filepath.Join(h.workDir, lockfile.FileName))
if !contains(lock, `"good-skill": "superpowers-good-skill"`) {
t.Errorf("rename map must be pinned in the lockfile:\n%s", lock)
}
if out := h.mustRun(t, "validate"); !contains(out, "valid") {
t.Errorf("renamed state must validate:\n%s", out)
}
}
func TestCollisionRenameToAnotherCollision(t *testing.T) {
h := newHarness(t)
ownSkillFixture(h, t)
standardFixture(h, t)
out, err := h.run(t, "vendor", "add", "superpowers", h.upstreamDir,
"--rename", "good-skill=broken-skill")
if err == nil {
t.Fatalf("renaming onto an existing deployed name must fail:\n%s", out)
}
if !contains(out, "collides") {
t.Errorf("error must report the collision:\n%s", out)
}
}
func TestValidateDetectsHandEditedCollision(t *testing.T) {
h := newHarness(t)
standardFixture(h, t)
h.mustRun(t, "vendor", "add", "superpowers", h.upstreamDir)
h.mustRun(t, "vendor", "add", "second-source", h.upstreamDir, "--include", "good-skill",
"--rename", "good-skill=second-good")
mutateLockfile(t, h, func(lf *lockfile.Lockfile) {
lf.Sources["second-source"].Renames["good-skill"] = "broken-skill"
})
out, err := h.run(t, "validate")
if err == nil {
t.Fatalf("hand-edited rename collision must fail validation:\n%s", out)
}
if !contains(out, "collision") {
t.Errorf("rule must be reported as collision:\n%s", out)
}
}
-239
View File
@@ -1,239 +0,0 @@
package e2e
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
// configChainEnv isolates HOME/XDG/AGENT_LIB_* so config-chain e2e tests see
// only the fixture paths they explicitly create.
type configChainEnv struct {
home string
xdg string
stateDir string
}
func newConfigChainEnv(t *testing.T) *configChainEnv {
t.Helper()
base := t.TempDir()
env := &configChainEnv{
home: filepath.Join(base, "home"),
xdg: filepath.Join(base, "xdg"),
stateDir: filepath.Join(base, "state"),
}
for _, d := range []string{env.home, env.xdg, env.stateDir} {
if err := os.MkdirAll(d, 0o755); err != nil {
t.Fatal(err)
}
}
return env
}
func (e *configChainEnv) run(t *testing.T, extraEnv map[string]string, args ...string) (string, error) {
t.Helper()
cmd := agentLibCmd(args...)
scrubbed := []string{}
for _, kv := range os.Environ() {
if strings.HasPrefix(kv, "AGENT_LIB_") || strings.HasPrefix(kv, "XDG_CONFIG_HOME=") || strings.HasPrefix(kv, "HOME=") {
continue
}
scrubbed = append(scrubbed, kv)
}
cmd.Env = append(scrubbed,
"HOME="+e.home, "USERPROFILE="+e.home,
"XDG_CONFIG_HOME="+e.xdg,
"AGENT_LIB_STATE_DIR="+e.stateDir,
)
for k, v := range extraEnv {
cmd.Env = append(cmd.Env, k+"="+v)
}
out, err := cmd.CombinedOutput()
return string(out), err
}
func (e *configChainEnv) userConfigPath() string {
return filepath.Join(e.xdg, "agent-lib", "config.json")
}
func (e *configChainEnv) writeUserConfig(t *testing.T, repoURL string) {
t.Helper()
writeJSONConfig(t, e.userConfigPath(), repoURL)
}
func writeJSONConfig(t *testing.T, path, repoURL string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
data, err := json.Marshal(map[string]string{"repo_url": repoURL, "ref": "main"})
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, data, 0o600); err != nil {
t.Fatal(err)
}
}
// buildNamedRepo creates a committed work repo whose skills/<id>/SKILL.md
// carries a distinctive id, so the deployed skill identifies the winning
// config source.
func buildNamedRepo(t *testing.T, h *harness, dir, skillID string) {
t.Helper()
h.git(t, dir, "init", "-b", "main")
p := filepath.Join(dir, "skills", skillID, "SKILL.md")
os.MkdirAll(filepath.Dir(p), 0o755)
os.WriteFile(p, []byte("---\nname: "+skillID+"\n---\n# "+skillID+"\n"), 0o644)
h.git(t, dir, "add", "-A")
h.git(t, dir, "commit", "-m", "repo with "+skillID)
}
func deployedSkillPath(home, skillID string) string {
return filepath.Join(home, ".agents", "skills", skillID, "SKILL.md")
}
func TestSyncRepoFlagZeroConfig(t *testing.T) {
h := newHarness(t)
env := newConfigChainEnv(t)
repo := filepath.Join(t.TempDir(), "work")
os.MkdirAll(repo, 0o755)
buildNamedRepo(t, h, repo, "zero-config-skill")
out, err := env.run(t, nil, "sync", "--repo", repo)
if err != nil {
t.Fatalf("zero-config sync via --repo failed: %v\n%s", err, out)
}
if _, err := os.Stat(deployedSkillPath(env.home, "zero-config-skill")); err != nil {
t.Error("--repo must deploy without any config file")
}
if _, err := os.Stat(filepath.Join(env.stateDir, "manifest.json")); err != nil {
t.Error("--repo run must write a manifest")
}
}
func TestSyncRepoFlagOverridesConfiguredRepo(t *testing.T) {
h := newHarness(t)
env := newConfigChainEnv(t)
repoA := filepath.Join(t.TempDir(), "repo-a")
repoB := filepath.Join(t.TempDir(), "repo-b")
os.MkdirAll(repoA, 0o755)
os.MkdirAll(repoB, 0o755)
buildNamedRepo(t, h, repoA, "from-config-skill")
buildNamedRepo(t, h, repoB, "from-flag-skill")
env.writeUserConfig(t, repoA)
out, err := env.run(t, nil, "sync", "--repo", repoB)
if err != nil {
t.Fatalf("sync with --repo over config failed: %v\n%s", err, out)
}
if _, err := os.Stat(deployedSkillPath(env.home, "from-flag-skill")); err != nil {
t.Error("--repo must beat the configured repo_url")
}
if _, err := os.Stat(deployedSkillPath(env.home, "from-config-skill")); err == nil {
t.Error("configured repo must not also deploy")
}
}
func TestSyncUserConfigDiscoveredWithoutFlags(t *testing.T) {
h := newHarness(t)
env := newConfigChainEnv(t)
repo := filepath.Join(t.TempDir(), "work")
os.MkdirAll(repo, 0o755)
buildNamedRepo(t, h, repo, "user-config-skill")
env.writeUserConfig(t, repo)
out, err := env.run(t, nil, "sync")
if err != nil {
t.Fatalf("sync with only a user-level config failed: %v\n%s", err, out)
}
if _, err := os.Stat(deployedSkillPath(env.home, "user-config-skill")); err != nil {
t.Error("user-level config must be picked up without flags or env")
}
}
func TestSyncConfigSearchOrder(t *testing.T) {
h := newHarness(t)
env := newConfigChainEnv(t)
flagRepo := filepath.Join(t.TempDir(), "flag-repo")
envRepo := filepath.Join(t.TempDir(), "env-repo")
os.MkdirAll(flagRepo, 0o755)
os.MkdirAll(envRepo, 0o755)
buildNamedRepo(t, h, flagRepo, "flag-wins-skill")
buildNamedRepo(t, h, envRepo, "env-wins-skill")
flagCfg := filepath.Join(t.TempDir(), "flag.json")
envCfg := filepath.Join(t.TempDir(), "env.json")
writeJSONConfig(t, flagCfg, flagRepo)
writeJSONConfig(t, envCfg, envRepo)
env.writeUserConfig(t, envRepo)
out, err := env.run(t, map[string]string{"AGENT_LIB_CONFIG": envCfg}, "sync", "--config", flagCfg)
if err != nil {
t.Fatalf("flag>env sync failed: %v\n%s", err, out)
}
if _, err := os.Stat(deployedSkillPath(env.home, "flag-wins-skill")); err != nil {
t.Error("--config flag must beat AGENT_LIB_CONFIG")
}
out, err = env.run(t, map[string]string{"AGENT_LIB_CONFIG": envCfg}, "sync")
if err != nil {
t.Fatalf("env>user sync failed: %v\n%s", err, out)
}
if _, err := os.Stat(deployedSkillPath(env.home, "env-wins-skill")); err != nil {
t.Error("AGENT_LIB_CONFIG must beat the user config")
}
}
func TestSyncMissingConfigErrorIsActionable(t *testing.T) {
newHarness(t)
env := newConfigChainEnv(t)
out, err := env.run(t, nil, "sync")
if err == nil {
t.Fatalf("sync without any config must fail:\n%s", out)
}
for _, want := range []string{
"no client config found",
"user config",
"admin default",
env.userConfigPath(),
`"repo_url"`,
"--repo",
} {
if !contains(out, want) {
t.Errorf("missing-config error must mention %q:\n%s", want, out)
}
}
}
func TestSyncRefWithoutRepoIsError(t *testing.T) {
newHarness(t)
env := newConfigChainEnv(t)
out, err := env.run(t, nil, "sync", "--ref", "main")
if err == nil {
t.Fatalf("--ref without --repo must fail:\n%s", out)
}
if !contains(out, "--ref requires --repo") {
t.Errorf("error must explain the --ref/--repo relationship:\n%s", out)
}
}
func TestStatusRepoFlagZeroConfig(t *testing.T) {
h := newHarness(t)
env := newConfigChainEnv(t)
repo := filepath.Join(t.TempDir(), "work")
os.MkdirAll(repo, 0o755)
buildNamedRepo(t, h, repo, "status-repo-skill")
if out, err := env.run(t, nil, "sync", "--repo", repo); err != nil {
t.Fatalf("sync failed: %v\n%s", err, out)
}
out, err := env.run(t, nil, "status", "--repo", repo, "--json")
if err != nil {
t.Fatalf("status --repo --json failed: %v\n%s", err, out)
}
if !contains(out, `"in_sync": true`) {
t.Errorf("status via --repo must report in sync:\n%s", out)
}
}
-235
View File
@@ -1,235 +0,0 @@
package e2e
import (
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/m3tam3re/agent-lib/internal/lockfile"
)
func healthySource(t *testing.T, h *harness) {
t.Helper()
standardFixture(h, t)
h.mustRun(t, "vendor", "add", "superpowers", h.upstreamDir)
}
func mutateLockfile(t *testing.T, h *harness, fn func(*lockfile.Lockfile)) {
t.Helper()
path := filepath.Join(h.workDir, lockfile.FileName)
lf, err := lockfile.Load(path)
if err != nil {
t.Fatal(err)
}
fn(lf)
if err := lf.Save(path); err != nil {
t.Fatal(err)
}
}
func TestValidateHealthy(t *testing.T) {
h := newHarness(t)
healthySource(t, h)
out := h.mustRun(t, "validate")
if !contains(out, "valid") {
t.Errorf("healthy state must validate:\n%s", out)
}
jsonOut := h.mustRun(t, "validate", "--json")
var result struct {
Valid bool `json:"valid"`
Errors []struct {
Source string `json:"source"`
Rule string `json:"rule"`
} `json:"errors"`
}
if err := json.Unmarshal([]byte(jsonOut), &result); err != nil {
t.Fatalf("validate --json not parseable: %v\n%s", err, jsonOut)
}
if !result.Valid || len(result.Errors) != 0 {
t.Errorf("healthy state must be valid in json: %+v", result)
}
}
func TestValidateAllWithInclude(t *testing.T) {
h := newHarness(t)
healthySource(t, h)
mutateLockfile(t, h, func(lf *lockfile.Lockfile) {
lf.Sources["superpowers"].Selection.Include = []string{"good-skill"}
})
out, err := h.run(t, "validate")
if err == nil {
t.Fatalf("all+include must fail:\n%s", out)
}
if !contains(out, "superpowers") || !contains(out, "include list is set") {
t.Errorf("error must name source and rule:\n%s", out)
}
}
func TestValidateExcludeWithoutAll(t *testing.T) {
h := newHarness(t)
healthySource(t, h)
mutateLockfile(t, h, func(lf *lockfile.Lockfile) {
lf.Sources["superpowers"].Selection.Mode = lockfile.ModeInclude
lf.Sources["superpowers"].Selection.Include = []string{"good-skill"}
lf.Sources["superpowers"].Selection.Exclude = []string{"scout"}
})
out, err := h.run(t, "validate")
if err == nil {
t.Fatalf("exclude without all must fail:\n%s", out)
}
if !contains(out, "exclude list is only valid in all mode") {
t.Errorf("error must name the rule:\n%s", out)
}
}
func TestValidateOrphanedInclude(t *testing.T) {
h := newHarness(t)
healthySource(t, h)
mutateLockfile(t, h, func(lf *lockfile.Lockfile) {
lf.Sources["superpowers"].Selection.Mode = lockfile.ModeInclude
lf.Sources["superpowers"].Selection.Include = []string{"good-skill", "vanished-item"}
})
out, err := h.run(t, "validate")
if err == nil {
t.Fatalf("orphaned include must fail:\n%s", out)
}
if !contains(out, "vanished-item") || !contains(out, "pinned inventory") {
t.Errorf("error must name source and item:\n%s", out)
}
jsonOut, _ := h.run(t, "validate", "--json")
var result struct {
Valid bool `json:"valid"`
Errors []struct {
Source string `json:"source"`
} `json:"errors"`
}
if err := json.Unmarshal([]byte(jsonOut), &result); err != nil {
t.Fatalf("json output not parseable: %v", err)
}
if result.Valid || len(result.Errors) == 0 || result.Errors[0].Source != "superpowers" {
t.Errorf("json must carry the error with source: %+v", result)
}
}
func TestValidateTreeLockfileDivergence(t *testing.T) {
h := newHarness(t)
healthySource(t, h)
os.Remove(filepath.Join(h.workDir, "external/superpowers/agents/scout.md"))
out, err := h.run(t, "validate")
if err == nil {
t.Fatalf("missing tree item must fail:\n%s", out)
}
if !contains(out, "agents") || !contains(out, "scout") {
t.Errorf("error must name type and item:\n%s", out)
}
stray := filepath.Join(h.workDir, "external/superpowers/commands/ghost.md")
os.WriteFile(stray, []byte("# ghost\n"), 0o644)
out, err = h.run(t, "validate")
if err == nil {
t.Fatalf("stray tree item must fail:\n%s", out)
}
if !contains(out, "ghost") {
t.Errorf("error must name the stray item:\n%s", out)
}
}
func TestVendorList(t *testing.T) {
h := newHarness(t)
healthySource(t, h)
h.mustRun(t, "vendor", "add", "curated", h.upstreamDir, "--include", "good-skill",
"--rename", "good-skill=curated-good")
out := h.mustRun(t, "vendor", "list")
for _, want := range []string{"superpowers", "curated", "all", "include", "main"} {
if !contains(out, want) {
t.Errorf("list output missing %q:\n%s", want, out)
}
}
jsonOut := h.mustRun(t, "vendor", "list", "--json")
var parsed struct {
Sources []struct {
Name string `json:"name"`
URL string `json:"url"`
Ref string `json:"ref"`
Rev string `json:"rev"`
Mode string `json:"mode"`
Counts map[string]int `json:"counts"`
Total int `json:"total"`
} `json:"sources"`
}
if err := json.Unmarshal([]byte(jsonOut), &parsed); err != nil {
t.Fatalf("list --json not parseable: %v\n%s", err, jsonOut)
}
if len(parsed.Sources) != 2 {
t.Fatalf("want 2 sources, got %d", len(parsed.Sources))
}
super := parsed.Sources[1]
if super.Name != "superpowers" || super.Mode != "all" || super.Total != 5 {
t.Errorf("superpowers summary wrong: %+v", super)
}
if super.Counts["skills"] != 2 || super.Counts["mcp"] != 1 {
t.Errorf("counts wrong: %+v", super.Counts)
}
}
func TestVendorInspect(t *testing.T) {
h := newHarness(t)
healthySource(t, h)
out := h.mustRun(t, "vendor", "inspect", "superpowers")
for _, want := range []string{"good-skill", "broken-skill", "scout", "search", "name=Good Skill", "warning"} {
if !contains(out, want) {
t.Errorf("inspect output missing %q:\n%s", want, out)
}
}
jsonOut := h.mustRun(t, "vendor", "inspect", "superpowers", "--json")
var report struct {
Name string `json:"name"`
Ref string `json:"ref"`
Items map[string][]struct {
UpstreamID string `json:"upstream_id"`
DeployedID string `json:"deployed_id"`
Name string `json:"name"`
Description string `json:"description"`
Warnings []string `json:"warnings"`
} `json:"items"`
}
if err := json.Unmarshal([]byte(jsonOut), &report); err != nil {
t.Fatalf("inspect --json not parseable: %v\n%s", err, jsonOut)
}
if report.Name != "superpowers" || len(report.Items["skills"]) != 2 {
t.Errorf("inspect json wrong: %+v", report)
}
for _, it := range report.Items["skills"] {
if it.UpstreamID == "good-skill" && it.Name != "Good Skill" {
t.Errorf("frontmatter metadata missing: %+v", it)
}
if it.UpstreamID == "broken-skill" && len(it.Warnings) == 0 {
t.Errorf("recorded warnings missing: %+v", it)
}
}
}
func TestVendorInspectUnknownSource(t *testing.T) {
h := newHarness(t)
healthySource(t, h)
out, err := h.run(t, "vendor", "inspect", "nope")
if err == nil {
t.Fatalf("unknown source must fail:\n%s", out)
}
if !contains(out, "not in the lockfile") {
t.Errorf("error must be explicit:\n%s", out)
}
}
-89
View File
@@ -1,89 +0,0 @@
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")
}
}
-343
View File
@@ -1,343 +0,0 @@
package e2e
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"testing"
)
func buildTwentySkillUpstream(t *testing.T, h *harness) {
t.Helper()
for i := 1; i <= 20; i++ {
h.write(t, fmt.Sprintf("skills/skill-%02d/SKILL.md", i), fmt.Sprintf("---\nname: Skill %02d\ndescription: s%d\n---\n# %02d\n", i, i, i))
}
h.commitUpstream(t, "twenty skills")
}
type lockView struct {
Version int `json:"version"`
Sources map[string]struct {
Rev string `json:"rev"`
Renames map[string]string `json:"renames"`
Selection struct {
Mode string `json:"mode"`
Exclude []string `json:"exclude"`
Include []string `json:"include"`
} `json:"selection"`
Inventory map[string][]string `json:"inventory"`
} `json:"sources"`
}
func readLock(t *testing.T, workDir string) lockView {
t.Helper()
data := readFile(t, filepath.Join(workDir, "agent-lib.lock.json"))
var v lockView
if err := json.Unmarshal([]byte(data), &v); err != nil {
t.Fatalf("lockfile not parseable: %v", err)
}
return v
}
func externalSkillIDs(t *testing.T, workDir, name string) []string {
t.Helper()
dir := filepath.Join(workDir, "external", name, "skills")
entries, err := os.ReadDir(dir)
if err != nil {
if os.IsNotExist(err) {
return nil
}
t.Fatal(err)
}
var out []string
for _, e := range entries {
if e.IsDir() {
out = append(out, e.Name())
}
}
sort.Strings(out)
return out
}
func snapshotTree(t *testing.T, root string) string {
t.Helper()
var paths []string
filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error {
if err == nil {
paths = append(paths, p)
}
return nil
})
sort.Strings(paths)
out := ""
for _, p := range paths {
data, err := os.ReadFile(p)
if err == nil {
out += p + ":" + fmt.Sprint(len(data)) + "\n"
} else {
out += p + ":dir\n"
}
}
return out
}
func addWithInclude(t *testing.T, h *harness, firstFive string) {
t.Helper()
h.mustRun(t, "vendor", "add", "superpowers", h.upstreamDir, "--include", firstFive)
}
func TestVendorSelectAddGrowsSelection(t *testing.T) {
h := newHarness(t)
buildTwentySkillUpstream(t, h)
addWithInclude(t, h, "skill-01,skill-02,skill-03,skill-04,skill-05")
revBefore := readLock(t, h.workDir).Sources["superpowers"].Rev
out := h.mustRun(t, "vendor", "select", "superpowers", "--add", "skill-06,skill-07,skill-08")
if !contains(out, "skill-06 (added)") || !contains(out, "skill-08 (added)") {
t.Errorf("report must list added items:\n%s", out)
}
got := externalSkillIDs(t, h.workDir, "superpowers")
if len(got) != 8 {
t.Errorf("external area must hold exactly 8 skills, got %d: %v", len(got), got)
}
v := readLock(t, h.workDir).Sources["superpowers"]
if len(v.Selection.Include) != 8 {
t.Errorf("include list must hold 8 ids, got %v", v.Selection.Include)
}
if v.Rev != revBefore {
t.Error("select must never advance the pinned rev")
}
if out := h.mustRun(t, "validate"); contains(out, "invalid") {
t.Errorf("validate must stay green:\n%s", out)
}
}
func TestVendorSelectRemoveInIncludeMode(t *testing.T) {
h := newHarness(t)
buildTwentySkillUpstream(t, h)
addWithInclude(t, h, "skill-01,skill-02,skill-03,skill-04,skill-05")
out := h.mustRun(t, "vendor", "select", "superpowers", "--remove", "skill-02,skill-04")
if !contains(out, "skill-02 (removed)") || !contains(out, "skill-04 (removed)") {
t.Errorf("report must list removed items:\n%s", out)
}
got := externalSkillIDs(t, h.workDir, "superpowers")
want := []string{"skill-01", "skill-03", "skill-05"}
if fmt.Sprint(got) != fmt.Sprint(want) {
t.Errorf("external skills = %v, want %v", got, want)
}
v := readLock(t, h.workDir).Sources["superpowers"]
if fmt.Sprint(v.Selection.Include) != fmt.Sprint(want) {
t.Errorf("include list = %v, want %v", v.Selection.Include, want)
}
lockPath := filepath.Join(h.workDir, "agent-lib.lock.json")
before := readFile(t, lockPath)
h.mustRun(t, "vendor", "select", "superpowers", "--add", "skill-01")
if after := readFile(t, lockPath); after != before {
t.Error("no-op select must leave the lockfile byte-identical")
}
}
func TestVendorSelectRemoveInAllMode(t *testing.T) {
h := newHarness(t)
buildTwentySkillUpstream(t, h)
h.mustRun(t, "vendor", "add", "superpowers", h.upstreamDir)
h.mustRun(t, "vendor", "select", "superpowers", "--remove", "skill-03,skill-17")
v := readLock(t, h.workDir).Sources["superpowers"]
if v.Selection.Mode != "all" {
t.Errorf("mode must stay all, got %q", v.Selection.Mode)
}
if fmt.Sprint(v.Selection.Exclude) != fmt.Sprint([]string{"skill-03", "skill-17"}) {
t.Errorf("exclude list = %v", v.Selection.Exclude)
}
got := externalSkillIDs(t, h.workDir, "superpowers")
if len(got) != 18 {
t.Errorf("external area must hold 18 skills, got %d", len(got))
}
for _, gone := range []string{"skill-03", "skill-17"} {
if _, err := os.Stat(filepath.Join(h.workDir, "external", "superpowers", "skills", gone)); !os.IsNotExist(err) {
t.Errorf("removed skill %s must be gone from the external area", gone)
}
}
h.mustRun(t, "validate")
}
func TestVendorSelectModeAllResets(t *testing.T) {
h := newHarness(t)
buildTwentySkillUpstream(t, h)
addWithInclude(t, h, "skill-01,skill-02,skill-03")
out := h.mustRun(t, "vendor", "select", "superpowers", "--mode", "all")
for _, id := range []string{"skill-04", "skill-20"} {
if !contains(out, id+" (added)") {
t.Errorf("report must list what arrived (missing %s):\n%s", id, out)
}
}
v := readLock(t, h.workDir).Sources["superpowers"]
if v.Selection.Mode != "all" || len(v.Selection.Include) > 0 || len(v.Selection.Exclude) > 0 {
t.Errorf("mode all must clear include/exclude: %+v", v.Selection)
}
if got := externalSkillIDs(t, h.workDir, "superpowers"); len(got) != 20 {
t.Errorf("all 20 skills must be materialized, got %d", len(got))
}
h.mustRun(t, "validate")
}
func TestVendorSelectAddTypoIsHardError(t *testing.T) {
h := newHarness(t)
buildTwentySkillUpstream(t, h)
addWithInclude(t, h, "skill-01,skill-02")
lockPath := filepath.Join(h.workDir, "agent-lib.lock.json")
lockBefore := readFile(t, lockPath)
treeBefore := snapshotTree(t, filepath.Join(h.workDir, "external"))
out, err := h.run(t, "vendor", "select", "superpowers", "--add", "skill-99")
if err == nil {
t.Fatalf("unknown id must be a hard error:\n%s", out)
}
if !contains(out, "skill-99") || !contains(out, "skill-01") {
t.Errorf("error must name the missing id and list available ids:\n%s", out)
}
if readFile(t, lockPath) != lockBefore {
t.Error("failed select must not mutate the lockfile")
}
if snapshotTree(t, filepath.Join(h.workDir, "external")) != treeBefore {
t.Error("failed select must not mutate the external area")
}
}
func TestVendorSelectRemoveTypoInIncludeMode(t *testing.T) {
h := newHarness(t)
buildTwentySkillUpstream(t, h)
addWithInclude(t, h, "skill-01,skill-02")
out, err := h.run(t, "vendor", "select", "superpowers", "--remove", "skill-09")
if err == nil {
t.Fatalf("--remove of an unselected id must be a hard error:\n%s", out)
}
if !contains(out, "not in the current selection") {
t.Errorf("error must explain the id is not selected:\n%s", out)
}
}
func TestVendorSelectAddInAllModeIsError(t *testing.T) {
h := newHarness(t)
buildTwentySkillUpstream(t, h)
h.mustRun(t, "vendor", "add", "superpowers", h.upstreamDir)
out, err := h.run(t, "vendor", "select", "superpowers", "--add", "skill-04")
if err == nil {
t.Fatalf("--add in all mode must be a hard error:\n%s", out)
}
if !contains(out, "already selected in all mode") {
t.Errorf("error must explain that everything is selected in all mode:\n%s", out)
}
}
func TestVendorSelectCollisionGuardAndRenameHonored(t *testing.T) {
h := newHarness(t)
buildTwentySkillUpstream(t, h)
addWithInclude(t, h, "skill-01,skill-02")
os.MkdirAll(filepath.Join(h.workDir, "skills", "skill-09"), 0o755)
os.WriteFile(filepath.Join(h.workDir, "skills", "skill-09", "SKILL.md"), []byte("---\nname: Own Nine\n---\n"), 0o644)
out, err := h.run(t, "vendor", "select", "superpowers", "--add", "skill-09")
if err == nil {
t.Fatalf("collision must abort the select:\n%s", out)
}
if !contains(out, "collides with own skills") {
t.Errorf("error must name both parties:\n%s", out)
}
lockPath := filepath.Join(h.workDir, "agent-lib.lock.json")
var raw map[string]any
if err := json.Unmarshal([]byte(readFile(t, lockPath)), &raw); err != nil {
t.Fatal(err)
}
src := raw["sources"].(map[string]any)["superpowers"].(map[string]any)
src["renames"] = map[string]string{"skill-09": "nine-renamed"}
data, _ := json.Marshal(raw)
os.WriteFile(lockPath, data, 0o644)
h.mustRun(t, "vendor", "select", "superpowers", "--add", "skill-09")
if _, err := os.Stat(filepath.Join(h.workDir, "external", "superpowers", "skills", "nine-renamed", "SKILL.md")); err != nil {
t.Error("renamed item must materialize under its deployed name")
}
v := readLock(t, h.workDir).Sources["superpowers"]
if v.Renames["skill-09"] != "nine-renamed" {
t.Errorf("rename map must survive select: %v", v.Renames)
}
if out := h.mustRun(t, "validate"); contains(out, "invalid") {
t.Errorf("validate must stay green after rename select:\n%s", out)
}
}
func TestVendorSelectModeAllRejectsCombinedFlags(t *testing.T) {
h := newHarness(t)
buildTwentySkillUpstream(t, h)
addWithInclude(t, h, "skill-01")
out, err := h.run(t, "vendor", "select", "superpowers", "--mode", "all", "--add", "skill-02")
if err == nil {
t.Fatalf("--mode all with --add must be rejected:\n%s", out)
}
if !contains(out, "cannot be combined") {
t.Errorf("error must explain the flag conflict:\n%s", out)
}
}
func TestVendorSelectNoFlagsIsError(t *testing.T) {
h := newHarness(t)
buildTwentySkillUpstream(t, h)
addWithInclude(t, h, "skill-01")
out, err := h.run(t, "vendor", "select", "superpowers")
if err == nil {
t.Fatalf("select without flags must be rejected:\n%s", out)
}
if !contains(out, "nothing to do") {
t.Errorf("error must list the available actions:\n%s", out)
}
}
func TestVendorSelectUnknownSourceAndUpstreamAdvance(t *testing.T) {
h := newHarness(t)
buildTwentySkillUpstream(t, h)
addWithInclude(t, h, "skill-01,skill-02,skill-03,skill-04,skill-05")
revPinned := readLock(t, h.workDir).Sources["superpowers"].Rev
if out, err := h.run(t, "vendor", "select", "nope"); err == nil {
t.Fatalf("unknown source must fail:\n%s", out)
} else if !contains(out, "not in the lockfile") {
t.Errorf("error must name the lockfile:\n%s", out)
}
h.write(t, "skills/skill-01/SKILL.md", "---\nname: Skill 01\ndescription: changed upstream\n---\n# changed\n")
h.commitUpstream(t, "upstream moves on")
h.mustRun(t, "vendor", "select", "superpowers", "--add", "skill-06")
v := readLock(t, h.workDir).Sources["superpowers"]
if v.Rev != revPinned {
t.Error("select must keep the pinned rev even when upstream moved on")
}
changed, err := os.ReadFile(filepath.Join(h.workDir, "external", "superpowers", "skills", "skill-01", "SKILL.md"))
if err != nil {
t.Fatal(err)
}
if contains(string(changed), "changed upstream") {
t.Error("select must materialize pinned content, not the ref head")
}
if out := h.mustRun(t, "validate"); contains(out, "invalid") {
t.Errorf("validate must stay green:\n%s", out)
}
}
-86
View File
@@ -1,86 +0,0 @@
package e2e
import (
"os"
"path/filepath"
"strings"
"testing"
)
func docFixture(h *harness, t *testing.T) {
t.Helper()
h.write(t, "skills/good-skill/SKILL.md", "---\nname: Good Skill\ndescription: works\n---\n# Good\n")
h.write(t, "agents/scout.md", "---\ndescription: a real agent\n---\nbody\n")
h.write(t, "agents/SCHEMA.md", "# Schema\npure documentation, no frontmatter\n")
h.write(t, "commands/review.md", "---\nargument-hint: [files]\n---\nbody\n")
h.write(t, "commands/README.md", "Documentation for the commands directory.\n")
h.commitUpstream(t, "fixture with documentation files")
}
func TestVendorAddSkipsDocMarkdownWithWarning(t *testing.T) {
h := newHarness(t)
docFixture(h, t)
out := h.mustRun(t, "vendor", "add", "superpowers", h.upstreamDir)
if !contains(out, "agents/SCHEMA.md: no agent frontmatter, skipped") {
t.Errorf("add report must warn about skipped SCHEMA.md:\n%s", out)
}
if !contains(out, "commands/README.md: no command frontmatter, skipped") {
t.Errorf("add report must warn about skipped README.md:\n%s", out)
}
lock := readFile(t, filepath.Join(h.workDir, "agent-lib.lock.json"))
if !contains(lock, "agents/SCHEMA.md: no agent frontmatter, skipped") {
t.Errorf("lockfile warnings must record the skip:\n%s", lock)
}
for _, dir := range []string{"agents", "commands"} {
entries, err := os.ReadDir(filepath.Join(h.workDir, "external", "superpowers", dir))
if err != nil {
t.Fatalf("external %s area must exist: %v", dir, err)
}
for _, e := range entries {
name := e.Name()
if (dir == "agents" && name == "SCHEMA.md") || (dir == "commands" && name == "README.md") {
t.Errorf("documentation file %s/%s must not be materialized", dir, name)
}
}
}
if !contains(out, "1 agents") || !contains(out, "1 commands") {
t.Errorf("counts must reflect real items only:\n%s", out)
}
h.mustRun(t, "validate")
}
func TestVendorAddIncludeErrorOmitsSkippedDocs(t *testing.T) {
h := newHarness(t)
docFixture(h, t)
out, err := h.run(t, "vendor", "add", "superpowers", h.upstreamDir, "--include", "typo")
if err == nil {
t.Fatalf("include with typo must fail:\n%s", out)
}
if contains(out, "SCHEMA") || contains(out, "README") {
t.Errorf("skipped documentation must not appear as available ids:\n%s", out)
}
for _, want := range []string{"scout", "review", "good-skill"} {
if !contains(out, want) {
t.Errorf("real ids must still be listed as available (missing %s):\n%s", want, out)
}
}
}
func TestVendorUpdateSelectKeepSkippingDocs(t *testing.T) {
h := newHarness(t)
docFixture(h, t)
h.mustRun(t, "vendor", "add", "superpowers", h.upstreamDir, "--include", "scout,review")
out := h.mustRun(t, "vendor", "select", "superpowers", "--add", "good-skill")
if contains(out, "SCHEMA") {
t.Errorf("select report must not surface skipped docs:\n%s", out)
}
lock := readFile(t, filepath.Join(h.workDir, "agent-lib.lock.json"))
if got := strings.Count(lock, "no agent frontmatter, skipped"); got != 1 {
t.Errorf("warning must stay recorded exactly once in the lockfile, got %d", got)
}
h.mustRun(t, "validate")
}
-140
View File
@@ -1,140 +0,0 @@
package e2e
import (
"encoding/json"
"os"
"path/filepath"
"testing"
)
func statusRun(t *testing.T, env *syncEnv, jsonFlag bool) (string, error) {
t.Helper()
args := []string{"status", "--config", env.config}
if jsonFlag {
args = append(args, "--json")
}
cmd := agentLibCmd(args...)
cmd.Env = append(os.Environ(),
"HOME="+env.home, "USERPROFILE="+env.home,
"AGENT_LIB_STATE_DIR="+env.stateDir,
)
out, err := cmd.CombinedOutput()
return string(out), err
}
func TestStatusInSync(t *testing.T) {
h := newHarness(t)
env := newSyncEnv(t, h)
buildWorkRepo(t, h, env.workRepo)
env.writeConfig(t, env.workRepo, "")
syncOnce(t, env)
out, err := statusRun(t, env, false)
if err != nil {
t.Fatalf("in-sync status must exit 0: %v\n%s", err, out)
}
for _, want := range []string{"in sync", "deployed revision", "repository revision", "agent-lib"} {
if !contains(out, want) {
t.Errorf("status output missing %q:\n%s", want, out)
}
}
}
func TestStatusDriftNonZero(t *testing.T) {
h := newHarness(t)
env := newSyncEnv(t, h)
buildWorkRepo(t, h, env.workRepo)
env.writeConfig(t, env.workRepo, "")
syncOnce(t, env)
os.WriteFile(filepath.Join(env.home, ".agents/skills/own-skill/SKILL.md"),
[]byte("---\nname: Own Skill\n---\n# my edits\n"), 0o644)
p := filepath.Join(env.workRepo, "skills/own-skill/SKILL.md")
os.WriteFile(p, []byte("---\nname: Own Skill\ndescription: v2\n---\n# Upstream v2\n"), 0o644)
commitWorkRepo(t, h, env.workRepo, "change own-skill")
out, err := statusRun(t, env, false)
if err == nil {
t.Fatalf("blocked-update drift must exit non-zero:\n%s", out)
}
for _, want := range []string{"skipped", "own-skill", "locally modified", "drift"} {
if !contains(out, want) {
t.Errorf("status missing %q:\n%s", want, out)
}
}
jsonOut, err := statusRun(t, env, true)
if err == nil {
t.Fatalf("json status must keep the drift exit code:\n%s", jsonOut)
}
var report struct {
InSync bool `json:"in_sync"`
Drift bool `json:"problematic_drift"`
Skipped []struct {
Item string `json:"item"`
Reason string `json:"reason"`
} `json:"skipped_items"`
Pending []struct {
Item string `json:"item"`
} `json:"pending_changes"`
}
if err := json.Unmarshal([]byte(jsonOut), &report); err != nil {
t.Fatalf("status --json not parseable: %v\n%s", err, jsonOut)
}
if !report.Drift || report.InSync {
t.Errorf("json flags wrong: %+v", report)
}
if len(report.Skipped) != 1 || report.Skipped[0].Item != "skills/own-skill" {
t.Errorf("skipped item missing from json: %+v", report.Skipped)
}
}
func TestStatusUnrecognizedButNoDrift(t *testing.T) {
h := newHarness(t)
env := newSyncEnv(t, h)
buildWorkRepo(t, h, env.workRepo)
env.writeConfig(t, env.workRepo, "")
syncOnce(t, env)
mine := filepath.Join(env.home, ".agents/skills/my-own-thing")
os.MkdirAll(mine, 0o755)
os.WriteFile(filepath.Join(mine, "SKILL.md"), []byte("---\nname: Mine\n---\n"), 0o644)
out, err := statusRun(t, env, false)
if err != nil {
t.Fatalf("unrecognized items alone are not problematic drift:\n%s", out)
}
if !contains(out, "unrecognized local items") || !contains(out, "my-own-thing") {
t.Errorf("unrecognized item must be listed:\n%s", out)
}
if contains(out, "drift:") {
t.Errorf("no drift line expected:\n%s", out)
}
}
func TestStatusNeverSynced(t *testing.T) {
h := newHarness(t)
env := newSyncEnv(t, h)
buildWorkRepo(t, h, env.workRepo)
env.writeConfig(t, env.workRepo, "")
out, err := statusRun(t, env, true)
if err != nil {
t.Fatalf("fresh status must exit 0: %v\n%s", err, out)
}
var report struct {
DeployedRev string `json:"deployed_revision"`
Pending []struct {
Item string `json:"item"`
} `json:"pending_changes"`
}
if err := json.Unmarshal([]byte(out), &report); err != nil {
t.Fatalf("json not parseable: %v", err)
}
if report.DeployedRev != "" {
t.Errorf("never synced must have empty deployed revision: %q", report.DeployedRev)
}
if len(report.Pending) == 0 {
t.Error("fresh status must list everything as pending deploy")
}
}
-42
View File
@@ -1,42 +0,0 @@
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")
}
}
-83
View File
@@ -1,83 +0,0 @@
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")
}
}
-279
View File
@@ -1,279 +0,0 @@
package e2e
import (
"encoding/json"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
func agentLibCmd(args ...string) *exec.Cmd {
return exec.Command(binPath, args...)
}
type syncEnv struct {
home string
stateDir string
configDir string
config string
workRepo string
}
func newSyncEnv(t *testing.T, h *harness) *syncEnv {
t.Helper()
base := t.TempDir()
env := &syncEnv{
home: filepath.Join(base, "home"),
stateDir: filepath.Join(base, "state"),
configDir: filepath.Join(base, "config"),
workRepo: filepath.Join(base, "work-repo"),
}
for _, d := range []string{env.home, env.stateDir, env.configDir, env.workRepo} {
if err := os.MkdirAll(d, 0o755); err != nil {
t.Fatal(err)
}
}
return env
}
func (e *syncEnv) writeConfig(t *testing.T, repoURL, token string) {
t.Helper()
cfg := map[string]string{"repo_url": repoURL, "ref": "main"}
if token != "" {
cfg["token"] = token
}
data, err := json.Marshal(cfg)
if err != nil {
t.Fatal(err)
}
e.config = filepath.Join(e.configDir, "config.json")
os.WriteFile(e.config, data, 0o600)
}
func (e *syncEnv) run(t *testing.T, args ...string) (string, error) {
t.Helper()
cmd := agentLibCmd(append([]string{"sync", "--config", e.config}, args...)...)
cmd.Env = append(os.Environ(),
"HOME="+e.home, "USERPROFILE="+e.home,
"AGENT_LIB_STATE_DIR="+e.stateDir,
)
out, err := cmd.CombinedOutput()
return string(out), err
}
func buildWorkRepo(t *testing.T, h *harness, dir string) {
t.Helper()
h.git(t, dir, "init", "-b", "main")
write := func(rel, content string) {
p := filepath.Join(dir, rel)
os.MkdirAll(filepath.Dir(p), 0o755)
os.WriteFile(p, []byte(content), 0o644)
}
write("skills/own-skill/SKILL.md", "---\nname: Own Skill\n---\n# Own\n")
write("skills/own-skill/run.sh", "#!/bin/sh\necho hi\n")
os.Chmod(filepath.Join(dir, "skills/own-skill/run.sh"), 0o755)
write("commands/deploy.md", "---\nname: Deploy\n---\nbody\n")
write("agents/helper.md", "---\nname: Helper\n---\nbody\n")
write("mcp/internal.yaml", "servers: {}\n")
h.git(t, dir, "add", "-A")
h.git(t, dir, "commit", "-m", "work repo")
}
func TestSyncHappyPathAndManifest(t *testing.T) {
h := newHarness(t)
env := newSyncEnv(t, h)
buildWorkRepo(t, h, env.workRepo)
env.writeConfig(t, env.workRepo, "")
out, err := env.run(t)
if err != nil {
t.Fatalf("sync failed: %v\n%s", err, out)
}
skillMd := filepath.Join(env.home, ".agents/skills/own-skill/SKILL.md")
if _, err := os.Stat(skillMd); err != nil {
t.Error("skill must deploy to ~/.agents/skills/<id>/")
}
runSh := filepath.Join(env.home, ".agents/skills/own-skill/run.sh")
info, err := os.Stat(runSh)
if err != nil {
t.Fatal("skill folder artifacts must be preserved")
}
if info.Mode()&0o111 == 0 {
t.Error("executable bit must survive deployment")
}
if _, err := os.Stat(filepath.Join(env.home, ".config/opencode/commands/deploy.md")); err != nil {
t.Error("command must deploy to ~/.config/opencode/commands/<id>.md")
}
if _, err := os.Stat(filepath.Join(env.home, ".config/opencode/agents/helper.md")); err != nil {
t.Error("agent must deploy to ~/.config/opencode/agents/<id>.md")
}
if _, err := os.Stat(filepath.Join(env.home, ".config/opencode/mcp")); err == nil {
t.Error("MCP must never be deployed")
}
mcpEverywhere := false
filepath.WalkDir(env.home, func(p string, d os.DirEntry, err error) error {
if d != nil && !d.IsDir() && strings.HasSuffix(p, ".yaml") {
mcpEverywhere = true
}
return nil
})
if mcpEverywhere {
t.Error("no yaml fragment may land anywhere in HOME")
}
manifestData, err := os.ReadFile(filepath.Join(env.stateDir, "manifest.json"))
if err != nil {
t.Fatal("manifest must exist in the state dir")
}
var manifest struct {
Version int `json:"version"`
Items map[string]struct {
Name string `json:"name"`
Type string `json:"type"`
Origin string `json:"origin"`
Revision string `json:"revision"`
Hash string `json:"hash"`
} `json:"items"`
}
if err := json.Unmarshal(manifestData, &manifest); err != nil {
t.Fatalf("manifest not parseable: %v", err)
}
skill := manifest.Items["skills/own-skill"]
if skill.Origin != "own" || skill.Hash == "" || skill.Revision == "" {
t.Errorf("manifest record incomplete: %+v", skill)
}
}
func TestSyncIdempotentSecondRun(t *testing.T) {
h := newHarness(t)
env := newSyncEnv(t, h)
buildWorkRepo(t, h, env.workRepo)
env.writeConfig(t, env.workRepo, "")
if _, err := env.run(t); err != nil {
t.Fatal(err)
}
skillMd := filepath.Join(env.home, ".agents/skills/own-skill/SKILL.md")
firstInfo, _ := os.Stat(skillMd)
manifestBefore := readFile(t, filepath.Join(env.stateDir, "manifest.json"))
out, err := env.run(t)
if err != nil {
t.Fatalf("second sync failed: %v\n%s", err, out)
}
if !contains(out, "kept: 3") {
t.Errorf("second run must keep everything:\n%s", out)
}
secondInfo, _ := os.Stat(skillMd)
if !firstInfo.ModTime().Equal(secondInfo.ModTime()) {
t.Error("unchanged items must not be rewritten (byte-level no-op)")
}
if got := readFile(t, filepath.Join(env.stateDir, "manifest.json")); got != manifestBefore {
t.Error("manifest bytes must not change on a no-op sync")
}
}
func TestSyncUnreachableRepoKeepsState(t *testing.T) {
h := newHarness(t)
env := newSyncEnv(t, h)
buildWorkRepo(t, h, env.workRepo)
env.writeConfig(t, env.workRepo, "")
if _, err := env.run(t); err != nil {
t.Fatal(err)
}
skillBefore := readFile(t, filepath.Join(env.home, ".agents/skills/own-skill/SKILL.md"))
env.writeConfig(t, filepath.Join(t.TempDir(), "does-not-exist"), "")
out, err := env.run(t)
if err == nil {
t.Fatalf("unreachable repo must fail:\n%s", out)
}
if !contains(out, "error") {
t.Errorf("failure must be a clean error:\n%s", out)
}
if got := readFile(t, filepath.Join(env.home, ".agents/skills/own-skill/SKILL.md")); got != skillBefore {
t.Error("previous state must survive a failed sync")
}
}
func TestSyncPicksUpChanges(t *testing.T) {
h := newHarness(t)
env := newSyncEnv(t, h)
buildWorkRepo(t, h, env.workRepo)
env.writeConfig(t, env.workRepo, "")
env.run(t)
p := filepath.Join(env.workRepo, "commands/deploy.md")
os.WriteFile(p, []byte("---\nname: Deploy\ndescription: updated\n---\nnew body\n"), 0o644)
h.git(t, env.workRepo, "add", "-A")
h.git(t, env.workRepo, "commit", "-m", "update command")
out, err := env.run(t)
if err != nil {
t.Fatalf("sync after upstream change failed: %v\n%s", err, out)
}
if !contains(out, "updated: 1") {
t.Errorf("changed item must be updated:\n%s", out)
}
deployed := readFile(t, filepath.Join(env.home, ".config/opencode/commands/deploy.md"))
if !contains(deployed, "new body") {
t.Error("updated content must land on disk")
}
}
func TestSyncVendoredContentDeploys(t *testing.T) {
h := newHarness(t)
standardFixture(h, t)
env := newSyncEnv(t, h)
buildWorkRepo(t, h, env.workRepo)
upstreamWork := env.workRepo
cmd := agentLibCmd("vendor", "add", "superpowers", h.upstreamDir)
cmd.Dir = upstreamWork
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("vendor add into work repo: %v\n%s", err, out)
}
h.git(t, upstreamWork, "add", "-A")
h.git(t, upstreamWork, "commit", "-m", "vendor superpowers")
env.writeConfig(t, upstreamWork, "")
out, err := env.run(t)
if err != nil {
t.Fatalf("sync with vendored content failed: %v\n%s", err, out)
}
if _, err := os.Stat(filepath.Join(env.home, ".agents/skills/good-skill/SKILL.md")); err != nil {
t.Error("vendored skill must deploy under its deployed name")
}
manifestData := []byte(readFile(t, filepath.Join(env.stateDir, "manifest.json")))
if !contains(string(manifestData), `"origin": "superpowers"`) {
t.Errorf("manifest must record the source origin:\n%s", manifestData)
}
}
func TestSyncTokenNeverLeaked(t *testing.T) {
h := newHarness(t)
env := newSyncEnv(t, h)
buildWorkRepo(t, h, env.workRepo)
env.writeConfig(t, env.workRepo, "super-secret-token")
out, err := env.run(t)
if err != nil {
t.Fatalf("sync with token failed: %v\n%s", err, out)
}
if contains(out, "super-secret-token") {
t.Errorf("token must never appear in output:\n%s", out)
}
for _, path := range []string{
filepath.Join(env.stateDir, "manifest.json"),
filepath.Join(env.workRepo, "agent-lib.lock.json"),
} {
if data, err := os.ReadFile(path); err == nil && strings.Contains(string(data), "super-secret-token") {
t.Errorf("token leaked into %s", path)
}
}
}
-218
View File
@@ -1,218 +0,0 @@
package e2e
import (
"os"
"path/filepath"
"testing"
"github.com/m3tam3re/agent-lib/internal/lockfile"
)
func bumpUpstream(h *harness, t *testing.T) {
t.Helper()
h.write(t, "skills/fresh-skill/SKILL.md", "---\nname: Fresh\n---\n# Fresh\n")
h.write(t, "skills/good-skill/SKILL.md", "---\nname: Good Skill\ndescription: changed upstream\n---\n# Changed\n")
os.RemoveAll(filepath.Join(h.upstreamDir, "skills/broken-skill"))
os.Remove(filepath.Join(h.upstreamDir, "agents/scout.md"))
h.commitUpstream(t, "fixture: add fresh, change good, remove broken+scout")
}
func TestVendorUpdateHappyPath(t *testing.T) {
h := newHarness(t)
standardFixture(h, t)
h.mustRun(t, "vendor", "add", "superpowers", h.upstreamDir)
oldLock := readFile(t, filepath.Join(h.workDir, lockfile.FileName))
bumpUpstream(h, t)
out := h.mustRun(t, "vendor", "update", "superpowers")
for _, want := range []string{"fresh-skill (added)", "good-skill (changed)", "broken-skill (removed)", "scout (removed)"} {
if !contains(out, want) {
t.Errorf("report missing %q:\n%s", want, out)
}
}
newSkill := filepath.Join(h.workDir, "external/superpowers/skills/fresh-skill/SKILL.md")
if _, err := os.Stat(newSkill); err != nil {
t.Error("added skill must be materialized")
}
if _, err := os.Stat(filepath.Join(h.workDir, "external/superpowers/skills/broken-skill")); err == nil {
t.Error("removed skill must be gone from the external area")
}
if _, err := os.Stat(filepath.Join(h.workDir, "external/superpowers/agents/scout.md")); err == nil {
t.Error("removed agent must be gone from the external area")
}
newLock := readFile(t, filepath.Join(h.workDir, lockfile.FileName))
if newLock == oldLock {
t.Fatal("lockfile must advance its rev")
}
if !contains(newLock, "fresh-skill") || contains(newLock, "broken-skill") {
t.Errorf("inventory must reflect the new selection:\n%s", newLock)
}
if out := h.mustRun(t, "validate"); !contains(out, "valid") {
t.Errorf("updated state must validate:\n%s", out)
}
}
func TestVendorUpdateIncludeModeHoldsSelection(t *testing.T) {
h := newHarness(t)
standardFixture(h, t)
h.mustRun(t, "vendor", "add", "curated", h.upstreamDir, "--include", "good-skill")
bumpUpstream(h, t)
diffOut := h.mustRun(t, "vendor", "diff", "curated")
if !contains(diffOut, "fresh-skill (available upstream, not selected)") {
t.Errorf("diff must surface new upstream items as available:\n%s", diffOut)
}
out := h.mustRun(t, "vendor", "update", "curated")
if contains(out, "fresh-skill (added)") {
t.Errorf("include mode must not pull new upstream items:\n%s", out)
}
if _, err := os.Stat(filepath.Join(h.workDir, "external/curated/skills/fresh-skill")); err == nil {
t.Error("fresh-skill must not be materialized in include mode")
}
if !contains(out, "good-skill (changed)") {
t.Errorf("included item changes must still arrive:\n%s", out)
}
}
func TestVendorUpdateVanishedIncludeFailsLoud(t *testing.T) {
h := newHarness(t)
standardFixture(h, t)
h.mustRun(t, "vendor", "add", "curated", h.upstreamDir, "--include", "good-skill")
lockBefore := readFile(t, filepath.Join(h.workDir, lockfile.FileName))
os.RemoveAll(filepath.Join(h.upstreamDir, "skills/good-skill"))
h.commitUpstream(t, "fixture: remove good-skill")
out, err := h.run(t, "vendor", "update", "curated")
if err == nil {
t.Fatalf("vanished include entry must fail the update:\n%s", out)
}
if !contains(out, "good-skill") || !contains(out, "not found upstream") {
t.Errorf("error must name the vanished entry:\n%s", out)
}
if got := readFile(t, filepath.Join(h.workDir, lockfile.FileName)); got != lockBefore {
t.Error("failed update must leave the lockfile untouched")
}
}
func TestVendorUpdateUpToDateIdempotent(t *testing.T) {
h := newHarness(t)
standardFixture(h, t)
h.mustRun(t, "vendor", "add", "superpowers", h.upstreamDir)
lockBefore := readFile(t, filepath.Join(h.workDir, lockfile.FileName))
out := h.mustRun(t, "vendor", "update", "superpowers")
if !contains(out, "already up to date") {
t.Errorf("unchanged upstream must report up-to-date:\n%s", out)
}
if got := readFile(t, filepath.Join(h.workDir, lockfile.FileName)); got != lockBefore {
t.Error("up-to-date update must not touch the lockfile")
}
}
func TestVendorDiffReadOnly(t *testing.T) {
h := newHarness(t)
standardFixture(h, t)
h.mustRun(t, "vendor", "add", "superpowers", h.upstreamDir)
lockBefore := readFile(t, filepath.Join(h.workDir, lockfile.FileName))
out := h.mustRun(t, "vendor", "diff", "superpowers")
if !contains(out, "up to date") {
t.Errorf("unchanged upstream diff:\n%s", out)
}
bumpUpstream(h, t)
out = h.mustRun(t, "vendor", "diff", "superpowers")
for _, want := range []string{"fresh-skill", "good-skill", "broken-skill"} {
if !contains(out, want) {
t.Errorf("diff must list %q:\n%s", want, out)
}
}
if got := readFile(t, filepath.Join(h.workDir, lockfile.FileName)); got != lockBefore {
t.Error("diff must not modify the lockfile")
}
if _, err := os.Stat(filepath.Join(h.workDir, "external/superpowers/skills/fresh-skill")); err == nil {
t.Error("diff must not materialize anything")
}
if _, err := os.Stat(filepath.Join(h.workDir, "external/superpowers/skills/broken-skill")); err != nil {
t.Error("diff must not remove anything")
}
}
func TestVendorRemoveLeavesNoResidue(t *testing.T) {
h := newHarness(t)
standardFixture(h, t)
h.mustRun(t, "vendor", "add", "superpowers", h.upstreamDir)
out := h.mustRun(t, "vendor", "remove", "superpowers")
if !contains(out, "removed") {
t.Errorf("remove must confirm:\n%s", out)
}
if _, err := os.Stat(filepath.Join(h.workDir, "external/superpowers")); err == nil {
t.Error("external area must be gone")
}
if _, err := os.Stat(filepath.Join(h.workDir, "external")); err == nil {
t.Error("empty external root must be cleaned up")
}
lock := readFile(t, filepath.Join(h.workDir, lockfile.FileName))
if contains(lock, "superpowers") {
t.Errorf("lockfile entry must be gone:\n%s", lock)
}
}
func TestVendorUpdateAll(t *testing.T) {
h := newHarness(t)
standardFixture(h, t)
h.mustRun(t, "vendor", "add", "alpha", h.upstreamDir)
h.mustRun(t, "vendor", "add", "beta", h.upstreamDir, "--include", "good-skill",
"--rename", "good-skill=beta-good")
bumpUpstream(h, t)
out := h.mustRun(t, "vendor", "update", "--all")
if !contains(out, "alpha") || !contains(out, "beta") {
t.Errorf("update --all must report per source:\n%s", out)
}
if _, err := os.Stat(filepath.Join(h.workDir, "external/alpha/skills/fresh-skill/SKILL.md")); err != nil {
t.Error("alpha (all mode) must receive fresh-skill")
}
if _, err := os.Stat(filepath.Join(h.workDir, "external/beta/skills/fresh-skill")); err == nil {
t.Error("beta (include mode) must not receive fresh-skill")
}
if _, err := os.Stat(filepath.Join(h.workDir, "external/beta/skills/beta-good/SKILL.md")); err != nil {
t.Error("beta rename must survive the update")
}
}
func TestVendorUpdateCollisionWithOwn(t *testing.T) {
h := newHarness(t)
standardFixture(h, t)
h.mustRun(t, "vendor", "add", "superpowers", h.upstreamDir)
lockBefore := readFile(t, filepath.Join(h.workDir, lockfile.FileName))
ownDir := filepath.Join(h.workDir, "skills", "fresh-skill")
if err := os.MkdirAll(ownDir, 0o755); err != nil {
t.Fatal(err)
}
os.WriteFile(filepath.Join(ownDir, "SKILL.md"), []byte("---\nname: My Own Fresh\n---\n"), 0o644)
h.write(t, "skills/fresh-skill/SKILL.md", "---\nname: Upstream Fresh\n---\n")
h.commitUpstream(t, "fixture: add fresh-skill that collides")
out, err := h.run(t, "vendor", "update", "superpowers")
if err == nil {
t.Fatalf("upstream collision with own item must fail:\n%s", out)
}
if !contains(out, "collides") || !contains(out, "own") {
t.Errorf("error must name both parties:\n%s", out)
}
if got := readFile(t, filepath.Join(h.workDir, lockfile.FileName)); got != lockBefore {
t.Error("failed update must not touch the lockfile")
}
if _, err := os.Stat(filepath.Join(h.workDir, "external/superpowers/skills/good-skill/SKILL.md")); err != nil {
t.Error("previous external area must survive the failed update")
}
}
-282
View File
@@ -1,282 +0,0 @@
// Package e2e runs the compiled agent-lib binary as a black box against
// local fixture git repositories — fully offline.
package e2e
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
var binPath string
func TestMain(m *testing.M) {
dir, err := os.MkdirTemp("", "agent-lib-e2e-bin")
if err != nil {
os.Exit(1)
}
binPath = filepath.Join(dir, "agent-lib")
build := exec.Command("go", "build", "-o", binPath, ".")
build.Dir = "../.."
if out, err := build.CombinedOutput(); err != nil {
os.Stderr.Write(out)
os.Exit(1)
}
code := m.Run()
os.RemoveAll(dir)
os.Exit(code)
}
type harness struct {
t *testing.T
workDir string
upstreamDir string
}
func newHarness(t *testing.T) *harness {
t.Helper()
base := t.TempDir()
h := &harness{
t: t,
workDir: filepath.Join(base, "work"),
upstreamDir: filepath.Join(base, "upstream"),
}
for _, d := range []string{h.workDir, h.upstreamDir} {
if err := os.MkdirAll(d, 0o755); err != nil {
t.Fatal(err)
}
}
h.git(t, h.upstreamDir, "init", "-b", "main")
return h
}
func (h *harness) git(t *testing.T, dir string, args ...string) string {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = dir
cmd.Env = append(os.Environ(),
"GIT_AUTHOR_NAME=test", "GIT_AUTHOR_EMAIL=test@test",
"GIT_COMMITTER_NAME=test", "GIT_COMMITTER_EMAIL=test@test",
"GIT_AUTHOR_DATE=1700000000 +0000", "GIT_COMMITTER_DATE=1700000000 +0000",
)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git %v in %s: %v\n%s", args, dir, err, out)
}
return string(out)
}
func (h *harness) write(t *testing.T, rel, content string) {
t.Helper()
path := filepath.Join(h.upstreamDir, rel)
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
func (h *harness) commitUpstream(t *testing.T, msg string) {
t.Helper()
h.git(t, h.upstreamDir, "add", "-A")
h.git(t, h.upstreamDir, "commit", "-m", msg)
}
func (h *harness) run(t *testing.T, args ...string) (string, error) {
t.Helper()
cmd := exec.Command(binPath, args...)
cmd.Dir = h.workDir
out, err := cmd.CombinedOutput()
return string(out), err
}
func (h *harness) mustRun(t *testing.T, args ...string) string {
t.Helper()
out, err := h.run(t, args...)
if err != nil {
t.Fatalf("agent-lib %v: %v\n%s", args, err, out)
}
return out
}
func standardFixture(h *harness, t *testing.T) {
h.write(t, "skills/good-skill/SKILL.md", "---\nname: Good Skill\ndescription: works\ntags: a, b\n---\n# Good\n")
h.write(t, "skills/good-skill/helper.py", "print('hi')\n")
h.write(t, "skills/broken-skill/SKILL.md", "---\nname: Broken\nthis line has no colon\n")
h.write(t, "commands/review.md", "---\nname: Review\ndescription: review things\n---\nbody\n")
h.write(t, "agents/scout.md", "---\nname: Scout\n---\nbody\n")
h.write(t, "mcp/search.yaml", "servers:\n search:\n command: search\n")
h.write(t, "README.md", "upstream readme\n")
h.commitUpstream(t, "fixture: initial content")
}
func TestVendorAddAllMode(t *testing.T) {
h := newHarness(t)
standardFixture(h, t)
out := h.mustRun(t, "vendor", "add", "superpowers", h.upstreamDir)
if !contains(out, "ref: main") {
t.Errorf("report missing resolved ref:\n%s", out)
}
if !contains(out, "4 skills") && !contains(out, "2 skills") {
t.Errorf("report should list skill count:\n%s", out)
}
if !contains(out, "warnings") {
t.Errorf("malformed frontmatter must produce a warning in the report:\n%s", out)
}
for _, p := range []string{
"external/superpowers/skills/good-skill/SKILL.md",
"external/superpowers/skills/good-skill/helper.py",
"external/superpowers/skills/broken-skill/SKILL.md",
"external/superpowers/commands/review.md",
"external/superpowers/agents/scout.md",
"external/superpowers/mcp/search.yaml",
} {
if _, err := os.Stat(filepath.Join(h.workDir, p)); err != nil {
t.Errorf("missing materialized file %s", p)
}
}
if _, err := os.Stat(filepath.Join(h.workDir, "external/superpowers/README.md")); err == nil {
t.Error("README must not be vendored")
}
lockBytes, err := os.ReadFile(filepath.Join(h.workDir, "agent-lib.lock.json"))
if err != nil {
t.Fatal(err)
}
lock := string(lockBytes)
if !contains(lock, `"version": 2`) {
t.Errorf("lockfile must be schema v2:\n%s", lock)
}
if !contains(lock, `"mode": "all"`) {
t.Errorf("default selection must be all:\n%s", lock)
}
if !contains(lock, h.upstreamDir) {
t.Errorf("lockfile must pin the url:\n%s", lock)
}
if !contains(lock, "frontmatter") {
t.Errorf("recorded warnings missing from lockfile:\n%s", lock)
}
}
func TestVendorAddDeterministicRerun(t *testing.T) {
h := newHarness(t)
standardFixture(h, t)
h.mustRun(t, "vendor", "add", "superpowers", h.upstreamDir)
secondWork := filepath.Join(t.TempDir(), "work2")
if err := os.MkdirAll(secondWork, 0o755); err != nil {
t.Fatal(err)
}
cmd := exec.Command(binPath, "vendor", "add", "superpowers", h.upstreamDir)
cmd.Dir = secondWork
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("second add: %v\n%s", err, out)
}
b1 := readFile(t, filepath.Join(h.workDir, "agent-lib.lock.json"))
b2 := readFile(t, filepath.Join(secondWork, "agent-lib.lock.json"))
if b1 != b2 {
t.Fatalf("same upstream commit must produce identical lockfiles:\n%s\n---\n%s", b1, b2)
}
}
func TestVendorAddIncludeMode(t *testing.T) {
h := newHarness(t)
standardFixture(h, t)
h.mustRun(t, "vendor", "add", "curated", h.upstreamDir, "--include", "good-skill,review")
if _, err := os.Stat(filepath.Join(h.workDir, "external/curated/skills/good-skill/SKILL.md")); err != nil {
t.Error("included skill must be materialized")
}
if _, err := os.Stat(filepath.Join(h.workDir, "external/curated/commands/review.md")); err != nil {
t.Error("included command must be materialized")
}
if _, err := os.Stat(filepath.Join(h.workDir, "external/curated/agents/scout.md")); err == nil {
t.Error("non-included agent must NOT be materialized")
}
lock := readFile(t, filepath.Join(h.workDir, "agent-lib.lock.json"))
if !contains(lock, `"mode": "include"`) {
t.Errorf("selection mode must be include:\n%s", lock)
}
if !contains(lock, `"include": [`) {
t.Errorf("include list missing:\n%s", lock)
}
}
func TestVendorAddIncludeTypoFailsClean(t *testing.T) {
h := newHarness(t)
standardFixture(h, t)
out, err := h.run(t, "vendor", "add", "curated", h.upstreamDir, "--include", "good-skill,nope")
if err == nil {
t.Fatalf("typo in include list must fail:\n%s", out)
}
if !contains(out, "nope") {
t.Errorf("error must name the missing entry:\n%s", out)
}
if _, err := os.Stat(filepath.Join(h.workDir, "agent-lib.lock.json")); err == nil {
t.Error("failed add must not write a lockfile")
}
if _, err := os.Stat(filepath.Join(h.workDir, "external")); err == nil {
t.Error("failed add must not create the external area")
}
}
func TestVendorAddDuplicateName(t *testing.T) {
h := newHarness(t)
standardFixture(h, t)
h.mustRun(t, "vendor", "add", "superpowers", h.upstreamDir)
out, err := h.run(t, "vendor", "add", "superpowers", h.upstreamDir)
if err == nil {
t.Fatalf("duplicate source name must fail:\n%s", out)
}
if !contains(out, "already exists") {
t.Errorf("error must be explicit about the duplicate:\n%s", out)
}
}
func TestVendorAddOrphanExternalDir(t *testing.T) {
h := newHarness(t)
standardFixture(h, t)
os.MkdirAll(filepath.Join(h.workDir, "external", "ghost"), 0o755)
out, err := h.run(t, "vendor", "add", "ghost", h.upstreamDir)
if err == nil {
t.Fatalf("orphan external dir must fail:\n%s", out)
}
if !contains(out, "not in the lockfile") {
t.Errorf("error must explain the orphan:\n%s", out)
}
}
func TestVendorAddAtRef(t *testing.T) {
h := newHarness(t)
standardFixture(h, t)
h.git(t, h.upstreamDir, "tag", "v1.0")
out := h.mustRun(t, "vendor", "add", "pinned", h.upstreamDir, "--ref", "v1.0")
if !contains(out, "ref: v1.0") {
t.Errorf("tag ref must be pinned:\n%s", out)
}
}
func contains(haystack, needle string) bool {
return strings.Contains(haystack, needle)
}
func readFile(t *testing.T, path string) string {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
return string(data)
}
-75
View File
@@ -1,75 +0,0 @@
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)
}
}
-162
View File
@@ -1,162 +0,0 @@
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)
}
}
-180
View File
@@ -1,180 +0,0 @@
package e2e
import (
"os"
"path/filepath"
"testing"
)
func syncOnce(t *testing.T, env *syncEnv) {
t.Helper()
if out, err := env.run(t); err != nil {
t.Fatalf("sync failed: %v\n%s", err, out)
}
}
func commitWorkRepo(t *testing.T, h *harness, dir, msg string) {
t.Helper()
h.git(t, dir, "add", "-A")
h.git(t, dir, "commit", "-m", msg)
}
func TestSyncSkipsLocallyModifiedItem(t *testing.T) {
h := newHarness(t)
env := newSyncEnv(t, h)
buildWorkRepo(t, h, env.workRepo)
env.writeConfig(t, env.workRepo, "")
syncOnce(t, env)
skillPath := filepath.Join(env.home, ".agents/skills/own-skill/SKILL.md")
os.WriteFile(skillPath, []byte("---\nname: Own Skill\n---\n# MY local edits\n"), 0o644)
p := filepath.Join(env.workRepo, "skills/own-skill/SKILL.md")
os.WriteFile(p, []byte("---\nname: Own Skill\ndescription: changed upstream\n---\n# Upstream v2\n"), 0o644)
commitWorkRepo(t, h, env.workRepo, "change own-skill upstream")
out, err := env.run(t)
if err != nil {
t.Fatalf("sync with local mods must not fail: %v\n%s", err, out)
}
if !contains(out, "skipped (local modifications kept): 1") {
t.Errorf("modified item must be skipped with a warning:\n%s", out)
}
kept := readFile(t, skillPath)
if !contains(kept, "MY local edits") {
t.Error("local version must be kept, not overwritten")
}
log := readFile(t, filepath.Join(env.stateDir, "sync.log"))
if !contains(log, "SKIP skills/own-skill") || !contains(log, "locally modified") {
t.Errorf("warning log must record item and reason:\n%s", log)
}
manifest := readFile(t, filepath.Join(env.stateDir, "manifest.json"))
if !contains(manifest, "own-skill") {
t.Error("skipped item must keep its manifest record for future syncs")
}
}
func TestSyncLeavesSelfCreatedItemsUntouched(t *testing.T) {
h := newHarness(t)
env := newSyncEnv(t, h)
buildWorkRepo(t, h, env.workRepo)
env.writeConfig(t, env.workRepo, "")
syncOnce(t, env)
mineDir := filepath.Join(env.home, ".agents/skills/my-secret-skill")
os.MkdirAll(mineDir, 0o755)
os.WriteFile(filepath.Join(mineDir, "SKILL.md"), []byte("---\nname: Mine\n---\n# private\n"), 0o644)
out, err := env.run(t)
if err != nil {
t.Fatalf("sync must not fail on unmanaged items: %v\n%s", err, out)
}
if !contains(out, "unmanaged items left untouched: 1") {
t.Errorf("self-created item must be reported as left:\n%s", out)
}
if _, err := os.Stat(filepath.Join(mineDir, "SKILL.md")); err != nil {
t.Error("self-created item must survive untouched")
}
log := readFile(t, filepath.Join(env.stateDir, "sync.log"))
if !contains(log, "LEAVE skills/my-secret-skill") || !contains(log, "unmanaged local item") {
t.Errorf("leave warning must be logged with reason:\n%s", log)
}
manifest := readFile(t, filepath.Join(env.stateDir, "manifest.json"))
if contains(manifest, "my-secret-skill") {
t.Error("unmanaged items must never enter the manifest")
}
}
func TestSyncRemovesUpstreamDeletedItems(t *testing.T) {
h := newHarness(t)
env := newSyncEnv(t, h)
buildWorkRepo(t, h, env.workRepo)
env.writeConfig(t, env.workRepo, "")
syncOnce(t, env)
os.RemoveAll(filepath.Join(env.workRepo, "skills/own-skill"))
os.Remove(filepath.Join(env.workRepo, "agents/helper.md"))
os.Remove(filepath.Join(env.workRepo, "commands/deploy.md"))
commitWorkRepo(t, h, env.workRepo, "remove everything deployable")
modifiedAgent := filepath.Join(env.home, ".config/opencode/agents/helper.md")
os.WriteFile(modifiedAgent, []byte("---\nname: Helper\n---\n# my tweaks\n"), 0o644)
out, err := env.run(t)
if err != nil {
t.Fatalf("sync with removals failed: %v\n%s", err, out)
}
if !contains(out, "removed: 2") {
t.Errorf("unmodified deleted items must be removed:\n%s", out)
}
if _, err := os.Stat(filepath.Join(env.home, ".agents/skills/own-skill")); err == nil {
t.Error("unmodified skill must be removed after upstream deletion")
}
if _, err := os.Stat(modifiedAgent); err != nil {
t.Error("locally modified agent must survive the upstream deletion")
}
if !contains(out, "skipped (local modifications kept): 1") {
t.Errorf("modified+deleted item must be skipped with warning:\n%s", out)
}
log := readFile(t, filepath.Join(env.stateDir, "sync.log"))
if !contains(log, "upstream deleted but the local copy was modified") {
t.Errorf("log must explain the kept deletion:\n%s", log)
}
manifest := readFile(t, filepath.Join(env.stateDir, "manifest.json"))
if contains(manifest, "own-skill") || contains(manifest, "deploy") {
t.Errorf("removed items must leave the manifest:\n%s", manifest)
}
if !contains(manifest, "helper") {
t.Error("kept modified item must keep its manifest record")
}
}
func TestSyncRestoresDeletedManagedItem(t *testing.T) {
h := newHarness(t)
env := newSyncEnv(t, h)
buildWorkRepo(t, h, env.workRepo)
env.writeConfig(t, env.workRepo, "")
syncOnce(t, env)
os.RemoveAll(filepath.Join(env.home, ".agents/skills/own-skill"))
out, err := env.run(t)
if err != nil {
t.Fatalf("restore sync failed: %v\n%s", err, out)
}
if !contains(out, "updated: 1") {
t.Errorf("locally deleted managed item must be restored:\n%s", out)
}
if _, err := os.Stat(filepath.Join(env.home, ".agents/skills/own-skill/SKILL.md")); err != nil {
t.Error("item must be back on disk")
}
}
func TestSyncNewUpstreamItemBlockedByUnmanagedOccupant(t *testing.T) {
h := newHarness(t)
env := newSyncEnv(t, h)
buildWorkRepo(t, h, env.workRepo)
mineDir := filepath.Join(env.home, ".agents/skills/own-skill")
os.MkdirAll(mineDir, 0o755)
os.WriteFile(filepath.Join(mineDir, "SKILL.md"), []byte("---\nname: My Own\n---\n# private version\n"), 0o644)
env.writeConfig(t, env.workRepo, "")
out, err := env.run(t)
if err != nil {
t.Fatalf("sync must not fail on occupant conflict: %v\n%s", err, out)
}
if !contains(out, "skipped (local modifications kept): 1") {
t.Errorf("new item blocked by unmanaged occupant must be skipped:\n%s", out)
}
kept := readFile(t, filepath.Join(mineDir, "SKILL.md"))
if !contains(kept, "private version") {
t.Error("occupant content must be preserved")
}
}
-212
View File
@@ -1,212 +0,0 @@
// Package gitsource clones external git sources in-process via go-git and
// exposes their commit trees for discovery — no git subprocess at runtime.
package gitsource
import (
"fmt"
"io"
"os"
"sort"
"strings"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/filemode"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/go-git/go-git/v5/storage/memory"
"github.com/m3tam3re/agent-lib/internal/discovery"
)
// Env names for optional basic auth on HTTPS sources (deploy/personal token).
const (
TokenEnv = "AGENT_LIB_GIT_TOKEN"
UserEnv = "AGENT_LIB_GIT_USER"
)
// Repo is a cloned source pinned to one resolved revision.
type Repo struct {
Repository *git.Repository
Rev string
Ref string
}
// Clone fetches url — at ref (branch or tag), otherwise the default branch —
// fully in-process and pins the resolved revision.
func Clone(url, ref string) (*Repo, error) {
repo, err := git.Clone(memory.NewStorage(), memfs.New(), cloneOptions(url, ref))
if err != nil && ref != "" {
repo, err = git.Clone(memory.NewStorage(), memfs.New(), tagOptions(url, ref))
}
if err != nil {
return nil, fmt.Errorf("cloning %s: %w", url, err)
}
return resolveHead(repo, ref)
}
func cloneOptions(url, ref string) *git.CloneOptions {
opts := &git.CloneOptions{URL: url}
if ref != "" {
opts.ReferenceName = plumbing.NewBranchReferenceName(ref)
}
applyAuth(url, opts)
return opts
}
func tagOptions(url, ref string) *git.CloneOptions {
opts := &git.CloneOptions{URL: url, ReferenceName: plumbing.NewTagReferenceName(ref)}
applyAuth(url, opts)
return opts
}
func applyAuth(url string, opts *git.CloneOptions) {
if !strings.HasPrefix(url, "https://") {
return
}
token := os.Getenv(TokenEnv)
if token == "" {
return
}
user := os.Getenv(UserEnv)
if user == "" {
user = "agent-lib"
}
opts.Auth = &http.BasicAuth{Username: user, Password: token}
}
func resolveHead(repo *git.Repository, requestedRef string) (*Repo, error) {
head, err := repo.Head()
if err != nil {
return nil, fmt.Errorf("resolving HEAD: %w", err)
}
r := &Repo{Repository: repo, Rev: head.Hash().String()}
switch {
case head.Name().IsBranch() || head.Name().IsTag():
r.Ref = head.Name().Short()
case requestedRef != "":
r.Ref = requestedRef
default:
r.Ref = head.Name().String()
}
return r, nil
}
// Pin returns a copy of the repo resolved to an explicit revision, so a
// selection can be re-materialized at the pinned rev without advancing it.
func (r *Repo) Pin(rev string) (*Repo, error) {
if _, err := r.Repository.CommitObject(plumbing.NewHash(rev)); err != nil {
return nil, fmt.Errorf("pinned revision %s not found in %s: %w", rev, r.URL(), err)
}
pinned := *r
pinned.Rev = rev
return &pinned, nil
}
func (r *Repo) URL() string {
if r.Repository == nil {
return ""
}
remote, err := r.Repository.Remote(git.DefaultRemoteName)
if err != nil || len(remote.Config().URLs) == 0 {
return ""
}
return remote.Config().URLs[0]
}
// Tree returns the commit tree of the pinned revision as a discovery.Tree.
func (r *Repo) Tree() (discovery.Tree, error) {
commit, err := r.Repository.CommitObject(plumbing.NewHash(r.Rev))
if err != nil {
return nil, fmt.Errorf("resolving commit %s: %w", r.Rev, err)
}
tree, err := commit.Tree()
if err != nil {
return nil, fmt.Errorf("reading tree of %s: %w", r.Rev, err)
}
return &GitTree{tree: tree}, nil
}
// GitTree adapts a git commit tree to the discovery.Tree interface.
type GitTree struct {
tree *object.Tree
}
// NewGitTree wraps a commit tree for discovery and materialization.
func NewGitTree(t *object.Tree) *GitTree {
return &GitTree{tree: t}
}
func (g *GitTree) Walk(fn func(rel string, isDir bool) error) error {
walker := object.NewTreeWalker(g.tree, true, nil)
defer walker.Close()
for {
name, entry, err := walker.Next()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
if name == "." {
continue
}
if err := fn(name, entry.Mode == filemode.Dir); err != nil {
return err
}
}
}
func (g *GitTree) ReadFile(rel string) ([]byte, error) {
f, err := g.tree.File(rel)
if err != nil {
return nil, err
}
r, err := f.Blob.Reader()
if err != nil {
return nil, err
}
defer r.Close()
return io.ReadAll(r)
}
// FilesUnder lists every file (recursively) below prefix, sorted. A prefix of
// "" lists the whole tree.
func (g *GitTree) FilesUnder(prefix string) ([]string, error) {
var out []string
walker := object.NewTreeWalker(g.tree, true, nil)
defer walker.Close()
for {
name, entry, err := walker.Next()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
if name == "." || entry.Mode == filemode.Dir {
continue
}
if prefix == "" || strings.HasPrefix(name, strings.TrimSuffix(prefix, "/")+"/") {
out = append(out, name)
}
}
sort.Strings(out)
return out, nil
}
// MaterializeFile writes the blob at rel to dst, preserving the executable
// bit from the tree entry.
func (g *GitTree) MaterializeFile(rel, dst string) error {
data, err := g.ReadFile(rel)
if err != nil {
return fmt.Errorf("reading %s: %w", rel, err)
}
mode := os.FileMode(0o644)
entry, err := g.tree.FindEntry(rel)
if err == nil && entry.Mode == filemode.Executable {
mode = 0o755
}
return os.WriteFile(dst, data, mode)
}
-16
View File
@@ -1,16 +0,0 @@
package gitsource
import "strings"
// RedactURL strips user:password credentials embedded in a URL so tokens
// never surface in error messages or logs.
func RedactURL(u string) string {
scheme, rest, found := strings.Cut(u, "://")
if !found {
return u
}
if at := strings.Index(rest, "@"); at >= 0 && !strings.Contains(rest[:at], "/") {
return scheme + "://" + rest[at+1:]
}
return u
}
-41
View File
@@ -1,41 +0,0 @@
package gitsource
import (
"fmt"
"regexp"
"strings"
)
var (
githubTreeRe = regexp.MustCompile(`^https://([^/]*github[^/]*)/([^/]+)/([^/]+)/tree/([^/]+)(/.*)?$`)
gitlabTreeRe = regexp.MustCompile(`^https://([^/]*gitlab[^/]*)/([^/]+)/([^/]+)/-/tree/([^/]+)(/.*)?$`)
)
// NormalizeURL converts pasted GitHub/GitLab web-tree URLs into plain git
// clone URLs and returns the implied discovery root ("" for the repo root).
// URLs that are already cloneable pass through unchanged.
func NormalizeURL(raw string) (url, root string, err error) {
s := strings.TrimSpace(raw)
if s == "" {
return "", "", fmt.Errorf("empty source URL")
}
if m := githubTreeRe.FindStringSubmatch(s); m != nil {
return fmt.Sprintf("https://%s/%s/%s.git", m[1], m[2], m[3]), strings.TrimPrefix(m[5], "/"), nil
}
if m := gitlabTreeRe.FindStringSubmatch(s); m != nil {
return fmt.Sprintf("https://%s/%s/%s.git", m[1], m[2], m[3]), strings.TrimPrefix(m[5], "/"), nil
}
if strings.HasSuffix(s, ".git") {
return s, "", nil
}
if m := regexp.MustCompile(`^https://([^/]*github[^/]*)/([^/]+)/([^/]+)$`).FindStringSubmatch(s); m != nil {
return fmt.Sprintf("https://%s/%s/%s.git", m[1], m[2], m[3]), "", nil
}
if m := regexp.MustCompile(`^https://([^/]*gitlab[^/]*)/([^/]+)/([^/]+)$`).FindStringSubmatch(s); m != nil {
return fmt.Sprintf("https://%s/%s/%s.git", m[1], m[2], m[3]), "", nil
}
if strings.HasPrefix(s, "file://") {
return strings.TrimPrefix(s, "file://"), "", nil
}
return s, "", nil
}
-35
View File
@@ -1,35 +0,0 @@
package gitsource
import "testing"
func TestNormalizeURL(t *testing.T) {
cases := []struct {
name, in, wantURL, wantRoot string
}{
{"github repo", "https://github.com/org/repo", "https://github.com/org/repo.git", ""},
{"github tree with subpath", "https://github.com/org/repo/tree/main/skills", "https://github.com/org/repo.git", "skills"},
{"github tree nested subpath", "https://github.com/org/repo/tree/main/content/skills", "https://github.com/org/repo.git", "content/skills"},
{"github tree no subpath", "https://github.com/org/repo/tree/main", "https://github.com/org/repo.git", ""},
{"gitlab tree with subpath", "https://gitlab.com/org/repo/-/tree/main/agents", "https://gitlab.com/org/repo.git", "agents"},
{"gitlab plain repo", "https://gitlab.com/org/repo", "https://gitlab.com/org/repo.git", ""},
{"already normalized github", "https://github.com/org/repo.git", "https://github.com/org/repo.git", ""},
{"ssh url untouched", "git@github.com:org/repo.git", "git@github.com:org/repo.git", ""},
{"https url untouched", "https://example.com/repo.git", "https://example.com/repo.git", ""},
{"local path untouched", "/tmp/fixture-upstream", "/tmp/fixture-upstream", ""},
{"file url stripped", "file:///tmp/fixture-upstream", "/tmp/fixture-upstream", ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
url, root, err := NormalizeURL(tc.in)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if url != tc.wantURL {
t.Errorf("url = %q, want %q", url, tc.wantURL)
}
if root != tc.wantRoot {
t.Errorf("root = %q, want %q", root, tc.wantRoot)
}
})
}
}
-168
View File
@@ -1,168 +0,0 @@
// Package lockfile defines agent-lib lockfile schema v2: the deterministic
// JSON document pinning vendored sources, their selection and renames.
package lockfile
import (
"encoding/json"
"errors"
"fmt"
"os"
"sort"
)
const (
// Version is the schema version of lockfile v2.
Version = 2
// FileName is the lockfile name inside the work repository root.
FileName = "agent-lib.lock.json"
)
// ErrNotExist reports that no lockfile exists yet.
var ErrNotExist = errors.New("no lockfile found")
// Content type names used across discovery, lockfile and the external area.
const (
TypeSkill = "skills"
TypeCommand = "commands"
TypeAgent = "agents"
TypeMcp = "mcp"
)
// Types lists all content types in canonical order.
var Types = []string{TypeSkill, TypeCommand, TypeAgent, TypeMcp}
// Discovery configures where items are found inside a source repository.
// Empty values select the standard layouts (skills/, commands/, agents/, mcp/
// relative to Root).
type Discovery struct {
Root string `json:"root,omitempty"`
SkillsDir string `json:"skills_dir,omitempty"`
CommandsDir string `json:"commands_dir,omitempty"`
AgentsDir string `json:"agents_dir,omitempty"`
McpDir string `json:"mcp_dir,omitempty"`
}
func (d Discovery) Resolve() Discovery {
r := d
if r.SkillsDir == "" {
r.SkillsDir = TypeSkill
}
if r.CommandsDir == "" {
r.CommandsDir = TypeCommand
}
if r.AgentsDir == "" {
r.AgentsDir = TypeAgent
}
if r.McpDir == "" {
r.McpDir = TypeMcp
}
return r
}
// SelectionMode is either "all" or "include".
type SelectionMode string
const (
ModeAll SelectionMode = "all"
ModeInclude SelectionMode = "include"
)
// Selection expresses what enters the work repository: everything minus
// 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 {
Mode SelectionMode `json:"mode"`
Exclude []string `json:"exclude,omitempty"`
Include []string `json:"include,omitempty"`
ExcludeTypes []string `json:"exclude_types,omitempty"`
}
// Source pins one vendored git source.
type Source struct {
URL string `json:"url"`
Ref string `json:"ref"`
Rev string `json:"rev"`
Discovery *Discovery `json:"discovery,omitempty"`
Selection Selection `json:"selection"`
Renames map[string]string `json:"renames,omitempty"`
Inventory map[string][]string `json:"inventory,omitempty"`
Warnings []string `json:"warnings,omitempty"`
}
// Lockfile is the root document of schema v2.
type Lockfile struct {
Version int `json:"version"`
Sources map[string]*Source `json:"sources"`
}
// New returns an empty lockfile v2.
func New() *Lockfile {
return &Lockfile{Version: Version, Sources: map[string]*Source{}}
}
// ParseBytes unmarshals and validates lockfile JSON content.
func ParseBytes(data []byte) (*Lockfile, error) {
var l Lockfile
if err := json.Unmarshal(data, &l); err != nil {
return nil, fmt.Errorf("lockfile is not valid JSON: %w", err)
}
if l.Version != Version {
return nil, fmt.Errorf("lockfile has schema version %d, want %d", l.Version, Version)
}
if l.Sources == nil {
l.Sources = map[string]*Source{}
}
return &l, nil
}
// Load reads the lockfile at path. A missing file yields ErrNotExist.
func Load(path string) (*Lockfile, error) {
data, err := os.ReadFile(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, ErrNotExist
}
return nil, err
}
var l Lockfile
if err := json.Unmarshal(data, &l); err != nil {
return nil, fmt.Errorf("lockfile %s is not valid JSON: %w", path, err)
}
if l.Version != Version {
return nil, fmt.Errorf("lockfile %s has schema version %d, want %d", path, l.Version, Version)
}
if l.Sources == nil {
l.Sources = map[string]*Source{}
}
return &l, nil
}
// Save canonically orders all slices and maps, then writes deterministic JSON.
func (l *Lockfile) Save(path string) error {
for _, src := range l.Sources {
sort.Strings(src.Selection.Exclude)
sort.Strings(src.Selection.Include)
sort.Strings(src.Selection.ExcludeTypes)
sort.Strings(src.Warnings)
for _, items := range src.Inventory {
sort.Strings(items)
}
}
data, err := Marshal(l)
if err != nil {
return err
}
return os.WriteFile(path, data, 0o644)
}
// Marshal renders the lockfile as deterministic bytes: fixed field order via
// struct layout, sorted map keys, two-space indent, trailing newline.
func Marshal(l *Lockfile) ([]byte, error) {
data, err := json.MarshalIndent(l, "", " ")
if err != nil {
return nil, err
}
return append(data, '\n'), nil
}
-129
View File
@@ -1,129 +0,0 @@
package lockfile
import (
"os"
"path/filepath"
"testing"
)
func readFile(t *testing.T, path string) string {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
return string(data)
}
func TestMarshalDeterministic(t *testing.T) {
l1 := New()
l1.Sources["beta"] = &Source{
URL: "https://example.com/beta.git", Ref: "main", Rev: "cafe123",
Selection: Selection{Mode: ModeAll},
Renames: map[string]string{"zeta": "beta-zeta"},
Inventory: map[string][]string{TypeSkill: {"a", "zeta"}},
Warnings: []string{"a-warning", "b-warning"},
}
l1.Sources["alpha"] = &Source{
URL: "https://example.com/alpha.git", Ref: "v1.0", Rev: "abcd00",
Selection: Selection{Mode: ModeInclude, Include: []string{"a", "x"}},
}
l2 := New()
l2.Sources["alpha"] = l1.Sources["alpha"]
l2.Sources["beta"] = l1.Sources["beta"]
b1, err := Marshal(l1)
if err != nil {
t.Fatal(err)
}
b2, err := Marshal(l2)
if err != nil {
t.Fatal(err)
}
if string(b1) != string(b2) {
t.Fatalf("marshal not deterministic:\n%s\n--- vs ---\n%s", b1, b2)
}
if b1[len(b1)-1] != '\n' {
t.Error("missing trailing newline")
}
l1.Save(filepath.Join(t.TempDir(), FileName))
b3, err := Marshal(l1)
if err != nil {
t.Fatal(err)
}
if string(b1) != string(b3) {
t.Fatalf("save mutated already-canonical bytes:\n%s\n--- vs ---\n%s", b1, b3)
}
}
func TestSaveCanonicalizesUnsortedInput(t *testing.T) {
l := New()
l.Sources["s"] = &Source{
URL: "u", Ref: "r", Rev: "rev",
Selection: Selection{Mode: ModeInclude, Include: []string{"z", "a"}},
Warnings: []string{"w2", "w1"},
Inventory: map[string][]string{TypeSkill: {"z", "a"}},
}
path := filepath.Join(t.TempDir(), FileName)
if err := l.Save(path); err != nil {
t.Fatal(err)
}
got, err := Load(path)
if err != nil {
t.Fatal(err)
}
src := got.Sources["s"]
wantInclude := []string{"a", "z"}
if !slicesEqual(src.Selection.Include, wantInclude) {
t.Errorf("include = %v, want %v", src.Selection.Include, wantInclude)
}
wantWarnings := []string{"w1", "w2"}
if !slicesEqual(src.Warnings, wantWarnings) {
t.Errorf("warnings = %v, want %v", src.Warnings, wantWarnings)
}
wantInv := []string{"a", "z"}
if !slicesEqual(src.Inventory[TypeSkill], wantInv) {
t.Errorf("inventory = %v, want %v", src.Inventory[TypeSkill], wantInv)
}
}
func slicesEqual(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
func TestLoadRoundTrip(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, FileName)
l := New()
l.Sources["s"] = &Source{URL: "u", Ref: "r", Rev: "rev1", Selection: Selection{Mode: ModeAll}}
if err := l.Save(path); err != nil {
t.Fatal(err)
}
got, err := Load(path)
if err != nil {
t.Fatal(err)
}
if got.Version != Version || got.Sources["s"].Rev != "rev1" {
t.Fatalf("round trip lost data: %+v", got)
}
if _, err := Load(filepath.Join(dir, "missing.json")); err != ErrNotExist {
t.Fatalf("want ErrNotExist, got %v", err)
}
os.WriteFile(path, []byte(`{"version": 1, "sources": {}}`), 0o644)
if _, err := Load(path); err == nil {
t.Fatal("version 1 lockfile must be rejected")
}
}
-11
View File
@@ -1,11 +0,0 @@
//go:build !windows
package notify
// Noop drops every notification; Linux and macOS stay silent by design.
type Noop struct{}
func (Noop) Send(title, body string) error { return nil }
// Platform returns the no-op sender on Linux and macOS.
func Platform() Sender { return Noop{} }
-9
View File
@@ -1,9 +0,0 @@
// Package notify fires user-facing notifications. The platform sender is a
// Windows toast (PowerShell-backed, mirroring go-toast's script); Linux and
// macOS are deliberate no-ops.
package notify
// Sender delivers one notification.
type Sender interface {
Send(title, body string) error
}
-55
View File
@@ -1,55 +0,0 @@
//go:build windows
package notify
import (
"fmt"
"os/exec"
"strings"
"syscall"
)
// createNoWindow is the Win32 CREATE_NO_WINDOW process creation flag.
const createNoWindow = 0x08000000
// PowerShellToast raises a Windows toast notification by invoking
// PowerShell with an AppId-tagged script — the same mechanism go-toast
// uses, without the dependency.
type PowerShellToast struct {
AppID string
}
// Platform returns the PowerShell toast sender on Windows.
func Platform() Sender { return PowerShellToast{AppID: "agent-lib"} }
var toastScript = `$app = '%[1]s'
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
$tmpl = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)
$txt = $tmpl.GetElementsByTagName('text')
$txt.Item(0).AppendChild($tmpl.CreateTextNode('%[2]s')) | Out-Null
$txt.Item(1).AppendChild($tmpl.CreateTextNode('%[3]s')) | Out-Null
$toast = [Windows.UI.Notifications.ToastNotification]::new($tmpl)
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($app).Show($toast)`
// Send fires one toast. It requires an interactive user session; callers
// must treat errors as non-fatal.
func (p PowerShellToast) Send(title, body string) error {
appID := p.AppID
if appID == "" {
appID = "agent-lib"
}
script := fmt.Sprintf(toastScript, escape(appID), escape(title), escape(body))
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 {
return fmt.Errorf("toast failed: %v: %s", err, strings.TrimSpace(string(out)))
}
return nil
}
// escape makes s safe inside a PowerShell single-quoted string.
func escape(s string) string {
r := strings.NewReplacer("'", "''", "\n", " ", "\r", " ")
return r.Replace(s)
}
-71
View File
@@ -1,71 +0,0 @@
// Package target maps content types to runtime-specific deployment paths.
// The OpenCode target is the thin v2 implementation: a type filter plus
// path mapping, leaving the door open for future targets.
package target
import (
"os"
"path/filepath"
"strings"
"github.com/m3tam3re/agent-lib/internal/lockfile"
)
// OpenCode maps items into the OpenCode runtime layout, rooted at the
// user's home directory.
type OpenCode struct {
Home string
}
// NewOpenCode resolves the home directory once for all path mappings.
func NewOpenCode() (*OpenCode, error) {
home, err := os.UserHomeDir()
if err != nil {
return nil, err
}
return &OpenCode{Home: home}, nil
}
// DeployPath returns the absolute destination for an item; ok is false for
// types this target never deploys (MCP stays under fleet control).
func (o *OpenCode) DeployPath(typ, name string) (path string, ok bool) {
switch typ {
case lockfile.TypeSkill:
return filepath.Join(o.Home, ".agents", "skills", name), true
case lockfile.TypeCommand:
return filepath.Join(o.Home, ".config", "opencode", "commands", name+".md"), true
case lockfile.TypeAgent:
return filepath.Join(o.Home, ".config", "opencode", "agents", name+".md"), true
default:
return "", false
}
}
// ScanTargetDirs lists every item currently present in the target dirs,
// keyed "<type>/<name>" — the raw material for detecting unmanaged occupants.
func (o *OpenCode) ScanTargetDirs() map[string]bool {
out := map[string]bool{}
skillsDir := filepath.Join(o.Home, ".agents", "skills")
if entries, err := os.ReadDir(skillsDir); err == nil {
for _, e := range entries {
if e.IsDir() {
out[lockfile.TypeSkill+"/"+e.Name()] = true
}
}
}
for typ, dir := range map[string]string{
lockfile.TypeCommand: filepath.Join(o.Home, ".config", "opencode", "commands"),
lockfile.TypeAgent: filepath.Join(o.Home, ".config", "opencode", "agents"),
} {
entries, err := os.ReadDir(dir)
if err != nil {
continue
}
for _, e := range entries {
if !e.IsDir() && strings.HasSuffix(e.Name(), ".md") {
out[typ+"/"+strings.TrimSuffix(e.Name(), ".md")] = true
}
}
}
return out
}
-392
View File
@@ -1,392 +0,0 @@
// Package vendor implements the curator-side commands: add, update, diff,
// remove, list and inspect over the external area and lockfile v2.
package vendor
import (
"fmt"
"io"
"os"
"path"
"path/filepath"
"sort"
"strings"
"github.com/m3tam3re/agent-lib/internal/deploy"
"github.com/m3tam3re/agent-lib/internal/discovery"
"github.com/m3tam3re/agent-lib/internal/gitsource"
"github.com/m3tam3re/agent-lib/internal/lockfile"
)
const externalDir = "external"
// AddOptions parameterize vendor add.
type AddOptions struct {
Name string
URL string
Ref string
Include []string
Exclude []string
OnlyTypes []string
ExcludeTypes []string
Renames map[string]string
}
// Add vendors a new source into the work repository at workDir: it clones,
// discovers, applies the selection and materializes external/<name>/ plus the
// lockfile entry. Nothing is written before every check has passed.
func Add(workDir string, opts AddOptions, stdout io.Writer) error {
lockPath := filepath.Join(workDir, lockfile.FileName)
lf, err := lockfile.Load(lockPath)
if err != nil {
if err != lockfile.ErrNotExist {
return err
}
lf = lockfile.New()
}
if _, exists := lf.Sources[opts.Name]; exists {
return fmt.Errorf("source %q already exists in %s", opts.Name, lockfile.FileName)
}
extRoot := filepath.Join(workDir, externalDir, opts.Name)
if _, err := os.Stat(extRoot); err == nil {
return fmt.Errorf("%s exists but %q is not in the lockfile; remove the directory or pick another name", extRoot, opts.Name)
}
normalized, root, err := gitsource.NormalizeURL(opts.URL)
if err != nil {
return err
}
cfg := discoveryFromTreeRoot(root)
repo, err := gitsource.Clone(normalized, opts.Ref)
if err != nil {
return err
}
tree, err := repo.Tree()
if err != nil {
return err
}
items, err := discovery.Scan(tree, discovery.FromLockfileDiscovery(cfg))
if err != nil {
return err
}
if len(opts.Include) > 0 && len(opts.Exclude) > 0 {
return fmt.Errorf("--include and --exclude cannot be combined (a v2 selection is either include mode or all mode minus excludes)")
}
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
}
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)
if len(selected) == 0 {
return fmt.Errorf("source %q selected zero items; refusing to add an empty source", opts.Name)
}
if err := checkCollisions(workDir, lf, opts.Name, selected, opts.Renames); err != nil {
return err
}
src := &lockfile.Source{
URL: normalized,
Ref: repo.Ref,
Rev: repo.Rev,
Selection: sel,
Renames: map[string]string{},
}
if len(opts.Renames) > 0 {
src.Renames = opts.Renames
}
if cfg != (lockfile.Discovery{}) {
src.Discovery = &cfg
}
for _, it := range items {
src.Warnings = append(src.Warnings, it.Warnings...)
}
src.Warnings = dedupe(src.Warnings)
inventory, err := materialize(workDir, opts.Name, tree, selected, src.Renames)
if err != nil {
return err
}
src.Inventory = inventory
lf.Sources[opts.Name] = src
if err := lf.Save(lockPath); err != nil {
return err
}
reportAdd(stdout, opts.Name, src, items, selected)
return nil
}
// discoveryFromTreeRoot maps a pasted tree sub-path onto discovery config.
// A sub-path ending in a standard type directory (e.g. ".../tree/main/skills")
// selects that directory as the type root; anything else becomes the
// discovery root under which the standard layout is expected.
func discoveryFromTreeRoot(root string) lockfile.Discovery {
if root == "" {
return lockfile.Discovery{}
}
parent, base := path.Split(strings.TrimSuffix(root, "/"))
parent = strings.TrimSuffix(parent, "/")
d := lockfile.Discovery{Root: parent}
switch base {
case lockfile.TypeSkill:
d.SkillsDir = base
case lockfile.TypeCommand:
d.CommandsDir = base
case lockfile.TypeAgent:
d.AgentsDir = base
case lockfile.TypeMcp:
d.McpDir = base
default:
return lockfile.Discovery{Root: root}
}
if d == (lockfile.Discovery{}) {
return lockfile.Discovery{}
}
return d
}
// 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{}
for _, it := range items {
if !it.Skipped {
available[it.UpstreamID] = true
}
}
for _, want := range ids {
if !available[want] {
return fmt.Errorf("source %q: %s entry %q not found upstream (available: %s)", name, flag, want, strings.Join(sortedKeys(available), ", "))
}
}
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 {
exclude := map[string]bool{}
for _, e := range sel.Exclude {
exclude[e] = true
}
include := map[string]bool{}
for _, i := range sel.Include {
include[i] = true
}
excludedTypes := map[string]bool{}
for _, t := range sel.ExcludeTypes {
excludedTypes[t] = true
}
var out []discovery.Item
for _, it := range items {
if it.Skipped {
continue
}
if excludedTypes[it.Type] {
continue
}
switch sel.Mode {
case lockfile.ModeInclude:
if include[it.UpstreamID] {
out = append(out, it)
}
default:
if !exclude[it.UpstreamID] {
out = append(out, it)
}
}
}
return out
}
func deployedName(upstreamID string, renames map[string]string) string {
if d, ok := renames[upstreamID]; ok && d != "" {
return d
}
return upstreamID
}
func materialize(workDir, name string, tree discovery.Tree, selected []discovery.Item, renames map[string]string) (map[string][]string, error) {
inventory := map[string][]string{}
for _, it := range selected {
dep := deployedName(it.UpstreamID, renames)
base := filepath.Join(workDir, externalDir, name, it.Type)
var dst string
var err error
switch it.Type {
case lockfile.TypeSkill:
dst = filepath.Join(base, dep)
err = deploy.Dir(tree, it.RelPath, dst)
if err == nil && dep != it.UpstreamID {
err = rewriteSkillName(dst, dep)
}
default:
dst = filepath.Join(base, dep+filepath.Ext(it.RelPath))
err = deploy.File(tree, it.RelPath, dst)
}
if err != nil {
return nil, fmt.Errorf("materializing %s/%s: %w", it.Type, it.UpstreamID, err)
}
inventory[it.Type] = append(inventory[it.Type], it.UpstreamID)
}
return inventory, nil
}
func reportAdd(w io.Writer, name string, src *lockfile.Source, discovered, selected []discovery.Item) {
real := 0
for _, it := range discovered {
if !it.Skipped {
real++
}
}
counts := func(items []discovery.Item) string {
per := map[string]int{}
for _, it := range items {
if !it.Skipped {
per[it.Type]++
}
}
var parts []string
for _, t := range lockfile.Types {
if per[t] > 0 {
parts = append(parts, fmt.Sprintf("%d %s", per[t], t))
}
}
if len(parts) == 0 {
return "0 items"
}
return strings.Join(parts, ", ")
}
fmt.Fprintf(w, "source %s pinned\n", name)
fmt.Fprintf(w, " url: %s\n", src.URL)
fmt.Fprintf(w, " ref: %s\n", src.Ref)
fmt.Fprintf(w, " rev: %s\n", src.Rev)
fmt.Fprintf(w, "discovered %d items (%s)\n", real, counts(discovered))
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))
if len(src.Warnings) > 0 {
fmt.Fprintf(w, "warnings:\n")
for _, warn := range src.Warnings {
fmt.Fprintf(w, " - %s\n", warn)
}
}
fmt.Fprintf(w, "lockfile %s written\n", lockfile.FileName)
}
func dedupe(in []string) []string {
seen := map[string]bool{}
var out []string
for _, s := range in {
if !seen[s] {
seen[s] = true
out = append(out, s)
}
}
sort.Strings(out)
return out
}
func sortedKeys(m map[string]bool) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
sort.Strings(out)
return out
}
-173
View File
@@ -1,173 +0,0 @@
package vendor
import (
"fmt"
"sort"
"strings"
"github.com/m3tam3re/agent-lib/internal/discovery"
"github.com/m3tam3re/agent-lib/internal/lockfile"
)
// CollisionError names both parties of a deployed-name clash.
type CollisionError struct {
Type string `json:"type"`
DeployedID string `json:"deployed_id"`
Source string `json:"source"`
OtherOwner string `json:"other_owner"`
OtherID string `json:"other_id"`
}
func (e *CollisionError) Error() string {
return fmt.Sprintf("source %q: %s %q collides with %s %s %q",
e.Source, e.Type, e.DeployedID, e.OtherOwner, e.Type, e.OtherID)
}
// deployedIndex maps type -> deployed name -> owner description, built from
// the work repository's own items and every lockfile source except skip.
type deployedIndex map[string]map[string]owner
type owner struct {
source string
id string
}
func ownDeployed(workDir string) (deployedIndex, error) {
items, err := discovery.Scan(&discovery.FsTree{Root: workDir}, discovery.Config{})
if err != nil {
return nil, err
}
idx := deployedIndex{}
for _, it := range items {
if it.Skipped {
continue
}
idx.add(it.Type, it.UpstreamID, owner{source: "own", id: it.UpstreamID})
}
return idx, nil
}
func lockfileDeployed(lf *lockfile.Lockfile, skip string) deployedIndex {
idx := deployedIndex{}
for name, src := range lf.Sources {
if name == skip {
continue
}
for typ, ids := range src.Inventory {
for _, id := range ids {
idx.add(typ, deployedName(id, src.Renames), owner{source: name, id: id})
}
}
}
return idx
}
func (d deployedIndex) add(typ, deployed string, o owner) {
if d[typ] == nil {
d[typ] = map[string]owner{}
}
d[typ][deployed] = o
}
func (d deployedIndex) find(typ, deployed string) (owner, bool) {
o, ok := d[typ][deployed]
return o, ok
}
func mergeIndex(a, b deployedIndex) deployedIndex {
out := deployedIndex{}
for typ, m := range a {
for dep, o := range m {
out.add(typ, dep, o)
}
}
for typ, m := range b {
for dep, o := range m {
out.add(typ, dep, o)
}
}
return out
}
// checkCollisions verifies that every selected item of source deploys into
// the flat namespace without clashing — against own items, against other
// sources, and within the source itself (renames included). It performs no
// filesystem mutation.
func checkCollisions(workDir string, lf *lockfile.Lockfile, source string, selected []discovery.Item, renames map[string]string) error {
own, err := ownDeployed(workDir)
if err != nil {
return fmt.Errorf("scanning own items: %w", err)
}
existing := mergeIndex(own, lockfileDeployed(lf, source))
seen := map[string]string{}
for _, it := range selected {
deployed := deployedName(it.UpstreamID, renames)
if deployed != 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 {
return &CollisionError{
Type: it.Type, DeployedID: deployed, Source: source,
OtherOwner: "source " + source, OtherID: prev,
}
}
seen[deployed] = it.UpstreamID
if o, clash := existing.find(it.Type, deployed); clash {
return &CollisionError{
Type: it.Type, DeployedID: deployed, Source: source,
OtherOwner: o.source, OtherID: o.id,
}
}
}
return nil
}
// validateCollisions re-checks the deployed namespace across own items and
// all lockfile sources — the offline equivalent used by validate.
func validateCollisions(workDir string, lf *lockfile.Lockfile) []ValidationError {
own, err := ownDeployed(workDir)
if err != nil {
return []ValidationError{{Rule: "collision", Message: fmt.Sprintf("scanning own items: %v", err)}}
}
idx := mergeIndex(own, deployedIndex{})
var errs []ValidationError
for _, name := range sortedSourceNames(lf) {
src := lf.Sources[name]
for typ, ids := range src.Inventory {
for _, id := range ids {
deployed := deployedName(id, src.Renames)
if prev, dup := idx.find(typ, deployed); dup {
errs = append(errs, ValidationError{
Source: name,
Rule: "collision",
Message: fmt.Sprintf("source %q: %s %q (upstream %q) collides with %s %q",
name, typ, deployed, id, prev.source, prev.id),
})
continue
}
idx.add(typ, deployed, owner{source: name, id: id})
}
}
}
sort.Slice(errs, func(i, j int) bool { return errs[i].Message < errs[j].Message })
return errs
}
// ParseRenames converts --rename upstream-id=deployed-name flag values.
func ParseRenames(pairs []string) (map[string]string, error) {
if len(pairs) == 0 {
return nil, nil
}
out := map[string]string{}
for _, p := range pairs {
upstream, deployed, ok := strings.Cut(p, "=")
if !ok || strings.TrimSpace(upstream) == "" || strings.TrimSpace(deployed) == "" {
return nil, fmt.Errorf("invalid --rename %q (want upstream-id=deployed-name)", p)
}
out[strings.TrimSpace(upstream)] = strings.TrimSpace(deployed)
}
return out, nil
}
-260
View File
@@ -1,260 +0,0 @@
package vendor
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"github.com/m3tam3re/agent-lib/internal/discovery"
"github.com/m3tam3re/agent-lib/internal/lockfile"
)
// ValidationError names one broken rule.
type ValidationError struct {
Source string `json:"source,omitempty"`
Rule string `json:"rule"`
Message string `json:"message"`
}
// Validation is the full offline verdict over a lockfile and its external area.
type Validation struct {
Valid bool `json:"valid"`
Errors []ValidationError `json:"errors"`
}
// Validate checks the hard selection rules and the lockfile/external-area
// consistency, entirely offline.
func Validate(workDir string, lf *lockfile.Lockfile) Validation {
v := Validation{Valid: true}
for _, name := range sortedSourceNames(lf) {
src := lf.Sources[name]
v.checkSelection(name, src)
v.checkExternalArea(workDir, name, src)
}
v.Errors = append(v.Errors, validateCollisions(workDir, lf)...)
sort.Slice(v.Errors, func(i, j int) bool {
if v.Errors[i].Source != v.Errors[j].Source {
return v.Errors[i].Source < v.Errors[j].Source
}
return v.Errors[i].Rule < v.Errors[j].Rule
})
v.Valid = len(v.Errors) == 0
return v
}
func (v *Validation) fail(source, rule, format string, args ...any) {
v.Errors = append(v.Errors, ValidationError{
Source: source,
Rule: rule,
Message: fmt.Sprintf(format, args...),
})
}
func (v *Validation) checkSelection(name string, src *lockfile.Source) {
switch src.Selection.Mode {
case lockfile.ModeAll:
if len(src.Selection.Include) > 0 {
v.fail(name, "selection", "source %q: include list is set but mode is all (remove the include list or switch to include mode)", name)
}
case lockfile.ModeInclude:
if len(src.Selection.Exclude) > 0 {
v.fail(name, "selection", "source %q: exclude list is only valid in all mode", name)
}
inventory := map[string]bool{}
for _, items := range src.Inventory {
for _, id := range items {
inventory[id] = true
}
}
for _, inc := range src.Selection.Include {
if !inventory[inc] {
v.fail(name, "selection", "source %q: include entry %q is not in the pinned inventory", name, inc)
}
}
default:
v.fail(name, "selection", "source %q: unknown selection mode %q (want %q or %q)", name, src.Selection.Mode, lockfile.ModeAll, lockfile.ModeInclude)
}
}
func (v *Validation) checkExternalArea(workDir, name string, src *lockfile.Source) {
base := filepath.Join(workDir, externalDir, name)
if _, err := os.Stat(base); err != nil {
v.fail(name, "tree", "source %q: external area %s is missing", name, base)
return
}
for _, typ := range lockfile.Types {
want := map[string]bool{}
for _, upstreamID := range src.Inventory[typ] {
want[deployedName(upstreamID, src.Renames)] = true
}
got, err := scanDeployedNames(filepath.Join(base, typ), typ)
if err != nil {
v.fail(name, "tree", "source %q: reading %s area: %v", name, typ, err)
continue
}
for _, dep := range sortedSet(want) {
if !got[dep] {
v.fail(name, "tree", "source %q: %s item %q is pinned in the lockfile but missing from the external area", name, typ, dep)
}
}
for _, dep := range sortedSet(got) {
if !want[dep] {
v.fail(name, "tree", "source %q: %s item %q exists in the external area but is not in the lockfile", name, typ, dep)
}
}
}
}
func scanDeployedNames(dir, typ string) (map[string]bool, error) {
out := map[string]bool{}
entries, err := os.ReadDir(dir)
if err != nil {
if os.IsNotExist(err) {
return out, nil
}
return nil, err
}
for _, e := range entries {
switch typ {
case lockfile.TypeSkill:
if e.IsDir() {
out[e.Name()] = true
}
case lockfile.TypeCommand, lockfile.TypeAgent:
if strings.HasSuffix(e.Name(), ".md") {
out[strings.TrimSuffix(e.Name(), ".md")] = true
}
case lockfile.TypeMcp:
name := e.Name()
if strings.HasSuffix(name, ".yaml") {
out[strings.TrimSuffix(name, ".yaml")] = true
} else if strings.HasSuffix(name, ".yml") {
out[strings.TrimSuffix(name, ".yml")] = true
}
}
}
return out, nil
}
func sortedSourceNames(lf *lockfile.Lockfile) []string {
out := make([]string, 0, len(lf.Sources))
for name := range lf.Sources {
out = append(out, name)
}
sort.Strings(out)
return out
}
func sortedSet(m map[string]bool) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
sort.Strings(out)
return out
}
// ItemInfo describes one deployed item for inspect.
type ItemInfo struct {
UpstreamID string `json:"upstream_id"`
DeployedID string `json:"deployed_id"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Tags []string `json:"tags,omitempty"`
Warnings []string `json:"warnings,omitempty"`
}
// SourceSummary is one row of vendor list.
type SourceSummary struct {
Name string `json:"name"`
URL string `json:"url"`
Ref string `json:"ref"`
Rev string `json:"rev"`
Mode string `json:"mode"`
Counts map[string]int `json:"counts"`
Total int `json:"total"`
}
// List summarizes every source from the lockfile.
func List(lf *lockfile.Lockfile) []SourceSummary {
var out []SourceSummary
for _, name := range sortedSourceNames(lf) {
src := lf.Sources[name]
s := SourceSummary{Name: name, URL: src.URL, Ref: src.Ref, Rev: src.Rev, Mode: string(src.Selection.Mode), Counts: map[string]int{}}
for _, typ := range lockfile.Types {
n := len(src.Inventory[typ])
if n > 0 {
s.Counts[typ] = n
s.Total += n
}
}
out = append(out, s)
}
return out
}
// InspectReport is the full per-source view with metadata from the external area.
type InspectReport struct {
Name string `json:"name"`
URL string `json:"url"`
Ref string `json:"ref"`
Rev string `json:"rev"`
Mode string `json:"mode"`
Items map[string][]ItemInfo `json:"items"`
Warnings []string `json:"warnings,omitempty"`
}
// Inspect reads the external area of one source and enriches the pinned
// inventory with frontmatter metadata from the deployed files.
func Inspect(workDir, name string, lf *lockfile.Lockfile) (*InspectReport, error) {
src, ok := lf.Sources[name]
if !ok {
return nil, fmt.Errorf("source %q is not in the lockfile", name)
}
base := filepath.Join(workDir, externalDir, name)
tree := &discovery.FsTree{Root: base}
warningsByPrefix := map[string][]string{}
for _, w := range src.Warnings {
prefix, rest, found := strings.Cut(w, ": ")
if found {
warningsByPrefix[prefix] = append(warningsByPrefix[prefix], rest)
}
}
report := &InspectReport{
Name: name,
URL: src.URL,
Ref: src.Ref,
Rev: src.Rev,
Mode: string(src.Selection.Mode),
Items: map[string][]ItemInfo{},
Warnings: src.Warnings,
}
for _, typ := range lockfile.Types {
for _, upstreamID := range src.Inventory[typ] {
dep := deployedName(upstreamID, src.Renames)
info := ItemInfo{UpstreamID: upstreamID, DeployedID: dep, Warnings: warningsByPrefix[typ+"/"+upstreamID]}
switch typ {
case lockfile.TypeSkill:
if data, err := tree.ReadFile(typ + "/" + dep + "/SKILL.md"); err == nil {
fillFrontmatter(&info, data)
}
case lockfile.TypeMcp:
default:
if data, err := tree.ReadFile(typ + "/" + dep + ".md"); err == nil {
fillFrontmatter(&info, data)
}
}
report.Items[typ] = append(report.Items[typ], info)
}
}
return report, nil
}
func fillFrontmatter(info *ItemInfo, data []byte) {
fm, _ := discovery.ParseFrontmatter(data)
info.Name = fm.Name
info.Description = fm.Description
info.Tags = fm.Tags
}
-180
View File
@@ -1,180 +0,0 @@
package vendor
import (
"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/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
}
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
}
-213
View File
@@ -1,213 +0,0 @@
package vendor
import (
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"github.com/m3tam3re/agent-lib/internal/discovery"
"github.com/m3tam3re/agent-lib/internal/gitsource"
"github.com/m3tam3re/agent-lib/internal/lockfile"
)
// SelectOptions parameterize vendor select.
type SelectOptions struct {
Add []string
Remove []string
ModeAll bool
OnlyTypes []string
ExcludeTypes []string
}
// Select changes what a vendored source contributes — without advancing the
// pinned revision (that is vendor update's job). Ids are validated against
// the pinned upstream, collisions re-run, and the external area is rewritten
// deterministically to match the new selection.
func Select(workDir, name string, opts SelectOptions, stdout io.Writer) (*ChangeReport, error) {
lockPath := filepath.Join(workDir, lockfile.FileName)
lf, err := lockfile.Load(lockPath)
if err != nil {
return nil, err
}
src, ok := lf.Sources[name]
if !ok {
return nil, fmt.Errorf("source %q is not in the lockfile", name)
}
newSel, err := planSelection(src, opts, name)
if err != nil {
return nil, err
}
repo, err := gitsource.Clone(src.URL, src.Ref)
if err != nil {
return nil, err
}
pinned, err := repo.Pin(src.Rev)
if err != nil {
return nil, fmt.Errorf("%w — run vendor update to re-pin", err)
}
tree, err := pinned.Tree()
if err != nil {
return nil, err
}
items, err := discovery.Scan(tree, discovery.FromLockfileDiscovery(derefDiscovery(src)))
if err != nil {
return nil, err
}
if err := validateSelectIDs(items, src, opts, name); err != nil {
return nil, err
}
if err := checkIncludeVsTypes(items, newSel, name); err != nil {
return nil, err
}
selected := applySelection(items, newSel)
if err := checkCollisions(workDir, lf, name, selected, src.Renames); err != nil {
return nil, err
}
report := &ChangeReport{Source: name, FromRev: src.Rev, ToRev: src.Rev}
report.Added, report.Removed = membershipDiff(inventorySet(src.Inventory), idSet(selected))
cleanupStaleStaging(workDir)
staging := filepath.Join(workDir, externalDir, ".staging-"+name)
if err := os.RemoveAll(staging); err != nil {
return nil, err
}
if err := materializeTree(tree, selected, src.Renames, staging); err != nil {
os.RemoveAll(staging)
return nil, err
}
if err := fillChanged(report, name, lf, staging); err != nil {
os.RemoveAll(staging)
return nil, err
}
oldDir := filepath.Join(workDir, externalDir, name)
if err := os.RemoveAll(oldDir); err != nil {
return nil, fmt.Errorf("replacing %s: %w", oldDir, err)
}
if err := os.Rename(staging, oldDir); err != nil {
return nil, fmt.Errorf("swapping in new external area: %w", err)
}
src.Selection = newSel
src.Inventory = inventoryOf(selected)
src.Warnings = dedupe(warningsOf(items))
if err := lf.Save(lockPath); err != nil {
return nil, err
}
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)
return report, nil
}
// planSelection derives the new selection from the flags — pure, before any
// upstream contact: --mode all resets to everything; include mode grows and
// shrinks the include list; all mode --remove moves ids onto the exclude
// 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) {
typeFilter, err := TypeFilter(opts.OnlyTypes, opts.ExcludeTypes)
if err != nil {
return lockfile.Selection{}, err
}
if opts.ModeAll {
if len(opts.Add) > 0 || len(opts.Remove) > 0 || typeFilter != nil {
return lockfile.Selection{}, fmt.Errorf("--mode all cannot be combined with --add, --remove, --types or --exclude-types")
}
return lockfile.Selection{Mode: lockfile.ModeAll}, nil
}
if len(opts.Add) == 0 && len(opts.Remove) == 0 && typeFilter == nil {
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 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)
}
newSel = lockfile.Selection{
Mode: lockfile.ModeAll,
Exclude: unionIDs(src.Selection.Exclude, opts.Remove),
}
} else {
newSel = lockfile.Selection{
Mode: lockfile.ModeInclude,
Include: unionIDs(minusIDs(src.Selection.Include, opts.Remove), opts.Add),
}
}
if typeFilter != nil {
newSel.ExcludeTypes = typeFilter
} else {
newSel.ExcludeTypes = src.Selection.ExcludeTypes
}
return newSel, nil
}
// validateSelectIDs checks flag ids against the pinned upstream (and, for
// --remove in include mode, against the current selection) so typos fail
// before anything is mutated.
func validateSelectIDs(items []discovery.Item, src *lockfile.Source, opts SelectOptions, name string) error {
if len(opts.Add) > 0 {
if err := checkIDEntries(items, opts.Add, name, "include"); err != nil {
return fmt.Errorf("--add: %w", err)
}
}
if len(opts.Remove) > 0 && src.Selection.Mode == lockfile.ModeInclude {
selected := map[string]bool{}
for _, id := range src.Selection.Include {
selected[id] = true
}
for _, id := range opts.Remove {
if !selected[id] {
return fmt.Errorf("source %q: --remove id %q is not in the current selection (selected: %s)", name, id, strings.Join(sortedKeys(selected), ", "))
}
}
}
if len(opts.Remove) > 0 && src.Selection.Mode == lockfile.ModeAll {
if err := checkIDEntries(items, opts.Remove, name, "exclude"); err != nil {
return fmt.Errorf("--remove: %w", err)
}
}
return nil
}
func unionIDs(a, b []string) []string {
seen := map[string]bool{}
for _, id := range a {
seen[id] = true
}
out := append([]string{}, a...)
for _, id := range b {
if !seen[id] {
out = append(out, id)
seen[id] = true
}
}
sort.Strings(out)
return out
}
func minusIDs(a, remove []string) []string {
drop := map[string]bool{}
for _, id := range remove {
drop[id] = true
}
var out []string
for _, id := range a {
if !drop[id] {
out = append(out, id)
}
}
sort.Strings(out)
return out
}
-91
View File
@@ -1,91 +0,0 @@
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
}
-39
View File
@@ -1,39 +0,0 @@
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)
}
}
}
-512
View File
@@ -1,512 +0,0 @@
package vendor
import (
"bytes"
"crypto/sha256"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"github.com/m3tam3re/agent-lib/internal/deploy"
"github.com/m3tam3re/agent-lib/internal/discovery"
"github.com/m3tam3re/agent-lib/internal/gitsource"
"github.com/m3tam3re/agent-lib/internal/lockfile"
)
// ChangeReport describes one update (or diff preview) for one source.
type ChangeReport struct {
Source string `json:"source"`
FromRev string `json:"from_rev,omitempty"`
ToRev string `json:"to_rev,omitempty"`
UpToDate bool `json:"up_to_date,omitempty"`
Added map[string][]string `json:"added,omitempty"`
Removed map[string][]string `json:"removed,omitempty"`
Changed map[string][]string `json:"changed,omitempty"`
Available map[string][]string `json:"available,omitempty"`
}
// Update refreshes one source to the latest revision of its pinned ref,
// rewrites the external area deterministically and reports the changes.
func Update(workDir, name string, stdout io.Writer) (*ChangeReport, error) {
lf, err := lockfile.Load(filepath.Join(workDir, lockfile.FileName))
if err != nil {
return nil, err
}
src, ok := lf.Sources[name]
if !ok {
return nil, fmt.Errorf("source %q is not in the lockfile", name)
}
plan, err := computeUpdate(workDir, lf, name, true)
if err != nil {
return nil, err
}
if plan.Report.UpToDate {
fmt.Fprintf(stdout, "source %s already up to date (rev %s)\n", name, src.Rev)
return plan.Report, nil
}
cleanupStaleStaging(workDir)
staging := filepath.Join(workDir, externalDir, ".staging-"+name)
if err := os.RemoveAll(staging); err != nil {
return nil, err
}
if err := materializeTree(plan.Tree, plan.Selected, src.Renames, staging); err != nil {
os.RemoveAll(staging)
return nil, err
}
if err := fillChanged(plan.Report, name, lf, staging); err != nil {
os.RemoveAll(staging)
return nil, err
}
oldDir := filepath.Join(workDir, externalDir, name)
if err := os.RemoveAll(oldDir); err != nil {
return nil, fmt.Errorf("replacing %s: %w", oldDir, err)
}
if err := os.Rename(staging, oldDir); err != nil {
return nil, fmt.Errorf("swapping in new external area: %w", err)
}
src.Rev = plan.Repo.Rev
src.Inventory = inventoryOf(plan.Selected)
src.Warnings = dedupe(warningsOf(plan.Items))
if err := lf.Save(filepath.Join(workDir, lockfile.FileName)); err != nil {
return nil, err
}
printChangeReport(stdout, plan.Report)
return plan.Report, nil
}
// UpdateAll refreshes every source; a failing source does not block the
// others, but the run reports every failure and exits non-zero.
func UpdateAll(workDir string, stdout io.Writer) error {
lf, err := lockfile.Load(filepath.Join(workDir, lockfile.FileName))
if err != nil {
return err
}
if len(lf.Sources) == 0 {
fmt.Fprintln(stdout, "no sources to update")
return nil
}
var failures []string
for _, name := range sortedSourceNames(lf) {
if _, err := Update(workDir, name, stdout); err != nil {
fmt.Fprintf(stdout, "source %s: FAILED: %v\n", name, err)
failures = append(failures, name)
}
}
if len(failures) > 0 {
return fmt.Errorf("update failed for: %s", strings.Join(failures, ", "))
}
return nil
}
// Diff previews an update without touching the work repository, surfacing
// new upstream items that the current selection would not bring in.
func Diff(workDir, name string, stdout io.Writer) (*ChangeReport, error) {
lf, err := lockfile.Load(filepath.Join(workDir, lockfile.FileName))
if err != nil {
return nil, err
}
src, ok := lf.Sources[name]
if !ok {
return nil, fmt.Errorf("source %q is not in the lockfile", name)
}
plan, err := computeUpdate(workDir, lf, name, false)
if err != nil {
return nil, err
}
if plan.Report.UpToDate {
fmt.Fprintf(stdout, "source %s up to date (rev %s); no changes upstream\n", name, src.Rev)
return plan.Report, nil
}
tmp, err := os.MkdirTemp("", "agent-lib-diff-")
if err != nil {
return nil, err
}
defer os.RemoveAll(tmp)
staged := filepath.Join(tmp, "staged")
if err := materializeTree(plan.Tree, plan.Selected, src.Renames, staged); err != nil {
return nil, err
}
if err := fillChanged(plan.Report, name, lf, staged); err != nil {
return nil, err
}
fmt.Fprintf(stdout, "source %s: pending changes vs upstream %s…\n", name, short(plan.Report.ToRev))
printChangeReport(stdout, plan.Report)
return plan.Report, nil
}
// Remove deletes a source's external area and lockfile entry.
func Remove(workDir, name string, stdout io.Writer) error {
lockPath := filepath.Join(workDir, lockfile.FileName)
lf, err := lockfile.Load(lockPath)
if err != nil {
return err
}
if _, ok := lf.Sources[name]; !ok {
return fmt.Errorf("source %q is not in the lockfile", name)
}
if err := os.RemoveAll(filepath.Join(workDir, externalDir, name)); err != nil {
return fmt.Errorf("removing external area: %w", err)
}
delete(lf.Sources, name)
if err := lf.Save(lockPath); err != nil {
return err
}
externalRoot := filepath.Join(workDir, externalDir)
if entries, err := os.ReadDir(externalRoot); err == nil && len(entries) == 0 {
os.Remove(externalRoot)
}
fmt.Fprintf(stdout, "source %s removed (external area and lockfile entry)\n", name)
return nil
}
type updatePlan struct {
Report *ChangeReport
Selected []discovery.Item
Items []discovery.Item
Tree discovery.Tree
Repo *gitsource.Repo
}
// computeUpdate clones the pinned ref, rediscovers and reselects. With
// withCollisions it also runs the namespace checks that must gate a real
// update; diff skips them to stay a pure preview.
func computeUpdate(workDir string, lf *lockfile.Lockfile, name string, withCollisions bool) (*updatePlan, error) {
src := lf.Sources[name]
repo, err := gitsource.Clone(src.URL, src.Ref)
if err != nil {
return nil, err
}
tree, err := repo.Tree()
if err != nil {
return nil, err
}
items, err := discovery.Scan(tree, discovery.FromLockfileDiscovery(derefDiscovery(src)))
if err != nil {
return nil, err
}
if src.Selection.Mode == lockfile.ModeInclude {
if err := checkIDEntries(items, src.Selection.Include, name, "include"); err != nil {
return nil, err
}
}
selected := applySelection(items, src.Selection)
if withCollisions {
if err := checkCollisions(workDir, lf, name, selected, src.Renames); err != nil {
return nil, err
}
}
report := &ChangeReport{
Source: name,
FromRev: src.Rev,
ToRev: repo.Rev,
UpToDate: src.Rev == repo.Rev,
}
report.Added, report.Removed = membershipDiff(inventorySet(src.Inventory), idSet(selected))
report.Available = availableSince(inventorySet(src.Inventory), items, selected)
return &updatePlan{Report: report, Selected: selected, Items: items, Tree: tree, Repo: repo}, nil
}
// availableSince lists upstream items that appeared since the pinned
// inventory and that the current selection would not bring in (relevant in
// include mode; empty in all mode by construction).
func availableSince(old map[string]map[string]bool, items []discovery.Item, selected []discovery.Item) map[string][]string {
inSelection := idSet(selected)
out := map[string][]string{}
for _, it := range items {
if it.Skipped || old[it.Type][it.UpstreamID] || inSelection[it.Type][it.UpstreamID] {
continue
}
out[it.Type] = append(out[it.Type], it.UpstreamID)
}
for _, ids := range out {
sort.Strings(ids)
}
return out
}
func cleanupStaleStaging(workDir string) {
entries, err := os.ReadDir(filepath.Join(workDir, externalDir))
if err != nil {
return
}
for _, e := range entries {
if strings.HasPrefix(e.Name(), ".staging-") {
os.RemoveAll(filepath.Join(workDir, externalDir, e.Name()))
}
}
}
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 {
dep := deployedName(it.UpstreamID, renames)
base := filepath.Join(dst, it.Type)
var target string
var err error
switch it.Type {
case lockfile.TypeSkill:
target = filepath.Join(base, dep)
err = deploy.Dir(tree, it.RelPath, target)
if err == nil && dep != it.UpstreamID {
err = rewriteSkillName(target, dep)
}
default:
target = filepath.Join(base, dep+filepath.Ext(it.RelPath))
err = deploy.File(tree, it.RelPath, target)
}
if err != nil {
return fmt.Errorf("materializing %s/%s: %w", it.Type, it.UpstreamID, err)
}
}
return nil
}
// fillChanged byte-compares the staged tree against the previous external
// area to populate the changed-section of the report.
func fillChanged(report *ChangeReport, name string, lf *lockfile.Lockfile, staging string) error {
report.Changed = map[string][]string{}
src := lf.Sources[name]
for _, typ := range lockfile.Types {
for _, id := range src.Inventory[typ] {
if report.itemIn(typ, id, report.Added) || report.itemIn(typ, id, report.Removed) {
continue
}
dep := deployedName(id, src.Renames)
ext := extFor(typ, staging, dep)
oldDir := filepath.Join(externalDir, name, typ)
newDir := filepath.Join(staging, typ)
same, err := treesEqual(filepath.Join(oldDir, dep+ext), filepath.Join(newDir, dep+ext))
if typ == lockfile.TypeSkill {
same, err = treesEqual(filepath.Join(oldDir, dep), filepath.Join(newDir, dep))
}
if err != nil {
return fmt.Errorf("comparing %s/%s: %w", typ, id, err)
}
if !same {
report.Changed[typ] = append(report.Changed[typ], id)
}
}
}
return nil
}
func extFor(typ, staging, dep string) string {
switch typ {
case lockfile.TypeSkill:
return ""
case lockfile.TypeMcp:
if _, err := os.Stat(filepath.Join(staging, typ, dep+".yaml")); err == nil {
return ".yaml"
}
return ".yml"
default:
return ".md"
}
}
func (r *ChangeReport) itemIn(typ, id string, m map[string][]string) bool {
for _, x := range m[typ] {
if x == id {
return true
}
}
return false
}
func membershipDiff(oldSets, newSets map[string]map[string]bool) (added, removed map[string][]string) {
added = map[string][]string{}
removed = map[string][]string{}
for _, typ := range lockfile.Types {
for id := range newSets[typ] {
if !oldSets[typ][id] {
added[typ] = append(added[typ], id)
}
}
for id := range oldSets[typ] {
if !newSets[typ][id] {
removed[typ] = append(removed[typ], id)
}
}
sort.Strings(added[typ])
sort.Strings(removed[typ])
}
return added, removed
}
func inventorySet(inv map[string][]string) map[string]map[string]bool {
out := map[string]map[string]bool{}
for typ, ids := range inv {
if out[typ] == nil {
out[typ] = map[string]bool{}
}
for _, id := range ids {
out[typ][id] = true
}
}
return out
}
func idSet(items []discovery.Item) map[string]map[string]bool {
out := map[string]map[string]bool{}
for _, it := range items {
if out[it.Type] == nil {
out[it.Type] = map[string]bool{}
}
out[it.Type][it.UpstreamID] = true
}
return out
}
func treesEqual(a, b string) (bool, error) {
filesA, errA := listFilesRecursive(a)
filesB, errB := listFilesRecursive(b)
if errA != nil || errB != nil {
if os.IsNotExist(errA) || os.IsNotExist(errB) {
return false, nil
}
return false, fmt.Errorf("walking %s or %s: %w/%w", a, b, errA, errB)
}
if len(filesA) != len(filesB) {
return false, nil
}
for i := range filesA {
if filesA[i] != filesB[i] {
return false, nil
}
ha, err := hashFile(filepath.Join(a, filesA[i]))
if err != nil {
return false, err
}
hb, err := hashFile(filepath.Join(b, filesB[i]))
if err != nil {
return false, err
}
if !bytes.Equal(ha, hb) {
return false, nil
}
}
return true, nil
}
func listFilesRecursive(root string) ([]string, error) {
var out []string
err := filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
rel, err := filepath.Rel(root, p)
if err != nil {
return err
}
out = append(out, filepath.ToSlash(rel))
return nil
})
if err != nil {
return nil, err
}
sort.Strings(out)
return out, nil
}
func hashFile(path string) ([]byte, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return nil, err
}
return h.Sum(nil), nil
}
func derefDiscovery(src *lockfile.Source) lockfile.Discovery {
if src.Discovery == nil {
return lockfile.Discovery{}
}
return *src.Discovery
}
func inventoryOf(selected []discovery.Item) map[string][]string {
out := map[string][]string{}
for _, it := range selected {
out[it.Type] = append(out[it.Type], it.UpstreamID)
}
for _, ids := range out {
sort.Strings(ids)
}
return out
}
func warningsOf(items []discovery.Item) []string {
var out []string
for _, it := range items {
out = append(out, it.Warnings...)
}
return out
}
func printChangeReport(w io.Writer, r *ChangeReport) {
empty := true
for _, typ := range lockfile.Types {
added := r.Added[typ]
removed := r.Removed[typ]
changed := r.Changed[typ]
available := r.Available[typ]
if len(added)+len(removed)+len(changed)+len(available) == 0 {
continue
}
if empty {
if r.FromRev != "" && r.ToRev != "" && r.FromRev != r.ToRev {
fmt.Fprintf(w, "source %s: %s… → %s…\n", r.Source, short(r.FromRev), short(r.ToRev))
} else {
fmt.Fprintf(w, "source %s:\n", r.Source)
}
empty = false
}
fmt.Fprintf(w, " %s:\n", typ)
for _, id := range added {
fmt.Fprintf(w, " + %s (added)\n", id)
}
for _, id := range changed {
fmt.Fprintf(w, " ~ %s (changed)\n", id)
}
for _, id := range removed {
fmt.Fprintf(w, " - %s (removed)\n", id)
}
for _, id := range available {
fmt.Fprintf(w, " ? %s (available upstream, not selected)\n", id)
}
}
if empty {
fmt.Fprintf(w, "source %s: no item changes\n", r.Source)
}
}
func short(rev string) string {
if len(rev) > 8 {
return rev[:8]
}
return rev
}
-7
View File
@@ -1,7 +0,0 @@
// Package version carries the build-time version of the agent-lib binary.
package version
// Version is injected at build time via
// -ldflags "-X internal/version.Version=<version>". It defaults to "dev"
// for plain `go build` runs.
var Version = "dev"
-13
View File
@@ -1,13 +0,0 @@
package main
import (
"os"
"github.com/m3tam3re/agent-lib/internal/cli"
)
func main() {
if err := cli.Execute(); err != nil {
os.Exit(1)
}
}
-279
View File
@@ -1,279 +0,0 @@
#!/usr/bin/env bash
# Offline end-to-end acceptance walk of the agent-lib v2 spec:
# fixture upstream -> vendor add -> simulated commit -> employee sync ->
# local modification -> upstream update cycle -> protected sync -> status.
# Asserts filesystem state, lockfile, manifest and exit codes throughout.
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
WORK="$(mktemp -d /tmp/agent-lib-acceptance.XXXXXX)"
trap 'rm -rf "$WORK"' EXIT
BIN="$WORK/agent-lib"
PASS=0
FAIL=0
step() { printf '\n\033[1m== %s\033[0m\n' "$*"; }
ok() { printf ' \033[32mok\033[0m %s\n' "$*"; PASS=$((PASS+1)); }
fail() { printf ' \033[31mFAIL\033[0m %s\n' "$*"; FAIL=$((FAIL+1)); }
assert_contains() { # file|output needle label
if grep -qF "$2" "$1" 2>/dev/null; then ok "$3"; else fail "$3 (missing: $2)"; fi
}
assert_file() { if [ -e "$1" ]; then ok "$2"; else fail "$2 ($1 missing)"; fi; }
assert_no_file() { if [ ! -e "$1" ]; then ok "$2"; else fail "$2 ($1 exists)"; fi; }
assert_exit_zero() { if [ "$1" -eq 0 ]; then ok "$2"; else fail "$2 (exit $1)"; fi; }
assert_exit_nonzero() { if [ "$1" -ne 0 ]; then ok "$2"; else fail "$2 (exit 0)"; fi; }
git() { command git -c user.name=acceptance -c user.email=acceptance@test "$@"; }
step "build binary"
(cd "$REPO_ROOT" && go build -o "$BIN" .) || { echo "build failed"; exit 1; }
ok "agent-lib built"
step "fixture upstream repository"
UP="$WORK/upstream"
mkdir -p "$UP"/{skills/good-skill,skills/broken-skill,commands,agents,mcp}
git -C "$UP" init -q -b main
printf -- '---\nname: Good Skill\ndescription: works\n---\n# Good\n' > "$UP/skills/good-skill/SKILL.md"
printf 'print hi\n' > "$UP/skills/good-skill/helper.py"
printf -- '---\nname: Broken\nno colon here\n' > "$UP/skills/broken-skill/SKILL.md"
printf -- '---\nname: Review\n---\nbody\n' > "$UP/commands/review.md"
printf -- '---\nname: Scout\n---\nbody\n' > "$UP/agents/scout.md"
printf 'servers: {}\n' > "$UP/mcp/search.yaml"
git -C "$UP" add -A && git -C "$UP" commit -qm "fixture upstream"
ok "upstream ready (4 types + broken frontmatter)"
step "work repository + vendor add"
WR="$WORK/work-repo"
mkdir -p "$WR/skills/own-skill"
git -C "$WR" init -q -b main
printf -- '---\nname: Own Skill\n---\n# Own\n' > "$WR/skills/own-skill/SKILL.md"
git -C "$WR" add -A && git -C "$WR" commit -qm "own contribution"
(cd "$WR" && "$BIN" vendor add superpowers "$UP") > "$WORK/add.log" 2>&1
assert_exit_zero $? "vendor add succeeds"
assert_contains "$WORK/add.log" "ref: main" "default branch resolved"
assert_contains "$WORK/add.log" "warnings" "malformed frontmatter warned, not failed"
assert_file "$WR/external/superpowers/skills/good-skill/SKILL.md" "skill vendored"
assert_file "$WR/external/superpowers/commands/review.md" "command vendored with extension"
assert_file "$WR/external/superpowers/agents/scout.md" "agent vendored"
assert_file "$WR/external/superpowers/mcp/search.yaml" "mcp fragment vendored"
assert_no_file "$WR/external/superpowers/README.md" "non-content files excluded"
assert_contains "$WR/agent-lib.lock.json" '"version": 2' "lockfile v2 written"
step "lockfile determinism"
WR2="$WORK/work-repo-2"
mkdir -p "$WR2"
(cd "$WR2" && "$BIN" vendor add superpowers "$UP") >/dev/null 2>&1
if cmp -s "$WR/agent-lib.lock.json" "$WR2/agent-lib.lock.json"; then ok "identical reruns produce identical bytes"; else fail "lockfile not deterministic"; fi
step "collision hard error + rename resolution"
WR3="$WORK/work-repo-3"
mkdir -p "$WR3/skills/good-skill"
printf -- '---\nname: My Good\n---\n' > "$WR3/skills/good-skill/SKILL.md"
set +e
(cd "$WR3" && "$BIN" vendor add sp "$UP") > "$WORK/collide.log" 2>&1; RC=$?
set -e
assert_exit_nonzero "$RC" "own-vs-vendored collision aborts"
assert_contains "$WORK/collide.log" "collides" "collision names the rule"
assert_no_file "$WR3/external" "no partial external area"
(cd "$WR3" && "$BIN" vendor add sp "$UP" --rename good-skill=sp-good) >/dev/null 2>&1
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"
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"
(cd "$WR" && "$BIN" validate) > "$WORK/validate.log" 2>&1
assert_exit_zero $? "healthy state validates"
(cd "$WR" && "$BIN" vendor list --json) > "$WORK/list.json" 2>&1
assert_contains "$WORK/list.json" '"mode": "all"' "list --json carries selection mode"
(cd "$WR" && "$BIN" vendor inspect superpowers --json) > "$WORK/inspect.json" 2>&1
assert_contains "$WORK/inspect.json" "Good Skill" "inspect surfaces frontmatter metadata"
step "vendor update cycle"
mkdir -p "$UP/skills/fresh-skill"
printf -- '---\nname: Fresh\n---\n# Fresh\n' > "$UP/skills/fresh-skill/SKILL.md"
printf -- '---\nname: Good Skill\ndescription: changed\n---\n# v2\n' > "$UP/skills/good-skill/SKILL.md"
rm -rf "$UP/skills/broken-skill"
git -C "$UP" add -A && git -C "$UP" commit -qm "upstream: add fresh, change good, remove broken"
LOCK_BEFORE="$(sha256sum "$WR/agent-lib.lock.json" | cut -d' ' -f1)"
(cd "$WR" && "$BIN" vendor diff superpowers) > "$WORK/diff.log" 2>&1
assert_contains "$WORK/diff.log" "fresh-skill" "diff previews upstream changes"
LOCK_AFTER_DIFF="$(sha256sum "$WR/agent-lib.lock.json" | cut -d' ' -f1)"
[ "$LOCK_BEFORE" = "$LOCK_AFTER_DIFF" ] && ok "diff left lockfile untouched" || fail "diff mutated the lockfile"
(cd "$WR" && "$BIN" vendor update superpowers) > "$WORK/update.log" 2>&1
assert_exit_zero $? "update succeeds"
assert_contains "$WORK/update.log" "fresh-skill (added)" "update reports additions"
assert_contains "$WORK/update.log" "good-skill (changed)" "update reports changes"
assert_contains "$WORK/update.log" "broken-skill (removed)" "update reports removals"
assert_file "$WR/external/superpowers/skills/fresh-skill/SKILL.md" "added item materialized"
assert_no_file "$WR/external/superpowers/skills/broken-skill" "removed item gone"
(cd "$WR" && "$BIN" validate) >/dev/null 2>&1
assert_exit_zero $? "updated tree validates"
(cd "$WR" && "$BIN" vendor remove superpowers) >/dev/null 2>&1
assert_no_file "$WR/external/superpowers" "remove leaves no residue"
(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)"
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"
HOME_DIR="$WORK/employee-home"
STATE="$WORK/employee-state"
mkdir -p "$HOME_DIR" "$STATE"
CFG="$WORK/client-config.json"
printf '{"repo_url":"%s","ref":"main"}\n' "$WR" > "$CFG"
sync_run() {
HOME="$HOME_DIR" USERPROFILE="$HOME_DIR" AGENT_LIB_STATE_DIR="$STATE" \
"$BIN" sync --config "$CFG" 2>&1
}
set +e; OUT="$(sync_run)"; RC=$?; set -e
assert_exit_zero "$RC" "sync succeeds"
printf '%s' "$OUT" > "$WORK/sync1.log"
assert_file "$HOME_DIR/.agents/skills/own-skill/SKILL.md" "own skill deployed"
assert_file "$HOME_DIR/.agents/skills/fresh-skill/SKILL.md" "vendored skill deployed"
assert_file "$HOME_DIR/.config/opencode/commands/review.md" "command deployed"
assert_file "$HOME_DIR/.config/opencode/agents/scout.md" "agent deployed"
assert_no_file "$HOME_DIR/.config/opencode/mcp" "mcp never deployed"
if find "$HOME_DIR" -name '*.yaml' | grep -q .; then fail "no yaml in HOME"; else ok "no mcp yaml anywhere in HOME"; fi
assert_contains "$STATE/manifest.json" '"origin": "superpowers"' "manifest records origins"
assert_contains "$STATE/manifest.json" '"hash"' "manifest records content hashes"
step "idempotent second sync"
set +e; OUT2="$(sync_run)"; RC2=$?; set -e
assert_exit_zero "$RC2" "second sync succeeds"
printf '%s' "$OUT2" > "$WORK/sync2.log"
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"
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"
git -C "$WR" add -A && git -C "$WR" commit -qm "change own-skill upstream"
set +e; OUT3="$(sync_run)"; RC3=$?; set -e
assert_exit_zero "$RC3" "sync with local mods does not fail"
printf '%s' "$OUT3" > "$WORK/sync3.log"
assert_contains "$WORK/sync3.log" "skipped (local modifications kept): 1" "modification skipped with warning"
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"
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"
MINE="$HOME_DIR/.agents/skills/my-private-skill"
mkdir -p "$MINE" && printf -- '---\nname: Mine\n---\n' > "$MINE/SKILL.md"
set +e; OUT4="$(sync_run)"; RC4=$?; set -e
assert_exit_zero "$RC4" "sync tolerates unmanaged items"
printf '%s' "$OUT4" > "$WORK/sync4.log"
assert_contains "$WORK/sync4.log" "unmanaged items left untouched: 1" "self-created item reported"
assert_file "$MINE/SKILL.md" "self-created item untouched"
if grep -q "my-private-skill" "$STATE/manifest.json"; then fail "unmanaged item leaked into manifest"; else ok "manifest stays clean"; fi
step "upstream deletion: unmodified removed, modified kept"
rm -rf "$WR/skills/own-skill" "$WR/external/superpowers/agents" "$WR/external/superpowers/commands"
printf -- '---\nname: Scout\n---\n# MY AGENT TWEAKS\n' > "$HOME_DIR/.config/opencode/agents/scout.md"
git -C "$WR" add -A && git -C "$WR" commit -qm "remove own-skill and vendored agents+commands"
set +e; OUT5="$(sync_run)"; RC5=$?; set -e
assert_exit_zero "$RC5" "sync with deletions succeeds"
printf '%s' "$OUT5" > "$WORK/sync5.log"
assert_contains "$WORK/sync5.log" "removed:" "unmodified deletions removed"
assert_no_file "$HOME_DIR/.config/opencode/commands/review.md" "unmodified deleted command removed locally"
grep -q "MY EDITS" "$HOME_DIR/.agents/skills/own-skill/SKILL.md" && ok "modified skill survives deletion" || fail "modified skill destroyed"
grep -q "MY AGENT TWEAKS" "$HOME_DIR/.config/opencode/agents/scout.md" && ok "modified agent survives deletion" || fail "modified agent destroyed"
assert_contains "$STATE/sync.log" "upstream deleted but the local copy was modified" "kept deletions warned"
step "status drift detection"
status_run() {
HOME="$HOME_DIR" USERPROFILE="$HOME_DIR" AGENT_LIB_STATE_DIR="$STATE" \
"$BIN" status --config "$CFG" 2>&1
}
set +e; OUTS="$(status_run)"; RCS=$?; set -e
assert_exit_nonzero "$RCS" "blocked update drift exits non-zero"
printf '%s' "$OUTS" > "$WORK/status.log"
assert_contains "$WORK/status.log" "drift" "status reports drift"
set +e; OUTSJ="$(HOME="$HOME_DIR" USERPROFILE="$HOME_DIR" AGENT_LIB_STATE_DIR="$STATE" "$BIN" status --config "$CFG" --json 2>&1)"; RCSJ=$?; set -e
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"
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"
BEFORE="$(cat "$HOME_DIR/.agents/skills/fresh-skill/SKILL.md")"
printf '{"repo_url":"%s","ref":"main"}\n' "$WORK/nonexistent-repo" > "$CFG"
set +e; sync_run > "$WORK/unreachable.log" 2>&1; RC6=$?; set -e
assert_exit_nonzero "$RC6" "unreachable repo fails cleanly"
AFTER="$(cat "$HOME_DIR/.agents/skills/fresh-skill/SKILL.md" 2>/dev/null || true)"
[ "$BEFORE" = "$AFTER" ] && ok "previous state intact" || fail "state damaged by failed sync"
printf '\n\033[1mACCEPTANCE: %d passed, %d failed\033[0m\n' "$PASS" "$FAIL"
[ "$FAIL" -eq 0 ]