Skip to content

Commit cc1b3ad

Browse files
authored
Say how to recover a broken connect.json, and keep reporting around it (#1053)
* Say how to recover a broken connect.json, and keep reporting around it A typo in connect.json used to stop connect doctor, status, show and setup at one line with no position, and nothing said how to get out of it: setup said to fix or remove the file, the skill said never to edit it. - Parse errors name the line and column, and an unknown key names the key it was probably meant to be ("did you mean watch_completions?"). - connect doctor fails its connect.json row with the recovery command, and still runs the token, identity, ticket, feed, Pings and ledger checks, finding the profile's connector state from its state directory or its credential. - connect status still shows the ledger, leads with the problem, and counts requests held as config_unreadable. - connect setup --reset sets the profile up from the run's flags alone; the old file is moved aside as connect.json.broken-<time> only when the new one is written, and put back if that write fails. - basecamp doctor has a line per connector profile. - Hints that said to remove the file point at --reset, and the skill says what a person or agent does when the file no longer reads. * Place every key refusal where it is, and keep reset's hints runnable From the second adversarial pass and Copilot's review of 7381f55: - A ledger that opens and then can't be read no longer hides a broken connect.json from status. - Unknown keys are placed in the object that refused them, found by the schema's own types at each path, and only a key valid in that object is suggested. A key not spelled canonically and a duplicated key are placed too. - The recovery hint names --serve, since a reset serves nothing unless told to, and a reset refused for serving nothing says to reset again with one. - Status says requests are held because the file couldn't be read, without claiming a connector is retrying them. - --reset alone at a terminal runs scripted setup, not guided: pinned. * Place keys by object, and make reset's hint the command that works From the third adversarial pass and Copilot's review of 8014d38: - A duplicate key is placed in the object that has it: objects are told apart by instance, so sibling objects in an array are two. - An unknown key is never placed on a map's id: only a struct refuses a key. - A reset refused for serving nothing hints with this run again, every flag it had, and --serve: following it works, and a test follows it. - basecamp doctor's line for a broken profile says whether its connector is still running, from the profile's state directory. * Replay setup's own flags alone in reset's hint, and name the agent that runs From the fourth adversarial pass over ec04243: - The hint for a reset that serves nothing repeats setup's own flags and leaves inherited ones out: a count such as -v came back as "--verbose 1", which the CLI reads as a stray argument. A test runs it under a root with those flags and has a shell parse the hint back into its words. - basecamp doctor's line for a broken profile names the agent whose connector state it read, since the credential may since be another's. * Treat a connect.json copied from another profile as one that can't be used Copilot, in the body of its review of ec04243: basecamp doctor called a valid file naming another profile "set up", though connect show and setup refuse it. One loader for doctor, status and the doctor line now refuses it, so each reports it with the recovery hint. * Refuse another profile's connect.json in reports only, not in the commands that stop a connector The fifth adversarial pass over 2760c22: the connector itself takes a file naming another profile, so refusing it in every operator command left a running connector that connect stop and the worker commands could no longer reach. Only doctor, status and the doctor line call it a problem now. The doctor line no longer claims a running connector holds requests, which it doesn't for a mismatch. * Read this profile's own state when its connect.json was copied from another Copilot on 90c36a7: a copied file names another profile's agent, and following it, status found no ledger and doctor skipped the one that is there. The profile's one state directory is preferred, as for a file that can't be read; the copy's agent is the fallback. * Refuse a copied connect.json from the read already made Copilot's review body on 9c431fe: the report read the file a second time to build the refusal, and a repair in between left a profile with no refusal and no policy, which doctor would have passed and then failed to verify. The refusal is now made from the first read.
1 parent 40249ab commit cc1b3ad

15 files changed

Lines changed: 1633 additions & 52 deletions

‎.surface-skill-drift‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ CMD basecamp connect setup
2525
FLAG basecamp --operator-profile
2626
FLAG basecamp --serve
2727
FLAG basecamp --shadow
28+
FLAG basecamp --reset
2829
CMD basecamp connect discard
2930
CMD basecamp connect ask
3031
CMD basecamp connect doctor

‎internal/commands/connect.go‎

Lines changed: 99 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818

1919
surfguard "github.com/basecamp/surfguard/go"
2020
"github.com/spf13/cobra"
21+
"github.com/spf13/pflag"
2122

2223
"github.com/basecamp/basecamp-sdk/go/pkg/basecamp"
2324

@@ -231,13 +232,13 @@ func runConnectShow(app *appctx.App) error {
231232
"The connector's setup is not supported on Windows: this CLI cannot verify who can change connect.json there.")
232233
case err != nil:
233234
return output.ErrUsageHint("connect.json cannot be used: "+setup.ErrorText(err),
234-
"Nothing of it was shown. Fix or remove "+richtext.SanitizeSingleLine(path)+", then run setup again.")
235+
"Nothing of it was shown. "+connectResetHint(name)+", or fix "+richtext.SanitizeSingleLine(path)+" by hand.")
235236
}
236237
if f.Profile != name {
237238
// A policy copied from another profile's directory is not this
238239
// profile's, however valid it is on its own: setup refuses it too.
239240
return output.ErrUsageHint(fmt.Sprintf("%s names profile %q, not %q", richtext.SanitizeSingleLine(path), f.Profile, name),
240-
"Nothing of it was shown. Remove "+richtext.SanitizeSingleLine(path)+" and run setup again for this profile.")
241+
"Nothing of it was shown. "+connectResetHint(name)+".")
241242
}
242243

243244
// The generic object renderer drops nested maps, which is where the
@@ -405,6 +406,11 @@ type connectSetupFlags struct {
405406
ackBoost optionalString
406407
noAckBoost bool
407408

409+
// reset sets the profile up afresh from this run's flags alone, over a
410+
// connect.json that cannot be used or is for another agent: the old
411+
// file is moved aside only when the new one is written.
412+
reset bool
413+
408414
serve []string
409415
classes []string
410416
watch []string
@@ -596,6 +602,7 @@ Examples:
596602
fl.StringArrayVar(&f.unlistenCampfires, "no-listen-campfire", nil, "Require mentions again: <project-id>:<campfire-id> (repeatable)")
597603
fl.Var(&f.ackBoost, "ack-boost", fmt.Sprintf("Boost the connector acknowledges each request with, as the agent, before handing it off (default %s; at most %d characters)", setup.DefaultAckContent, setup.AckContentMax))
598604
fl.BoolVar(&f.noAckBoost, "no-ack-boost", false, "Don't acknowledge requests in the connector; the session reading them boosts instead")
605+
fl.BoolVar(&f.reset, "reset", false, "Set the profile up afresh from this run's flags, ignoring connect.json; the old file is kept beside the new one as connect.json.broken-<time>")
599606
cmd.MarkFlagsMutuallyExclusive("operator", "operator-profile")
600607
cmd.MarkFlagsMutuallyExclusive("ack-boost", "no-ack-boost")
601608

@@ -643,12 +650,22 @@ func runConnectSetup(cmd *cobra.Command, app *appctx.App, f *connectSetupFlags)
643650

644651
existing, err := setup.Load(path)
645652
exists := err == nil
653+
// replacing is a --reset over a file that is there, usable or not: it
654+
// is set aside, and this run starts from nothing.
655+
replacing := false
646656
switch {
657+
case f.reset:
658+
if _, statErr := os.Lstat(path); statErr == nil {
659+
replacing = true
660+
} else if !errors.Is(statErr, os.ErrNotExist) {
661+
return fmt.Errorf("could not look at %s: %w", richtext.SanitizeSingleLine(path), statErr)
662+
}
663+
existing, exists = setup.New(name), false
647664
case errors.Is(err, os.ErrNotExist):
648665
existing = setup.New(name)
649666
case err != nil:
650-
return output.ErrUsageHint("connect.json cannot be used: "+err.Error(),
651-
"Nothing was changed. Fix or remove "+richtext.SanitizeSingleLine(path)+", then run setup again.")
667+
return output.ErrUsageHint("connect.json cannot be used: "+setup.ErrorText(err),
668+
"Nothing was changed. "+connectResetHint(name)+", or fix "+richtext.SanitizeSingleLine(path)+" by hand and run setup again.")
652669
}
653670
if existing.Profile != name {
654671
return output.ErrUsage(fmt.Sprintf("%s names profile %q, not %q", path, existing.Profile, name))
@@ -686,7 +703,7 @@ func runConnectSetup(cmd *cobra.Command, app *appctx.App, f *connectSetupFlags)
686703
if exists && !accountIDsEqual(existing.AccountID, accountID) {
687704
return output.ErrUsageHint(
688705
fmt.Sprintf("connect.json was set up in account %s, and profile %q is bound to account %s", existing.AccountID, name, accountID),
689-
"Nothing was changed. Remove "+richtext.SanitizeSingleLine(path)+" to set this profile up afresh.")
706+
"Nothing was changed. To set this profile up afresh: basecamp connect setup -P "+richtext.ShellQuote(name)+" --reset, with the flags it needs.")
690707
}
691708
kind, err := connectCredentialKind(ctx, app)
692709
if err != nil {
@@ -695,10 +712,10 @@ func runConnectSetup(cmd *cobra.Command, app *appctx.App, f *connectSetupFlags)
695712
// The credential's own disagreement with connect.json comes first: it is
696713
// the wrong credential whatever the flags say.
697714
if exists && kind != "" && existing.Agent.Kind != kind {
698-
return output.ErrAuth(fmt.Sprintf("connect.json was set up for a %s credential, and profile %q now holds a %s one; remove %s to set this profile up afresh",
699-
existing.Agent.Kind, name, kind, richtext.SanitizeSingleLine(path)))
715+
return output.ErrAuth(fmt.Sprintf("connect.json was set up for a %s credential, and profile %q now holds a %s one; to set this profile up afresh, run setup again with --reset",
716+
existing.Agent.Kind, name, kind))
700717
}
701-
if err := refuseCredentialConflicts(name, path, kind, expect, exists, existing); err != nil {
718+
if err := refuseCredentialConflicts(name, kind, expect, exists, existing); err != nil {
702719
return err
703720
}
704721
if kind == setup.KindBotUser {
@@ -709,8 +726,8 @@ func runConnectSetup(cmd *cobra.Command, app *appctx.App, f *connectSetupFlags)
709726
// Rebinding the file to another bot is a deliberate act, not a
710727
// flag: connect.json's trust was recorded for the agent it names.
711728
return output.ErrAuth(fmt.Sprintf(
712-
"connect.json is set up for identity %d, and --expect-identity names %d; remove %s to set this profile up for another bot",
713-
existing.Agent.IdentityID, expect, richtext.SanitizeSingleLine(path)))
729+
"connect.json is set up for identity %d, and --expect-identity names %d; to set this profile up for another bot, run setup again with --reset",
730+
existing.Agent.IdentityID, expect))
714731
}
715732
}
716733

@@ -754,8 +771,8 @@ func runConnectSetup(cmd *cobra.Command, app *appctx.App, f *connectSetupFlags)
754771
}
755772
checks = append(checks, identityCheck)
756773
if exists && existing.Agent.PersonID != me.ID {
757-
return output.ErrAuth(fmt.Sprintf("connect.json was set up for agent person %d, and profile %q now authenticates as person %d; if this is a different agent on purpose, remove %s and run setup again",
758-
existing.Agent.PersonID, name, me.ID, richtext.SanitizeSingleLine(path)))
774+
return output.ErrAuth(fmt.Sprintf("connect.json was set up for agent person %d, and profile %q now authenticates as person %d; if this is a different agent on purpose, run setup again with --reset",
775+
existing.Agent.PersonID, name, me.ID))
759776
}
760777
checks = append(checks, setup.ScopeCheck(creds.OAuthType, creds.Scope))
761778

@@ -837,7 +854,18 @@ func runConnectSetup(cmd *cobra.Command, app *appctx.App, f *connectSetupFlags)
837854
}
838855
report.Add(checks...)
839856
report.Add(setup.TicketCheck(ctx, reader, kind))
840-
report.Add(setup.ProjectChecks(ctx, reader, next, !exists)...)
857+
projectChecks := setup.ProjectChecks(ctx, reader, next, !exists)
858+
if f.reset {
859+
// A reset starts from nothing, so the run that fixes this one is this
860+
// run again, every flag it had, with a project: without --reset setup
861+
// reads the old file again, and without the rest it forgets them.
862+
for i, c := range projectChecks {
863+
if c.Status == setup.StatusFail && c.Name == "Projects" {
864+
projectChecks[i].Hint = "Serve one: " + connectSetupRerun(cmd, name) + " --serve <project-id>"
865+
}
866+
}
867+
}
868+
report.Add(projectChecks...)
841869
// A command the person stopped did not find the connector unready: it
842870
// found nothing, and says so as an interruption.
843871
if err := ctx.Err(); err != nil {
@@ -869,7 +897,22 @@ func runConnectSetup(cmd *cobra.Command, app *appctx.App, f *connectSetupFlags)
869897
if err := next.VerifyAgent(kind, me.ID, expect); err != nil {
870898
return output.ErrAuth(err.Error())
871899
}
872-
return setup.Save(held, path, next)
900+
if !replacing {
901+
return setup.Save(held, path, next)
902+
}
903+
aside, err := setup.MoveAside(path, time.Now())
904+
if err != nil {
905+
return err
906+
}
907+
if err := connectSaveFile(held, path, next); err != nil {
908+
// The old file goes back: a failed reset leaves what was there.
909+
if restoreErr := os.Rename(aside, path); restoreErr != nil {
910+
return fmt.Errorf("%w; and the old file could not be put back from %s: %w", err, richtext.SanitizeSingleLine(aside), restoreErr)
911+
}
912+
return err
913+
}
914+
report.MovedAside = aside
915+
return nil
873916
})
874917
if saveErr != nil {
875918
return classifyWriteError(name, saveErr)
@@ -886,12 +929,50 @@ func runConnectSetup(cmd *cobra.Command, app *appctx.App, f *connectSetupFlags)
886929
return nil
887930
case styled:
888931
renderChecksStyled(w, title, summary)
889-
fmt.Fprintf(w, " connect.json written: %s\n\n", richtext.SanitizeSingleLine(path))
932+
fmt.Fprintf(w, " connect.json written: %s\n", richtext.SanitizeSingleLine(path))
933+
if report.MovedAside != "" {
934+
fmt.Fprintf(w, " The old file was kept as %s\n", richtext.SanitizeSingleLine(report.MovedAside))
935+
}
936+
fmt.Fprintln(w)
890937
return nil
891938
}
892939
return app.OK(report, output.WithSummary("connect.json written; "+summary.Summary()))
893940
}
894941

942+
// connectSetupRerun is the setup command this run was: the profile, and
943+
// every flag of setup's own it was given, each value quoted for a shell.
944+
// Inherited flags (-v, --json) are left out: they don't decide what setup
945+
// writes, and some (a count) can't be written back as given.
946+
func connectSetupRerun(cmd *cobra.Command, name string) string {
947+
parts := []string{"basecamp connect setup -P", richtext.ShellQuote(name)}
948+
own := cmd.LocalNonPersistentFlags()
949+
cmd.Flags().Visit(func(fl *pflag.Flag) {
950+
if own.Lookup(fl.Name) == nil {
951+
return
952+
}
953+
if fl.Value.Type() == "bool" {
954+
if fl.Value.String() == "true" {
955+
parts = append(parts, "--"+fl.Name)
956+
} else {
957+
parts = append(parts, "--"+fl.Name+"=false")
958+
}
959+
return
960+
}
961+
values := []string{fl.Value.String()}
962+
if slice, ok := fl.Value.(pflag.SliceValue); ok {
963+
values = slice.GetSlice()
964+
}
965+
for _, v := range values {
966+
parts = append(parts, "--"+fl.Name, richtext.ShellQuote(v))
967+
}
968+
})
969+
return strings.Join(parts, " ")
970+
}
971+
972+
// connectSaveFile is setup.Save, as a reset writes over a file it moved
973+
// aside; a variable so a test can make the write fail after the move.
974+
var connectSaveFile = setup.Save
975+
895976
// classifyWriteError puts the last step's failures in the command's exit
896977
// contract: a credential that is gone or unreadable is auth, another
897978
// process holding the profile's credential or the profile's policy lock is busy, a
@@ -1191,15 +1272,15 @@ func parsePositiveID(flag, raw string) (int64, error) {
11911272
// one with no credential (setup does not obtain one), --expect-identity
11921273
// against an Agent's credential or connect.json, and a person's login with
11931274
// nothing pinning it to the bot.
1194-
func refuseCredentialConflicts(name, path, held string, expect int64, exists bool, existing setup.File) error {
1275+
func refuseCredentialConflicts(name, held string, expect int64, exists bool, existing setup.File) error {
11951276
profile := richtext.ShellQuote(name)
11961277
switch {
11971278
// What connect.json already says comes first: a remediation that the
11981279
// existing file would refuse anyway is no remediation.
11991280
case expect != 0 && exists && existing.Agent.Kind == setup.KindAgent:
12001281
return output.ErrUsageHint("--expect-identity is for the bot-user path, and connect.json was set up for an Agent",
1201-
fmt.Sprintf("Connect the agent again (basecamp auth agent connect -P %s) and drop --expect-identity, or remove %s to set this profile up as a bot user.",
1202-
profile, richtext.SanitizeSingleLine(path)))
1282+
fmt.Sprintf("Connect the agent again (basecamp auth agent connect -P %s) and drop --expect-identity, or add --reset to set this profile up as a bot user.",
1283+
profile))
12031284
case held == "" && (expect != 0 || (exists && existing.Agent.Kind == setup.KindBotUser)):
12041285
identity := expect
12051286
if identity == 0 {

‎internal/commands/connect_console.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ func (c *connectConsole) checks(ctx context.Context) []console.Check {
118118
if err != nil {
119119
return []console.Check{{Name: "connect.json", Status: setup.StatusFail,
120120
Message: "It cannot be used as it now stands: " + setup.ErrorText(err),
121-
Hint: "Run basecamp connect setup -P " + richtext.ShellQuote(p.name) + " again, then press r."}}
121+
Hint: connectResetHint(p.name) + ", then press r."}}
122122
}
123123
var checks []console.Check
124124
for _, check := range connectDoctorChecks(ctx, p) {

0 commit comments

Comments
 (0)