test(extras): integration tests for flatten sync

Covers: flatten merge (files land flat), collision detection (warn and
skip), and config YAML round-trip.

Ref: #97
This commit is contained in:
Willie
2026-03-25 21:14:16 +08:00
parent 4c83ef71fb
commit 31db9fa36f
4 changed files with 167 additions and 11 deletions
+113
View File
@@ -5,6 +5,7 @@ package integration
import (
"os"
"path/filepath"
"strings"
"testing"
"skillshare/internal/testutil"
@@ -407,3 +408,115 @@ extras:
// Sync auto-creates missing extras source directories (same as target dirs)
result.AssertAnyOutputContains(t, "Created source directory")
}
func TestSyncExtras_FlattenMerge(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
sb.CreateSkill("placeholder", map[string]string{
"SKILL.md": "# Placeholder",
})
targetPath := sb.CreateTarget("claude")
sourceRoot := filepath.Dir(sb.SourcePath)
agentsSource := filepath.Join(sourceRoot, "extras", "agents")
os.MkdirAll(filepath.Join(agentsSource, "curriculum"), 0755)
os.MkdirAll(filepath.Join(agentsSource, "software"), 0755)
os.WriteFile(filepath.Join(agentsSource, "curriculum", "tactician.md"), []byte("# Tactician"), 0644)
os.WriteFile(filepath.Join(agentsSource, "software", "implementer.md"), []byte("# Implementer"), 0644)
os.WriteFile(filepath.Join(agentsSource, "reviewer.md"), []byte("# Reviewer"), 0644)
agentsTarget := filepath.Join(sb.Home, ".claude", "agents")
os.MkdirAll(agentsTarget, 0755)
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + targetPath + `
extras:
- name: agents
targets:
- path: ` + agentsTarget + `
flatten: true
`)
result := sb.RunCLI("sync", "extras")
result.AssertSuccess(t)
result.AssertAnyOutputContains(t, "3 files")
for _, name := range []string{"tactician.md", "implementer.md", "reviewer.md"} {
if !sb.IsSymlink(filepath.Join(agentsTarget, name)) {
t.Errorf("%s should be a flat symlink in target", name)
}
}
if _, err := os.Stat(filepath.Join(agentsTarget, "curriculum")); !os.IsNotExist(err) {
t.Error("curriculum/ should not exist in target")
}
}
func TestSyncExtras_FlattenCollision(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
sb.CreateSkill("placeholder", map[string]string{
"SKILL.md": "# Placeholder",
})
targetPath := sb.CreateTarget("claude")
sourceRoot := filepath.Dir(sb.SourcePath)
agentsSource := filepath.Join(sourceRoot, "extras", "agents")
os.MkdirAll(filepath.Join(agentsSource, "team-a"), 0755)
os.MkdirAll(filepath.Join(agentsSource, "team-b"), 0755)
os.WriteFile(filepath.Join(agentsSource, "team-a", "agent.md"), []byte("# Team A"), 0644)
os.WriteFile(filepath.Join(agentsSource, "team-b", "agent.md"), []byte("# Team B"), 0644)
agentsTarget := filepath.Join(sb.Home, ".claude", "agents")
os.MkdirAll(agentsTarget, 0755)
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + targetPath + `
extras:
- name: agents
targets:
- path: ` + agentsTarget + `
flatten: true
`)
result := sb.RunCLI("sync", "extras")
result.AssertSuccess(t)
result.AssertAnyOutputContains(t, "flatten conflict")
if !sb.IsSymlink(filepath.Join(agentsTarget, "agent.md")) {
t.Error("agent.md should be a symlink")
}
}
func TestSyncExtras_FlattenConfigRoundTrip(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
sb.CreateSkill("placeholder", map[string]string{
"SKILL.md": "# Placeholder",
})
targetPath := sb.CreateTarget("claude")
agentsTarget := filepath.Join(sb.Home, ".claude", "agents")
sb.WriteConfig(`source: ` + sb.SourcePath + `
targets:
claude:
path: ` + targetPath + `
extras:
- name: agents
targets:
- path: ` + agentsTarget + `
flatten: true
`)
content := sb.ReadFile(sb.ConfigPath)
if !strings.Contains(content, "flatten: true") {
t.Error("config should contain flatten: true")
}
}
+3 -2
View File
@@ -72,6 +72,7 @@ function createSSEStream(
export interface ExtraTarget {
path: string;
mode: string;
flatten: boolean;
status: string; // "synced" | "drift" | "not synced" | "no source"
}
@@ -351,10 +352,10 @@ export const api = {
}),
deleteExtra: (name: string) =>
apiFetch<{ success: boolean }>(`/extras/${encodeURIComponent(name)}`, { method: 'DELETE' }),
setExtraMode: (name: string, target: string, mode: string) =>
setExtraMode: (name: string, target: string, mode: string, flatten?: boolean) =>
apiFetch<{ success: boolean }>(`/extras/${encodeURIComponent(name)}/mode`, {
method: 'PATCH',
body: JSON.stringify({ target, mode }),
body: JSON.stringify({ target, mode, ...(flatten !== undefined && { flatten }) }),
}),
// Log
+5
View File
@@ -105,6 +105,11 @@ export const fieldDocs: Record<string, FieldDoc> = {
allowedValues: ['merge', 'symlink', 'copy'],
example: 'mode: merge',
},
'extras.targets.flatten': {
description: 'When true, files from subdirectories are synced directly into the target root. Cannot be used with symlink mode.',
type: 'boolean',
example: 'flatten: true',
},
// --- Audit ---
audit: {
+46 -9
View File
@@ -23,6 +23,7 @@ import { PageSkeleton } from '../components/Skeleton';
interface TargetEntry {
path: string;
mode: string;
flatten: boolean;
}
const MODE_OPTIONS = [
@@ -41,12 +42,12 @@ function AddExtraModal({
const { toast } = useToast();
const [name, setName] = useState('');
const [source, setSource] = useState('');
const [targets, setTargets] = useState<TargetEntry[]>([{ path: '', mode: 'merge' }]);
const [targets, setTargets] = useState<TargetEntry[]>([{ path: '', mode: 'merge', flatten: false }]);
const [saving, setSaving] = useState(false);
const addTarget = () => setTargets((prev) => [...prev, { path: '', mode: 'merge' }]);
const addTarget = () => setTargets((prev) => [...prev, { path: '', mode: 'merge', flatten: false }]);
const updateTarget = (i: number, field: keyof TargetEntry, value: string) => {
const updateTarget = (i: number, field: keyof TargetEntry, value: string | boolean) => {
setTargets((prev) => prev.map((t, idx) => (idx === i ? { ...t, [field]: value } : t)));
};
@@ -69,7 +70,7 @@ function AddExtraModal({
await api.createExtra({
name: name.trim(),
...(source.trim() && { source: source.trim() }),
targets: validTargets.map((t) => ({ path: t.path.trim(), mode: t.mode })),
targets: validTargets.map((t) => ({ path: t.path.trim(), mode: t.mode, flatten: t.flatten })),
});
toast(`Extra "${name.trim()}" created`, 'success');
onCreated();
@@ -139,10 +140,25 @@ function AddExtraModal({
<div className="w-36 shrink-0">
<Select
value={t.mode}
onChange={(v) => updateTarget(i, 'mode', v)}
onChange={(v) => {
updateTarget(i, 'mode', v);
if (v === 'symlink') updateTarget(i, 'flatten', false);
}}
options={MODE_OPTIONS}
/>
</div>
<label className="flex items-center gap-1.5 shrink-0 cursor-pointer select-none mt-2.5">
<input
type="checkbox"
checked={t.flatten}
onChange={(e) => updateTarget(i, 'flatten', e.target.checked)}
disabled={saving || t.mode === 'symlink'}
className="accent-primary"
/>
<span className={`text-xs ${t.mode === 'symlink' ? 'text-pencil-light/50' : 'text-pencil-light'}`}>
Flatten
</span>
</label>
{targets.length > 1 && (
<IconButton
icon={<X size={16} strokeWidth={2.5} />}
@@ -196,7 +212,7 @@ function ExtraCard({
onSync: (name: string) => Promise<void>;
onForceSync: (name: string) => Promise<void>;
onRemove: (name: string) => void;
onModeChange: (name: string, target: string, mode: string) => Promise<void>;
onModeChange: (name: string, target: string, mode: string, flatten?: boolean) => Promise<void>;
}) {
const [syncing, setSyncing] = useState(false);
const [changingMode, setChangingMode] = useState<string | null>(null);
@@ -293,6 +309,26 @@ function ExtraCard({
{t.status}
</Badge>
</div>
<label className="flex items-center gap-1 shrink-0 cursor-pointer select-none">
<input
type="checkbox"
checked={t.flatten}
onChange={async (e) => {
const newFlatten = e.target.checked;
setChangingMode(t.path);
try {
await onModeChange(extra.name, t.path, t.mode, newFlatten);
} finally {
setChangingMode(null);
}
}}
disabled={changingMode === t.path || t.mode === 'symlink'}
className="accent-primary"
/>
<span className={`text-xs ${t.mode === 'symlink' ? 'text-pencil-light/50' : 'text-pencil-light'}`}>
Flatten
</span>
</label>
<Select
value={t.mode}
onChange={async (v) => {
@@ -437,10 +473,11 @@ export default function ExtrasPage() {
}
};
const handleModeChange = async (name: string, target: string, mode: string) => {
const handleModeChange = async (name: string, target: string, mode: string, flatten?: boolean) => {
try {
await api.setExtraMode(name, target, mode);
toast(`Mode changed to "${mode}"`, 'success');
await api.setExtraMode(name, target, mode, flatten);
const msg = flatten !== undefined ? `Updated (flatten=${flatten})` : `Mode changed to "${mode}"`;
toast(msg, 'success');
invalidate();
} catch (err: any) {
toast(err.message, 'error');