Files
skillshare/internal/server/handler_hooks_test.go
ed3c825c49 feat(hooks): record Codex hook trust on sync with --trust (#829)
* feat(hooks): record Codex hook trust on sync with --trust

Codex runs a user-level hook only after its trusted_hash is stored in that
home's config.toml, keyed by the hook's position in hooks.json. Only the
TUI's /hooks review writes it, so every hook Skillshare adds or moves starts
untrusted and codex exec skips it without a word.

`hooks sync --trust` (global mode, opt-in) asks each Codex home's
`codex app-server` for the current hash of the hooks Skillshare owns and
writes trusted_hash through config/batchWrite, the same calls /hooks makes,
so the hash is always the one Codex computes. It changes nothing else in
config.toml: disabled hooks stay disabled and are reported. Trust it wrote
is remembered in the hooks state directory, so when a hook moves or is
removed the next --trust sync clears the old position, unless that trust
has changed since. Without codex on PATH the hook files are still written
and the command fails saying trust was not recorded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(hooks): scope Codex trust to config owner

Scope trust selection and saved hashes to the active config owner so a global config cannot trust or reconcile another config’s hooks.

Recheck hooks.json after hooks/list to avoid trusting a handler from a stale position, and only report trusted or cleared actions after config/batchWrite succeeds. Keep v1 ownerless hashes cleanup-only so upgraded installs clear stale trust after hook removal without trusting foreign hooks.

* fix(hooks): retain parked Codex trust receipts

Locate hooks using all records for their canonical file before selecting the active config owner, so identical hooks remain identifiable across shared and symlinked homes. Keep cleanup receipts for parked registrations whose native group still matches, including when duplicate counts make locate ambiguous, while clearing receipts for removed hooks.

Add regressions for identical hooks across config owners, symlink aliases, parked-home restoration, ambiguous duplicates, and stale receipt cleanup.

* fix(hooks): coalesce symlinked Codex trust homes

Canonicalize current-owner and legacy trust receipts so symlink spellings of one hooks.json are processed once. Remove the redundant parked-position branch because the hash-matching fallback below covers it. Add regression coverage for current and legacy receipts.

* fix(hooks): coalesce removed Codex hook homes

Resolve existing home directories when hook files have been removed so trust receipts for symlink aliases reconcile once. Correct canonical key expectations and exercise coalescing without unsupported ledger migration.

* fix(hooks): read reconciled trust fixture into fresh state

JSON decoding retains existing map entries, so reusing the seeded receipt map makes the alias appear to survive reconciliation. Decode the persisted state into a new value to verify its actual contents.

* feat(hooks): confirm Codex trust before recording it and drop the receipts file

`hooks sync --trust` recorded trust for every owned hook without showing
what it was trusting, and tracked its own writes in codex-trust.json so
it could clear them later. Codex's review exists so that a person sees a
command before it runs, and the receipts file was the source of most of
the edge cases found in review.

Trust is now two steps. A preview asks Codex which owned hooks are new
or changed and returns them with their commands and a revision; the
write takes that revision and is refused when the hooks changed since.
The CLI lists the hooks and asks once, `--yes` skips the question, and
without a terminal nothing is trusted unless `--yes` is given. The
dashboard gets the same two steps as API routes.

Nothing is cleared any more: a leftover entry only matches a hook with
the same event, matcher and handler at that position, which is the hook
the user already approved. That removes codex-trust.json.

The app-server is started without CODEX_HOME for the default home.
Codex resolves the symlinks of CODEX_HOME but not of ~/.codex, so a
symlinked default home got a trust key the user's own Codex never looks
up.

A home whose write fails no longer stops the other homes, and the error
names which were recorded. A preview releases the hooks operation lock
before it waits on Codex, so a slow Codex does not fail other hooks
operations.

Refs #828

* feat(ui): trust Codex hooks from the Hooks page

The dashboard could sync Codex hooks but left them untrusted, so Codex
skipped them until the user ran the CLI or approved each one in Codex.

The Sync box now offers "Trust Codex hooks" in the global scope when a
hook is bound to a Codex target. The dialog shows each hook that needs
trust with its full command and records trust for exactly that list; a
change since the list was shown is refused. The button is hidden while
changes are pending, because trust covers the hooks on disk and the next
sync would invalidate it.

Refs #828

* test(ui): cover the Codex trust dialog's refused, empty and disabled states

Only the happy path was tested, so a regression in the states where the
dialog must not offer a write would have passed. The docs sentence on
several Codex homes now says what is isolated: a failed write, not a
home that cannot be listed.

Refs #828

* refactor(hooks): split the trust prompt and output rendering out of the handlers

hooks_handlers.go had grown past 500 lines and mixed orchestration with
the confirmation prompt and every print function, which the CLI layering
rule asks to keep apart. The code is moved unchanged: the prompt goes to
hooks_prompt.go and the printing to hooks_render.go.

* fix(hooks): leave out a Codex home that cannot be listed instead of stopping

With several Codex homes, one home Codex could not list aborted the whole
trust run, so a broken account home kept every other home untrusted.

A home that fails to list is now reported and left out, and the other
homes are previewed and trusted as usual. The CLI warns before the
question and exits with an error that names the home; the dashboard
dialog shows the same note. When no home can be listed the preview still
fails.

Codex answers a home it cannot load, such as one with an invalid
config.toml, with a successful reply that has no hooks and the reason in
`errors`. That was read as a home without hooks and passed silently. It
is now a failed listing that carries Codex's own message.

Refs #828

* fix(hooks): check the reviewed Codex hooks per home when recording trust

The revision was one digest over every home's hooks. When a home was
listed in the preview but failed to list again at the write, its hooks
dropped out of the digest, so the write was refused as stale: the homes
the user had just reviewed stayed untrusted and the real listing error
was hidden behind "changed since they were listed".

The revision now has one part per home. A home is refused only when its
own hooks changed; a home that cannot be listed any more is reported and
the reviewed homes are still trusted.

Refs #828

* chore: release as 0.30.10

Keep the next release on the patch version the maintainer asked for,
instead of the 0.31.0 that Release Please derives from the feat commit.

Release-As: 0.30.10

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Willie <egg358358@gmail.com>
2026-11-17 15:54:20 +08:00

453 lines
19 KiB
Go

package server
import (
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"skillshare/internal/hooks"
"skillshare/internal/oplog"
)
const hooksTestMutation = `{"name":"bash-log","entry":{"bindings":{"claude":{"events":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"echo skillshare-hooks-test"}]}]}}}}}`
func hooksTestHome(t *testing.T) string {
t.Helper()
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("CLAUDE_CONFIG_DIR", "")
return home
}
func hooksPost(s *Server, handler http.HandlerFunc, path, body string) *httptest.ResponseRecorder {
w := httptest.NewRecorder()
handler(w, httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)))
return w
}
// hooksPreviewRevision previews the mutation and returns its revision.
func hooksPreviewRevision(t *testing.T, s *Server, mutation string) string {
t.Helper()
w := hooksPost(s, s.handleHooksPreview, "/api/hooks/preview", `{"mutation":`+mutation+`}`)
var p struct {
Revision string `json:"revision"`
}
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &p) != nil || p.Revision == "" {
t.Fatalf("preview: %d %s", w.Code, w.Body)
}
return p.Revision
}
func TestHooksAPIPreviewThenApply(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
home := hooksTestHome(t)
settings := filepath.Join(home, ".claude", "settings.json")
revision := hooksPreviewRevision(t, s, hooksTestMutation)
if _, err := os.Stat(settings); !os.IsNotExist(err) {
t.Fatal("preview wrote native configuration")
}
w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+hooksTestMutation+`,"revision":"`+revision+`","sync":true}`)
if w.Code != http.StatusOK {
t.Fatalf("apply: %d %s", w.Code, w.Body)
}
data, err := os.ReadFile(settings)
if err != nil || !strings.Contains(string(data), "skillshare-hooks-test") {
t.Fatalf("apply did not write Claude settings: %v %s", err, data)
}
list := httptest.NewRecorder()
s.handleHooksList(list, httptest.NewRequest(http.MethodGet, "/api/hooks", nil))
var view struct {
Source struct {
Entries map[string]json.RawMessage `json:"entries"`
} `json:"source"`
}
if list.Code != http.StatusOK || json.Unmarshal(list.Body.Bytes(), &view) != nil || view.Source.Entries["bash-log"] == nil {
t.Fatalf("list: %d %s", list.Code, list.Body)
}
}
func TestHooksAPIProjectModeWritesProjectFiles(t *testing.T) {
s, root := newTestProjectServerWithExtras(t, nil)
home := hooksTestHome(t)
revision := hooksPreviewRevision(t, s, hooksTestMutation)
w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+hooksTestMutation+`,"revision":"`+revision+`","sync":true}`)
if w.Code != http.StatusOK {
t.Fatalf("apply: %d %s", w.Code, w.Body)
}
if data, err := os.ReadFile(filepath.Join(root, ".claude", "settings.json")); err != nil || !strings.Contains(string(data), "skillshare-hooks-test") {
t.Fatalf("project apply did not write project settings: %v", err)
}
if _, err := os.Stat(filepath.Join(home, ".claude", "settings.json")); !os.IsNotExist(err) {
t.Fatal("project apply wrote global settings")
}
}
func TestHooksAPIRejectsUnpreviewedOrStaleSaves(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
hooksTestHome(t)
missing := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+hooksTestMutation+`,"sync":true}`)
if missing.Code != http.StatusBadRequest {
t.Fatalf("save without revision: %d %s", missing.Code, missing.Body)
}
stale := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+hooksTestMutation+`,"revision":"stale","sync":true}`)
if stale.Code != http.StatusConflict {
t.Fatalf("stale revision: %d %s", stale.Code, stale.Body)
}
}
func TestHooksAPIRejectsMalformedRequests(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
hooksTestHome(t)
for _, tc := range []struct {
name string
handler http.HandlerFunc
body string
}{
{"unknown field", s.handleHooksPreview, `{"mutation":{},"extra":true}`},
{"two documents", s.handleHooksPreview, `{"mutation":{}}{"mutation":{}}`},
{"import unknown field", s.handleHooksImport, `{"from":"claude","piExtension":"builtin"}`},
{"restore without backup", s.handleHooksRestore, `{"preview":true}`},
{"restore without preview", s.handleHooksRestore, `{"backupId":"x"}`},
} {
if w := hooksPost(s, tc.handler, "/", tc.body); w.Code != http.StatusBadRequest {
t.Errorf("%s: %d %s", tc.name, w.Code, w.Body)
}
}
large := hooksPost(s, s.handleHooksPreview, "/", `{"mutation":{"name":"`+strings.Repeat("x", int(defaultJSONBodyLimit))+`"}}`)
if large.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("oversized body: %d", large.Code)
}
}
func TestHooksAPIImportListsCandidatesWithoutExecuting(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
home := hooksTestHome(t)
marker := filepath.Join(t.TempDir(), "executed")
settings := filepath.Join(home, ".claude", "settings.json")
if err := os.MkdirAll(filepath.Dir(settings), 0755); err != nil {
t.Fatal(err)
}
native := `{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"touch ` + marker + `"}]}]}}`
if err := os.WriteFile(settings, []byte(native), 0644); err != nil {
t.Fatal(err)
}
w := hooksPost(s, s.handleHooksImport, "/api/hooks/import", `{"from":"claude"}`)
var result struct {
Candidates []struct {
Name string `json:"name"`
} `json:"candidates"`
}
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &result) != nil || len(result.Candidates) == 0 {
t.Fatalf("import: %d %s", w.Code, w.Body)
}
if _, err := os.Stat(marker); !os.IsNotExist(err) {
t.Fatal("import executed a hook command")
}
}
// Trust is recorded only for a reviewed list, and only in global Codex homes.
func TestHooksCodexTrustNeedsARevisionAndGlobalScope(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
hooksTestHome(t)
if w := hooksPost(s, s.handleHooksCodexTrust, "/api/hooks/codex-trust", `{}`); w.Code != http.StatusBadRequest {
t.Fatalf("trust without revision: %d %s", w.Code, w.Body)
}
s.projectRoot = t.TempDir()
if w := hooksPost(s, s.handleHooksCodexTrustPreview, "/api/hooks/codex-trust/preview", `{}`); w.Code != http.StatusBadRequest {
t.Fatalf("project preview: %d %s", w.Code, w.Body)
}
if w := hooksPost(s, s.handleHooksCodexTrust, "/api/hooks/codex-trust", `{"revision":"x"}`); w.Code != http.StatusBadRequest {
t.Fatalf("project trust: %d %s", w.Code, w.Body)
}
}
func TestHooksRoutesRejectRebindingHost(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
s.addr = "127.0.0.1:19420"
for _, route := range []string{"GET /api/hooks", "POST /api/hooks", "POST /api/hooks/preview", "POST /api/hooks/render", "POST /api/hooks/import", "POST /api/hooks/native", "POST /api/hooks/native/preview", "POST /api/hooks/restore", "POST /api/hooks/codex-trust/preview", "POST /api/hooks/codex-trust", "GET /api/hooks/catalog"} {
method, path, _ := strings.Cut(route, " ")
req := httptest.NewRequest(method, path, strings.NewReader(`{}`))
req.RemoteAddr = "127.0.0.1:5555"
req.Host = "attacker.example:19420"
w := httptest.NewRecorder()
s.mux.ServeHTTP(w, req)
if w.Code != http.StatusForbidden {
t.Fatalf("%s: status = %d, want 403", route, w.Code)
}
}
}
func TestHooksAPIRenderShowsOneHookWithoutWriting(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
home := hooksTestHome(t)
config := readOrEmpty(s.configPath())
root := t.TempDir()
for _, tc := range []struct{ mutation, path string }{
{hooksTestMutation, filepath.Join(home, ".claude", "settings.json")},
{hooksProjectEntry(root, "guard", "echo skillshare-hooks-test"), filepath.Join(root, ".claude", "settings.json")},
} {
w := hooksPost(s, s.handleHooksRender, "/api/hooks/render", `{"mutation":`+tc.mutation+`}`)
var body struct {
Rendered []struct {
Target, Path, Content, Error string
} `json:"rendered"`
}
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &body) != nil || len(body.Rendered) != 1 {
t.Fatalf("render: %d %s", w.Code, w.Body)
}
f := body.Rendered[0]
if f.Target != "claude" || f.Path != tc.path || f.Error != "" || !strings.Contains(f.Content, `"hooks"`) || !strings.Contains(f.Content, "skillshare-hooks-test") {
t.Fatalf("rendered: %+v", f)
}
if _, err := os.Stat(tc.path); !os.IsNotExist(err) {
t.Fatal("render wrote native configuration")
}
}
if readOrEmpty(s.configPath()) != config {
t.Fatal("render must not save the source")
}
if entries, _ := oplog.Read(s.configPath(), oplog.OpsFile, 10); len(entries) != 0 {
t.Fatalf("render must not write the operations log: %+v", entries)
}
}
func TestHooksAPIRenderRejectsNonRenderRequests(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
hooksTestHome(t)
for _, body := range []string{
`{"mutation":` + hooksTestMutation + `,"revision":"x"}`,
`{"mutation":{"name":"bash-log","remove":true}}`,
`{"mutation":{"name":"bash-log"}}`,
`{"mutation":{"entry":{"bindings":{}}}}`,
`{"mutation":` + strings.Replace(hooksTestMutation, `"name"`, `"replace":true,"name"`, 1) + `}`,
`{"mutation":` + hooksTestMutation + `}{}`,
} {
if w := hooksPost(s, s.handleHooksRender, "/api/hooks/render", body); w.Code != http.StatusBadRequest {
t.Fatalf("%s: status %d %s", body, w.Code, w.Body)
}
}
}
// hooksSave previews and saves a mutation to the source without syncing.
func hooksSave(t *testing.T, s *Server, mutation string) {
t.Helper()
revision := hooksPreviewRevision(t, s, mutation)
if w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+mutation+`,"revision":"`+revision+`"}`); w.Code != http.StatusOK {
t.Fatalf("save %s: %d %s", mutation, w.Code, w.Body)
}
}
func hooksProjectEntry(root, name, command string) string {
return `{"project":"` + root + `","name":"` + name + `","entry":{"bindings":{"claude":{"events":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"` + command + `"}]}]}}}}}`
}
func readOrEmpty(path string) string {
data, _ := os.ReadFile(path)
return string(data)
}
func TestHooksAPIProjectSyncAppliesOnlyThatRoot(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
home := hooksTestHome(t)
rootA, rootB := t.TempDir(), t.TempDir()
settingsA := filepath.Join(rootA, ".claude", "settings.json")
if err := os.MkdirAll(filepath.Dir(settingsA), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(settingsA, []byte(`{"theme":"dark"}`), 0644); err != nil {
t.Fatal(err)
}
hooksSave(t, s, hooksProjectEntry(rootA, "a", "echo hook-a"))
hooksSave(t, s, hooksProjectEntry(rootB, "b", "echo hook-b"))
hooksSave(t, s, hooksTestMutation)
revision := hooksPreviewRevision(t, s, `{}`)
w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":{},"revision":"`+revision+`","sync":true,"root":"`+rootA+`"}`)
if w.Code != http.StatusOK {
t.Fatalf("project sync: %d %s", w.Code, w.Body)
}
if got := readOrEmpty(settingsA); !strings.Contains(got, "echo hook-a") || !strings.Contains(got, `"theme"`) {
t.Fatalf("root A not synced with its settings kept:\n%s", got)
}
if got := readOrEmpty(filepath.Join(rootB, ".claude", "settings.json")); got != "" {
t.Fatalf("syncing root A wrote root B:\n%s", got)
}
if got := readOrEmpty(filepath.Join(home, ".claude", "settings.json")); got != "" {
t.Fatalf("syncing root A wrote the global settings:\n%s", got)
}
stale := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":{},"revision":"`+revision+`","sync":true,"root":"`+rootB+`"}`)
if stale.Code != http.StatusConflict {
t.Fatalf("reused revision: %d %s", stale.Code, stale.Body)
}
hooksSave(t, s, `{"project":"`+rootA+`","name":"a","remove":true}`)
revision = hooksPreviewRevision(t, s, `{}`)
if w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":{},"revision":"`+revision+`","sync":true,"root":"`+rootA+`"}`); w.Code != http.StatusOK {
t.Fatalf("prune sync: %d %s", w.Code, w.Body)
}
if got := readOrEmpty(settingsA); strings.Contains(got, "echo hook-a") || !strings.Contains(got, `"theme"`) {
t.Fatalf("prune did not remove only the owned hook:\n%s", got)
}
if got := readOrEmpty(filepath.Join(rootB, ".claude", "settings.json")); got != "" {
t.Fatalf("pruning root A wrote root B:\n%s", got)
}
}
func TestHooksAPIProjectSyncRejectsInvalidRoot(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
hooksTestHome(t)
root := t.TempDir()
hooksSave(t, s, hooksProjectEntry(root, "a", "echo hook-a"))
revision := hooksPreviewRevision(t, s, `{}`)
for name, body := range map[string]string{
"with changes": `{"mutation":{"name":"a","remove":true},"revision":"` + revision + `","sync":true,"root":"` + root + `"}`,
"without sync": `{"mutation":{},"revision":"` + revision + `","root":"` + root + `"}`,
"unknown root": `{"mutation":{},"revision":"` + revision + `","sync":true,"root":"` + t.TempDir() + `"}`,
} {
if w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", body); w.Code != http.StatusBadRequest {
t.Errorf("%s: %d %s", name, w.Code, w.Body)
}
}
project, _ := newTestProjectServerWithExtras(t, nil)
revision = hooksPreviewRevision(t, project, `{}`)
w := hooksPost(project, project.handleHooksConfigure, "/api/hooks", `{"mutation":{},"revision":"`+revision+`","sync":true,"root":"`+root+`"}`)
if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), "global mode") {
t.Fatalf("project mode root: %d %s", w.Code, w.Body)
}
}
func TestHooksAPIImportReadsProjectRoot(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
hooksTestHome(t)
root := t.TempDir()
hooksSave(t, s, `{"project":"`+root+`"}`)
settings := filepath.Join(root, ".claude", "settings.json")
if err := os.MkdirAll(filepath.Dir(settings), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(settings, []byte(`{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"echo project-native"}]}]}}`), 0644); err != nil {
t.Fatal(err)
}
w := hooksPost(s, s.handleHooksImport, "/api/hooks/import", `{"from":"claude","root":"`+root+`"}`)
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "project-native") {
t.Fatalf("project import: %d %s", w.Code, w.Body)
}
global := hooksPost(s, s.handleHooksImport, "/api/hooks/import", `{"from":"claude"}`)
if global.Code != http.StatusOK || strings.Contains(global.Body.String(), "project-native") {
t.Fatalf("global import read the project file: %d %s", global.Code, global.Body)
}
if w := hooksPost(s, s.handleHooksImport, "/api/hooks/import", `{"from":"claude","root":"`+t.TempDir()+`"}`); w.Code != http.StatusBadRequest {
t.Fatalf("unknown import root: %d %s", w.Code, w.Body)
}
}
func TestHooksAPICatalogListsCommandAgentEvents(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
w := httptest.NewRecorder()
s.handleHooksCatalog(w, httptest.NewRequest(http.MethodGet, "/api/hooks/catalog", nil))
var catalog map[string]struct {
Events []struct {
Name string `json:"name"`
Description string `json:"description"`
Matcher bool `json:"matcher"`
} `json:"events"`
TimeoutUnit string `json:"timeoutUnit"`
}
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &catalog) != nil {
t.Fatalf("catalog: %d %s", w.Code, w.Body)
}
if c := catalog["gemini"]; c.TimeoutUnit != "milliseconds" || len(c.Events) == 0 || c.Events[0].Description == "" {
t.Fatalf("gemini catalog: %+v", c)
}
if _, ok := catalog["pi"]; ok {
t.Fatal("code Agents have no event catalog")
}
}
func TestHooksAPIImportSaveTakesOverWithoutReplace(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
home := hooksTestHome(t)
settings := filepath.Join(home, ".claude", "settings.json")
native := `{"model":"opus","hooks":{"Stop":[{"hooks":[{"type":"command","command":"echo stop"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"echo guard"}]}]}}`
if err := os.MkdirAll(filepath.Dir(settings), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(settings, []byte(native), 0644); err != nil {
t.Fatal(err)
}
w := hooksPost(s, s.handleHooksImport, "/api/hooks/import", `{"from":"claude","name":"claude-stop"}`)
var imported struct {
Candidates []struct {
Entry json.RawMessage `json:"entry"`
} `json:"candidates"`
}
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &imported) != nil || len(imported.Candidates) != 1 {
t.Fatalf("import: %d %s", w.Code, w.Body)
}
mutation := `{"name":"claude-stop","entry":` + string(imported.Candidates[0].Entry) + `,"adopt":true}`
revision := hooksPreviewRevision(t, s, mutation)
if w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+mutation+`,"revision":"`+revision+`","sync":false}`); w.Code != http.StatusOK {
t.Fatalf("save: %d %s", w.Code, w.Body)
}
preview := hooksPost(s, s.handleHooksPreview, "/api/hooks/preview", `{"mutation":{}}`)
var plan struct {
Blocked bool `json:"blocked"`
Changes []struct {
Action string `json:"action"`
} `json:"changes"`
}
if json.Unmarshal(preview.Body.Bytes(), &plan) != nil || plan.Blocked || len(plan.Changes) != 1 || plan.Changes[0].Action != "adopt" {
t.Fatalf("sync after an imported save: %s", preview.Body)
}
}
func TestHooksAPIPreviewCarriesFileTexts(t *testing.T) {
s, _ := newTestServerWithExtras(t, nil, "")
home := hooksTestHome(t)
w := hooksPost(s, s.handleHooksPreview, "/api/hooks/preview", `{"mutation":`+hooksTestMutation+`}`)
var p struct {
Revision string `json:"revision"`
Files []struct {
Target, Path, Before, After string
} `json:"files"`
}
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &p) != nil || len(p.Files) != 1 {
t.Fatalf("preview: %d %s", w.Code, w.Body)
}
f := p.Files[0]
if f.Target != "claude" || f.Path != filepath.Join(home, ".claude", "settings.json") || f.Before != "" || !strings.Contains(f.After, "skillshare-hooks-test") {
t.Fatalf("file diff: %+v", f)
}
if w := hooksPost(s, s.handleHooksConfigure, "/api/hooks", `{"mutation":`+hooksTestMutation+`,"revision":"`+p.Revision+`","sync":true}`); w.Code != http.StatusOK {
t.Fatalf("apply: %d %s", w.Code, w.Body)
}
if data, _ := os.ReadFile(f.Path); string(data) != f.After {
t.Fatalf("written file differs from the preview:\n%s", data)
}
}
// A write that failed part-way names the files it already wrote, so the dashboard keeps the rest pending.
func TestWriteHooksFailure_ListsAppliedFiles(t *testing.T) {
w := httptest.NewRecorder()
writeHooksFailure(w, &hooks.Result{Applied: []string{"/a/settings.json"}, BackupIDs: []string{"b1"}}, errors.New("write failed"))
var body struct {
Params struct {
Applied []string `json:"applied"`
} `json:"error_params"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || w.Code != http.StatusConflict || len(body.Params.Applied) != 1 || body.Params.Applied[0] != "/a/settings.json" {
t.Fatalf("want the applied file in error_params: %d %s", w.Code, w.Body)
}
}