High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: details.remedy means four different things across ten producers, so an agent that executes it mis-runs eight — one validated constructor owns the field, and one undocumented remedy is dropped from the TLS refusal (PIN-193)
Luigi Agosti80060a872689
diff --git a/cmd/pinchtab/capability_remedy_executable_test.go b/cmd/pinchtab/capability_remedy_executable_test.goindex 88cdba05..b1a85bb8 100644--- a/cmd/pinchtab/capability_remedy_executable_test.go+++ b/cmd/pinchtab/capability_remedy_executable_test.go@@ -1,12 +1,15 @@package mainimport (+ "reflect""strings""testing""github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/httpx"+ "github.com/pinchtab/pinchtab/internal/remedy""github.com/pinchtab/pinchtab/internal/routes"+ "github.com/spf13/cobra")// capabilitySettings are the config paths a capability refusal can name, derived@@ -30,47 +33,110 @@ func capabilitySettings(t *testing.T) []string {return settings}-// A remedy an agent cannot execute is not a remedy. This resolves each command in-// the refusal against the REAL command tree — the same rootCmd the binary runs —-// rather than eyeballing the string, because the failure mode being closed is a-// remedy that reads plausibly and dead-ends when run.-func TestCapabilityRemedyCommandsResolveInTheCLI(t *testing.T) {- for _, setting := range capabilitySettings(t) {- remedy, _ := httpx.DisabledEndpointDetails(setting)["remedy"].(string)+// A remedy an agent cannot execute is not a remedy. This resolves each command in EVERY+// declared remedy against the REAL command tree — the same rootCmd the binary runs — rather+// than eyeballing the strings, because the failure mode being closed is a remedy that reads+// plausibly and dead-ends when run.+//+// It walks remedy.Templates() rather than a list of producers, which is why it covers a+// producer added after it was written: declaring a remedy anywhere in the binary's import+// graph registers it, and this test links the whole binary. The guard started life covering+// the capability refusal alone, and every other producer of the field was free to mean+// something else; the population it walks is now the population that exists.+func TestEveryDeclaredRemedyResolvesInTheCLI(t *testing.T) {+ declared := remedy.Templates()+ // The floor is a vacuity check, not a census: the producers are enumerated by the+ // registry above. It must fail if linking stops pulling the producer packages in,+ // because an empty walk passes for the wrong reason.+ if len(declared) < 8 {+ t.Fatalf("only %d remedies are declared in the whole binary (%v); the walk has lost the producer packages and would pass vacuously", len(declared), declared)+ }+ for _, line := range declared {+ t.Run(line, func(t *testing.T) {+ assertRemedyRuns(t, line)+ })+ }+}++// assertRemedyRuns is the check itself, separated so a test can show it RED against a line+// the property forbids.+func assertRemedyRuns(t *testing.T, line string) {+ t.Helper()- commands := strings.Split(remedy, "&&")- if len(commands) != 2 {- t.Fatalf("remedy for %s is not two shell-joined commands: %q", setting, remedy)+ segments := remedy.Segments(line)+ if len(segments) == 0 {+ t.Fatalf("remedy %q is not a shell command line", line)+ }+ for _, words := range segments {+ if words[0] != "pinchtab" {+ t.Errorf("remedy command %v does not invoke pinchtab", words)+ continue}- for _, command := range commands {- fields := strings.Fields(strings.TrimSpace(command))- if len(fields) == 0 || fields[0] != "pinchtab" {- t.Errorf("remedy command %q does not invoke pinchtab", command)+ var args, flags []string+ for _, word := range words[1:] {+ if strings.HasPrefix(word, "-") {+ flags = append(flags, word)continue}- args := fields[1:]+ args = append(args, word)+ }- found, rest, err := rootCmd.Find(args)- if err != nil {- t.Errorf("remedy command %q does not resolve: %v", command, err)- continue- }- if !found.Runnable() {- t.Errorf("remedy command %q resolves to %q, which is a command group and does nothing when run",- command, found.CommandPath())- continue+ found, rest, err := rootCmd.Find(args)+ if err != nil {+ t.Errorf("remedy command %v does not resolve: %v", words, err)+ continue+ }+ if !found.Runnable() || printsGroupHelp(found) {+ t.Errorf("remedy command %v resolves to %q, which is a command group and only prints help when run",+ words, found.CommandPath())+ continue+ }+ if found.Args != nil {+ if err := found.Args(found, rest); err != nil {+ t.Errorf("remedy command %v resolves to %q but its arguments %v are rejected: %v",+ words, found.CommandPath(), rest, err)}- if found.Args != nil {- if err := found.Args(found, rest); err != nil {- t.Errorf("remedy command %q resolves to %q but its arguments %v are rejected: %v",- command, found.CommandPath(), rest, err)- }+ }+ // A flag the resolved command does not define is the same dead end as a missing+ // verb, and it is the likelier one: a remedy naming --wait-nav outlives a rename.+ for _, flag := range flags {+ name := strings.TrimLeft(flag, "-")+ if found.Flags().Lookup(name) == nil && found.InheritedFlags().Lookup(name) == nil {+ t.Errorf("remedy command %v names flag %q, which %q does not define", words, flag, found.CommandPath())}}}}+// printsGroupHelp reports whether the command's only action is the help the unknown-subcommand+// guard installs on groups. Runnable() alone stopped answering this question when that guard+// landed: every group is now runnable, and a remedy naming one still does nothing.+func printsGroupHelp(cmd *cobra.Command) bool {+ if cmd.Run != nil || cmd.RunE == nil {+ return false+ }+ return reflect.ValueOf(cmd.RunE).Pointer() == reflect.ValueOf(printGroupHelp).Pointer()+}++// The guard has to be able to fail, and these are the shapes it must fail on: a verb that+// does not exist, a group that does nothing when run, and a flag the command never defined.+// Each is a remedy that reads plausibly and dead-ends when an agent runs it.+func TestTheRemedyGuardRedsOnACommandThatCannotRun(t *testing.T) {+ for _, line := range []string{+ "pinchtab unclog",+ "pinchtab config get security.allowedDomains && pinchtab unclog",+ "pinchtab session",+ "pinchtab back --wait-nav",+ } {+ fake := &testing.T{}+ assertRemedyRuns(fake, line)+ if !fake.Failed() {+ t.Errorf("the guard accepts %q, so it would accept a remedy nobody can run", line)+ }+ }+}+// The other half of executable: `config set <path> true` is only real if the// config editor accepts that path. A setting present in the schema but missing// from the editor's field table dead-ends every message that cites it.@@ -87,11 +153,11 @@ func TestCapabilityRemedySettingsAreAcceptedByTheConfigEditor(t *testing.T) {// through the tree rather than asserting the literal means a renamed or moved// verb reds here instead of shipping a remedy nobody can run.func TestCapabilityRemedyRestartCommandExists(t *testing.T) {- remedy, _ := httpx.DisabledEndpointDetails("security.allowCookies")["remedy"].(string)+ line, _ := httpx.DisabledEndpointDetails("security.allowCookies")["remedy"].(string)const restart = "pinchtab server restart"- if !strings.Contains(remedy, restart) {- t.Fatalf("remedy = %q, want it to name %q", remedy, restart)+ if !strings.Contains(line, restart) {+ t.Fatalf("remedy = %q, want it to name %q", line, restart)}found, _, err := rootCmd.Find([]string{"server", "restart"})if err != nil || found.CommandPath() != "pinchtab server restart" {diff --git a/cmd/pinchtab/cmd_session.go b/cmd/pinchtab/cmd_session.goindex 333d30cd..8db456a7 100644--- a/cmd/pinchtab/cmd_session.go+++ b/cmd/pinchtab/cmd_session.go@@ -133,30 +133,37 @@ func init() {// carries no code at all — falls through to the generic API error. A permissive default// here would silently reuse the config remedy for the next mode, which is the conflation// this replaced.-func sessionUnavailableAdvice(rawBody []byte) (message, remedy string, ok bool) {+// Both halves are read because only one state has a remedy: enabling agent sessions on a+// full server is a file edit plus a restart, which is not one command, so that state carries+// its guidance as a hint. A reader of the remedy alone would print nothing there.+func sessionUnavailableAdvice(rawBody []byte) (message, hint, remedy string, ok bool) {var resp struct {Code string `json:"code"`Error string `json:"error"`Details struct {+ Hint string `json:"hint"`Remedy string `json:"remedy"`} `json:"details"`}if json.Unmarshal(rawBody, &resp) != nil {- return "", "", false+ return "", "", "", false}switch resp.Code {case server.CodeSessionsUnavailableInBridgeMode, server.CodeSessionsDisabled:- return resp.Error, resp.Details.Remedy, true+ return resp.Error, resp.Details.Hint, resp.Details.Remedy, true}- return "", "", false+ return "", "", "", false}func exitSessionUnavailable(rawBody []byte) {- message, remedy, ok := sessionUnavailableAdvice(rawBody)+ message, hint, remedy, ok := sessionUnavailableAdvice(rawBody)if !ok {return}fmt.Fprintf(os.Stderr, "Error: %s\n", message)+ if hint != "" {+ output.Hint(hint)+ }if remedy != "" {output.Hint(remedy)}diff --git a/cmd/pinchtab/cmd_session_unavailable_test.go b/cmd/pinchtab/cmd_session_unavailable_test.goindex 73878672..dd99288a 100644--- a/cmd/pinchtab/cmd_session_unavailable_test.go+++ b/cmd/pinchtab/cmd_session_unavailable_test.go@@ -36,27 +36,30 @@ func TestSessionCreateAdviceDiffersPerUnavailableState(t *testing.T) {register func(*http.ServeMux)path stringwantAdvice bool- wantRemedy string- banned string- why string+ // wantGuidance is matched against hint AND remedy together: the two states carry+ // their guidance in different fields, because only one of them has a single command+ // to run, and the CLI prints whichever is present.+ wantGuidance string+ banned string+ why string}{{- name: "bridge mode",- register: server.RegisterSessionsUnavailableInBridgeMode,- path: "/sessions",- wantAdvice: true,- wantRemedy: "pinchtab server",- banned: "sessions.agent.enabled",- why: "no config value mounts the family on a bridge, so a config remedy is the unescapable loop this card fixes",+ name: "bridge mode",+ register: server.RegisterSessionsUnavailableInBridgeMode,+ path: "/sessions",+ wantAdvice: true,+ wantGuidance: "pinchtab server",+ banned: "sessions.agent.enabled",+ why: "no config value mounts the family on a bridge, so a config remedy is the unescapable loop this card fixes",},{- name: "server with sessions disabled",- register: server.RegisterSessionsDisabled,- path: "/sessions",- wantAdvice: true,- wantRemedy: "sessions.agent.enabled",- banned: "",- why: "this is the one state the config remedy fits",+ name: "server with sessions disabled",+ register: server.RegisterSessionsDisabled,+ path: "/sessions",+ wantAdvice: true,+ wantGuidance: "sessions.agent.enabled",+ banned: "",+ why: "this is the one state the config edit fits, and it is a file edit rather than a command",},{name: "unknown path",@@ -69,7 +72,8 @@ func TestSessionCreateAdviceDiffersPerUnavailableState(t *testing.T) {t.Run(tc.name, func(t *testing.T) {body := sessionCreateResponse(t, tc.register, tc.path)- message, remedy, ok := sessionUnavailableAdvice(body)+ message, hint, remedy, ok := sessionUnavailableAdvice(body)+ guidance := hint + " " + remedyif ok != tc.wantAdvice {t.Fatalf("advice recognised = %v, want %v; %s (body=%s)", ok, tc.wantAdvice, tc.why, body)}@@ -79,11 +83,11 @@ func TestSessionCreateAdviceDiffersPerUnavailableState(t *testing.T) {if message == "" {t.Errorf("no message, so the CLI prints an empty Error: line")}- if !strings.Contains(remedy, tc.wantRemedy) {- t.Errorf("remedy = %q, want it to name %q; %s", remedy, tc.wantRemedy, tc.why)+ if !strings.Contains(guidance, tc.wantGuidance) {+ t.Errorf("guidance = %q, want it to name %q; %s", guidance, tc.wantGuidance, tc.why)}- if tc.banned != "" && strings.Contains(remedy, tc.banned) {- t.Errorf("remedy = %q, which prescribes %q; %s", remedy, tc.banned, tc.why)+ if tc.banned != "" && strings.Contains(guidance, tc.banned) {+ t.Errorf("guidance = %q, which prescribes %q; %s", guidance, tc.banned, tc.why)}})}@@ -100,7 +104,7 @@ func TestAnUnrecognisedCodeGetsNoSessionAdvice(t *testing.T) {`404 page not found`,``,} {- if _, _, ok := sessionUnavailableAdvice([]byte(body)); ok {+ if _, _, _, ok := sessionUnavailableAdvice([]byte(body)); ok {t.Errorf("body %q was treated as a known unavailable state; an unrecognised code must fall through to the generic error", body)}}diff --git a/internal/cli/apiclient/apierror.go b/internal/cli/apiclient/apierror.goindex f2745a70..1f49af56 100644--- a/internal/cli/apiclient/apierror.go+++ b/internal/cli/apiclient/apierror.go@@ -8,6 +8,8 @@ import ("net/url""os""strings"++ "github.com/pinchtab/pinchtab/internal/remedy")// mustRequest is doRequest with the common fatal-on-transport-error policy.@@ -99,15 +101,22 @@ func namesCachedTab(statusCode int, body []byte) bool {bytes.Contains(body, []byte(cachedTab.TabID))}-// staleTabRemedy says where the id came from, and claims nothing about the cache's+// A fresh tab is the one command this CLI-side advice can name. The prose that used to+// carry it — where the id came from, and that a retry is enough — is a hint, because this+// line prints into the same slot a server remedy does and a caller cannot tell them apart:+// see internal/remedy for what that slot promises.+var openFreshTab = remedy.Declare("pinchtab nav <url>")++// staleTabAdvice says where the id came from, and claims nothing about the cache's// current state — it is emitted on returning paths too, where nothing is cleared.// A retry is still the right advice there: the cached id is re-probed at the start// of every command, so the next one drops it.-func staleTabRemedy(statusCode int, body []byte) string {+func staleTabAdvice(statusCode int, body []byte) (string, remedy.Remedy) {if !namesCachedTab(statusCode, body) {- return ""+ return "", remedy.None}- return fmt.Sprintf(" Remedy: that tab id is this CLI's cached current tab for %s, not something you asked for; retry the command (or run `pinchtab nav <url>` to open a fresh tab)\n", cachedTab.Base)+ return fmt.Sprintf("that tab id is this CLI's cached current tab for %s, not something you asked for; retry the command, or open a fresh tab", cachedTab.Base),+ openFreshTab.Remedy()}// clearCachedTabOnFailure drops the cache that produced the dead id and reports@@ -143,14 +152,24 @@ func renderAPIErrorBody(statusCode int, body []byte) string {}if errResp.Details != nil {- if hint, ok := errResp.Details["hint"].(string); ok && hint != "" {- fmt.Fprintf(&b, "\n💡 %s\n", hint)- }- if remedy, ok := errResp.Details["remedy"].(string); ok && remedy != "" {- fmt.Fprintf(&b, " Remedy: %s\n", remedy)- }+ hint, _ := errResp.Details["hint"].(string)+ line, _ := errResp.Details["remedy"].(string)+ b.WriteString(renderGuidance(hint, remedy.Remedy(line)))+ }+ b.WriteString(renderGuidance(staleTabAdvice(statusCode, body)))+ return b.String()+}++// renderGuidance is the ONE writer of both guidance slots, so a second producer cannot+// print prose into the line a caller reads as executable. Either half may be absent.+func renderGuidance(hint string, r remedy.Remedy) string {+ var b strings.Builder+ if hint != "" {+ fmt.Fprintf(&b, "\n💡 %s\n", hint)+ }+ if !r.Empty() {+ fmt.Fprintf(&b, " Remedy: %s\n", r)}- b.WriteString(staleTabRemedy(statusCode, body))return b.String()}diff --git a/internal/dashboard/agent_session_api.go b/internal/dashboard/agent_session_api.goindex 58395f13..d32b61eb 100644--- a/internal/dashboard/agent_session_api.go+++ b/internal/dashboard/agent_session_api.go@@ -9,6 +9,7 @@ import ("github.com/pinchtab/pinchtab/internal/authn""github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/httpx"+ "github.com/pinchtab/pinchtab/internal/remedy""github.com/pinchtab/pinchtab/internal/session")@@ -147,20 +148,26 @@ func (a *SessionAPI) handleGet(w http.ResponseWriter, r *http.Request) {// authenticated as one at all. Handing that back is safe — the caller already holds// that session's secret — and it is the whole remedy, so they need no second command.// Returns nil for anything that is not a token, leaving the plain refusal alone.+//+// When the caller's own id is unknown the remedy is the listing, because that is the one+// command that always works here: `session info` needs PINCHTAB_SESSION exported, which is+// a precondition this refusal cannot verify, so it belongs in the hint.func tokenSuppliedForIDDetails(supplied, callerSessionID string) map[string]any {if !session.LooksLikeToken(supplied) {return nil}- remedy := "pinchtab session info (with PINCHTAB_SESSION set) prints the id, or pinchtab session list"+ r := listSessions.Remedy()if callerSessionID != "" {- remedy = "pinchtab session revoke " + callerSessionID- }- return map[string]any{- "hint": "that is a session TOKEN, not a session id — these endpoints take the id so an operator can end a session without holding its secret",- "remedy": remedy,+ r = revokeCallerSession.Fill(callerSessionID)}+ return remedy.Details("that is a session TOKEN, not a session id — these endpoints take the id so an operator can end a session without holding its secret. With PINCHTAB_SESSION set, pinchtab session info prints the id.", r)}+var (+ listSessions = remedy.Declare("pinchtab session list")+ revokeCallerSession = remedy.Declare("pinchtab session revoke <session-id>")+)+func respondSessionNotFound(w http.ResponseWriter, supplied string) {httpx.ErrorCode(w, http.StatusNotFound, "session_not_found", "session not found", false,tokenSuppliedForIDDetails(supplied, ""))diff --git a/internal/dashboard/agent_session_api_test.go b/internal/dashboard/agent_session_api_test.goindex 1c03af48..411f4cd6 100644--- a/internal/dashboard/agent_session_api_test.go+++ b/internal/dashboard/agent_session_api_test.go@@ -317,10 +317,14 @@ func TestSupplyingATokenWhereAnIDGoesExplainsTheDifference(t *testing.T) {if !strings.Contains(details["hint"], "TOKEN") || !strings.Contains(details["hint"], "not a session id") {t.Errorf("hint does not name the id/token distinction: %q", details["hint"])}- for _, want := range []string{"session info", "session list"} {- if !strings.Contains(details["remedy"], want) {- t.Errorf("remedy %q does not point at %q, so the id is unreachable without already knowing it", details["remedy"], want)- }+ // The listing is the remedy because it is the one command that works with+ // nothing else set up; `session info` needs PINCHTAB_SESSION exported, a+ // precondition a remedy cannot state, so it is named in the hint instead.+ if want := "pinchtab session list"; details["remedy"] != want {+ t.Errorf("remedy = %q, want %q — the id is unreachable without a command that lists it", details["remedy"], want)+ }+ if !strings.Contains(details["hint"], "session info") {+ t.Errorf("hint %q does not mention session info, the other way to reach the id", details["hint"])}})}diff --git a/internal/dashboard/auth_api.go b/internal/dashboard/auth_api.goindex df43b6ca..a35c3018 100644--- a/internal/dashboard/auth_api.go+++ b/internal/dashboard/auth_api.go@@ -12,6 +12,7 @@ import ("github.com/pinchtab/pinchtab/internal/browsersession""github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/httpx"+ "github.com/pinchtab/pinchtab/internal/remedy")type AuthAPI struct {@@ -82,10 +83,11 @@ func (a *AuthAPI) HandleLogin(w http.ResponseWriter, r *http.Request) {}if a.requiresHTTPSForDashboardSession(r) {- httpx.ErrorCode(w, http.StatusBadRequest, "secure_cookie_requires_https", "server.cookieSecure=true requires HTTPS for dashboard login", false, map[string]any{- "hint": "Use HTTPS directly or through a trusted reverse proxy, or set server.cookieSecure back to auto/false for plain HTTP local use.",- "remedy": "If TLS terminates in front of PinchTab, also enable server.trustProxyHeaders so forwarded https requests are recognized.",- })+ // No remedy: the fix is a choice between three postures, not one command, and an+ // absent field says that truthfully. The guidance survives in the hint.+ httpx.ErrorCode(w, http.StatusBadRequest, "secure_cookie_requires_https", "server.cookieSecure=true requires HTTPS for dashboard login", false,+ remedy.Details("Use HTTPS directly or through a trusted reverse proxy, or set server.cookieSecure back to auto/false for plain HTTP local use. If TLS terminates in front of PinchTab, also enable server.trustProxyHeaders so forwarded https requests are recognized.",+ remedy.None))return}diff --git a/internal/handlers/actions.go b/internal/handlers/actions.goindex 609b44f1..009588f8 100644--- a/internal/handlers/actions.go+++ b/internal/handlers/actions.go@@ -18,6 +18,7 @@ import ("github.com/pinchtab/pinchtab/internal/browsers""github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/httpx"+ "github.com/pinchtab/pinchtab/internal/remedy""github.com/pinchtab/pinchtab/internal/routes""github.com/pinchtab/pinchtab/internal/selector""github.com/pinchtab/pinchtab/internal/session"@@ -85,15 +86,16 @@ func rejectMultiStepSubmitClicks(w http.ResponseWriter, actions []bridge.ActionRreturn true}-const navigationChangedHint = "The action navigated the page, which the guard reports unless the request declares it: set waitNav true to wait for the navigation, or submit true when the click submits a form."+const navigationChangedHint = "The action navigated the page, which the guard reports unless the request declares it: set waitNav true to wait for the navigation, or submit true when the click submits a form. From the CLI those are --wait-nav and --submit."-const navigationChangedRemedy = "pinchtab click <ref> --wait-nav (use --submit instead when the click submits a form)"+// The ref stays a placeholder: this guard reports on an action it did not receive the ref+// for — it is reached from the post-action navigation check, which sees only the error —+// so there is no value here to interpolate. The alternative flag stays in the hint,+// because a remedy names one command to run.+var navigationChangedRemedy = remedy.Declare("pinchtab click <ref> --wait-nav")func navigationChangedDetails(err error) map[string]any {- details := map[string]any{- "hint": navigationChangedHint,- "remedy": navigationChangedRemedy,- }+ details := remedy.Details(navigationChangedHint, navigationChangedRemedy.Remedy())if url := navigatedToURL(err); url != "" {details["url"] = url}diff --git a/internal/handlers/actions_test.go b/internal/handlers/actions_test.goindex bd61af6e..cd6b9f5e 100644--- a/internal/handlers/actions_test.go+++ b/internal/handlers/actions_test.go@@ -677,11 +677,17 @@ func TestHandleAction_NavigationChangedCarriesHintAndRemedy(t *testing.T) {t.Fatalf("hint %q does not name request field %q", hint, want)}}- remedy, _ := resp.Details["remedy"].(string)- for _, want := range []string{"--wait-nav", "--submit"} {- if !strings.Contains(remedy, want) {- t.Fatalf("remedy %q does not name CLI flag %q", remedy, want)- }+ // One command, one flag: the remedy is a line a caller can run, so the alternative+ // flag belongs in the hint. Naming both here is what made the field unrunnable.+ line, _ := resp.Details["remedy"].(string)+ if want := "pinchtab click <ref> --wait-nav"; line != want {+ t.Fatalf("remedy = %q, want %q", line, want)+ }+ if strings.Contains(line, "--submit") {+ t.Fatalf("remedy %q offers two flags, so it is not one command to run", line)+ }+ if !strings.Contains(hint, "--submit") {+ t.Fatalf("hint %q does not name the --submit alternative the remedy dropped", hint)}if got, _ := resp.Details["url"].(string); got != "https://pinchtab.com/docs/" {t.Fatalf("details[url] = %q, want the resulting URL", got)diff --git a/internal/handlers/dialog_blocked.go b/internal/handlers/dialog_blocked.goindex ccec92c5..8d0e493d 100644--- a/internal/handlers/dialog_blocked.go+++ b/internal/handlers/dialog_blocked.go@@ -6,13 +6,17 @@ import ("github.com/pinchtab/pinchtab/internal/bridge""github.com/pinchtab/pinchtab/internal/httpx"+ "github.com/pinchtab/pinchtab/internal/remedy")const dialogBlockedCode = "dialog_blocked"-const dialogBlockedHint = "a JavaScript dialog is open on this tab and blocks every page interaction until it is answered. It belongs to this tab, so retrying, activating the tab or opening a fresh one cannot clear it."+const dialogBlockedHint = "a JavaScript dialog is open on this tab and blocks every page interaction until it is answered. It belongs to this tab, so retrying, activating the tab or opening a fresh one cannot clear it. Use pinchtab dialog dismiss to cancel it instead of accepting, or pass --dialog-action accept|dismiss on the action that opens the dialog."-const dialogBlockedRemedy = "pinchtab dialog accept|dismiss (or pass --dialog-action accept|dismiss on the action that opens the dialog)"+// Accepting is the remedy because it is the answer that lets the blocked interaction+// proceed; dismissing is the other choice a reader may want and lives in the hint. The+// old value offered both as "accept|dismiss", which a shell reads as a pipeline.+var dialogBlockedRemedy = remedy.Declare("pinchtab dialog accept")func pendingTabDialog(b bridge.BridgeAPI, tabID string) *bridge.DialogState {if b == nil || tabID == "" {@@ -30,13 +34,11 @@ func dialogBlockedMessage(tabID string, dialog *bridge.DialogState) string {}func dialogBlockedDetails(tabID string, dialog *bridge.DialogState) map[string]any {- return map[string]any{- "tabId": tabID,- "dialogType": dialog.Type,- "dialogMessage": dialog.Message,- "hint": dialogBlockedHint,- "remedy": dialogBlockedRemedy,- }+ details := remedy.Details(dialogBlockedHint, dialogBlockedRemedy.Remedy())+ details["tabId"] = tabID+ details["dialogType"] = dialog.Type+ details["dialogMessage"] = dialog.Message+ return details}func writeDialogBlocked(w http.ResponseWriter, tabID string, dialog *bridge.DialogState, message string) {diff --git a/internal/handlers/dialog_blocked_test.go b/internal/handlers/dialog_blocked_test.goindex ed2157b5..c2168ea6 100644--- a/internal/handlers/dialog_blocked_test.go+++ b/internal/handlers/dialog_blocked_test.go@@ -45,7 +45,7 @@ func decodeDialogBlocked(t *testing.T, w *httptest.ResponseRecorder, dialog *briif failure.Details.DialogType != dialog.Type || failure.Details.DialogMessage != dialog.Message {t.Fatalf("dialog not named: %s", w.Body.String())}- if failure.Details.Remedy != dialogBlockedRemedy {+ if failure.Details.Remedy != dialogBlockedRemedy.String() {t.Fatalf("remedy = %q, want %q", failure.Details.Remedy, dialogBlockedRemedy)}if failure.Details.Hint == "" {diff --git a/internal/handlers/idpi_domain_block.go b/internal/handlers/idpi_domain_block.goindex 8ce4c2d3..7f9febc1 100644--- a/internal/handlers/idpi_domain_block.go+++ b/internal/handlers/idpi_domain_block.go@@ -1,12 +1,12 @@package handlersimport (- "fmt""net/http""strings""github.com/pinchtab/pinchtab/internal/httpx""github.com/pinchtab/pinchtab/internal/navguard"+ "github.com/pinchtab/pinchtab/internal/remedy")// idpiDomainBlockedCode is the one code every IDPI domain block reports, so a@@ -22,9 +22,9 @@ const idpiDomainBlockedCode = "idpi_domain_blocked"// that lead erodes the posture instead of recovering. Going back does recover —// no navigation or history endpoint consults this guard, so `back` can always// reach a tab the read verbs have locked out.-const idpiDriftedTabHint = "the tab navigated to a domain outside security.allowedDomains, so this page was never read — the block describes where the tab is, not what you asked for. Do not widen the allowlist to get past it."+const idpiDriftedTabHint = "the tab navigated to a domain outside security.allowedDomains, so this page was never read — the block describes where the tab is, not what you asked for. Do not widen the allowlist to get past it. Going back returns the tab to the previous allowed page; when there is no history entry, navigate to an allowed URL or close the tab."-const idpiDriftedTabRemedy = "pinchtab back (returns the tab to the previous allowed page; use pinchtab nav <allowed-url> when there is no history entry, or close the tab)"+var idpiDriftedTabRemedy = remedy.Declare("pinchtab back")// A refused target URL is the opposite case: nothing navigated, there is nothing// to recover from, and the allowlist genuinely is the only lever — so this is the@@ -38,21 +38,16 @@ func writeIDPIDomainBlocked(w http.ResponseWriter, message string, details map[s}func idpiDriftedTabDetails(url string) map[string]any {- return idpiBlockDetails(url, idpiDriftedTabHint, idpiDriftedTabRemedy)+ return idpiBlockDetails(url, idpiDriftedTabHint, idpiDriftedTabRemedy.Remedy())}func idpiRefusedURLDetails(url string) map[string]any {return idpiBlockDetails(url, idpiRefusedURLHint, idpiAllowlistRemedy(url))}-func idpiBlockDetails(url, hint, remedy string) map[string]any {- details := map[string]any{- "hint": hint,- "url": url,- }- if remedy != "" {- details["remedy"] = remedy- }+func idpiBlockDetails(url, hint string, r remedy.Remedy) map[string]any {+ details := remedy.Details(hint, r)+ details["url"] = url// The domain is a discrete field as well as prose so MCP and dashboard// consumers do not have to parse the sentence to learn what was blocked.if host, ok := navguard.ExtractHost(url); ok && strings.TrimSpace(host) != "" {@@ -61,15 +56,18 @@ func idpiBlockDetails(url, hint, remedy string) map[string]any {return details}-// idpiAllowlistRemedy is the copy-pasteable widening of the allowlist, appending-// to the current value rather than replacing it. A hostless target (about:blank)-// cannot be allowlisted at all, so it gets no remedy instead of one that cannot-// work.-func idpiAllowlistRemedy(url string) string {+// allowlistWidening appends to the current allowlist rather than replacing it, and carries+// the restart because the security block is snapshotted at boot.+var allowlistWidening = remedy.Declare(+ `pinchtab config set security.allowedDomains "$(pinchtab config get security.allowedDomains),<domain>" && pinchtab server restart`)++// idpiAllowlistRemedy is the copy-pasteable widening of the allowlist. A hostless target+// (about:blank) cannot be allowlisted at all, so it gets no remedy instead of one that+// cannot work.+func idpiAllowlistRemedy(url string) remedy.Remedy {host, ok := navguard.ExtractHost(url)if !ok || strings.TrimSpace(host) == "" {- return ""+ return remedy.None}- return fmt.Sprintf("pinchtab config set security.allowedDomains "+- "\"$(pinchtab config get security.allowedDomains),%s\" then: pinchtab server restart", host)+ return allowlistWidening.Fill(host)}diff --git a/internal/handlers/navigation.go b/internal/handlers/navigation.goindex 22703750..db4e3785 100644--- a/internal/handlers/navigation.go+++ b/internal/handlers/navigation.go@@ -17,6 +17,7 @@ import ("github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/httpx""github.com/pinchtab/pinchtab/internal/navguard"+ "github.com/pinchtab/pinchtab/internal/remedy")// HandleNavigate navigates a tab to a URL or creates a new tab.@@ -692,12 +693,15 @@ func isNavigateAbortedOnBinary(err error, url string) bool {return false}+// The pair used to be inverted: the remedy held the bare verb "download" and the hint held+// the command. The URL is known here, so the remedy is the whole command.+var downloadInstead = remedy.Declare(`pinchtab download "<url>"`)+func navigateErrorWithHint(w http.ResponseWriter, code int, err error, url string) {if isNavigateAbortedOnBinary(err, url) {- httpx.ErrorCode(w, 502, "nav_binary_aborted", fmt.Sprintf("navigate: %s", err.Error()), false, map[string]any{- "remedy": "download",- "hint": fmt.Sprintf("Chrome cannot render binary/compressed files. Use: pinchtab download %q", url),- })+ httpx.ErrorCode(w, 502, "nav_binary_aborted", fmt.Sprintf("navigate: %s", err.Error()), false,+ remedy.Details("Chrome cannot render binary/compressed files, so this URL has to be downloaded instead.",+ downloadInstead.Fill(url)))return}httpx.Error(w, code, fmt.Errorf("navigate: %w", err))diff --git a/internal/handlers/navigation_idpi_hint_test.go b/internal/handlers/navigation_idpi_hint_test.goindex 4769eab0..0d9489b2 100644--- a/internal/handlers/navigation_idpi_hint_test.go+++ b/internal/handlers/navigation_idpi_hint_test.go@@ -10,26 +10,26 @@ import (// the properties that made it usable: name the host, append to the current value// instead of replacing it, and carry no placeholder a user would paste literally.func TestIDPIAllowlistRemedy(t *testing.T) {- remedy := idpiAllowlistRemedy("https://example.com/some/path")- if !strings.Contains(remedy, "example.com") {- t.Errorf("remedy should name the blocked host; got %q", remedy)+ line := idpiAllowlistRemedy("https://example.com/some/path").String()+ if !strings.Contains(line, "example.com") {+ t.Errorf("remedy should name the blocked host; got %q", line)}- if !strings.Contains(remedy, "security.allowedDomains") {- t.Errorf("remedy should name the allowlist config key; got %q", remedy)+ if !strings.Contains(line, "security.allowedDomains") {+ t.Errorf("remedy should name the allowlist config key; got %q", line)}- if !strings.Contains(remedy, "server restart") {- t.Errorf("remedy should remind the user to restart; got %q", remedy)+ if !strings.Contains(line, "server restart") {+ t.Errorf("remedy should remind the user to restart; got %q", line)}- if strings.ContainsRune(remedy, '…') {- t.Errorf("remedy must not contain the … placeholder; got %q", remedy)+ if strings.ContainsRune(line, '…') {+ t.Errorf("remedy must not contain the … placeholder; got %q", line)}- if !strings.Contains(remedy, "config get security.allowedDomains") {- t.Errorf("remedy should append to existing domains via config get; got %q", remedy)+ if !strings.Contains(line, "config get security.allowedDomains") {+ t.Errorf("remedy should append to existing domains via config get; got %q", line)}// A hostless target cannot be allowlisted, so it gets no remedy rather than// one that cannot work.- if got := idpiAllowlistRemedy("about:blank"); got != "" {+ if got := idpiAllowlistRemedy("about:blank"); !got.Empty() {t.Errorf("expected no remedy for a hostless url; got %q", got)}if _, ok := idpiRefusedURLDetails("about:blank")["remedy"]; ok {diff --git a/internal/httpx/endpointlock.go b/internal/httpx/endpointlock.goindex 1cd666c2..b2e5af99 100644--- a/internal/httpx/endpointlock.go+++ b/internal/httpx/endpointlock.go@@ -3,6 +3,8 @@ package httpximport ("fmt""net/http"++ "github.com/pinchtab/pinchtab/internal/remedy")// DisabledEndpointMessage returns a consistent message for locked endpoint@@ -13,22 +15,22 @@ func DisabledEndpointMessage(capability, setting string) string {return fmt.Sprintf("this endpoint requires the %s capability; enable %s in config to use it", capability, setting)}-// DisabledEndpointDetails builds the error details every capability refusal-// carries, so the guidance is written once rather than restated at each gate.-//// The remedy names the restart because writing the config is not enough: the// security block is snapshotted at boot and is not rebuilt on a config edit, so// enabling a capability never takes effect until the server restarts. Without// the restart a caller who follows the remedy verbatim gets the identical 403// back, and an agent — which reads this refusal, not the config command's-// stdout — has no exit from that loop. The two commands are joined with && so-// the remedy is one line a shell accepts, not prose to be interpreted.+// stdout — has no exit from that loop.+var enableCapability = remedy.Declare("pinchtab config set <setting> true && pinchtab server restart")++// DisabledEndpointDetails builds the error details every capability refusal+// carries, so the guidance is written once rather than restated at each gate.func DisabledEndpointDetails(setting string) map[string]any {- return map[string]any{- "setting": setting,- "hint": fmt.Sprintf("Enable %s to use this feature.", setting),- "remedy": fmt.Sprintf("pinchtab config set %s true && pinchtab server restart", setting),- }+ details := remedy.Details(+ fmt.Sprintf("Enable %s to use this feature.", setting),+ enableCapability.Fill(setting))+ details["setting"] = setting+ return details}// DisabledEndpointHandler returns a handler that reports a capability gate lock.diff --git a/internal/remedy/census_test.go b/internal/remedy/census_test.gonew file mode 100644index 00000000..3b1df80a--- /dev/null+++ b/internal/remedy/census_test.go@@ -0,0 +1,79 @@+package remedy++import (+ "fmt"+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/srccensus"+)++// moduleRoot is this package's distance to the module root; the census is module-wide+// because the rule is about every producer, wherever it lands.+const moduleRoot = "../.."++// The floors are vacuity checks. They are counts of what the walk must still be finding, not+// a list of producers: the producers are whatever the walk returns.+const (+ minModuleFiles = 300+ minDeclareSites = 8+ ownerPackagePath = "internal/remedy/"+)++// sitesContaining returns every non-test line in the module holding needle. skipOwner drops+// this package, whose job is to hold the shapes the rule forbids elsewhere.+func sitesContaining(t *testing.T, needle string, skipOwner bool) []string {+ t.Helper()++ var sites []string+ for _, file := range srccensus.Tree(t, moduleRoot, minModuleFiles) {+ if skipOwner && strings.HasPrefix(file.Name, ownerPackagePath) {+ continue+ }+ for i, line := range strings.Split(file.Text, "\n") {+ if strings.Contains(line, needle) {+ sites = append(sites, fmt.Sprintf("%s:%d: %s", file.Name, i+1, strings.TrimSpace(line)))+ }+ }+ }+ return sites+}++// A producer that writes the field by hand is a producer outside the contract, and that is+// exactly how the field came to mean four things: eight sites each wrote their own value into+// their own details map. The key may be built in ONE place, so the property is checked where+// the value is written.+//+// If a legitimate site needs more fields than Details returns, add to the map Details returns+// — do not re-point this guard at a second writer.+func TestNoSiteOutsideThisPackageWritesTheRemedyField(t *testing.T) {+ if offenders := sitesContaining(t, `"remedy":`, true); len(offenders) > 0 {+ t.Errorf("these sites write details.remedy by hand instead of through remedy.Details, so nothing checks what they publish:\n%s",+ strings.Join(offenders, "\n"))+ }+}++// The vacuity floor for the guard above, and the census the card asked for: zero matches is+// its PASS condition, so the walk has to be shown to be finding the producers somewhere.+// Every remedy in the repo is declared, and the command-tree guard in cmd/pinchtab walks+// exactly what Declare registers.+func TestEveryRemedyInTheRepoIsDeclaredHere(t *testing.T) {+ sites := sitesContaining(t, "remedy.Declare(", true)+ if len(sites) < minDeclareSites {+ t.Fatalf("found %d remedy.Declare sites, want at least %d; the producers have stopped going through the constructor, so re-point this guard at whatever replaced it rather than lowering the floor:\n%s",+ len(sites), minDeclareSites, strings.Join(sites, "\n"))+ }+}++// The RENDERED slot is what a caller actually reads, and it cannot be told apart from a+// details.remedy by looking. A second site printing prose into "Remedy:" defeats the contract+// however honest the struct it came from — the CLI's own stale-tab advice used to do exactly+// that. So the slot has one writer, and this guard is keyed on the slot rather than on the+// field name for that reason.+func TestTheRenderedRemedySlotHasOneWriter(t *testing.T) {+ sites := sitesContaining(t, "Remedy: ", false)+ if len(sites) != 1 {+ t.Errorf("the \"Remedy:\" slot is written at %d sites, want exactly 1 — a second writer publishes prose into the line a caller reads as executable:\n%s",+ len(sites), strings.Join(sites, "\n"))+ }+}diff --git a/internal/remedy/remedy.go b/internal/remedy/remedy.gonew file mode 100644index 00000000..cc7d01b0--- /dev/null+++ b/internal/remedy/remedy.go@@ -0,0 +1,260 @@+// Package remedy owns details.remedy, the one field in an error response an agent may act+// on without reading English.+//+// THE PROPERTY. A remedy is ONE line a shell accepts as a single pinchtab invocation, or+// several joined with &&. Prose connectives ("then:", "or", a parenthetical tail), pipes,+// semicolons and redirections are not remedies: `pinchtab dialog accept|dismiss` is not two+// suggestions to a shell, it is a pipeline into a command named dismiss. A free slot is a+// <name> placeholder using the same angle-bracket convention the CLI's own help uses, and+// nothing else. Where the value is known at the point of production it is interpolated+// rather than left as a slot. When there is no single command the field is ABSENT: absence+// says truthfully that no command exists, which a client can handle and a sentence cannot.+//+// Prose belongs in details.hint, which is emitted beside remedy at every site.+//+// WHY AN OWNER. The field previously meant four different things across eight producers —+// executable line, command with a prose tail, bare verb, pure prose — while the CLI printed+// all of them into one "Remedy:" slot. A caller that learned the field is executable from+// one producer mis-executed the rest. Declare is the only way to build one, so a ninth+// producer cannot land in a ninth shape: the line is validated where it is written, and+// every declared line is walked by the guards (its commands resolve against the real+// command tree, and no site assembles the field by hand).+package remedy++import (+ "fmt"+ "regexp"+ "sort"+ "strings"+ "sync"+)++// Remedy is a validated remedy line, or None.+type Remedy string++// None is the absence of a remedy: no single command fixes this refusal.+const None Remedy = ""++func (r Remedy) String() string { return string(r) }++// Empty reports whether there is no remedy to publish.+func (r Remedy) Empty() bool { return r == None }++// Template is a declared remedy line, which may carry <name> slots. Declaring it registers+// it, and that registry is what lets a guard walk the producers instead of listing them.+type Template struct{ line string }++var (+ mu sync.Mutex+ templates []string+)++// Declare validates a remedy line and registers it. It panics on a line that violates the+// property, which is deliberate: every declaration in this repo is a constant, so the+// violation is a programming error that must surface at process start rather than reach a+// caller as guidance it cannot run.+func Declare(line string) Template {+ if err := Validate(line); err != nil {+ panic(fmt.Sprintf("remedy: %v", err))+ }+ mu.Lock()+ templates = append(templates, line)+ mu.Unlock()+ return Template{line: line}+}++// Remedy returns the declared line, slots intact. Use it where no value is known at the+// point of production: <ref> in the click remedy cannot be interpolated because the guard+// that produces it never receives the ref.+func (t Template) Remedy() Remedy { return Remedy(t.line) }++func (t Template) String() string { return t.line }++// Fill substitutes the leading slots, left to right, with values known at the point of+// production. A value that would break the property yields None rather than a line the+// caller cannot run — a URL with a quote in it has no remedy, and saying so is honest.+func (t Template) Fill(values ...string) Remedy {+ slots := placeholder.FindAllString(t.line, -1)+ if len(values) > len(slots) {+ panic(fmt.Sprintf("remedy: %d values for %d slots in %q", len(values), len(slots), t.line))+ }+ line := t.line+ for i, value := range values {+ line = strings.Replace(line, slots[i], value, 1)+ }+ if Validate(line) != nil {+ return None+ }+ return Remedy(line)+}++// Templates returns every declared line, for the guards that walk them.+func Templates() []string {+ mu.Lock()+ defer mu.Unlock()+ out := append([]string(nil), templates...)+ sort.Strings(out)+ return out+}++// Details is the guidance pair every refusal carries, built here so no site assembles the+// field by hand. An empty hint or remedy is omitted: the field's absence is the statement.+func Details(hint string, r Remedy) map[string]any {+ details := map[string]any{}+ if strings.TrimSpace(hint) != "" {+ details["hint"] = hint+ }+ if !r.Empty() {+ details["remedy"] = r.String()+ }+ return details+}++var placeholder = regexp.MustCompile(`<[a-z][a-z0-9-]*>`)++var forbidden = map[rune]string{+ '|': "a pipe: `a|b` reads as a pipeline, not as alternatives",+ ';': "a command separator; join commands with &&",+ '`': "a backquoted substitution; use $(...)",+ '#': "a comment",+ '(': "a parenthesis: a prose tail belongs in the hint",+ ')': "a parenthesis: a prose tail belongs in the hint",+ '\\': "an escape",+ '{': "a brace expansion; a free slot is a <name> placeholder",+ '}': "a brace expansion; a free slot is a <name> placeholder",+}++// Validate reports why line is not a remedy. It checks the shape a shell reads; whether the+// commands EXIST is the command-tree guard's question, and the two are deliberately+// separate so this package needs no dependency on the CLI.+func Validate(line string) error {+ if line == "" {+ return fmt.Errorf("remedy is empty; omit the field instead")+ }+ if strings.TrimSpace(line) != line {+ return fmt.Errorf("remedy %q has surrounding whitespace", line)+ }+ if strings.ContainsAny(line, "\n\r\t") {+ return fmt.Errorf("remedy %q is not one line", line)+ }+ if err := checkPlaceholders(line); err != nil {+ return err+ }+ segments, err := scan(line)+ if err != nil {+ return err+ }+ for _, words := range segments {+ if err := checkInvocation(line, words); err != nil {+ return err+ }+ }+ return nil+}++// Segments splits a remedy into the commands the shell would run, each already split into+// words the way a shell would: quotes and $(...) hold together. The command-tree guard reads+// it from here, because a second split written there would let the two disagree about what+// the shell sees, which is the whole subject of this package. An invalid line has no+// segments.+func Segments(line string) [][]string {+ if Validate(line) != nil {+ return nil+ }+ segments, _ := scan(line)+ return segments+}++func checkPlaceholders(line string) error {+ stripped := placeholder.ReplaceAllString(line, "")+ if idx := strings.IndexAny(stripped, "<>"); idx >= 0 {+ return fmt.Errorf("remedy %q has a free slot that is not a <name> placeholder", line)+ }+ return nil+}++func checkInvocation(line string, words []string) error {+ if len(words) < 2 {+ return fmt.Errorf("remedy %q has a command that is not a pinchtab invocation: %v", line, words)+ }+ if words[0] != "pinchtab" {+ return fmt.Errorf("remedy %q starts a command with %q rather than pinchtab, so it is prose", line, words[0])+ }+ for _, word := range words[1:] {+ if word == "pinchtab" {+ return fmt.Errorf("remedy %q runs two commands in one segment, so they are joined by prose rather than &&", line)+ }+ }+ return nil+}++// scan splits line into &&-joined segments of shell words, rejecting anything that would+// give the line a meaning other than "run these commands in order".+func scan(line string) ([][]string, error) {+ var (+ segments [][]string+ words []string+ word strings.Builder+ quoted bool+ subst int+ )+ flushWord := func() {+ if word.Len() > 0 {+ words = append(words, word.String())+ word.Reset()+ }+ }+ flushSegment := func() {+ flushWord()+ segments = append(segments, words)+ words = nil+ }++ runes := []rune(line)+ for i := 0; i < len(runes); i++ {+ c := runes[i]+ switch {+ case quoted:+ if c == '"' {+ quoted = false+ }+ word.WriteRune(c)+ case subst > 0:+ if c == '(' {+ subst+++ }+ if c == ')' {+ subst--+ }+ word.WriteRune(c)+ case c == '"':+ quoted = true+ word.WriteRune(c)+ case c == '$' && i+1 < len(runes) && runes[i+1] == '(':+ subst = 1+ word.WriteString("$(")+ i+++ case c == ' ':+ flushWord()+ case c == '&':+ if i+1 >= len(runes) || runes[i+1] != '&' {+ return nil, fmt.Errorf("remedy %q backgrounds a command with a bare &", line)+ }+ flushSegment()+ i+++ default:+ if reason, bad := forbidden[c]; bad {+ return nil, fmt.Errorf("remedy %q contains %s", line, reason)+ }+ word.WriteRune(c)+ }+ }+ if quoted {+ return nil, fmt.Errorf("remedy %q has an unclosed quote", line)+ }+ if subst > 0 {+ return nil, fmt.Errorf("remedy %q has an unclosed $( substitution", line)+ }+ flushSegment()+ return segments, nil+}diff --git a/internal/remedy/remedy_test.go b/internal/remedy/remedy_test.gonew file mode 100644index 00000000..49d684ea--- /dev/null+++ b/internal/remedy/remedy_test.go@@ -0,0 +1,179 @@+package remedy++import (+ "strings"+ "testing"+)++// THE CENSUS THIS CARD WAS FILED ON, pinned as a fixture. Each of these shipped as a+// details.remedy while the CLI printed them all into one "Remedy:" slot, so a caller that+// learned the field was executable from one of them mis-executed the rest. They are here as+// the guard's red cases: if the validator ever accepts one again, the field has gone back to+// meaning four things.+func TestTheHistoricalRemediesAreRejected(t *testing.T) {+ for _, tc := range []struct {+ was string+ line string+ why string+ }{+ {+ was: "two commands joined by the prose word then:",+ line: `pinchtab config set security.allowedDomains "$(pinchtab config get security.allowedDomains),example.com" then: pinchtab server restart`,+ why: "a shell runs the first command with then: and pinchtab as arguments",+ },+ {+ was: "a command with a prose tail carrying two alternatives",+ line: "pinchtab back (returns the tab to the previous allowed page; use pinchtab nav <allowed-url> when there is no history entry, or close the tab)",+ why: "the parenthesis is a subshell, not an explanation",+ },+ {+ was: "a command with a prose alternative",+ line: "pinchtab click <ref> --wait-nav (use --submit instead when the click submits a form)",+ why: "same parenthesis, and the alternative is a second command",+ },+ {+ was: "pure prose",+ line: "If TLS terminates in front of PinchTab, also enable server.trustProxyHeaders so forwarded https requests are recognized.",+ why: "there is no command at all, so the field must be absent",+ },+ {+ was: "a bare verb, with the command in the hint beside it",+ line: "download",+ why: "a verb is not an invocation",+ },+ {+ was: "two commands joined by prose, from the branch that had an executable sibling",+ line: "pinchtab session info (with PINCHTAB_SESSION set) prints the id, or pinchtab session list",+ why: "one producer emitted this and an executable line depending on a branch",+ },+ {+ was: "a verb leading the command",+ line: "run the full server instead: pinchtab server",+ why: "the command is behind prose, so the line does not start one",+ },+ {+ was: "prose describing a file edit",+ line: "set sessions.agent.enabled = true in config.json, then restart the server",+ why: "no command can do this, so the field must be absent",+ },+ {+ was: "alternatives offered with a pipe",+ line: "pinchtab dialog accept|dismiss (or pass --dialog-action accept|dismiss on the action that opens the dialog)",+ why: "the worst of them: a shell reads this as a pipeline into a command named dismiss, so it is valid and wrong rather than merely broken",+ },+ } {+ t.Run(tc.was, func(t *testing.T) {+ if err := Validate(tc.line); err == nil {+ t.Fatalf("Validate accepted %q; %s", tc.line, tc.why)+ }+ })+ }+}++func TestTheShapesARemedyMayTake(t *testing.T) {+ for _, line := range []string{+ "pinchtab back",+ "pinchtab dialog accept",+ "pinchtab session revoke <session-id>",+ `pinchtab download "<url>"`,+ "pinchtab config set security.allowClipboard true && pinchtab server restart",+ `pinchtab config set security.allowedDomains "$(pinchtab config get security.allowedDomains),example.com" && pinchtab server restart`,+ } {+ if err := Validate(line); err != nil {+ t.Errorf("Validate rejected a remedy that a shell runs: %q: %v", line, err)+ }+ }+}++// A slot must be a <name>, because that is the convention the CLI's own help uses and the+// only one an agent can be expected to substitute into.+func TestASlotMustBeANamedPlaceholder(t *testing.T) {+ // A bare uppercase word (pinchtab nav URL) is deliberately NOT rejected here: no local+ // check can tell it from a literal argument value, and the command-tree guard is the+ // layer that answers whether the command accepts it.+ for _, line := range []string{+ "pinchtab nav {url}",+ "pinchtab nav <URL>",+ "pinchtab nav <>",+ "pinchtab nav 2>/dev/null",+ } {+ if Validate(line) == nil {+ t.Errorf("Validate accepted %q, whose free slot no caller can fill", line)+ }+ }+ if err := Validate("pinchtab nav <url>"); err != nil {+ t.Errorf("Validate rejected the conventional placeholder: %v", err)+ }+}++func TestFillInterpolatesAKnownValue(t *testing.T) {+ template := Declare(`pinchtab download "<url>"`)++ if got := template.Fill("https://example.com/a.zip"); got != `pinchtab download "https://example.com/a.zip"` {+ t.Errorf("Fill = %q, want the value interpolated", got)+ }+ if got := template.Remedy(); got != `pinchtab download "<url>"` {+ t.Errorf("Remedy = %q, want the slot intact", got)+ }+ // A value that would break the property yields no remedy rather than a line the caller+ // cannot run: absence is the honest answer, and the caller still has the hint.+ if got := template.Fill(`a" && rm -rf /`); !got.Empty() {+ t.Errorf("Fill = %q, want none for a value that changes what the line does", got)+ }+}++func TestFillPanicsOnMoreValuesThanSlots(t *testing.T) {+ defer func() {+ if recover() == nil {+ t.Error("Fill accepted more values than the template has slots, so a value was silently dropped")+ }+ }()+ Declare("pinchtab session revoke <session-id>").Fill("a", "b")+}++func TestDeclarePanicsOnProse(t *testing.T) {+ defer func() {+ if recover() == nil {+ t.Error("Declare accepted prose, so a producer can publish guidance no shell runs")+ }+ }()+ Declare("just restart the server")+}++// Absence is a statement, so Details omits rather than emitting an empty field: a client+// reading remedy learns there is no command, not that there is an empty one.+func TestDetailsOmitsWhatIsAbsent(t *testing.T) {+ both := Details("prose", Declare("pinchtab back").Remedy())+ if both["hint"] != "prose" || both["remedy"] != "pinchtab back" {+ t.Errorf("Details = %#v, want both fields", both)+ }++ hintOnly := Details("prose", None)+ if _, ok := hintOnly["remedy"]; ok {+ t.Errorf("Details = %#v, want no remedy key when there is no command", hintOnly)+ }+ if _, ok := Details("", None)["hint"]; ok {+ t.Error("Details emitted an empty hint")+ }+}++// Segments is what the command-tree guard resolves, so a quoted value with a nested+// substitution must arrive as ONE word: split naively, `config set` looks like it was handed+// six arguments and the guard reports a defect that is not there.+func TestSegmentsSplitTheWayAShellWould(t *testing.T) {+ line := `pinchtab config set security.allowedDomains "$(pinchtab config get security.allowedDomains),example.com" && pinchtab server restart`++ segments := Segments(line)+ if len(segments) != 2 {+ t.Fatalf("Segments = %#v, want the two &&-joined commands", segments)+ }+ if len(segments[0]) != 5 {+ t.Errorf("first command = %#v, want pinchtab config set <path> <value> as five words", segments[0])+ }+ if got := []string{"pinchtab", "server", "restart"}; strings.Join(segments[1], " ") != strings.Join(got, " ") {+ t.Errorf("second command = %#v, want %#v", segments[1], got)+ }+ if Segments("restart the server") != nil {+ t.Error("Segments returned commands for prose")+ }+}diff --git a/internal/server/sessions_unavailable.go b/internal/server/sessions_unavailable.goindex 87a3346a..3aedfd08 100644--- a/internal/server/sessions_unavailable.go+++ b/internal/server/sessions_unavailable.go@@ -4,6 +4,7 @@ import ("net/http""github.com/pinchtab/pinchtab/internal/httpx"+ "github.com/pinchtab/pinchtab/internal/remedy""github.com/pinchtab/pinchtab/internal/session")@@ -23,28 +24,33 @@ const (const (msgSessionsUnavailableInBridgeMode = "agent sessions are unavailable in bridge mode"- remedySessionsUnavailableInBridge = "run the full server instead: pinchtab server"+ hintSessionsUnavailableInBridge = "no config value mounts the session family on a bridge; the full server is what serves it."msgSessionsDisabled = "agent sessions are not enabled on this server"// The config editor knows sessions.dashboard.* and no sessions.agent.* field, so// "pinchtab config set sessions.agent.enabled true" answers "unknown field" — the same- // dead end this family's remedy existed to remove, one state over. The file edit works,- // and it is what the shared CLI hint already tells a reader.- remedySessionsDisabled = "set sessions.agent.enabled = true in config.json, then restart the server"+ // dead end this family's remedy existed to remove, one state over. So this state has NO+ // remedy: the fix is a file edit plus a restart, which is not one command, and the hint+ // says so rather than a remedy naming a command that dead-ends.+ hintSessionsDisabled = "set sessions.agent.enabled = true in config.json and restart the server; the config editor has no field for that path, so it cannot be changed from the command line.")+// Running the full server is the bridge's whole remedy. The verb it used to lead with —+// "run the full server instead: pinchtab server" — put the command behind prose.+var runFullServer = remedy.Declare("pinchtab server")+// registerSessionsUnavailable answers the whole session family with one coded refusal.// Both modes that do not mount the family call it, and it ranges over the same// session.RoutePatterns() the live registration uses — that shared list is what stops a// route added later being reachable in server mode and a bare 404 everywhere else.//// The status stays 404: the family genuinely is not here. What changes is that the body is-// the product's error envelope with a code and a remedy instead of net/http's bare+// the product's error envelope with a code and guidance instead of net/http's bare// "404 page not found", which escaped the envelope entirely because no route was// registered at all.-func registerSessionsUnavailable(mux *http.ServeMux, code, message, remedy string) {- handler := func(w http.ResponseWriter, r *http.Request) {- httpx.ErrorCode(w, http.StatusNotFound, code, message, false, map[string]any{"remedy": remedy})+func registerSessionsUnavailable(mux *http.ServeMux, code, message, hint string, r remedy.Remedy) {+ handler := func(w http.ResponseWriter, _ *http.Request) {+ httpx.ErrorCode(w, http.StatusNotFound, code, message, false, remedy.Details(hint, r))}for _, pattern := range session.RoutePatterns() {mux.HandleFunc(pattern, handler)@@ -54,11 +60,11 @@ func registerSessionsUnavailable(mux *http.ServeMux, code, message, remedy strin// RegisterSessionsUnavailableInBridgeMode is the bridge's answer for the family.func RegisterSessionsUnavailableInBridgeMode(mux *http.ServeMux) {registerSessionsUnavailable(mux, CodeSessionsUnavailableInBridgeMode,- msgSessionsUnavailableInBridgeMode, remedySessionsUnavailableInBridge)+ msgSessionsUnavailableInBridgeMode, hintSessionsUnavailableInBridge, runFullServer.Remedy())}// RegisterSessionsDisabled is the full server's answer when sessions.agent.enabled is off.func RegisterSessionsDisabled(mux *http.ServeMux) {registerSessionsUnavailable(mux, CodeSessionsDisabled,- msgSessionsDisabled, remedySessionsDisabled)+ msgSessionsDisabled, hintSessionsDisabled, remedy.None)}diff --git a/internal/server/sessions_unavailable_test.go b/internal/server/sessions_unavailable_test.goindex ad49cbb9..3938e5af 100644--- a/internal/server/sessions_unavailable_test.go+++ b/internal/server/sessions_unavailable_test.go@@ -11,20 +11,25 @@ import ("github.com/pinchtab/pinchtab/internal/session")-func decodeSessionRefusal(t *testing.T, w *httptest.ResponseRecorder) (code, message, remedy string) {+// Both guidance fields are decoded because the two modes carry it in different ones: only+// the bridge has a single command to run, so the disabled mode's guidance is a hint and its+// remedy is absent. A decoder reading only the remedy would report the disabled mode as+// carrying no guidance at all.+func decodeSessionRefusal(t *testing.T, w *httptest.ResponseRecorder) (code, message, hint, remedy string) {t.Helper()var resp struct {Code string `json:"code"`Error string `json:"error"`Details struct {+ Hint string `json:"hint"`Remedy string `json:"remedy"`} `json:"details"`}if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {t.Fatalf("body is not the product's error envelope (%v): %s", err, w.Body.String())}- return resp.Code, resp.Error, resp.Details.Remedy+ return resp.Code, resp.Error, resp.Details.Hint, resp.Details.Remedy}func requestFor(pattern string) *http.Request {@@ -42,9 +47,12 @@ func TestBothUnavailableModesAnswerEveryRouteInTheFamilyWithACode(t *testing.T)register func(*http.ServeMux)wantCode stringwantRemedy string+ wantGuide string}{- {"bridge", RegisterSessionsUnavailableInBridgeMode, CodeSessionsUnavailableInBridgeMode, "pinchtab server"},- {"sessions disabled", RegisterSessionsDisabled, CodeSessionsDisabled, "sessions.agent.enabled"},+ {"bridge", RegisterSessionsUnavailableInBridgeMode, CodeSessionsUnavailableInBridgeMode, "pinchtab server", "bridge"},+ // No remedy: enabling the family is a file edit plus a restart, which is not one+ // command a caller can run, so the guidance is a hint and the field is absent.+ {"sessions disabled", RegisterSessionsDisabled, CodeSessionsDisabled, "", "sessions.agent.enabled"},} {t.Run(mode.name, func(t *testing.T) {mux := http.NewServeMux()@@ -64,15 +72,18 @@ func TestBothUnavailableModesAnswerEveryRouteInTheFamilyWithACode(t *testing.T)if strings.Contains(w.Body.String(), "404 page not found") {t.Errorf("%s: still the bare mux 404, which carries no code: %s", pattern, w.Body.String())}- code, message, remedy := decodeSessionRefusal(t, w)+ code, message, hint, remedy := decodeSessionRefusal(t, w)if code != mode.wantCode {t.Errorf("%s: code = %q, want %q", pattern, code, mode.wantCode)}if message == "" {t.Errorf("%s: refusal carries no message", pattern)}- if !strings.Contains(remedy, mode.wantRemedy) {- t.Errorf("%s: remedy = %q, want it to name %q — the remedy that can actually succeed in this mode", pattern, remedy, mode.wantRemedy)+ if remedy != mode.wantRemedy {+ t.Errorf("%s: remedy = %q, want %q — the only command that can succeed in this mode, or none when there is no single command", pattern, remedy, mode.wantRemedy)+ }+ if !strings.Contains(hint, mode.wantGuide) {+ t.Errorf("%s: hint = %q, want it to explain %q — the guidance this mode cannot express as a command", pattern, hint, mode.wantGuide)}}})@@ -87,24 +98,26 @@ func TestTheTwoUnavailableModesDoNotShareARemedy(t *testing.T) {register(mux)w := httptest.NewRecorder()mux.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/sessions", nil))- code, _, remedy := decodeSessionRefusal(t, w)- return code, remedy+ code, _, hint, remedy := decodeSessionRefusal(t, w)+ // The guidance is what must not converge, and the two modes carry it in different+ // fields, so the comparison is over both rather than over the remedy alone.+ return code, hint + " " + remedy}- bridgeCode, bridgeRemedy := answer(RegisterSessionsUnavailableInBridgeMode)- disabledCode, disabledRemedy := answer(RegisterSessionsDisabled)+ bridgeCode, bridgeGuidance := answer(RegisterSessionsUnavailableInBridgeMode)+ disabledCode, disabledGuidance := answer(RegisterSessionsDisabled)if bridgeCode == disabledCode {t.Errorf("both modes answer with %q, so the caller cannot tell them apart", bridgeCode)}- if bridgeRemedy == disabledRemedy {- t.Errorf("both modes prescribe %q; one of them cannot work", bridgeRemedy)+ if bridgeGuidance == disabledGuidance {+ t.Errorf("both modes prescribe %q; one of them cannot work", bridgeGuidance)}- if strings.Contains(bridgeRemedy, "sessions.agent.enabled") {- t.Errorf("the bridge remedy prescribes a config edit, which is the unescapable loop this fixes: %q", bridgeRemedy)+ if strings.Contains(bridgeGuidance, "sessions.agent.enabled") {+ t.Errorf("the bridge guidance prescribes a config edit, which is the unescapable loop this fixes: %q", bridgeGuidance)}- for mode, remedy := range map[string]string{"bridge": bridgeRemedy, "disabled": disabledRemedy} {+ for mode, remedy := range map[string]string{"bridge": bridgeGuidance, "disabled": disabledGuidance} {if field, prescribed := configSetFieldIn(remedy); prescribed {if err := config.SetConfigValue(&config.FileConfig{}, field, "true"); err != nil {t.Errorf("the %s remedy says to run `pinchtab config set %s`, and the config editor answers %v — a remedy that cannot run is the dead end this family's codes exist to remove", mode, field, err)