Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

feat(hooks): install DeepSeek Harness endpoint hooks

Claudea7fe3aafb1a6
diff --git a/cli/beacon/internal/endpoint/hooks/dsh.go b/cli/beacon/internal/endpoint/hooks/dsh.go
new file mode 100644
index 00000000..1368c3e4
--- /dev/null
+++ b/cli/beacon/internal/endpoint/hooks/dsh.go
@@ -0,0 +1,411 @@
+package hooks
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+// DeepSeek Harness is the one supported runtime where installing hooks takes two files, because
+// the runtime does not read a hooks file until something tells it to.
+//
+// `dsh` runs Claude Code hooks through `@deepseek-ai/dsh-hooks-claude-code`, a bridge DeepSeek
+// ships as a dependency of the CLI but does not mount. Nothing is loaded by convention: the
+// harness composes itself from a plugin tree, and a plugin that is not in the tree does not exist.
+// So Beacon writes
+//
+// 1. `$DSH_HOME/beacon-endpoint-hooks.json` -- a Claude Code hooks file Beacon owns outright, and
+// 2. one row in `$DSH_HOME/cordis.patch.yml` mounting the bridge at that file.
+//
+// The second file is the interesting one and it is not Beacon's. It is the user's own tweak layer,
+// applied over every profile, and it may already carry their rows, their comments and `!!js`
+// expressions evaluated at boot. So it is edited as a document rather than rewritten: parsed into
+// a yaml.Node, one element appended or removed, re-encoded. yaml.v3 preserves comments, quoting
+// style and custom tags through that round trip, which is what makes editing a live user file
+// defensible at all.
+//
+// Two properties of that file are load-bearing and neither is obvious:
+//
+// - An empty or comments-only patch file FAILS BOOT. It is not ignored and it is not a warning:
+// `dsh` refuses to start. So an uninstall that removes Beacon's last row must remove the file,
+// not truncate it -- an absent patch layer is fine, an empty one is not.
+//
+// - The home-level file outranks the per-profile one and applies to every profile. That is why
+// Beacon installs here rather than into `profiles/web/cordis.patch.yml`: one install covers the
+// CLI, Web, ACP and SDK surfaces, which are four compositions of one harness rather than four
+// products.
+//
+// There is no project scope, and its absence is a property of the runtime rather than a decision
+// here. The bridge's `configPath` is process-level -- read once at startup, resolved against the
+// launch directory -- and the bridge's own source records per-session discovery of a project-local
+// hooks file as unimplemented. There is nowhere for a repository to put one, so dshHooksPath
+// refuses the level with that explanation instead of writing a file nothing would read.
+//
+// Beacon owns its filename in the first file and its row id in the second, and refuses rather than
+// overwriting anything it did not write.
+
+const (
+ // dshHookFileName is the Claude Code hooks file Beacon owns. It sits beside cordis.patch.yml
+ // in the Harness home, which is also how the patch path is derived from it.
+ dshHookFileName = "beacon-endpoint-hooks.json"
+
+ // dshPatchFileName is the home-level user patch layer, applied over every profile. The name is
+ // the runtime's, not Beacon's choice.
+ dshPatchFileName = "cordis.patch.yml"
+
+ // dshBridgePackage is the plugin that runs Claude Code hooks against the harness's extension
+ // points. It ships as a dependency of the `dsh` CLI, so mounting it needs no install step --
+ // the row alone activates it, the same way the runtime's own webhook overlay works.
+ dshBridgePackage = "@deepseek-ai/dsh-hooks-claude-code"
+
+ // dshPatchEntryID identifies Beacon's row.
+ //
+ // Unlike every other runtime's detection, this is matched on an id rather than on the hook
+ // command -- the row carries no command, because the commands live in the hooks file it points
+ // at. That is sound here rather than a compromise: the loader itself diffs entries by `id`, so
+ // this string is load-bearing to the runtime and not a label a user would edit for cosmetic
+ // reasons. The hook commands are still what `dshHasEndpointHooks` checks in the other file, so
+ // an install is only reported complete when both halves are.
+ dshPatchEntryID = "beacon-endpoint-hooks"
+
+ // dshEnvHome is the environment variable that moves the Harness home. On a machine that sets
+ // it, ~/.dsh is not where dsh looks, so an install that ignored it would write two files
+ // nothing reads.
+ dshEnvHome = "DSH_HOME"
+
+ // dshHomeDirName is the default Harness home under the user's home directory.
+ dshHomeDirName = ".dsh"
+)
+
+// dsh hook timeouts are seconds -- the bridge reads a hook's `timeout` as `timeoutSec`, matching
+// Claude Code, and applies 600 seconds when one is absent.
+//
+// Stated at the value for the reason the Kiro, Muse, Qwen and OpenHands constants give: the same
+// `timeout` field means milliseconds on some runtimes and seconds here, the files look alike, and
+// getting it wrong kills every hook mid-write while the install still reports success. Explicit
+// values rather than the inherited default because ten minutes is a very long time to hold an
+// agent turn for a telemetry hook that finishes in milliseconds -- these are ceilings on a hang,
+// not budgets.
+//
+// The two long ones are long for a reason: the closing event flushes cloud telemetry, which has a
+// ten-second timeout of its own, and prompt submission does the heavier session bookkeeping.
+const (
+ dshSessionStartTimeoutSeconds = 10
+ dshPromptSubmitTimeoutSeconds = 30
+ dshToolTimeoutSeconds = 10
+ dshStopTimeoutSeconds = 45
+ dshSubagentTimeoutSeconds = 10
+)
+
+// dshEvent binds one bridge event to the beacon-hooks subcommand that maps it.
+type dshEvent struct {
+ name string
+ subcommand string
+ timeout int
+}
+
+// dshEvents are every event the bridge supports.
+//
+// All seven, which is unusual -- most installers leave something out. Here there is nothing to
+// leave out: the bridge supports exactly these, and each one maps onto a subcommand Beacon already
+// has. The 23 Claude Code events it does not support are not a choice Beacon makes; config for
+// them is discarded before the bridge's parser sees it, so writing them would be writing
+// instructions that are silently dropped.
+//
+// Stop is per turn rather than per session, and there is no SessionEnd on this runtime, so it is
+// the closing event -- the same shape as Kiro.
+var dshEvents = []dshEvent{
+ {"SessionStart", "session-start", dshSessionStartTimeoutSeconds},
+ {"UserPromptSubmit", "prompt-submit", dshPromptSubmitTimeoutSeconds},
+ {"PreToolUse", "pre-tool", dshToolTimeoutSeconds},
+ {"PostToolUse", "post-tool", dshToolTimeoutSeconds},
+ {"Stop", "stop", dshStopTimeoutSeconds},
+ {"SubagentStart", "subagent-start", dshSubagentTimeoutSeconds},
+ {"SubagentStop", "subagent-stop", dshSubagentTimeoutSeconds},
+}
+
+type DshOptions struct {
+ Level Level
+ LogPath string
+ UserMode bool
+}
+
+type DshStatus struct {
+ Installed bool `json:"installed"`
+ BinaryPath string `json:"binary_path,omitempty"`
+ HooksPath string `json:"hooks_path,omitempty"`
+ PatchPath string `json:"patch_path,omitempty"`
+ Message string `json:"message,omitempty"`
+}
+
+// dshHooksFile is the Claude Code hooks document Beacon writes: a bare event map.
+//
+// Bare rather than wrapped in a `hooks` key. The bridge accepts either -- it reads `root.hooks` and
+// falls back to the root itself -- and the bare form is unambiguous here because every key is an
+// event name. It is also its own type rather than the shared settingsHook* ones, for the reason
+// the Muse and Kiro types give: a field added to a shared struct for another runtime would silently
+// change what Beacon emits here.
+type dshHooksFile map[string][]dshHookGroup
+
+// dshHookGroup is one matcher group. `matcher` is absent by construction.
+//
+// Absent means match-all in this dialect, which is what a telemetry hook wants on every event. It
+// is not written as `"*"` even though that is also a match-all sentinel: the bridge validates a
+// matcher at parse time and rejects the whole config on an invalid one, so the value that needs no
+// validating is the safer one to write.
+type dshHookGroup struct {
+ Hooks []dshHookRef `json:"hooks"`
+}
+
+// dshHookRef is one command hook. `type` is always "command": the bridge runs only command
+// handlers and returns every other type as skipped, with a warning and no hook registered.
+type dshHookRef struct {
+ Type string `json:"type"`
+ Command string `json:"command"`
+ Timeout int `json:"timeout,omitempty"`
+}
+
+var dshRuntime = hookRuntime{
+ displayName: "DeepSeek Harness",
+ configPath: dshHooksPath,
+ install: installDshHooks,
+ uninstall: removeDshHooks,
+ isInstalled: isDshInstalledAt,
+}
+
+func InstallDsh(opts DshOptions) (DshStatus, error) {
+ status, err := installRuntimeHooks(dshRuntime, RuntimeOptions(opts))
+ if err != nil {
+ return DshStatus{}, err
+ }
+ return dshStatusFromRuntime(status), nil
+}
+
+func UninstallDsh(opts DshOptions) (DshStatus, error) {
+ status, err := uninstallRuntimeHooks(dshRuntime, RuntimeOptions(opts))
+ if err != nil {
+ return DshStatus{}, err
+ }
+ return dshStatusFromRuntime(status), nil
+}
+
+func DshHookStatus(opts DshOptions) DshStatus {
+ return dshStatusFromRuntime(runtimeHookStatus(dshRuntime, RuntimeOptions(opts)))
+}
+
+func IsDshInstalled(opts DshOptions) bool {
+ return isRuntimeInstalled(dshRuntime, RuntimeOptions(opts))
+}
+
+func dshStatusFromRuntime(status runtimeStatus) DshStatus {
+ dsh := DshStatus{
+ Installed: status.Installed,
+ BinaryPath: status.BinaryPath,
+ HooksPath: status.ConfigPath,
+ Message: status.Message,
+ }
+ // The patch path is reported alongside, because it is half the install and the half an
+ // operator is least likely to guess. A status naming only the hooks file would send someone
+ // looking for a mount that is not there.
+ if status.ConfigPath != "" {
+ dsh.PatchPath = dshPatchPathFor(status.ConfigPath)
+ }
+ return dsh
+}
+
+// dshPatchPathFor resolves the patch file that belongs to a hooks file.
+//
+// A sibling, because both live directly in the Harness home. Derived rather than resolved
+// independently so the two halves of an install cannot end up in different directories when
+// DSH_HOME changes between calls -- and so the shared hookRuntime plumbing, which carries one path,
+// still reaches both.
+func dshPatchPathFor(hooksPath string) string {
+ return filepath.Join(filepath.Dir(hooksPath), dshPatchFileName)
+}
+
+// installDshHooks writes Beacon's hooks file and mounts the bridge at it.
+//
+// The hooks file is rewritten wholesale because it is Beacon's: nothing a user wrote lives in it.
+// Rewriting is also what lets an install drop an event Beacon no longer subscribes to, which a
+// merge would leave behind pointing at a subcommand that had been removed.
+//
+// The patch file is merged, because it is not.
+//
+// Order matters and is deliberate: the hooks file first, the mount second. Between the two steps
+// the machine has a hooks file nothing reads, which is inert. The other order leaves a mount
+// pointing at a file that does not exist, and the bridge's answer to that is to log a warning and
+// register nothing -- an install that looks complete and captures nothing.
+func installDshHooks(path, binaryPath, logPath, configPath string) error {
+ if err := dshHookFileIsBeacons(path); err != nil {
+ return err
+ }
+ prefix := endpointCommandPrefix("dsh", binaryPath, logPath, configPath)
+ file := dshHooksFile{}
+ for _, event := range dshEvents {
+ file[event.name] = []dshHookGroup{{Hooks: []dshHookRef{{
+ Type: "command",
+ Command: prefix + " " + event.subcommand,
+ Timeout: event.timeout,
+ }}}}
+ }
+ data, err := json.MarshalIndent(file, "", " ")
+ if err != nil {
+ return err
+ }
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ return err
+ }
+ // 0644 rather than 0600. The Harness home is the user's own, but dsh may be launched by a
+ // service or a desktop host running as a different account, and a file only its author can
+ // read would make the hooks stop working there with no diagnostic -- the bridge logs a warning
+ // and registers nothing. The file contains a command line and no secrets.
+ if err := os.WriteFile(path, data, 0644); err != nil {
+ return err
+ }
+ return addDshPatchEntry(dshPatchPathFor(path), path)
+}
+
+// removeDshHooks removes both halves, and reports whether anything was there.
+//
+// The mount first, the hooks file second -- the reverse of install, for the same reason. Between
+// the two steps there is a hooks file nothing reads; the other order would leave a live mount
+// pointing at a file that had just been deleted.
+//
+// A hooks file that has since acquired a hook Beacon did not write is left alone rather than
+// deleted: an uninstall may remove what it added and nothing more.
+func removeDshHooks(path string) (bool, error) {
+ patchRemoved, err := removeDshPatchEntry(dshPatchPathFor(path))
+ if err != nil {
+ return false, err
+ }
+ if _, err := os.Stat(path); os.IsNotExist(err) {
+ return patchRemoved, nil
+ }
+ if err := dshHookFileIsBeacons(path); err != nil {
+ return patchRemoved, err
+ }
+ if err := os.Remove(path); err != nil {
+ return patchRemoved, err
+ }
+ return true, nil
+}
+
+// isDshInstalledAt reports whether telemetry will actually flow.
+//
+// Both halves, and the conjunction is the point. A hooks file alone is a file nothing reads; a
+// mount alone is a bridge that logs a warning and registers nothing. Reporting either one as
+// installed is how an operator ends up believing a machine is monitored when it is not -- which is
+// the same failure the other installers guard against by checking the hook command rather than the
+// file's existence, applied to a runtime where the evidence is split across two files.
+func isDshInstalledAt(path string) bool {
+ return dshHasEndpointHooks(path) && dshPatchHasEntry(dshPatchPathFor(path))
+}
+
+// dshHasEndpointHooks reports whether the hooks file registers a Beacon command.
+//
+// By the command, not by the file existing, for the reason every other installer gives: a file
+// left behind by an earlier version, or truncated by a failed write, exists and registers nothing.
+func dshHasEndpointHooks(path string) bool {
+ file, err := readDshHooks(path)
+ if err != nil {
+ return false
+ }
+ for _, groups := range file {
+ for _, group := range groups {
+ for _, hook := range group.Hooks {
+ if isEndpointHookCommand(hook.Command, "dsh") {
+ return true
+ }
+ }
+ }
+ }
+ return false
+}
+
+// dshHookFileIsBeacons reports whether Beacon may write the hooks file at path.
+//
+// It may when there is nothing there, when the file is empty, when it is unreadable as a hooks
+// document (which the bridge would be refusing to load anyway), or when every hook in it is one
+// Beacon wrote. Anything else is somebody's live registration under Beacon's chosen filename.
+func dshHookFileIsBeacons(path string) error {
+ file, err := readDshHooks(path)
+ if err != nil {
+ // A file Beacon cannot parse is one the bridge cannot load either -- it logs a warning and
+ // registers no hooks at all -- so there is nothing live in it to protect. Overwriting
+ // leaves the operator with working telemetry rather than an install that refuses over a
+ // file that was already broken.
+ return nil
+ }
+ for event, groups := range file {
+ for _, group := range groups {
+ for _, hook := range group.Hooks {
+ if !isEndpointHookCommand(hook.Command, "dsh") {
+ return fmt.Errorf(
+ "%s already defines a %s hook Beacon did not write (%q); Beacon owns that "+
+ "filename, so it will not overwrite it. Point the bridge at your own "+
+ "hooks file under a different name and run the install again",
+ path, event, hook.Command)
+ }
+ }
+ }
+ }
+ return nil
+}
+
+// readDshHooks parses the hooks file, or returns an empty one when there is none.
+func readDshHooks(path string) (dshHooksFile, error) {
+ file := dshHooksFile{}
+ data, err := os.ReadFile(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return file, nil
+ }
+ return nil, err
+ }
+ // An empty file is not malformed JSON to a person, and treating it as an error would make an
+ // install fail on a file somebody had created but not written.
+ if len(strings.TrimSpace(string(data))) == 0 {
+ return file, nil
+ }
+ if err := json.Unmarshal(data, &file); err != nil {
+ return nil, fmt.Errorf("read %s: %w", path, err)
+ }
+ return file, nil
+}
+
+func dshHooksPath(level Level) (string, error) {
+ dir, err := dshHomeDir(level)
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(dir, dshHookFileName), nil
+}
+
+// dshHomeDir resolves the Harness home for a scope.
+//
+// User scope only, and the project case is an error with its reason rather than a silent fallback
+// to user scope. Falling back would be worse than refusing: an operator asking for a repository-
+// scoped install would get a machine-wide one and no indication that is what happened.
+func dshHomeDir(level Level) (string, error) {
+ switch level {
+ case "", LevelUser:
+ if base := strings.TrimSpace(os.Getenv(dshEnvHome)); base != "" {
+ return base, nil
+ }
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(home, dshHomeDirName), nil
+ case LevelProject:
+ return "", fmt.Errorf(
+ "DeepSeek Harness has no project-scoped hook configuration: the hook bridge reads one " +
+ "process-level config chosen by the plugin tree, and the plugin tree is composed " +
+ "from the Harness home. Install at user scope, which covers every profile and " +
+ "every project on this machine")
+ default:
+ return "", fmt.Errorf("unknown hook level %q", level)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/hooks/dsh_patch.go b/cli/beacon/internal/endpoint/hooks/dsh_patch.go
new file mode 100644
index 00000000..bc6772b6
--- /dev/null
+++ b/cli/beacon/internal/endpoint/hooks/dsh_patch.go
@@ -0,0 +1,288 @@
+package hooks
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "gopkg.in/yaml.v3"
+)
+
+// Editing `$DSH_HOME/cordis.patch.yml`, which is the user's file and not Beacon's.
+//
+// Every other runtime Beacon installs into either gives it a file of its own or gives it a JSON
+// document, where "read, change one key, write" loses nothing. This is neither. The patch layer is
+// YAML a person writes by hand: it carries their comments, their quoting, and `!!js` expressions
+// the loader evaluates at boot. Decoding it into Go structs and re-encoding would silently discard
+// all three -- the comments explaining why a row exists, and the tag that makes an expression an
+// expression rather than the string "Number(process.env.DSH_PORT ?? 3081)".
+//
+// So the document is edited as a document: parsed into a yaml.Node tree, one element appended to or
+// removed from the top-level sequence, re-encoded from the same tree. yaml.v3 carries comments,
+// scalar style and custom tags through that round trip, which is what makes touching a live user
+// file defensible rather than merely convenient. A test pins it, because it is a property of the
+// library rather than of this code and a library change would take a user's boot configuration with
+// it.
+//
+// What Beacon appends is one self-contained element:
+//
+// - insert:
+// - id: beacon-endpoint-hooks
+// name: '@deepseek-ai/dsh-hooks-claude-code'
+// config:
+// configPath: /home/you/.dsh/beacon-endpoint-hooks.json
+//
+// Self-contained rather than a row pushed into somebody else's existing `insert:` list, for two
+// reasons. An uninstall can then remove exactly what an install added, by dropping one element,
+// rather than reaching into a list whose other rows it must leave untouched and whose emptiness it
+// would then have to reason about. And the loader applies patch elements in order, so an element of
+// Beacon's own cannot change when another row's position changes.
+//
+// The path in `configPath` is absolute, and that is required rather than tidy: the bridge resolves
+// a relative config path against the directory the process was launched from, which for an agent
+// runtime is wherever the user happened to be standing.
+
+// dshPatchDocument is a parsed patch file plus what the caller needs to write it back.
+type dshPatchDocument struct {
+ // node is the document node, or nil when the file does not exist.
+ node *yaml.Node
+ // existed records whether there was a file, which decides whether removing Beacon's last row
+ // should delete the file or leave an empty one. It must delete: see writeDshPatch.
+ existed bool
+}
+
+// readDshPatch parses the patch file, or reports that there is none.
+//
+// A file that exists but is empty or comments-only parses to a document with no content node.
+// That is not an error here even though it IS an error to dsh -- the runtime refuses to boot on
+// one -- because refusing to install over a file that already breaks the runtime would leave the
+// operator with the broken file and no telemetry. Appending Beacon's element fixes it as a side
+// effect, which is the better outcome and the same call the hooks-file reader makes.
+func readDshPatch(path string) (dshPatchDocument, error) {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return dshPatchDocument{}, nil
+ }
+ return dshPatchDocument{}, fmt.Errorf("read %s: %w", path, err)
+ }
+ var doc yaml.Node
+ if err := yaml.Unmarshal(data, &doc); err != nil {
+ // Unlike the hooks file, a patch file Beacon cannot parse is NOT overwritten. The two
+ // differ because the consequences differ: an unparsable hooks file registers nothing and
+ // costs nothing to replace, while this file is where the user's whole plugin tree is
+ // tweaked, and dsh's parser is not Go's -- a document this fails on may be one the runtime
+ // loads perfectly well. Refusing with the parse error names the file and leaves it intact.
+ return dshPatchDocument{}, fmt.Errorf(
+ "%s is not valid YAML (%w); Beacon will not rewrite a patch file it cannot read. "+
+ "Fix or move the file and run the install again", path, err)
+ }
+ if len(doc.Content) == 0 {
+ return dshPatchDocument{existed: true}, nil
+ }
+ return dshPatchDocument{node: &doc, existed: true}, nil
+}
+
+// dshPatchSequence returns the top-level sequence of patch elements, or an error when the document
+// is some other shape.
+//
+// A patch file is a list. A mapping or a scalar at the top level is a file whose author meant
+// something else, or a different file entirely that happens to be at this path, and appending a
+// list element to it would produce a document that is neither.
+func dshPatchSequence(doc dshPatchDocument, path string) (*yaml.Node, error) {
+ if doc.node == nil {
+ return nil, nil
+ }
+ root := doc.node.Content[0]
+ if root.Kind != yaml.SequenceNode {
+ return nil, fmt.Errorf(
+ "%s is not a list of patch entries; Beacon will not rewrite it. A dsh patch file is a "+
+ "YAML sequence -- see the runtime's own overlay examples", path)
+ }
+ return root, nil
+}
+
+// dshPatchEntryNode builds Beacon's element.
+func dshPatchEntryNode(hooksPath string) *yaml.Node {
+ row := &yaml.Node{Kind: yaml.MappingNode}
+ appendMapEntry(row, "id", scalar(dshPatchEntryID, 0))
+ // Single-quoted, because the package name begins with `@`. Unquoted it is still a valid YAML
+ // scalar, but the leading sigil is the kind of thing a reader edits "back" to something wrong,
+ // and every example in the runtime's own documentation quotes it.
+ appendMapEntry(row, "name", scalar(dshBridgePackage, yaml.SingleQuotedStyle))
+
+ config := &yaml.Node{Kind: yaml.MappingNode}
+ appendMapEntry(config, "configPath", scalar(hooksPath, yaml.SingleQuotedStyle))
+ appendMapEntry(row, "config", config)
+
+ insertList := &yaml.Node{Kind: yaml.SequenceNode, Content: []*yaml.Node{row}}
+ element := &yaml.Node{Kind: yaml.MappingNode}
+ appendMapEntry(element, "insert", insertList)
+ element.HeadComment = "Beacon endpoint telemetry. Mounts DeepSeek's Claude Code hook bridge at\n" +
+ "a hooks file Beacon owns. Local only: the hooks make no network calls.\n" +
+ "Managed by `beacon endpoint hooks`; remove with `beacon endpoint hooks uninstall`."
+ return element
+}
+
+func scalar(value string, style yaml.Style) *yaml.Node {
+ return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: value, Style: style}
+}
+
+func appendMapEntry(mapping *yaml.Node, key string, value *yaml.Node) {
+ mapping.Content = append(mapping.Content, scalar(key, 0), value)
+}
+
+// isDshBeaconElement reports whether one top-level patch element is Beacon's.
+//
+// By the row id inside its `insert` list, which is what the loader itself keys entries on. An
+// element carrying Beacon's row alongside rows somebody else added is deliberately NOT claimed:
+// removing it would take their rows with it, and Beacon only ever writes an element of its own.
+func isDshBeaconElement(element *yaml.Node) bool {
+ if element.Kind != yaml.MappingNode {
+ return false
+ }
+ insertList := mappingValue(element, "insert")
+ if insertList == nil || insertList.Kind != yaml.SequenceNode || len(insertList.Content) != 1 {
+ return false
+ }
+ id := mappingValue(insertList.Content[0], "id")
+ return id != nil && id.Kind == yaml.ScalarNode && id.Value == dshPatchEntryID
+}
+
+// mappingValue reads one key out of a mapping node, or nil.
+func mappingValue(mapping *yaml.Node, key string) *yaml.Node {
+ if mapping == nil || mapping.Kind != yaml.MappingNode {
+ return nil
+ }
+ for i := 0; i+1 < len(mapping.Content); i += 2 {
+ if mapping.Content[i].Value == key {
+ return mapping.Content[i+1]
+ }
+ }
+ return nil
+}
+
+// dshPatchHasEntry reports whether the bridge is mounted at a Beacon hooks file.
+func dshPatchHasEntry(path string) bool {
+ doc, err := readDshPatch(path)
+ if err != nil {
+ return false
+ }
+ root, err := dshPatchSequence(doc, path)
+ if err != nil || root == nil {
+ return false
+ }
+ for _, element := range root.Content {
+ if isDshBeaconElement(element) {
+ return true
+ }
+ }
+ return false
+}
+
+// addDshPatchEntry mounts the bridge, replacing Beacon's earlier row if there is one.
+//
+// Replacing rather than skipping, because the row carries the hooks file's absolute path: a
+// reinstall after DSH_HOME moved, or after a scope changed, must repoint the mount. Skipping would
+// leave it aimed at a file that is no longer there, and the bridge's answer to that is a warning in
+// a log nobody is reading.
+//
+// Appended at the end rather than inserted at the front. Later elements win in this layer, and the
+// end is also where a person adding a row by hand would put one -- so the file stays the shape its
+// author expects.
+func addDshPatchEntry(path, hooksPath string) error {
+ doc, err := readDshPatch(path)
+ if err != nil {
+ return err
+ }
+ root, err := dshPatchSequence(doc, path)
+ if err != nil {
+ return err
+ }
+ if root == nil {
+ root = &yaml.Node{Kind: yaml.SequenceNode}
+ doc.node = &yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{root}}
+ }
+ entry := dshPatchEntryNode(hooksPath)
+ replaced := false
+ for i, element := range root.Content {
+ if isDshBeaconElement(element) {
+ // The author's own comment above Beacon's row, if they wrote one, is theirs to keep.
+ entry.HeadComment = element.HeadComment
+ root.Content[i] = entry
+ replaced = true
+ break
+ }
+ }
+ if !replaced {
+ root.Content = append(root.Content, entry)
+ }
+ return writeDshPatch(path, doc)
+}
+
+// removeDshPatchEntry unmounts the bridge, and reports whether anything was there.
+func removeDshPatchEntry(path string) (bool, error) {
+ doc, err := readDshPatch(path)
+ if err != nil {
+ return false, err
+ }
+ root, err := dshPatchSequence(doc, path)
+ if err != nil || root == nil {
+ return false, err
+ }
+ kept := make([]*yaml.Node, 0, len(root.Content))
+ removed := false
+ for _, element := range root.Content {
+ if isDshBeaconElement(element) {
+ removed = true
+ continue
+ }
+ kept = append(kept, element)
+ }
+ if !removed {
+ return false, nil
+ }
+ root.Content = kept
+ return true, writeDshPatch(path, doc)
+}
+
+// writeDshPatch writes the document back, or deletes the file when nothing is left in it.
+//
+// The deletion is not tidiness. An empty or comments-only patch file does not boot dsh: the loader
+// treats it as a present-but-unreadable layer and fails startup, and the runtime's own guidance is
+// to write `[]` rather than leave one. An absent file, by contrast, is skipped cleanly. So an
+// uninstall that removed Beacon's last element must remove the file -- truncating it to an empty
+// list would work, but it would leave behind a file Beacon created and the user never asked for.
+//
+// A file that still has other elements is written back, and a file Beacon is emptying but did not
+// create is removed too: Beacon wrote every element that was in it, so there is nothing of the
+// user's to preserve, and the alternative is the non-booting file above.
+func writeDshPatch(path string, doc dshPatchDocument) error {
+ root := doc.node.Content[0]
+ if len(root.Content) == 0 {
+ if !doc.existed {
+ return nil
+ }
+ if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ return nil
+ }
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ return err
+ }
+ var buffer strings.Builder
+ encoder := yaml.NewEncoder(&buffer)
+ // Two spaces, matching the runtime's own overlay examples. yaml.v3 defaults to four, which
+ // would reindent every line of a file it did not write the first time Beacon touched it -- a
+ // diff an operator would have to read to find the one line that actually changed.
+ encoder.SetIndent(2)
+ if err := encoder.Encode(doc.node); err != nil {
+ return err
+ }
+ if err := encoder.Close(); err != nil {
+ return err
+ }
+ return os.WriteFile(path, []byte(buffer.String()), 0644)
+}
diff --git a/cli/beacon/internal/endpoint/hooks/dsh_test.go b/cli/beacon/internal/endpoint/hooks/dsh_test.go
new file mode 100644
index 00000000..ba4110b2
--- /dev/null
+++ b/cli/beacon/internal/endpoint/hooks/dsh_test.go
@@ -0,0 +1,558 @@
+package hooks
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
+ "gopkg.in/yaml.v3"
+)
+
+// The DeepSeek Harness install is two files and neither of them announces a problem.
+//
+// A hooks file the bridge cannot load produces a warning in the runtime's log and no registered
+// hooks; a patch file that does not mount the bridge produces nothing at all. Neither reaches an
+// operator, so the emitted shapes are pinned here rather than trusted -- and so is the property
+// that makes editing the patch file defensible at all, that a YAML round trip preserves what the
+// user wrote.
+
+// dshUserPaths points the user scope at a temp Harness home and returns both paths Beacon writes.
+//
+// DSH_HOME is set rather than cleared, unlike the Kiro fixture: it is the documented way to move
+// the Harness home, and setting it is also what proves the installer reads it.
+func dshUserPaths(t *testing.T) (hooksPath, patchPath string) {
+ t.Helper()
+ testenv.SetHome(t, t.TempDir())
+ t.Setenv("DSH_HOME", filepath.Join(t.TempDir(), "dsh-home"))
+ hooksPath, err := dshHooksPath(LevelUser)
+ if err != nil {
+ t.Fatalf("dshHooksPath: %v", err)
+ }
+ return hooksPath, dshPatchPathFor(hooksPath)
+}
+
+func installDshFixture(t *testing.T, hooksPath string) {
+ t.Helper()
+ if err := installDshHooks(hooksPath, "/opt/beacon/bin/beacon-hooks", "/var/log/beacon/runtime.jsonl", "/etc/beacon/config.json"); err != nil {
+ t.Fatalf("installDshHooks returned error: %v", err)
+ }
+}
+
+func readFile(t *testing.T, path string) string {
+ t.Helper()
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read %s: %v", path, err)
+ }
+ return string(data)
+}
+
+// ---------------------------------------------------------------------------
+// Paths
+// ---------------------------------------------------------------------------
+
+// DSH_HOME moves the Harness home, and on a machine that sets it ~/.dsh is not where dsh looks.
+func TestDshHooksPathHonorsDshHome(t *testing.T) {
+ testenv.SetHome(t, t.TempDir())
+ home := filepath.Join(t.TempDir(), "elsewhere")
+ t.Setenv("DSH_HOME", home)
+
+ path, err := dshHooksPath(LevelUser)
+ if err != nil {
+ t.Fatalf("dshHooksPath: %v", err)
+ }
+ if want := filepath.Join(home, dshHookFileName); path != want {
+ t.Fatalf("dshHooksPath = %q, want %q", path, want)
+ }
+ if want := filepath.Join(home, dshPatchFileName); dshPatchPathFor(path) != want {
+ t.Fatalf("patch path = %q, want %q", dshPatchPathFor(path), want)
+ }
+}
+
+func TestDshHooksPathDefaultsToDotDshUnderHome(t *testing.T) {
+ home := t.TempDir()
+ testenv.SetHome(t, home)
+ t.Setenv("DSH_HOME", "")
+
+ path, err := dshHooksPath(LevelUser)
+ if err != nil {
+ t.Fatalf("dshHooksPath: %v", err)
+ }
+ if want := filepath.Join(home, ".dsh", dshHookFileName); path != want {
+ t.Fatalf("dshHooksPath = %q, want %q", path, want)
+ }
+}
+
+// Project scope is refused rather than silently redirected to user scope. An operator asking for a
+// repository-scoped install must not get a machine-wide one without being told.
+func TestDshProjectScopeIsRefusedWithItsReason(t *testing.T) {
+ _, err := dshHooksPath(LevelProject)
+ if err == nil {
+ t.Fatal("dshHooksPath(project) returned no error; dsh has no project-scoped hook config")
+ }
+ if !strings.Contains(err.Error(), "user scope") {
+ t.Fatalf("error %q does not tell the operator what to do instead", err)
+ }
+}
+
+// ---------------------------------------------------------------------------
+// The hooks file
+// ---------------------------------------------------------------------------
+
+// The emitted hooks document, pinned field by field. The bridge parses this file once at startup
+// and registers nothing at all if it cannot -- with a warning in a log, not an error an operator
+// sees.
+func TestDshHooksFileShape(t *testing.T) {
+ hooksPath, _ := dshUserPaths(t)
+ installDshFixture(t, hooksPath)
+
+ var file map[string][]struct {
+ Matcher *string `json:"matcher"`
+ Hooks []struct {
+ Type string `json:"type"`
+ Command string `json:"command"`
+ Timeout int `json:"timeout"`
+ } `json:"hooks"`
+ }
+ if err := json.Unmarshal([]byte(readFile(t, hooksPath)), &file); err != nil {
+ t.Fatalf("emitted hooks file is not valid JSON: %v", err)
+ }
+
+ wantEvents := map[string]string{
+ "SessionStart": "session-start",
+ "UserPromptSubmit": "prompt-submit",
+ "PreToolUse": "pre-tool",
+ "PostToolUse": "post-tool",
+ "Stop": "stop",
+ "SubagentStart": "subagent-start",
+ "SubagentStop": "subagent-stop",
+ }
+ if len(file) != len(wantEvents) {
+ t.Fatalf("hooks file has %d events, want %d -- the bridge supports exactly seven",
+ len(file), len(wantEvents))
+ }
+ for event, subcommand := range wantEvents {
+ groups, ok := file[event]
+ if !ok || len(groups) != 1 || len(groups[0].Hooks) != 1 {
+ t.Fatalf("%s = %#v, want exactly one group with one hook", event, groups)
+ }
+ // A matcher is absent by construction: absent means match-all in this dialect, and the
+ // bridge validates a written one at parse time and rejects the whole config on a bad one.
+ if groups[0].Matcher != nil {
+ t.Fatalf("%s carries a matcher %q; absent is the match-all form that needs no validating",
+ event, *groups[0].Matcher)
+ }
+ hook := groups[0].Hooks[0]
+ if hook.Type != "command" {
+ t.Fatalf("%s hook type = %q; the bridge runs only command handlers", event, hook.Type)
+ }
+ if !strings.HasSuffix(hook.Command, " "+subcommand) {
+ t.Fatalf("%s command = %q, want it to end in %q", event, hook.Command, subcommand)
+ }
+ if !strings.Contains(hook.Command, "--platform dsh") {
+ t.Fatalf("%s command = %q, want --platform dsh", event, hook.Command)
+ }
+ // Seconds, not milliseconds. The bridge reads `timeout` as timeoutSec and applies 600
+ // seconds when it is absent -- ten minutes of held agent turn for a hook that finishes in
+ // milliseconds.
+ if hook.Timeout <= 0 || hook.Timeout > 60 {
+ t.Fatalf("%s timeout = %d; these are seconds and are ceilings on a hang", event, hook.Timeout)
+ }
+ }
+}
+
+// Beacon owns the filename, so it refuses rather than deleting a stranger's registrations.
+func TestDshInstallRefusesAHooksFileBeaconDidNotWrite(t *testing.T) {
+ hooksPath, _ := dshUserPaths(t)
+ if err := os.MkdirAll(filepath.Dir(hooksPath), 0755); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ theirs := `{"PreToolUse":[{"hooks":[{"type":"command","command":"/usr/local/bin/audit-tool"}]}]}`
+ if err := os.WriteFile(hooksPath, []byte(theirs), 0644); err != nil {
+ t.Fatalf("write: %v", err)
+ }
+
+ err := installDshHooks(hooksPath, "/opt/beacon/bin/beacon-hooks", "/log", "/config")
+ if err == nil {
+ t.Fatal("install overwrote a hooks file Beacon did not write")
+ }
+ if !strings.Contains(err.Error(), "audit-tool") {
+ t.Fatalf("error %q does not name the hook it refused to replace", err)
+ }
+ if got := readFile(t, hooksPath); got != theirs {
+ t.Fatalf("the file was modified anyway: %q", got)
+ }
+}
+
+// A reinstall replaces the hooks file wholesale, which is what lets Beacon drop an event it no
+// longer subscribes to. A merge would leave one behind pointing at a subcommand that was removed.
+func TestDshReinstallReplacesTheHooksFileWholesale(t *testing.T) {
+ hooksPath, _ := dshUserPaths(t)
+ installDshFixture(t, hooksPath)
+
+ file, err := readDshHooks(hooksPath)
+ if err != nil {
+ t.Fatalf("readDshHooks: %v", err)
+ }
+ // A stale Beacon event from an imagined earlier version.
+ file["PreCompact"] = []dshHookGroup{{Hooks: []dshHookRef{{
+ Type: "command",
+ // Spelled the way the installer spells one: isEndpointHookCommand recognizes a Beacon
+ // command by its binary AND its endpoint settings, so a fixture missing --log and --config
+ // is not one Beacon would be asked to replace.
+ Command: "'/opt/beacon/bin/beacon-hooks' --platform dsh --log '/var/log/beacon/runtime.jsonl' --config '/etc/beacon/config.json' pre-compact",
+ }}}}
+ data, _ := json.MarshalIndent(file, "", " ")
+ if err := os.WriteFile(hooksPath, data, 0644); err != nil {
+ t.Fatalf("write: %v", err)
+ }
+
+ installDshFixture(t, hooksPath)
+ if strings.Contains(readFile(t, hooksPath), "PreCompact") {
+ t.Fatal("a reinstall left a stale Beacon event behind")
+ }
+}
+
+// ---------------------------------------------------------------------------
+// The patch file
+// ---------------------------------------------------------------------------
+
+// The mount, pinned. Without it the hooks file is a file nothing reads.
+func TestDshInstallMountsTheBridge(t *testing.T) {
+ hooksPath, patchPath := dshUserPaths(t)
+ installDshFixture(t, hooksPath)
+
+ var elements []struct {
+ Insert []struct {
+ ID string `yaml:"id"`
+ Name string `yaml:"name"`
+ Config struct {
+ ConfigPath string `yaml:"configPath"`
+ } `yaml:"config"`
+ } `yaml:"insert"`
+ }
+ if err := yaml.Unmarshal([]byte(readFile(t, patchPath)), &elements); err != nil {
+ t.Fatalf("emitted patch file is not valid YAML: %v", err)
+ }
+ if len(elements) != 1 || len(elements[0].Insert) != 1 {
+ t.Fatalf("patch = %#v, want one element inserting one row", elements)
+ }
+ row := elements[0].Insert[0]
+ if row.ID != dshPatchEntryID {
+ t.Fatalf("row id = %q, want %q", row.ID, dshPatchEntryID)
+ }
+ if row.Name != dshBridgePackage {
+ t.Fatalf("row name = %q, want the bridge package", row.Name)
+ }
+ // Absolute, and this is required rather than tidy: the bridge resolves a relative config path
+ // against the directory the process was launched from.
+ if !filepath.IsAbs(row.Config.ConfigPath) {
+ t.Fatalf("configPath = %q, want an absolute path", row.Config.ConfigPath)
+ }
+ if row.Config.ConfigPath != hooksPath {
+ t.Fatalf("configPath = %q, want the hooks file Beacon wrote at %q", row.Config.ConfigPath, hooksPath)
+ }
+}
+
+// The property that makes editing a live user file defensible. It is a property of yaml.v3 rather
+// than of this code, which is exactly why it is pinned: a library change would take a user's boot
+// configuration with it, silently.
+func TestDshInstallPreservesCommentsQuotingAndJsTags(t *testing.T) {
+ hooksPath, patchPath := dshUserPaths(t)
+ if err := os.MkdirAll(filepath.Dir(patchPath), 0755); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ theirs := `# Our team's overlay. Do not remove the webhook row.
+- insert:
+ - id: github-webhook-server
+ name: '@deepseek-ai/dsh-host-webserver'
+ config:
+ host: '127.0.0.1'
+ port: !!js Number(process.env.DSH_WEBHOOK_PORT ?? 3081)
+- id: ui-schedule
+ disabled: false # re-enabled for the on-call rota
+`
+ if err := os.WriteFile(patchPath, []byte(theirs), 0644); err != nil {
+ t.Fatalf("write: %v", err)
+ }
+
+ installDshFixture(t, hooksPath)
+ got := readFile(t, patchPath)
+
+ for _, want := range []string{
+ "# Our team's overlay. Do not remove the webhook row.",
+ "# re-enabled for the on-call rota",
+ "!!js Number(process.env.DSH_WEBHOOK_PORT ?? 3081)",
+ "'127.0.0.1'",
+ "id: ui-schedule",
+ "id: github-webhook-server",
+ } {
+ if !strings.Contains(got, want) {
+ t.Fatalf("install lost %q from the user's patch file:\n%s", want, got)
+ }
+ }
+ if !strings.Contains(got, dshPatchEntryID) {
+ t.Fatalf("install did not add Beacon's row:\n%s", got)
+ }
+}
+
+// Beacon's element goes at the end, where later elements win and where a person adding a row by
+// hand would put one.
+func TestDshInstallAppendsRatherThanReordering(t *testing.T) {
+ hooksPath, patchPath := dshUserPaths(t)
+ if err := os.MkdirAll(filepath.Dir(patchPath), 0755); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ if err := os.WriteFile(patchPath, []byte("- id: agent-loop\n config:\n model: theirs\n"), 0644); err != nil {
+ t.Fatalf("write: %v", err)
+ }
+
+ installDshFixture(t, hooksPath)
+ got := readFile(t, patchPath)
+ if strings.Index(got, "agent-loop") > strings.Index(got, dshPatchEntryID) {
+ t.Fatalf("Beacon's element was put ahead of the user's:\n%s", got)
+ }
+}
+
+// A reinstall repoints the mount instead of adding a second one. The row carries an absolute path,
+// so a reinstall after DSH_HOME moved must update it -- skipping would leave the bridge aimed at a
+// file that is no longer there.
+func TestDshReinstallRepointsTheMountInPlace(t *testing.T) {
+ hooksPath, patchPath := dshUserPaths(t)
+ installDshFixture(t, hooksPath)
+
+ moved := filepath.Join(t.TempDir(), "moved-home", dshHookFileName)
+ if err := addDshPatchEntry(patchPath, moved); err != nil {
+ t.Fatalf("addDshPatchEntry: %v", err)
+ }
+
+ got := readFile(t, patchPath)
+ // Counted on the id line rather than on the bare string: the hooks filename contains the same
+ // characters, so a bare count is two for a single correct mount.
+ if strings.Count(got, "id: "+dshPatchEntryID) != 1 {
+ t.Fatalf("a second mount was added:\n%s", got)
+ }
+ if !strings.Contains(got, moved) {
+ t.Fatalf("the mount was not repointed at %q:\n%s", moved, got)
+ }
+ if strings.Contains(got, hooksPath) {
+ t.Fatalf("the old configPath survived:\n%s", got)
+ }
+}
+
+// A comment the user wrote above Beacon's row is theirs, and a reinstall must not replace it with
+// Beacon's own.
+func TestDshReinstallKeepsAUserCommentOnBeaconsRow(t *testing.T) {
+ hooksPath, patchPath := dshUserPaths(t)
+ installDshFixture(t, hooksPath)
+
+ withComment := strings.Replace(readFile(t, patchPath),
+ "- insert:", "# Approved by security 2026-03-02, ticket SEC-1188.\n- insert:", 1)
+ if err := os.WriteFile(patchPath, []byte(withComment), 0644); err != nil {
+ t.Fatalf("write: %v", err)
+ }
+
+ installDshFixture(t, hooksPath)
+ if !strings.Contains(readFile(t, patchPath), "SEC-1188") {
+ t.Fatalf("a reinstall discarded the user's comment:\n%s", readFile(t, patchPath))
+ }
+}
+
+// A patch file Beacon cannot parse is left alone, unlike a hooks file. The two differ because the
+// consequences do: this file is where the user's whole plugin tree is tweaked, and dsh's parser is
+// not Go's.
+func TestDshInstallRefusesAnUnparsablePatchFile(t *testing.T) {
+ hooksPath, patchPath := dshUserPaths(t)
+ if err := os.MkdirAll(filepath.Dir(patchPath), 0755); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ theirs := "- insert:\n - id: broken\n name: bad indent\n"
+ if err := os.WriteFile(patchPath, []byte(theirs), 0644); err != nil {
+ t.Fatalf("write: %v", err)
+ }
+
+ if err := installDshHooks(hooksPath, "/opt/beacon/bin/beacon-hooks", "/log", "/config"); err == nil {
+ t.Fatal("install rewrote a patch file it could not parse")
+ }
+ if got := readFile(t, patchPath); got != theirs {
+ t.Fatalf("the patch file was modified anyway:\n%s", got)
+ }
+}
+
+// A patch file that is a mapping or a scalar is not a patch file. Appending a sequence element to
+// it would produce a document that is neither.
+func TestDshInstallRefusesAPatchFileThatIsNotAList(t *testing.T) {
+ hooksPath, patchPath := dshUserPaths(t)
+ if err := os.MkdirAll(filepath.Dir(patchPath), 0755); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ theirs := "plugins:\n - name: something\n"
+ if err := os.WriteFile(patchPath, []byte(theirs), 0644); err != nil {
+ t.Fatalf("write: %v", err)
+ }
+
+ if err := installDshHooks(hooksPath, "/opt/beacon/bin/beacon-hooks", "/log", "/config"); err == nil {
+ t.Fatal("install rewrote a patch file that is not a list of entries")
+ }
+ if got := readFile(t, patchPath); got != theirs {
+ t.Fatalf("the patch file was modified anyway:\n%s", got)
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Installed-ness
+// ---------------------------------------------------------------------------
+
+// Both halves, and the conjunction is the point: a hooks file alone is a file nothing reads, and a
+// mount alone is a bridge that registers nothing. Reporting either as installed is how an operator
+// ends up believing a machine is monitored when it is not.
+func TestDshIsInstalledRequiresBothHalves(t *testing.T) {
+ t.Run("both", func(t *testing.T) {
+ hooksPath, _ := dshUserPaths(t)
+ installDshFixture(t, hooksPath)
+ if !isDshInstalledAt(hooksPath) {
+ t.Fatal("a complete install reports not installed")
+ }
+ })
+ t.Run("hooks file only", func(t *testing.T) {
+ hooksPath, patchPath := dshUserPaths(t)
+ installDshFixture(t, hooksPath)
+ if err := os.Remove(patchPath); err != nil {
+ t.Fatalf("remove: %v", err)
+ }
+ if isDshInstalledAt(hooksPath) {
+ t.Fatal("a hooks file with nothing mounted at it reports installed")
+ }
+ })
+ t.Run("mount only", func(t *testing.T) {
+ hooksPath, _ := dshUserPaths(t)
+ installDshFixture(t, hooksPath)
+ if err := os.Remove(hooksPath); err != nil {
+ t.Fatalf("remove: %v", err)
+ }
+ if isDshInstalledAt(hooksPath) {
+ t.Fatal("a mount pointing at a missing hooks file reports installed")
+ }
+ })
+ t.Run("nothing", func(t *testing.T) {
+ hooksPath, _ := dshUserPaths(t)
+ if isDshInstalledAt(hooksPath) {
+ t.Fatal("an untouched machine reports installed")
+ }
+ })
+}
+
+// ---------------------------------------------------------------------------
+// Uninstall
+// ---------------------------------------------------------------------------
+
+// The property that would otherwise break the runtime. An empty or comments-only patch file does
+// not boot dsh -- it is a present-but-unreadable layer, not an ignored one -- so removing Beacon's
+// last element must remove the file.
+func TestDshUninstallRemovesAPatchFileItWouldOtherwiseEmpty(t *testing.T) {
+ hooksPath, patchPath := dshUserPaths(t)
+ installDshFixture(t, hooksPath)
+
+ removed, err := removeDshHooks(hooksPath)
+ if err != nil {
+ t.Fatalf("removeDshHooks: %v", err)
+ }
+ if !removed {
+ t.Fatal("uninstall reported nothing was there")
+ }
+ if _, err := os.Stat(patchPath); !os.IsNotExist(err) {
+ t.Fatalf("the patch file survived as %q; an empty patch layer fails dsh boot",
+ readFile(t, patchPath))
+ }
+ if _, err := os.Stat(hooksPath); !os.IsNotExist(err) {
+ t.Fatal("the hooks file survived the uninstall")
+ }
+}
+
+// A patch file with the user's own rows in it is kept, with only Beacon's element gone.
+func TestDshUninstallKeepsTheUsersOwnRows(t *testing.T) {
+ hooksPath, patchPath := dshUserPaths(t)
+ if err := os.MkdirAll(filepath.Dir(patchPath), 0755); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ theirs := "# keep me\n- insert:\n - id: theirs\n name: '@deepseek-ai/dsh-webhook'\n"
+ if err := os.WriteFile(patchPath, []byte(theirs), 0644); err != nil {
+ t.Fatalf("write: %v", err)
+ }
+ installDshFixture(t, hooksPath)
+
+ if _, err := removeDshHooks(hooksPath); err != nil {
+ t.Fatalf("removeDshHooks: %v", err)
+ }
+ got := readFile(t, patchPath)
+ if !strings.Contains(got, "id: theirs") || !strings.Contains(got, "# keep me") {
+ t.Fatalf("uninstall took the user's rows with it:\n%s", got)
+ }
+ if strings.Contains(got, dshPatchEntryID) {
+ t.Fatalf("Beacon's element survived the uninstall:\n%s", got)
+ }
+}
+
+// An element carrying Beacon's row alongside somebody else's is not Beacon's, and removing it
+// would take their rows with it. Beacon only ever writes an element of its own.
+func TestDshUninstallDoesNotClaimASharedInsertElement(t *testing.T) {
+ _, patchPath := dshUserPaths(t)
+ if err := os.MkdirAll(filepath.Dir(patchPath), 0755); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ shared := "- insert:\n - id: " + dshPatchEntryID + "\n name: '" + dshBridgePackage + "'\n" +
+ " - id: theirs\n name: '@deepseek-ai/dsh-webhook'\n"
+ if err := os.WriteFile(patchPath, []byte(shared), 0644); err != nil {
+ t.Fatalf("write: %v", err)
+ }
+
+ removed, err := removeDshPatchEntry(patchPath)
+ if err != nil {
+ t.Fatalf("removeDshPatchEntry: %v", err)
+ }
+ if removed {
+ t.Fatal("uninstall claimed an element it did not write")
+ }
+ if got := readFile(t, patchPath); got != shared {
+ t.Fatalf("the shared element was modified:\n%s", got)
+ }
+}
+
+// Uninstalling twice is not an error, and the second time reports that nothing was there.
+func TestDshUninstallIsIdempotent(t *testing.T) {
+ hooksPath, _ := dshUserPaths(t)
+ installDshFixture(t, hooksPath)
+
+ if _, err := removeDshHooks(hooksPath); err != nil {
+ t.Fatalf("first uninstall: %v", err)
+ }
+ removed, err := removeDshHooks(hooksPath)
+ if err != nil {
+ t.Fatalf("second uninstall: %v", err)
+ }
+ if removed {
+ t.Fatal("the second uninstall reported it removed something")
+ }
+}
+
+// Install, uninstall, install: the machine ends where it started, with one mount and one hooks file.
+func TestDshInstallUninstallInstallIsStable(t *testing.T) {
+ hooksPath, patchPath := dshUserPaths(t)
+ installDshFixture(t, hooksPath)
+ first := readFile(t, patchPath)
+
+ if _, err := removeDshHooks(hooksPath); err != nil {
+ t.Fatalf("uninstall: %v", err)
+ }
+ installDshFixture(t, hooksPath)
+
+ if got := readFile(t, patchPath); got != first {
+ t.Fatalf("the patch file differs after a round trip:\nfirst:\n%s\nsecond:\n%s", first, got)
+ }
+ if !isDshInstalledAt(hooksPath) {
+ t.Fatal("the reinstall did not take")
+ }
+}