Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent): pass Hermes custom args before the acp subcommand (MUL-7748) (#8882)
Bohan Jiang138134d34104
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 6cea16d50e..94e32fca3f 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -7988,10 +7988,10 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot ivar hermesSessionStore stringif provider == "hermes" {// Resolve from the argv hermes will actually parse — launch prefix,- // `acp`, then the filtered custom args — which agent.HermesLaunchArgv+ // the filtered custom args, then `acp` — which agent.HermesLaunchArgv// assembles the same way the backend does. A custom runtime profile's// fixed_args are the launch prefix now, so they are scanned before- // custom_args, and the backend's own `acp` token sits between them and+ // custom_args, and the backend's own `acp` token closes the argv and// participates in the scan. Approximating that argv reads a different// profile than the process does, and the overlay ends up seeded from// the wrong home (GH #7046).@@ -8562,8 +8562,8 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// The overlay is authoritative once built, so nothing on the command line// may re-point HERMES_HOME out of it. Both argv regions are stripped// together, against the same assembled argv the resolver read: a selection- // can straddle them (a prefix ending in a bare `-p` captures the backend's- // `acp`), which per-region stripping cannot see.+ // can straddle them (a prefix ending in a bare `-p` captures the first+ // custom arg), which per-region stripping cannot see.var hermesOverlayCustomArgs []stringhermesOverlayActive := provider == "hermes" && env != nil && env.HermesHome != ""if hermesOverlayActive {diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex 135788ad2d..3bda712758 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -6543,7 +6543,7 @@ func TestBuildPromptSquadLeaderMultiThreadCarvesOutNoAction(t *testing.T) {// TestHermesProfileChainCoversLaunchPrefix is the daemon half of GH #7046's// Hermes regression. A custom runtime profile's fixed_args are no longer folded// into custom_args — they become the launch prefix and reach hermes ahead of-// custom_args, with the backend's own `acp` token between the two.+// custom_args, which in turn precede the backend's own `acp` token.//// Both halves of the profile chain therefore have to run against the argv the// backend really assembles. Resolving or stripping against a hand-built@@ -6552,10 +6552,10 @@ func TestBuildPromptSquadLeaderMultiThreadCarvesOutNoAction(t *testing.T) {func TestHermesProfileChainCoversLaunchPrefix(t *testing.T) {t.Parallel()- // A prefix ending in a value-taking flag: the `acp` token decides which- // selection hermes sees, so it must be present when the daemon resolves.- launchPrefix := []string{"--model"}- customArgs := []string{"-p", "research", "--yolo"}+ // A prefix ending in a bare `-p`: the selection straddles the two regions,+ // so only the assembled argv shows which profile hermes sees.+ launchPrefix := []string{"-p"}+ customArgs := []string{"research", "--yolo"}sel := agent.ParseHermesProfileArgs(agent.HermesLaunchArgv(launchPrefix, customArgs, slog.Default()))@@ -6571,10 +6571,10 @@ func TestHermesProfileChainCoversLaunchPrefix(t *testing.T) {agent.HermesLaunchArgv(strippedPrefix, strippedCustom, slog.Default())); sel.Found {t.Fatalf("the launched argv can still redirect HERMES_HOME: %+v", sel)}- if strings.Join(strippedPrefix, "\x00") != "--model" {- t.Errorf("prefix = %v, want the non-selector token kept", strippedPrefix)+ if len(strippedPrefix) != 0 {+ t.Errorf("prefix = %v, want the straddling `-p` removed", strippedPrefix)}if strings.Join(strippedCustom, "\x00") != "--yolo" {- t.Errorf("custom = %v, want only the selector removed", strippedCustom)+ t.Errorf("custom = %v, want only the selector's value removed", strippedCustom)}}diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.goindex a5a52179cf..14030a183f 100644--- a/server/pkg/agent/hermes.go+++ b/server/pkg/agent/hermes.go@@ -12,6 +12,7 @@ import ("os/exec""path/filepath""regexp"+ "slices""sort""strconv""strings"@@ -46,14 +47,15 @@ var hermesBlockedArgs = map[string]blockedArgMode{// validation lives in the daemon-side resolver (execenv.ResolveHermesProfile).var hermesArgProfileRe = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,63}$`)-// hermesValueFlags and hermesOptionalValueFlags mirror the value-taking flags-// Hermes skips while scanning argv for -p/--profile, so a value like the `coder`-// in `-m coder -p research` is never misread as the profile. Kept in sync with-// _apply_profile_override.value_flags / optional_value_flags.+// hermesValueFlags and hermesOptionalValueFlags mirror Hermes' top-level+// value-taking flags, which it skips while scanning argv for -p/--profile, so a+// value like the `coder` in `-m coder -p research` is never misread as the+// profile. Kept in sync with hermes_cli._parser.top_level_value_flag_sets+// (formerly the literal _apply_profile_override.value_flags).var hermesValueFlags = map[string]struct{}{"-z": {}, "--oneshot": {}, "-m": {}, "--model": {}, "--provider": {},- "-t": {}, "--toolsets": {}, "-r": {}, "--resume": {}, "-s": {},- "--skills": {}, "--usage-file": {},+ "--reasoning": {}, "-t": {}, "--toolsets": {}, "-r": {}, "--resume": {},+ "-s": {}, "--skills": {}, "--usage-file": {}, "--in": {},}var hermesOptionalValueFlags = map[string]struct{}{"-c": {}, "--continue": {}}@@ -137,43 +139,222 @@ func hermesInsideMcpAdd(args []string, index int) bool {}// hermesACPSubcommand is the subcommand the backend always launches with. It-// sits between the runtime's launch prefix and the agent's custom args, and it// is an ordinary argv token to Hermes' own parser — which is why the daemon// cannot reason about a profile selection without it.const hermesACPSubcommand = "acp"+// hermesACPSubcommandFlags are the options Hermes' `acp` subparser declares+// (hermes_cli/subcommands/acp.py, plus argparse's own -h/--help), all+// value-less. Argparse accepts them only after the subcommand, so they keep+// that position; every other custom arg is a global flag, which Hermes accepts+// only before it.+var hermesACPSubcommandFlags = map[string]struct{}{+ "--accept-hooks": {}, "--version": {}, "--check": {}, "--setup": {},+ "--setup-browser": {}, "--yes": {}, "-y": {}, "--help": {}, "-h": {},+}++// isHermesACPSubcommandFlag reports whether the `acp` subparser would read+// token as one of its own options, so it must stay behind the subcommand.+//+// Matching follows argparse, not string equality: Hermes keeps allow_abbrev, so+// behind `acp` a `--y` is `--yes` — while in front of it the root parser reads+// the same token as `--yolo`. A long token is the subparser's whenever it+// prefixes one of its options; an ambiguous prefix (`--se`) is a usage error+// there, exactly as it was before global flags moved. A short token is the+// subparser's when its flag letter is, since `-yh` bundles `-y` and `-h`.+func isHermesACPSubcommandFlag(token string) bool {+ arg := unshellQuoteArg(token)+ if strings.HasPrefix(arg, "--") {+ return hermesLongOptionPrefix(arg, hermesACPSubcommandFlags)+ }+ if len(arg) >= 2 && arg[0] == '-' {+ _, ok := hermesACPSubcommandFlags[arg[:2]]+ return ok+ }+ return false+}++// hermesLongOptionPrefix reports whether a `--name` token (any inline+// `=value` ignored) names one of the long options in options the way argparse+// resolves it: exactly, or as a prefix of it.+func hermesLongOptionPrefix(arg string, options map[string]struct{}) bool {+ name, _, _ := strings.Cut(arg, "=")+ if len(name) <= len("--") || !strings.HasPrefix(name, "--") {+ return false+ }+ for option := range options {+ if strings.HasPrefix(option, name) {+ return true+ }+ }+ return false+}+// hermesCLIArgsFrom assembles the argv the backend passes after the executable// and its launch prefix, from custom args that are already filtered.func hermesCLIArgsFrom(filteredCustomArgs []string) []string {- args := make([]string, 0, 1+len(filteredCustomArgs))+ args, _ := hermesCLIArgsLayout(filteredCustomArgs)+ return args+}++// hermesCLIArgsLayout places the filtered custom args around `acp` and reports,+// for each returned token, the index of the custom arg it came from (-1 for+// `acp` itself).+//+// Hermes splits its flags by position: global flags (`--provider`, `--yolo`,+// `-m`, ...) parse only before the subcommand, the flags `acp` declares only+// after it. Launching `hermes acp <custom args>` turned every global flag into+// an argparse usage error that exits before the ACP handshake (GH #8878), so+// global flags go in front — a value-taking flag keeping its value — and `acp`'s+// own flags stay behind. jcode, the other CLI behind this protocol family,+// declares its flags global, so it parses either position.+func hermesCLIArgsLayout(filteredCustomArgs []string) (args []string, origin []int) {+ args = make([]string, 0, len(filteredCustomArgs)+1)+ origin = make([]int, 0, len(filteredCustomArgs)+1)+ var subcommandFlags []int+ for i := 0; i < len(filteredCustomArgs); {+ if isHermesACPSubcommandFlag(filteredCustomArgs[i]) {+ subcommandFlags = append(subcommandFlags, i)+ i+++ continue+ }+ n, _ := hermesValueTokens(filteredCustomArgs, i)+ for end := i + n; i <= end; i++ {+ args = append(args, filteredCustomArgs[i])+ origin = append(origin, i)+ }+ }args = append(args, hermesACPSubcommand)- return append(args, filteredCustomArgs...)+ origin = append(origin, -1)+ for _, i := range subcommandFlags {+ args = append(args, filteredCustomArgs[i])+ origin = append(origin, i)+ }+ return args, origin+}++// hermesACPIndex returns where `acp` sits in an argv built by hermesCLIArgsFrom:+// only `acp`'s own flags follow it, so it is the last token that is not one.+func hermesACPIndex(args []string) int {+ i := len(args) - 1+ for i > 0 {+ if !isHermesACPSubcommandFlag(args[i]) {+ break+ }+ i--+ }+ return i}// hermesCLIArgs is what hermesBackend.Execute passes to the launch boundary.-func hermesCLIArgs(customArgs []string, logger *slog.Logger) []string {- return hermesCLIArgsFrom(filterCustomArgs(customArgs, hermesBlockedArgs, logger))+func hermesCLIArgs(launchPrefix, customArgs []string, logger *slog.Logger) []string {+ custom := filterCustomArgs(customArgs, hermesBlockedArgs, logger)+ return hermesCLIArgsFrom(dropHermesSubcommandCapture(launchPrefix, custom, logger))+}++// dropHermesSubcommandCapture removes the custom arg that would take the+// backend's `acp` token as its value.+//+// Global flags sit directly in front of the subcommand, so a value-taking flag+// left without its value — a bare `--provider`, a bare `-p` — consumes `acp`+// instead. Hermes then either selects a profile named `acp` or, with no+// subcommand left, starts interactive chat on the daemon's pipe and never+// answers the handshake, hanging the task until it times out. The flag has no+// value to apply either way, so dropping it keeps the launch on ACP.+//+// The launch prefix is scanned too, so a custom arg that is itself the value+// of a flag the prefix leaves open is paired the way Hermes pairs it.+func dropHermesSubcommandCapture(launchPrefix, filteredCustomArgs []string, logger *slog.Logger) []string {+ args, origin := hermesCLIArgsLayout(filteredCustomArgs)+ acp := hermesACPIndex(args)+ if acp == 0 || !hermesArgvAwaitsValue(Command{Prefix: launchPrefix}.Argv(args[:acp]...)) {+ return filteredCustomArgs+ }+ drop := origin[acp-1]+ if logger != nil {+ logger.Warn("hermes: dropping custom arg with no value; it would consume the acp subcommand",+ "flag", unshellQuoteArg(filteredCustomArgs[drop]))+ }+ return withoutIndices(filteredCustomArgs, []int{drop})+}++// hermesValueTokens reports how many tokens after args[i] Hermes reads as its+// value, and whether args[i] is a value-taking flag with nothing left to take.+// Beyond the exact names ParseHermesProfileArgs skips, it resolves long-flag+// abbreviations the way argparse does (`--prov` is `--provider`), since those+// consume the next token just the same.+func hermesValueTokens(args []string, i int) (n int, open bool) {+ arg := unshellQuoteArg(args[i])+ rest := len(args) - i - 1+ if arg == "--" {+ return rest, false+ }+ takes := func(options map[string]struct{}) bool {+ if _, ok := options[arg]; ok {+ return true+ }+ return !strings.Contains(arg, "=") && hermesLongOptionPrefix(arg, options)+ }+ required, optional := takes(hermesValueFlags), takes(hermesOptionalValueFlags)+ switch {+ case required || arg == "-p" || arg == "--profile":+ if rest == 0 {+ return 0, true+ }+ return 1, false+ case optional:+ if rest == 0 {+ return 0, true+ }+ if !strings.HasPrefix(unshellQuoteArg(args[i+1]), "-") {+ return 1, false+ }+ }+ return 0, false+}++// hermesArgvAwaitsValue reports whether args end on a value-taking flag whose+// value slot is still open, so the next token would be consumed as its value.+func hermesArgvAwaitsValue(args []string) bool {+ for i := 0; i < len(args); i++ {+ n, open := hermesValueTokens(args, i)+ if open {+ return true+ }+ i += n+ }+ return false+}++// withoutIndices returns s minus the elements at the given indexes, in order.+func withoutIndices(s []string, drop []int) []string {+ out := make([]string, 0, len(s))+ for i, v := range s {+ if !slices.Contains(drop, i) {+ out = append(out, v)+ }+ }+ return out}// HermesLaunchArgv returns the exact argv Hermes will parse: the runtime's-// launch prefix, then `acp`, then the agent's custom args after the same-// blocked-flag filtering the backend applies.+// launch prefix, then the agent's custom args after the same filtering the+// backend applies, placed around `acp` the way the backend places them.//// The daemon resolves the profile selection from this rather than from a// hand-assembled approximation. Concatenating prefix and custom args alone// silently disagrees with the real command line, because the `acp` token-// participates in Hermes' scan: with fixed_args `--model` and custom_args-// `-p research`, the approximation reads `-p` as `--model`'s value and finds-// no selection, while the real `--model acp -p research` skips `--model acp`-// and selects `research`. The overlay would then be seeded from the default-// home while the process runs under a different profile's config.+// participates in Hermes' scan: a launch prefix ending in a bare `-p`, with no+// global custom arg after it, finds no selection in the approximation, while+// the real `-p acp` selects a profile named `acp`. The overlay would then be+// seeded from the default home while the process asks for a different profile.func HermesLaunchArgv(launchPrefix, customArgs []string, logger *slog.Logger) []string {- return Command{Prefix: launchPrefix}.Argv(hermesCLIArgs(customArgs, logger)...)+ return Command{Prefix: launchPrefix}.Argv(hermesCLIArgs(launchPrefix, customArgs, logger)...)}// StripHermesProfileSelectors removes every profile selection from the argv// Hermes will parse and hands each surviving token back to the region it came-// from — launch prefix or custom args.+// from — launch prefix or custom args, the latter in their configured order.//// The daemon calls this only when it built the per-task overlay, where the// overlay's HERMES_HOME is authoritative and nothing on the command line may@@ -183,8 +364,9 @@ func HermesLaunchArgv(launchPrefix, customArgs []string, logger *slog.Logger) []// reasons, both of which leave a live selector behind if ignored://// - A selection can straddle the boundary. A launch prefix ending in a bare-// `-p` takes the backend's own `acp` token as its value, and neither region-// contains a complete selection to strip.+// `-p` takes the first global custom arg — or, with none, the backend's own+// `acp` token — as its value, and neither region contains a complete+// selection to strip.// - Removing one selection promotes the next. Hermes honours the first and// ignores the rest, so a single pass can hand the job to a later// occurrence — and with the prefix and custom args configured separately,@@ -198,32 +380,29 @@ func StripHermesProfileSelectors(launchPrefix, customArgs []string, logger *slogprefix := append([]string(nil), launchPrefix...)custom := append([]string(nil), filterCustomArgs(customArgs, hermesBlockedArgs, logger)...)for {- sel := ParseHermesProfileArgs(Command{Prefix: prefix}.Argv(hermesCLIArgsFrom(custom)...))+ args, origin := hermesCLIArgsLayout(custom)+ sel := ParseHermesProfileArgs(Command{Prefix: prefix}.Argv(args...))if !sel.Found {return prefix, custom}- acpIndex := len(prefix)- removed := false- // Walk back to front so earlier indices stay valid as tokens go.- for i := sel.ArgFrom + sel.ArgLen - 1; i >= sel.ArgFrom; i-- {+ var fromPrefix, fromCustom []int+ for i := sel.ArgFrom; i < sel.ArgFrom+sel.ArgLen; i++ {switch {- case i < acpIndex:- prefix = append(prefix[:i], prefix[i+1:]...)- removed = true- case i == acpIndex:- // Backend-owned; re-added at launch.+ case i < len(prefix):+ fromPrefix = append(fromPrefix, i)+ case origin[i-len(prefix)] >= 0:+ fromCustom = append(fromCustom, origin[i-len(prefix)])default:- if j := i - acpIndex - 1; j < len(custom) {- custom = append(custom[:j], custom[j+1:]...)- removed = true- }+ // `acp`: backend-owned; re-added at launch.}}- if !removed {+ if len(fromPrefix)+len(fromCustom) == 0 {// Defensive: a selection always contains a flag from one of the two// regions, so this cannot loop forever. Bail rather than spin.return prefix, custom}+ prefix = withoutIndices(prefix, fromPrefix)+ custom = withoutIndices(custom, fromCustom)}}@@ -287,7 +466,7 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt// Same assembly HermesLaunchArgv reproduces for the daemon, so the profile// the overlay is seeded from is the one this argv actually selects.- hermesArgs := hermesCLIArgs(opts.CustomArgs, b.cfg.Logger)+ hermesArgs := hermesCLIArgs(b.cfg.LaunchPrefix, opts.CustomArgs, b.cfg.Logger)cmd := b.cfg.commandAt(execPath).exec(runCtx, hermesArgs...)hideAgentWindow(cmd)// What makes the shutdown below bounded. Wait waits on the direct child, and@@ -298,7 +477,7 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt// Wait is what lets the forced shutdown join its readers at all. Same 10s// the claude, codearts and antigravity backends use.cmd.WaitDelay = 10 * time.Second- b.cfg.logAgentCommand(cmd, newAgentCommandLogArgs(hermesArgs, trustAgentCommandPositional(0, hermesACPSubcommand)))+ b.cfg.logAgentCommand(cmd, newAgentCommandLogArgs(hermesArgs, trustAgentCommandPositional(hermesACPIndex(hermesArgs), hermesACPSubcommand)))agentsMDPresent := falseif opts.Cwd != "" {cmd.Dir = opts.Cwddiff --git a/server/pkg/agent/hermes_test.go b/server/pkg/agent/hermes_test.goindex 321841fe83..47a052258b 100644--- a/server/pkg/agent/hermes_test.go+++ b/server/pkg/agent/hermes_test.go@@ -4285,6 +4285,7 @@ func TestParseHermesProfileArgs(t *testing.T) {{"amid other args", []string{"--yolo", "--profile", "coder", "-x"}, "coder", true, false, 1, 2},{"space-form invalid value ignored", []string{"-p", "no:xdist"}, "", false, false, -1, 0},{"value-flag hides a following -p", []string{"-m", "-p", "research"}, "", false, false, -1, 0},+ {"parser-derived value flags hide a following -p", []string{"--reasoning", "-p", "research", "--in", "-p", "coder"}, "", false, false, -1, 0},{"double-dash sentinel stops scan", []string{"--", "-p", "research"}, "", false, false, -1, 0},{"mcp add --args passthrough stops scan", []string{"mcp", "add", "srv", "--args", "-p", "research"}, "", false, false, -1, 0},{"only the first occurrence is selected", []string{"-p", "research", "--profile", "coder"}, "research", true, false, 0, 2},diff --git a/server/pkg/agent/launch_test.go b/server/pkg/agent/launch_test.goindex 8a054abc7b..ad9ad4fc69 100644--- a/server/pkg/agent/launch_test.go+++ b/server/pkg/agent/launch_test.go@@ -7,6 +7,7 @@ import ("os""os/exec""path/filepath"+ "slices""strings""testing")@@ -508,45 +509,116 @@ func TestZeroclawLaunchPrefixFiltersBlockedFlags(t *testing.T) {}}-// TestHermesLaunchArgvMatchesBackendAssembly is the root of the second-round-// Hermes finding: the daemon must resolve the profile from the argv the backend-// actually builds, not from a concatenation that leaves out `acp`.-//-// With fixed_args `--model` and custom_args `-p research`, the two disagree.-// `--model` is a value-taking flag, so the approximation `--model -p research`-// consumes `-p` as its value and finds no selection at all, while the real-// `--model acp -p research` skips `--model acp` and selects `research`. Seeding-// the overlay from the first answer while the process runs the second is a-// silent config mismatch.+// TestHermesLaunchArgvMatchesBackendAssembly: the daemon must resolve the+// profile from the argv the backend actually builds — global custom args ahead+// of the `acp` subcommand (GH #8878), `acp`'s own flags behind it — not from a+// concatenation that leaves `acp` out.func TestHermesLaunchArgvMatchesBackendAssembly(t *testing.T) {t.Parallel()- prefix := []string{"--model"}- custom := []string{"-p", "research"}+ prefix := []string{"--yolo"}+ custom := []string{"-p", "research", "--yes", "--provider", "zai"}argv := HermesLaunchArgv(prefix, custom, slog.Default())- if want := []string{"--model", "acp", "-p", "research"}; strings.Join(argv, "\x00") != strings.Join(want, "\x00") {+ if want := []string{"--yolo", "-p", "research", "--provider", "zai", "acp", "--yes"}; strings.Join(argv, "\x00") != strings.Join(want, "\x00") {t.Fatalf("HermesLaunchArgv = %v, want %v", argv, want)}// It must equal what the backend hands the launch boundary.- backend := Command{Prefix: prefix}.Argv(hermesCLIArgs(custom, slog.Default())...)+ backend := Command{Prefix: prefix}.Argv(hermesCLIArgs(prefix, custom, slog.Default())...)if strings.Join(argv, "\x00") != strings.Join(backend, "\x00") {t.Fatalf("resolver argv %v diverges from backend argv %v", argv, backend)}- sel := ParseHermesProfileArgs(argv)- if !sel.Found || sel.Name != "research" {+ if sel := ParseHermesProfileArgs(argv); !sel.Found || sel.Name != "research" {t.Fatalf("selection = %+v, want research — the profile the process really reads", sel)}- // The approximation this replaced is what got it wrong.- if naive := ParseHermesProfileArgs(append(append([]string{}, prefix...), custom...)); naive.Found {- t.Fatalf("expected the prefix++custom approximation to disagree, got %+v", naive)++ // `acp` participates in the scan: a prefix ending in a bare `-p` selects a+ // profile named `acp`, which the prefix-only approximation cannot see.+ bare := []string{"-p"}+ if sel := ParseHermesProfileArgs(HermesLaunchArgv(bare, []string{"--yes"}, slog.Default())); !sel.Found || sel.Name != "acp" {+ t.Fatalf("selection = %+v, want the `acp` token hermes itself consumes", sel)+ }+ if naive := ParseHermesProfileArgs(append(bare, "--yes")); naive.Found {+ t.Fatalf("expected the approximation without `acp` to disagree, got %+v", naive)+ }+}++// TestHermesCLIArgsPlaceFlagsAroundSubcommand pins GH #8878: Hermes accepts its+// global flags only before the subcommand and the flags `acp` declares only+// after it — `hermes acp --provider zai` and `hermes --yes acp` both exit with+// a usage error, `hermes --provider zai acp --yes` launches. A global flag left+// without its value must not capture `acp` either: Hermes would read it as that+// flag's value and start interactive chat instead of the ACP server.+func TestHermesCLIArgsPlaceFlagsAroundSubcommand(t *testing.T) {+ t.Parallel()++ cases := []struct {+ name string+ prefix []string+ custom []string+ want []string+ }{+ {"no custom args", nil, nil, []string{"acp"}},+ {"global flags go before acp", nil, []string{"--provider", "zai", "--yolo"}, []string{"--provider", "zai", "--yolo", "acp"}},+ {"acp flags stay after acp", nil, []string{"--yes", "-y", "--accept-hooks"}, []string{"acp", "--yes", "-y", "--accept-hooks"}},+ {"mixed keeps each group's order", nil, []string{"--yes", "-p", "research", "--accept-hooks", "--provider", "zai"}, []string{"-p", "research", "--provider", "zai", "acp", "--yes", "--accept-hooks"}},+ {"a value stays with its flag", nil, []string{"-m", "--yes"}, []string{"-m", "--yes", "acp"}},+ {"blocked acp is still filtered", nil, []string{"acp", "--yolo"}, []string{"--yolo", "acp"}},+ {"inline value is complete", nil, []string{"--provider=zai"}, []string{"--provider=zai", "acp"}},+ {"bare value flag is dropped", nil, []string{"--provider"}, []string{"acp"}},+ {"bare value flag after a pair is dropped", nil, []string{"-m", "x", "--reasoning"}, []string{"-m", "x", "acp"}},+ {"bare profile flag is dropped", nil, []string{"--yolo", "-p"}, []string{"--yolo", "acp"}},+ {"bare optional-value flag is dropped", nil, []string{"-c", "--yes"}, []string{"acp", "--yes"}},+ {"a flag that is itself a value is kept", nil, []string{"--model", "--provider"}, []string{"--model", "--provider", "acp"}},+ {"prefix pairs with the first custom arg", []string{"--model"}, []string{"--provider"}, []string{"--provider", "acp"}},+ // Behind `acp`, `--y` is `--yes`; in front, the root parser would read+ // it as `--yolo` and turn off dangerous-command approval.+ {"an abbreviated acp flag stays after acp", nil, []string{"--y"}, []string{"acp", "--y"}},+ {"abbreviations acp resolves stay after acp", nil, []string{"--ye", "--acc", "--provider", "zai"}, []string{"--provider", "zai", "acp", "--ye", "--acc"}},+ {"an ambiguous acp prefix keeps its position", nil, []string{"--se"}, []string{"acp", "--se"}},+ {"an abbreviated global flag goes before acp", nil, []string{"--prov", "zai", "--y"}, []string{"--prov", "zai", "acp", "--y"}},+ {"an inline abbreviated value is complete", nil, []string{"--prov=zai"}, []string{"--prov=zai", "acp"}},+ {"a bare abbreviated value flag is dropped", nil, []string{"--yolo", "--prov"}, []string{"--yolo", "acp"}},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ got := hermesCLIArgs(tc.prefix, tc.custom, slog.Default())+ if strings.Join(got, "\x00") != strings.Join(tc.want, "\x00") {+ t.Fatalf("hermesCLIArgs(%v, %v) = %v, want %v", tc.prefix, tc.custom, got, tc.want)+ }+ if i := hermesACPIndex(got); got[i] != "acp" || slices.Index(tc.want, "acp") != i {+ t.Fatalf("hermesACPIndex(%v) = %d, want the subcommand's position", got, i)+ }+ })+ }+}++// TestIsHermesACPSubcommandFlag: a token stays behind `acp` whenever the acp+// subparser would read it as its own option — argparse resolves unambiguous+// long-option abbreviations, so a string match would let `--y` (`--yes`) move+// in front of `acp`, where the root parser reads it as `--yolo`.+func TestIsHermesACPSubcommandFlag(t *testing.T) {+ t.Parallel()++ for token, want := range map[string]bool{+ "--yes": true, "--y": true, "--ye": true, "-y": true, "-yh": true,+ "--accept-hooks": true, "--acc": true, "--setup-browser": true,+ "--se": true, "--yes=1": true, "--help": true,+ "--yolo": false, "--provider": false, "--prov": false, "-p": false,+ "--": false, "zai": false, "": false,+ } {+ if got := isHermesACPSubcommandFlag(token); got != want {+ t.Errorf("isHermesACPSubcommandFlag(%q) = %v, want %v", token, got, want)+ }}}// TestStripHermesProfileSelectorsSpansRegionBoundary: a launch prefix ending in-// a bare `-p` captures the backend's own `acp` token as its profile value.-// Neither region holds a complete selection, so stripping them separately-// leaves the selector live and the task walks out of the overlay.+// a bare `-p` captures the first custom arg — or, with none, the backend's own+// `acp` token — as its profile value. Neither region holds a complete+// selection, so stripping them separately leaves the selector live and the+// task walks out of the overlay.func TestStripHermesProfileSelectorsSpansRegionBoundary(t *testing.T) {t.Parallel()@@ -558,8 +630,15 @@ func TestStripHermesProfileSelectorsSpansRegionBoundary(t *testing.T) {if len(prefix) != 0 {t.Fatalf("the straddling `-p` must be removed from the prefix, got %v", prefix)}- if strings.Join(custom, "\x00") != strings.Join([]string{"research", "--yolo"}, "\x00") {- t.Fatalf("custom args must survive intact, got %v", custom)+ if strings.Join(custom, "\x00") != "--yolo" {+ t.Fatalf("custom = %v, want only the captured value removed", custom)+ }++ // With no custom args the prefix captures `acp`, which the backend owns and+ // re-adds at launch: only the flag goes.+ prefix, custom = StripHermesProfileSelectors([]string{"wrapper-sub", "-p"}, nil, slog.Default())+ if strings.Join(prefix, "\x00") != "wrapper-sub" || len(custom) != 0 {+ t.Fatalf("prefix = %v, custom = %v, want only the `-p` removed", prefix, custom)}}@@ -587,6 +666,23 @@ func TestStripHermesProfileSelectorsRemovesEveryOccurrence(t *testing.T) {}}+// TestStripHermesProfileSelectorsKeepsCustomArgOrder: `acp`'s own flags launch+// behind the subcommand, so the assembled argv reorders custom args. Stripping+// must still remove the selection's own tokens and hand the rest back in their+// configured order.+func TestStripHermesProfileSelectorsKeepsCustomArgOrder(t *testing.T) {+ t.Parallel()++ prefix, custom := StripHermesProfileSelectors(nil,+ []string{"--yes", "-p", "research", "--accept-hooks", "--provider", "zai"}, slog.Default())+ if len(prefix) != 0 {+ t.Fatalf("prefix = %v, want empty", prefix)+ }+ if want := []string{"--yes", "--accept-hooks", "--provider", "zai"}; strings.Join(custom, "\x00") != strings.Join(want, "\x00") {+ t.Fatalf("custom = %v, want %v", custom, want)+ }+}+// TestStripHermesProfileSelectorsLeavesInvalidSelectionAlone: a value hermes// itself discards redirects nothing, so removing it would only mangle the// user's argv.