mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-19 02:17:09 +00:00
createLink always tried `mklink /J` first. mklink does not check the source type, so agents, single-file extras such as a shared AGENTS.md, and per-file extras links became directory junctions that point at a file: Explorer shows a folder and tools cannot read it. Sync then compared only the link destination and kept the broken junction forever. Files now get real symlinks only. When the OS cannot create them (Windows without Developer Mode, non-elevated), file-based link modes fall back to copies at the mode level, so status, doctor, the API and later syncs all see an effective `copy` mode. Fallback copies are tracked by hash so they keep updating and pruning without touching the user's own files, and turn back into links once links work. Single-file extras remember what they last wrote, so an unedited copy is replaced silently instead of producing a drift backup on every source edit, and switching a target back to import restores the user's attach-time content plus the import block. Includes a Windows runbook and script, verified on a Windows 11 ARM64 VM with and without symlink rights. Refs #299
696 lines
21 KiB
Go
696 lines
21 KiB
Go
package sync
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"skillshare/internal/resource"
|
|
"skillshare/internal/utils"
|
|
)
|
|
|
|
// AgentSyncResult holds the result of syncing agents to a target.
|
|
type AgentSyncResult struct {
|
|
Linked []string // Agents that were symlinked (merge) or copied (copy)
|
|
Skipped []string // Agents that already exist in target (kept local)
|
|
Updated []string // Agents that had broken symlinks fixed or content updated
|
|
}
|
|
|
|
// AgentCollision represents two agents that flatten to the same filename.
|
|
type AgentCollision struct {
|
|
FlatName string // The colliding flat name (e.g. "helper.md")
|
|
PathA string // First agent relative path
|
|
PathB string // Second agent relative path
|
|
}
|
|
|
|
// LocalAgentInfo describes a local agent file in a target directory.
|
|
type LocalAgentInfo struct {
|
|
Name string
|
|
Path string
|
|
TargetName string
|
|
}
|
|
|
|
// CheckAgentCollisions detects agents that flatten to the same filename.
|
|
func CheckAgentCollisions(agents []resource.DiscoveredResource) []AgentCollision {
|
|
seen := make(map[string]string) // flatName → first relPath
|
|
var collisions []AgentCollision
|
|
|
|
for _, a := range agents {
|
|
if prev, ok := seen[a.FlatName]; ok {
|
|
collisions = append(collisions, AgentCollision{
|
|
FlatName: a.FlatName,
|
|
PathA: prev,
|
|
PathB: a.RelPath,
|
|
})
|
|
} else {
|
|
seen[a.FlatName] = a.RelPath
|
|
}
|
|
}
|
|
|
|
return collisions
|
|
}
|
|
|
|
// SyncAgents dispatches to the appropriate sync mode for agents.
|
|
// mode: "merge" (per-file symlinks), "symlink" (whole dir), "copy" (file copy).
|
|
// projectRoot enables relative symlinks when non-empty.
|
|
func SyncAgents(agents []resource.DiscoveredResource, sourceDir, targetDir, mode string, dryRun, force bool, projectRoot ...string) (*AgentSyncResult, error) {
|
|
root := ""
|
|
if len(projectRoot) > 0 {
|
|
root = projectRoot[0]
|
|
}
|
|
|
|
switch mode {
|
|
case "symlink":
|
|
return syncAgentsSymlink(sourceDir, targetDir, dryRun, force, root)
|
|
case "copy":
|
|
return syncAgentsCopy(agents, targetDir, dryRun, force)
|
|
default: // "merge" or ""
|
|
if !canCreateFileLink() {
|
|
return syncAgentsMergeCopy(agents, targetDir, dryRun, force)
|
|
}
|
|
return syncAgentsMerge(agents, sourceDir, targetDir, dryRun, force, root)
|
|
}
|
|
}
|
|
|
|
// linkResolvesToSource reports whether a resolved symlink target (absLink) and a
|
|
// source path (absSource) reference the same file. The fast path is a direct
|
|
// string compare; the slow path canonicalizes both sides through EvalSymlinks so
|
|
// symlinked ancestors (e.g. macOS /var → /private/var) do not make a stable
|
|
// relative link look like it points elsewhere. Mirrors isSymlinkToSource in sync.go.
|
|
func linkResolvesToSource(absLink, absSource string) bool {
|
|
if utils.PathsEqual(absLink, absSource) {
|
|
return true
|
|
}
|
|
return utils.PathsEqual(utils.ResolveSymlink(absLink), utils.ResolveSymlink(absSource))
|
|
}
|
|
|
|
// syncAgentsMerge creates per-file symlinks in targetDir for each discovered agent.
|
|
// Existing non-symlink files are preserved (skipped) unless force is true.
|
|
func syncAgentsMerge(agents []resource.DiscoveredResource, sourceDir, targetDir string, dryRun, force bool, projectRoot string) (*AgentSyncResult, error) {
|
|
result := &AgentSyncResult{}
|
|
relative := shouldUseRelative(projectRoot, sourceDir, targetDir)
|
|
|
|
if !dryRun {
|
|
if err := os.MkdirAll(targetDir, 0755); err != nil {
|
|
return nil, fmt.Errorf("failed to create agent target directory: %w", err)
|
|
}
|
|
}
|
|
|
|
// Copies made while file links were unavailable are relinked.
|
|
copies := loadCopyTracker(targetDir)
|
|
|
|
for _, agent := range agents {
|
|
targetPath := filepath.Join(targetDir, agent.FlatName)
|
|
|
|
_, err := os.Lstat(targetPath)
|
|
if err == nil {
|
|
if utils.IsSymlinkOrJunction(targetPath) {
|
|
absLink, linkErr := utils.ResolveLinkTarget(targetPath)
|
|
if linkErr != nil {
|
|
return nil, fmt.Errorf("failed to resolve link for %s: %w", agent.FlatName, linkErr)
|
|
}
|
|
absSource, _ := filepath.Abs(agent.AbsPath)
|
|
|
|
if linkResolvesToSource(absLink, absSource) && fileLinkUsable(targetPath) {
|
|
dest, _ := os.Readlink(targetPath)
|
|
if !linkNeedsReformat(dest, relative) {
|
|
result.Linked = append(result.Linked, agent.FlatName)
|
|
continue
|
|
}
|
|
if !dryRun {
|
|
if err := reformatLink(targetPath, agent.AbsPath, relative); err != nil {
|
|
return nil, fmt.Errorf("failed to reformat symlink for %s: %w", agent.FlatName, err)
|
|
}
|
|
}
|
|
result.Updated = append(result.Updated, agent.FlatName)
|
|
continue
|
|
}
|
|
|
|
if !dryRun {
|
|
os.Remove(targetPath)
|
|
if err := createLink(targetPath, agent.AbsPath, relative); err != nil {
|
|
return nil, fmt.Errorf("failed to create symlink for %s: %w", agent.FlatName, err)
|
|
}
|
|
}
|
|
result.Updated = append(result.Updated, agent.FlatName)
|
|
} else {
|
|
if force || copies.owns(agent.FlatName) {
|
|
if !dryRun {
|
|
os.Remove(targetPath)
|
|
if err := createLink(targetPath, agent.AbsPath, relative); err != nil {
|
|
return nil, fmt.Errorf("failed to create symlink for %s: %w", agent.FlatName, err)
|
|
}
|
|
copies.forget(agent.FlatName)
|
|
}
|
|
result.Updated = append(result.Updated, agent.FlatName)
|
|
} else {
|
|
result.Skipped = append(result.Skipped, agent.FlatName)
|
|
}
|
|
}
|
|
} else if os.IsNotExist(err) {
|
|
if !dryRun {
|
|
if err := createLink(targetPath, agent.AbsPath, relative); err != nil {
|
|
return nil, fmt.Errorf("failed to create symlink for %s: %w", agent.FlatName, err)
|
|
}
|
|
}
|
|
result.Linked = append(result.Linked, agent.FlatName)
|
|
} else {
|
|
return nil, fmt.Errorf("failed to check target path for %s: %w", agent.FlatName, err)
|
|
}
|
|
}
|
|
|
|
if !dryRun {
|
|
if err := copies.save(); err != nil {
|
|
return nil, fmt.Errorf("failed to update agent manifest: %w", err)
|
|
}
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// syncAgentsMergeCopy is merge mode where file links are unavailable: each
|
|
// agent is copied and tracked, so later syncs keep the copies updated and
|
|
// pruned while local agent files stay preserved as in merge mode.
|
|
func syncAgentsMergeCopy(agents []resource.DiscoveredResource, targetDir string, dryRun, force bool) (*AgentSyncResult, error) {
|
|
result := &AgentSyncResult{}
|
|
|
|
if !dryRun {
|
|
if err := os.MkdirAll(targetDir, 0755); err != nil {
|
|
return nil, fmt.Errorf("failed to create agent target directory: %w", err)
|
|
}
|
|
}
|
|
copies := loadCopyTracker(targetDir)
|
|
|
|
for _, agent := range agents {
|
|
name := agent.FlatName
|
|
targetPath := filepath.Join(targetDir, name)
|
|
|
|
info, err := os.Lstat(targetPath)
|
|
exists := err == nil
|
|
switch {
|
|
case os.IsNotExist(err):
|
|
case err != nil:
|
|
return nil, fmt.Errorf("failed to check target path for %s: %w", name, err)
|
|
case utils.IsSymlinkOrJunction(targetPath):
|
|
// A merge-mode link, or a junction to a file that cannot be read.
|
|
case info.IsDir():
|
|
result.Skipped = append(result.Skipped, name)
|
|
continue
|
|
case contentEqual(agent.AbsPath, targetPath):
|
|
if !dryRun {
|
|
copies.record(name)
|
|
}
|
|
result.Linked = append(result.Linked, name)
|
|
continue
|
|
case !force && !copies.owns(name):
|
|
result.Skipped = append(result.Skipped, name)
|
|
continue
|
|
}
|
|
|
|
if !dryRun {
|
|
if exists {
|
|
if err := os.Remove(targetPath); err != nil {
|
|
return nil, fmt.Errorf("failed to replace %s: %w", name, err)
|
|
}
|
|
}
|
|
if err := copyFile(agent.AbsPath, targetPath); err != nil {
|
|
return nil, fmt.Errorf("failed to copy %s: %w", name, err)
|
|
}
|
|
copies.record(name)
|
|
}
|
|
if exists {
|
|
result.Updated = append(result.Updated, name)
|
|
} else {
|
|
result.Linked = append(result.Linked, name)
|
|
}
|
|
}
|
|
|
|
if !dryRun {
|
|
if err := copies.save(); err != nil {
|
|
return nil, fmt.Errorf("failed to update agent manifest: %w", err)
|
|
}
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// SyncedAgentCopies counts the agents whose target file is a copy made in
|
|
// place of a link that still matches its source. Status and doctor count them
|
|
// as in sync alongside healthy links; a stale copy is drift.
|
|
func SyncedAgentCopies(targetDir string, agents []resource.DiscoveredResource) int {
|
|
copies := loadCopyTracker(targetDir)
|
|
n := 0
|
|
for _, a := range agents {
|
|
if _, tracked := copies.m.Managed[a.FlatName]; !tracked {
|
|
continue
|
|
}
|
|
target := filepath.Join(targetDir, a.FlatName)
|
|
if info, err := os.Lstat(target); err == nil && info.Mode().IsRegular() && contentEqual(a.AbsPath, target) {
|
|
n++
|
|
}
|
|
}
|
|
return n
|
|
}
|
|
|
|
// syncAgentsSymlink creates a single directory symlink from targetDir to sourceDir.
|
|
// If targetDir already exists as a real directory, it's replaced only with force.
|
|
func syncAgentsSymlink(sourceDir, targetDir string, dryRun, force bool, projectRoot string) (*AgentSyncResult, error) {
|
|
result := &AgentSyncResult{}
|
|
relative := shouldUseRelative(projectRoot, sourceDir, targetDir)
|
|
|
|
if err := os.MkdirAll(filepath.Dir(targetDir), 0755); err != nil {
|
|
return nil, fmt.Errorf("failed to create target parent: %w", err)
|
|
}
|
|
|
|
info, err := os.Lstat(targetDir)
|
|
if err == nil {
|
|
if utils.IsLinkMode(targetDir, info.Mode()) {
|
|
// Already a symlink — check if correct
|
|
absLink, linkErr := utils.ResolveLinkTarget(targetDir)
|
|
if linkErr != nil {
|
|
return nil, fmt.Errorf("failed to resolve link: %w", linkErr)
|
|
}
|
|
absSource, _ := filepath.Abs(sourceDir)
|
|
|
|
if linkResolvesToSource(absLink, absSource) {
|
|
dest, _ := os.Readlink(targetDir)
|
|
if !linkNeedsReformat(dest, relative) {
|
|
result.Linked = append(result.Linked, "(directory)")
|
|
return result, nil
|
|
}
|
|
if !dryRun {
|
|
if err := reformatLink(targetDir, sourceDir, relative); err != nil {
|
|
return nil, fmt.Errorf("failed to reformat directory symlink: %w", err)
|
|
}
|
|
}
|
|
result.Updated = append(result.Updated, "(directory)")
|
|
return result, nil
|
|
}
|
|
|
|
// Wrong target
|
|
if !dryRun {
|
|
os.Remove(targetDir)
|
|
if err := createLink(targetDir, sourceDir, relative); err != nil {
|
|
return nil, fmt.Errorf("failed to create directory symlink: %w", err)
|
|
}
|
|
}
|
|
result.Updated = append(result.Updated, "(directory)")
|
|
} else {
|
|
// Real directory
|
|
if force {
|
|
if !dryRun {
|
|
os.RemoveAll(targetDir)
|
|
if err := createLink(targetDir, sourceDir, relative); err != nil {
|
|
return nil, fmt.Errorf("failed to create directory symlink: %w", err)
|
|
}
|
|
}
|
|
result.Updated = append(result.Updated, "(directory)")
|
|
} else {
|
|
result.Skipped = append(result.Skipped, "(directory)")
|
|
}
|
|
}
|
|
} else if os.IsNotExist(err) {
|
|
if !dryRun {
|
|
if err := createLink(targetDir, sourceDir, relative); err != nil {
|
|
return nil, fmt.Errorf("failed to create directory symlink: %w", err)
|
|
}
|
|
}
|
|
result.Linked = append(result.Linked, "(directory)")
|
|
} else {
|
|
return nil, fmt.Errorf("failed to check target path: %w", err)
|
|
}
|
|
|
|
return result, nil
|
|
}
|
|
|
|
// syncAgentsCopy copies agent .md files to targetDir.
|
|
// Existing files are overwritten if content differs; force replaces all.
|
|
func syncAgentsCopy(agents []resource.DiscoveredResource, targetDir string, dryRun, force bool) (*AgentSyncResult, error) {
|
|
result := &AgentSyncResult{}
|
|
|
|
if !dryRun {
|
|
if err := os.MkdirAll(targetDir, 0755); err != nil {
|
|
return nil, fmt.Errorf("failed to create agent target directory: %w", err)
|
|
}
|
|
}
|
|
|
|
for _, agent := range agents {
|
|
targetPath := filepath.Join(targetDir, agent.FlatName)
|
|
|
|
srcData, err := os.ReadFile(agent.AbsPath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to read source %s: %w", agent.FlatName, err)
|
|
}
|
|
|
|
// A link left by merge mode (or an unreadable junction) is replaced;
|
|
// writing through it would edit the source.
|
|
if utils.IsSymlinkOrJunction(targetPath) {
|
|
if !dryRun {
|
|
if err := os.Remove(targetPath); err != nil {
|
|
return nil, fmt.Errorf("failed to replace %s: %w", agent.FlatName, err)
|
|
}
|
|
if err := os.WriteFile(targetPath, srcData, 0644); err != nil {
|
|
return nil, fmt.Errorf("failed to write %s: %w", agent.FlatName, err)
|
|
}
|
|
}
|
|
result.Updated = append(result.Updated, agent.FlatName)
|
|
continue
|
|
}
|
|
|
|
if _, statErr := os.Stat(targetPath); statErr == nil {
|
|
// File exists — check if content matches
|
|
tgtData, readErr := os.ReadFile(targetPath)
|
|
if readErr == nil && string(tgtData) == string(srcData) && !force {
|
|
result.Linked = append(result.Linked, agent.FlatName)
|
|
continue
|
|
}
|
|
// Content differs or force — overwrite
|
|
if !dryRun {
|
|
if err := os.WriteFile(targetPath, srcData, 0644); err != nil {
|
|
return nil, fmt.Errorf("failed to write %s: %w", agent.FlatName, err)
|
|
}
|
|
}
|
|
result.Updated = append(result.Updated, agent.FlatName)
|
|
} else {
|
|
// New file
|
|
if !dryRun {
|
|
if err := os.WriteFile(targetPath, srcData, 0644); err != nil {
|
|
return nil, fmt.Errorf("failed to write %s: %w", agent.FlatName, err)
|
|
}
|
|
}
|
|
result.Linked = append(result.Linked, agent.FlatName)
|
|
}
|
|
}
|
|
|
|
return result, nil
|
|
}
|
|
|
|
// SyncAgentsTransform pipes each agent through spec and writes the output into
|
|
// targetDir, renamed per spec.OutputExt. Like copy mode, the target is owned by
|
|
// skillshare, so differing files are overwritten. A failing agent is reported in
|
|
// the returned error without stopping the others.
|
|
func SyncAgentsTransform(agents []resource.DiscoveredResource, sourceDir, targetDir, mode string, spec *ExtensionSpec, dryRun, force bool) (*AgentSyncResult, error) {
|
|
if _, err := ResolveExtensionMode(mode); err != nil {
|
|
return nil, err
|
|
}
|
|
result := &AgentSyncResult{}
|
|
var errs []error
|
|
|
|
// A symlink-mode leftover points the whole target at the source; writing
|
|
// through it would overwrite source agents.
|
|
if !dryRun && utils.IsSymlinkOrJunction(targetDir) {
|
|
if absLink, err := utils.ResolveLinkTarget(targetDir); err == nil && linkResolvesToSource(absLink, sourceDir) {
|
|
if err := os.Remove(targetDir); err != nil {
|
|
return nil, fmt.Errorf("failed to remove directory symlink: %w", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
for _, agent := range agents {
|
|
name := ApplyOutputExt(agent.FlatName, spec.OutputExt)
|
|
// A preview must never execute extension code, so dry-run can't know
|
|
// whether the output would change.
|
|
if dryRun {
|
|
result.Linked = append(result.Linked, name)
|
|
continue
|
|
}
|
|
|
|
tgtFile := filepath.Join(targetDir, name)
|
|
// Merge-mode leftovers link to the source; drop the link, never write through it.
|
|
if info, err := os.Lstat(tgtFile); err == nil && utils.IsLinkMode(tgtFile, info.Mode()) {
|
|
if err := os.Remove(tgtFile); err != nil {
|
|
errs = append(errs, fmt.Errorf("%s: remove symlink: %w", agent.FlatName, err))
|
|
continue
|
|
}
|
|
}
|
|
existing, readErr := os.ReadFile(tgtFile)
|
|
out, err := runExtension(spec, agent.AbsPath, map[string]string{
|
|
"SS_SRC_PATH": agent.AbsPath,
|
|
"SS_REL_PATH": agent.RelPath,
|
|
"SS_TARGET_DIR": targetDir,
|
|
"SS_MODE": "sync",
|
|
})
|
|
if err != nil {
|
|
// Keeping the old output would leave an unconverted agent active.
|
|
if readErr == nil {
|
|
os.Remove(tgtFile)
|
|
}
|
|
errs = append(errs, fmt.Errorf("%s: %w", agent.FlatName, err))
|
|
continue
|
|
}
|
|
if readErr == nil && bytes.Equal(existing, out) && !force {
|
|
result.Linked = append(result.Linked, name)
|
|
continue
|
|
}
|
|
if err := os.MkdirAll(targetDir, 0755); err != nil {
|
|
return nil, fmt.Errorf("failed to create agent target directory: %w", err)
|
|
}
|
|
if err := os.WriteFile(tgtFile, out, 0644); err != nil {
|
|
errs = append(errs, fmt.Errorf("%s: write target: %w", agent.FlatName, err))
|
|
continue
|
|
}
|
|
if readErr == nil {
|
|
result.Updated = append(result.Updated, name)
|
|
} else {
|
|
result.Linked = append(result.Linked, name)
|
|
}
|
|
}
|
|
|
|
return result, errors.Join(errs...)
|
|
}
|
|
|
|
// SyncAgentsToTarget creates file symlinks in targetDir for each discovered agent.
|
|
// Uses merge semantics. Kept for backward compatibility; prefer SyncAgents().
|
|
func SyncAgentsToTarget(agents []resource.DiscoveredResource, targetDir string, dryRun, force bool) (*AgentSyncResult, error) {
|
|
return syncAgentsMerge(agents, "", targetDir, dryRun, force, "")
|
|
}
|
|
|
|
// PruneOrphanAgentLinks removes file symlinks in targetDir that don't
|
|
// correspond to any discovered agent. For merge mode only.
|
|
func PruneOrphanAgentLinks(targetDir string, agents []resource.DiscoveredResource, dryRun bool) (removed []string, _ error) {
|
|
entries, err := os.ReadDir(targetDir)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return nil, nil
|
|
}
|
|
return nil, fmt.Errorf("failed to read agent target directory: %w", err)
|
|
}
|
|
|
|
expected := make(map[string]bool, len(agents))
|
|
for _, a := range agents {
|
|
expected[a.FlatName] = true
|
|
}
|
|
|
|
// Copies stand in for links when file links are unavailable.
|
|
copies := loadCopyTracker(targetDir)
|
|
removed = copies.pruneOrphans(expected, dryRun)
|
|
if !dryRun {
|
|
if err := copies.save(); err != nil {
|
|
return removed, fmt.Errorf("failed to update agent manifest: %w", err)
|
|
}
|
|
}
|
|
|
|
for _, entry := range entries {
|
|
name := entry.Name()
|
|
|
|
if !strings.HasSuffix(strings.ToLower(name), ".md") {
|
|
continue
|
|
}
|
|
|
|
info, err := entry.Info()
|
|
if err != nil {
|
|
continue
|
|
}
|
|
|
|
if !utils.IsLinkMode(filepath.Join(targetDir, name), info.Mode()) {
|
|
continue
|
|
}
|
|
|
|
if expected[name] {
|
|
continue
|
|
}
|
|
|
|
if !dryRun {
|
|
os.Remove(filepath.Join(targetDir, name))
|
|
}
|
|
removed = append(removed, name)
|
|
}
|
|
|
|
return removed, nil
|
|
}
|
|
|
|
// PruneOrphanAgentCopies removes copied .md files in targetDir that don't
|
|
// correspond to any discovered agent. For copy mode only. outputExt is the
|
|
// extension a transform renames outputs to ("" keeps .md); files with it are
|
|
// pruned too, and a stale .md copy of a transformed agent counts as an orphan.
|
|
func PruneOrphanAgentCopies(targetDir string, agents []resource.DiscoveredResource, outputExt string, dryRun bool) (removed []string, _ error) {
|
|
entries, err := os.ReadDir(targetDir)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return nil, nil
|
|
}
|
|
return nil, fmt.Errorf("failed to read agent target directory: %w", err)
|
|
}
|
|
|
|
expected := make(map[string]bool, len(agents))
|
|
for _, a := range agents {
|
|
expected[ApplyOutputExt(a.FlatName, outputExt)] = true
|
|
}
|
|
outSuffix := ""
|
|
if outputExt != "" {
|
|
outSuffix = "." + strings.ToLower(outputExt)
|
|
}
|
|
|
|
for _, entry := range entries {
|
|
name := entry.Name()
|
|
lower := strings.ToLower(name)
|
|
|
|
if !strings.HasSuffix(lower, ".md") && (outSuffix == "" || !strings.HasSuffix(lower, outSuffix)) {
|
|
continue
|
|
}
|
|
|
|
// Skip conventional excludes (user might have README.md etc.)
|
|
if resource.ConventionalExcludes[name] {
|
|
continue
|
|
}
|
|
|
|
if expected[name] {
|
|
continue
|
|
}
|
|
|
|
if !dryRun {
|
|
os.Remove(filepath.Join(targetDir, name))
|
|
}
|
|
removed = append(removed, name)
|
|
}
|
|
|
|
return removed, nil
|
|
}
|
|
|
|
// FindLocalAgents finds local (non-symlinked) agent files in a target directory.
|
|
// If the target directory itself is a symlink to sourcePath, it returns no local agents.
|
|
func FindLocalAgents(targetDir, sourcePath string) ([]LocalAgentInfo, error) {
|
|
var agents []LocalAgentInfo
|
|
|
|
info, err := os.Lstat(targetDir)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return agents, nil
|
|
}
|
|
return nil, fmt.Errorf("failed to read agent target directory: %w", err)
|
|
}
|
|
|
|
if utils.IsLinkMode(targetDir, info.Mode()) {
|
|
absLink, err := utils.ResolveLinkTarget(targetDir)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
absSource, _ := filepath.Abs(sourcePath)
|
|
if linkResolvesToSource(absLink, absSource) {
|
|
return agents, nil
|
|
}
|
|
resolved, statErr := os.Stat(targetDir)
|
|
if statErr != nil || !resolved.IsDir() {
|
|
return agents, nil
|
|
}
|
|
}
|
|
|
|
entries, err := os.ReadDir(targetDir)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return agents, nil
|
|
}
|
|
return nil, fmt.Errorf("failed to read agent target directory: %w", err)
|
|
}
|
|
|
|
copies := loadCopyTracker(targetDir)
|
|
for _, entry := range entries {
|
|
name := entry.Name()
|
|
|
|
if !strings.HasSuffix(strings.ToLower(name), ".md") {
|
|
continue
|
|
}
|
|
if utils.IsHidden(name) || resource.ConventionalExcludes[name] {
|
|
continue
|
|
}
|
|
if copies.owns(name) {
|
|
continue // a copy standing in for a link, not a local agent
|
|
}
|
|
|
|
info, err := entry.Info()
|
|
if err != nil {
|
|
continue
|
|
}
|
|
|
|
if info.IsDir() || utils.IsLinkMode(filepath.Join(targetDir, name), info.Mode()) {
|
|
continue
|
|
}
|
|
|
|
agents = append(agents, LocalAgentInfo{
|
|
Name: name,
|
|
Path: filepath.Join(targetDir, name),
|
|
})
|
|
}
|
|
|
|
return agents, nil
|
|
}
|
|
|
|
// PullAgent copies a single local agent file from target to source.
|
|
func PullAgent(agent LocalAgentInfo, sourcePath string, force bool) error {
|
|
destPath := filepath.Join(sourcePath, agent.Name)
|
|
|
|
if _, err := os.Stat(destPath); err == nil {
|
|
if !force {
|
|
return ErrAlreadyExists
|
|
}
|
|
if err := os.RemoveAll(destPath); err != nil {
|
|
return fmt.Errorf("failed to remove existing: %w", err)
|
|
}
|
|
}
|
|
|
|
data, err := os.ReadFile(agent.Path)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to read %s: %w", agent.Name, err)
|
|
}
|
|
if err := os.WriteFile(destPath, data, 0644); err != nil {
|
|
return fmt.Errorf("failed to write %s: %w", agent.Name, err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// PullAgents copies multiple local agent files from targets to source.
|
|
func PullAgents(agents []LocalAgentInfo, sourcePath string, opts PullOptions) (*PullResult, error) {
|
|
result := &PullResult{
|
|
Failed: make(map[string]error),
|
|
}
|
|
|
|
if !opts.DryRun {
|
|
if err := os.MkdirAll(sourcePath, 0755); err != nil {
|
|
return nil, fmt.Errorf("failed to create agent source dir: %w", err)
|
|
}
|
|
}
|
|
|
|
for _, agent := range agents {
|
|
if opts.DryRun {
|
|
result.Pulled = append(result.Pulled, agent.Name)
|
|
continue
|
|
}
|
|
|
|
err := PullAgent(agent, sourcePath, opts.Force)
|
|
if err != nil {
|
|
if errors.Is(err, ErrAlreadyExists) {
|
|
result.Skipped = append(result.Skipped, agent.Name)
|
|
} else {
|
|
result.Failed[agent.Name] = err
|
|
}
|
|
continue
|
|
}
|
|
|
|
result.Pulled = append(result.Pulled, agent.Name)
|
|
}
|
|
|
|
return result, nil
|
|
}
|