Files
skillshare/internal/server/handler_file_backups_test.go
T
Willie 6e176ddb0c feat(extras): share Markdown memory across agents (#349)
* feat(extras): add shared Markdown memory management

Store user-managed notes in extras/memory for global and project scopes.
Add CLI operations, a nested dashboard browser, versioned edits, and
backup-backed deletion and recovery.

Connect selected agents with reviewed, marked reading guidance while
preserving existing instruction files and routes. Add explicit INDEX
linking, conflict draft comparison, and copy-content previews.

Document the workflow in five website locales with English screenshots
and translate dashboard copy across all eleven locales. Native automatic
memory remains separate from this shared file overlay.

Validation: make check; 22 UI tests; TypeScript and ESLint; production UI
build; six isolated CLI E2E steps; five-locale website build; explicit
Claude-write/fresh-Codex-read smoke test.

* feat(memory): support dashboard note moves and redesign browser

Add version-checked rename and folder moves without replacing existing notes.
Back up the old path and preserve content and permissions while refreshing
selection, search, index warnings, and backup links.

Integrate the two-pane Memory browser and compact agent controls. Refresh all
English screenshots and document move/link/history behavior in five locales.

Validation: make check, scoped UI tests, TypeScript, ESLint, UI production build,
five-locale website build, locale parity, and visible Chrome workflow checks.

* fix(memory): recheck reviewed files before committing changes

Preserve external edits detected after note backup or draft preparation, and create new notes exclusively. Revalidate each guidance file before writing, report stale partial failures, and correct the built-in move/rename documentation.

* fix(memory): repair initialization and preserve note recovery scope

Detect missing starter files before dashboard note creation and refresh the index after initialization. Honor requested backup paths, include external project memory sources in recovery scope, and log initialization failures after partial mutations.

* fix(memory): protect guidance creates and match Windows history paths

Create new reviewed instruction files exclusively to preserve competing writes. Match Windows history links with native backup paths while keeping POSIX names and backup API paths intact.

* fix(memory): require configured extra for external backup access

Keep project backup scope inside the repository unless a valid memory folder extra enables its external source. Cover listing, version preview and restore denial without changing configured-source recovery.

* fix(memory): lock backup scope validation through restore

Validate project memory backup access under the restore write lock so concurrent extra deletion cannot revoke access between validation and writing. Hold read locks across scoped backup reads as well.
2026-10-03 14:16:58 +08:00

250 lines
10 KiB
Go

package server
import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"skillshare/internal/config"
syncpkg "skillshare/internal/sync"
)
type restoreScopeRecorder struct {
*httptest.ResponseRecorder
server *Server
unlocked bool
}
func (w *restoreScopeRecorder) WriteHeader(code int) {
// Scope rejection must be decided while restore owns the configuration lock.
if w.server.mu.TryRLock() {
w.unlocked = true
w.server.mu.RUnlock()
}
w.ResponseRecorder.WriteHeader(code)
}
// seedFileHistory backs up path's current content with reason, then writes
// next as the file's new content.
func seedFileHistory(t *testing.T, path, content, reason, next string) {
t.Helper()
os.MkdirAll(filepath.Dir(path), 0755)
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
t.Fatal(err)
}
if err := syncpkg.BackupFile(path, reason); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(next), 0644); err != nil {
t.Fatal(err)
}
}
func TestFileBackupsAPI_ListVersionsRestore(t *testing.T) {
s, _ := newTestServer(t)
path := filepath.Join(t.TempDir(), "CLAUDE.md")
seedFileHistory(t, path, "# before edit\n", syncpkg.BackupReasonEdit, "# now\n")
rr := serveJSON(t, s, http.MethodGet, "/api/file-backups", "")
var list struct {
Files []struct {
Path string `json:"path"`
Versions int `json:"versions"`
Latest string `json:"latest"`
} `json:"files"`
}
json.Unmarshal(rr.Body.Bytes(), &list)
if rr.Code != http.StatusOK || len(list.Files) != 1 || list.Files[0].Path != path || list.Files[0].Versions != 1 || list.Files[0].Latest == "" {
t.Fatalf("list: %d %s", rr.Code, rr.Body.String())
}
q := "?path=" + url.QueryEscape(path)
rr = serveJSON(t, s, http.MethodGet, "/api/file-backups/versions"+q, "")
var versions struct {
Current struct{ Exists bool } `json:"current"`
Versions []struct {
ID string `json:"id"`
Kind string `json:"kind"`
Reason string `json:"reason"`
Preview string `json:"preview"`
} `json:"versions"`
}
json.Unmarshal(rr.Body.Bytes(), &versions)
if rr.Code != http.StatusOK || !versions.Current.Exists || len(versions.Versions) != 1 {
t.Fatalf("versions: %d %s", rr.Code, rr.Body.String())
}
v := versions.Versions[0]
if v.Kind != "history" || v.Reason != "edit" || v.Preview != "# before edit" {
t.Fatalf("version = %+v", v)
}
rr = serveJSON(t, s, http.MethodGet, "/api/file-backups/version"+q+"&id="+url.QueryEscape(v.ID), "")
if rr.Code != http.StatusOK || !strings.Contains(rr.Body.String(), `"content":"# before edit\n"`) || !strings.Contains(rr.Body.String(), `"current":"# now\n"`) {
t.Fatalf("version: %d %s", rr.Code, rr.Body.String())
}
body, _ := json.Marshal(map[string]string{"path": path, "id": v.ID})
rr = serveJSON(t, s, http.MethodPost, "/api/file-backups/restore", string(body))
if rr.Code != http.StatusOK || !strings.Contains(rr.Body.String(), `"backup_id"`) {
t.Fatalf("restore: %d %s", rr.Code, rr.Body.String())
}
if data, _ := os.ReadFile(path); string(data) != "# before edit\n" {
t.Fatalf("content = %q", data)
}
}
func TestFileBackupsAPI_Errors(t *testing.T) {
s, _ := newTestServer(t)
tmp := t.TempDir()
path := filepath.Join(tmp, "CLAUDE.md")
seedFileHistory(t, path, "old", syncpkg.BackupReasonEdit, "now")
shared := filepath.Join(tmp, "AGENTS.md")
os.WriteFile(shared, []byte("shared"), 0644)
os.Remove(path)
if err := os.Symlink(shared, path); err != nil {
t.Fatal(err)
}
versions, _ := syncpkg.FileBackupVersions(path)
body, _ := json.Marshal(map[string]string{"path": path, "id": versions[0].ID})
rr := serveJSON(t, s, http.MethodPost, "/api/file-backups/restore", string(body))
if rr.Code != http.StatusConflict || !strings.Contains(rr.Body.String(), `"file_backup_is_link"`) {
t.Fatalf("link: %d %s", rr.Code, rr.Body.String())
}
rr = serveJSON(t, s, http.MethodGet, "/api/file-backups/versions?path="+url.QueryEscape(filepath.Join(tmp, "other.md")), "")
if rr.Code != http.StatusNotFound || !strings.Contains(rr.Body.String(), `"file_backup_not_found"`) {
t.Fatalf("unknown path: %d %s", rr.Code, rr.Body.String())
}
rr = serveJSON(t, s, http.MethodGet, "/api/file-backups/version?path="+url.QueryEscape(path)+"&id=../../etc", "")
if rr.Code != http.StatusNotFound {
t.Fatalf("bad id: %d %s", rr.Code, rr.Body.String())
}
}
func TestFileBackupsAPI_ProjectModeHidesOutsideFiles(t *testing.T) {
s, projectRoot := newTestProjectServerWithExtras(t, nil)
inside := filepath.Join(projectRoot, "CLAUDE.md")
outside := filepath.Join(t.TempDir(), "CLAUDE.md")
seedFileHistory(t, inside, "in", syncpkg.BackupReasonShim, "in2")
seedFileHistory(t, outside, "out", syncpkg.BackupReasonEdit, "out2")
rr := serveJSON(t, s, http.MethodGet, "/api/file-backups", "")
if !strings.Contains(rr.Body.String(), inside) || strings.Contains(rr.Body.String(), outside) {
t.Fatalf("list: %s", rr.Body.String())
}
rr = serveJSON(t, s, http.MethodGet, "/api/file-backups/versions?path="+url.QueryEscape(outside), "")
if rr.Code != http.StatusForbidden || !strings.Contains(rr.Body.String(), `"file_backup_outside_project"`) {
t.Fatalf("outside: %d %s", rr.Code, rr.Body.String())
}
}
func TestFileBackupsAPI_ProjectExternalMemorySource(t *testing.T) {
root := filepath.Join(t.TempDir(), "memory")
s, _ := newTestProjectServerWithExtras(t, []config.ExtraConfig{{Name: "memory"}})
s.projectCfg.Sources.Extras = filepath.Dir(root)
if err := s.saveConfig(); err != nil {
t.Fatal(err)
}
path := filepath.Join(root, "wiki", "note.md")
outside := filepath.Join(filepath.Dir(root), "unrelated.md")
seedFileHistory(t, path, "old memory", syncpkg.BackupReasonEdit, "current memory")
seedFileHistory(t, outside, "old unrelated", syncpkg.BackupReasonEdit, "current unrelated")
rr := serveJSON(t, s, http.MethodGet, "/api/file-backups", "")
if rr.Code != http.StatusOK || !strings.Contains(rr.Body.String(), path) || strings.Contains(rr.Body.String(), outside) {
t.Fatalf("list: %d %s", rr.Code, rr.Body)
}
rr = serveJSON(t, s, http.MethodGet, "/api/file-backups/versions?path="+url.QueryEscape(path), "")
if rr.Code != http.StatusOK || !strings.Contains(rr.Body.String(), "old memory") {
t.Fatalf("versions: %d %s", rr.Code, rr.Body)
}
versions, err := syncpkg.FileBackupVersions(path)
if err != nil || len(versions) != 1 {
t.Fatalf("versions: %+v, %v", versions, err)
}
body, _ := json.Marshal(map[string]string{"path": path, "id": versions[0].ID})
rr = serveJSON(t, s, http.MethodPost, "/api/file-backups/restore", string(body))
if rr.Code != http.StatusOK {
t.Fatalf("restore: %d %s", rr.Code, rr.Body)
}
if data, err := os.ReadFile(path); err != nil || string(data) != "old memory" {
t.Fatalf("content: %q, %v", data, err)
}
rr = serveJSON(t, s, http.MethodGet, "/api/file-backups/versions?path="+url.QueryEscape(outside), "")
if rr.Code != http.StatusForbidden {
t.Fatalf("outside: %d %s", rr.Code, rr.Body)
}
}
func TestFileBackupsAPI_ProjectUnconfiguredExternalMemorySource(t *testing.T) {
s, projectRoot := newTestProjectServerWithExtras(t, nil)
s.projectCfg.Sources.Extras = t.TempDir()
if err := s.saveConfig(); err != nil {
t.Fatal(err)
}
inside := filepath.Join(projectRoot, "AGENTS.md")
path := filepath.Join(s.projectCfg.Sources.Extras, "memory", "wiki", "note.md")
seedFileHistory(t, inside, "old rules", syncpkg.BackupReasonEdit, "current rules")
seedFileHistory(t, path, "old external", syncpkg.BackupReasonEdit, "current external")
versions, err := syncpkg.FileBackupVersions(path)
if err != nil || len(versions) != 1 {
t.Fatalf("versions: %+v, %v", versions, err)
}
rr := serveJSON(t, s, http.MethodGet, "/api/file-backups", "")
if rr.Code != http.StatusOK || !strings.Contains(rr.Body.String(), inside) || strings.Contains(rr.Body.String(), path) {
t.Fatalf("list: %d %s", rr.Code, rr.Body)
}
q := "?path=" + url.QueryEscape(path)
for _, route := range []string{"/api/file-backups/versions" + q, "/api/file-backups/version" + q + "&id=" + url.QueryEscape(versions[0].ID)} {
rr = serveJSON(t, s, http.MethodGet, route, "")
if rr.Code != http.StatusForbidden || !strings.Contains(rr.Body.String(), `"file_backup_outside_project"`) {
t.Errorf("%s: %d %s", route, rr.Code, rr.Body)
}
}
body, _ := json.Marshal(map[string]string{"path": path, "id": versions[0].ID})
rr = serveJSON(t, s, http.MethodPost, "/api/file-backups/restore", string(body))
if rr.Code != http.StatusForbidden || !strings.Contains(rr.Body.String(), `"file_backup_outside_project"`) {
t.Errorf("restore: %d %s", rr.Code, rr.Body)
}
if data, err := os.ReadFile(path); err != nil || string(data) != "current external" {
t.Fatalf("external content: %q, %v", data, err)
}
}
func TestFileBackupsAPI_RestoreValidatesScopeUnderWriteLock(t *testing.T) {
s, _ := newTestProjectServerWithExtras(t, []config.ExtraConfig{{Name: "memory"}})
s.projectCfg.Sources.Extras = t.TempDir()
path := filepath.Join(s.projectCfg.Sources.Extras, "memory", "note.md")
seedFileHistory(t, path, "old external", syncpkg.BackupReasonEdit, "current external")
versions, err := syncpkg.FileBackupVersions(path)
if err != nil || len(versions) != 1 {
t.Fatalf("versions: %+v, %v", versions, err)
}
// A preflight check must not authorize a later restore after configuration changes.
preflight := httptest.NewRecorder()
s.mu.RLock()
_, allowed := s.fileBackupPath(preflight, path)
s.mu.RUnlock()
if !allowed {
t.Fatalf("preflight: %d %s", preflight.Code, preflight.Body)
}
rr := serveJSON(t, s, http.MethodDelete, "/api/extras/memory", "")
if rr.Code != http.StatusOK {
t.Fatalf("delete extra: %d %s", rr.Code, rr.Body)
}
body, _ := json.Marshal(map[string]string{"path": path, "id": versions[0].ID})
w := &restoreScopeRecorder{ResponseRecorder: httptest.NewRecorder(), server: s}
s.handleRestoreFileBackup(w, httptest.NewRequest(http.MethodPost, "/api/file-backups/restore", strings.NewReader(string(body))))
if w.Code != http.StatusForbidden || w.unlocked {
t.Fatalf("restore scope was not rejected under write lock: %d, unlocked=%v, %s", w.Code, w.unlocked, w.Body)
}
if data, err := os.ReadFile(path); err != nil || string(data) != "current external" {
t.Fatalf("external content: %q, %v", data, err)
}
}