R-717: after_setup open_command — the family window reopens an app's DB-held sign-up switch

The command form ran only when the lock was SET, so a database switch closed by
`command` stayed closed through the household's 15-minute window. New twin
fields `open_command` + `open_success` (same service/user/args_env and the same
argv-safe expansion and success-marker rules as `command`/`success`).

- liftNativeLock (the window, via OpenSignupWindow → goNativeLock(false)): marks
  the gate record native_lock "opening" BEFORE anything opens, lifts the env,
  runs open_command; only full success records "lifted". A failed open closes
  the switch again at once and records after_setup {ok: false, step: open}; the
  app page shows its own line (app_info.signup_native_open_failed).
- The close: reconcileSignupBlocks (every 20 s and at controller start) runs
  `command` for any non-"applied" state once no window runs. A failed close
  after a window is logged ERROR ("may still be OPEN past the household's
  window") and retried every nativeLockOpenRetry (2 min) instead of 30.
- After a successful app update, verifyAndConclude → markNativeLockForReapply
  sets native_lock "" so the loop closes the switch again.
- A template with `command` but no `open_command` keeps today's window (env
  only) and logs once per app that its own switch cannot be reopened.

Tests: internal/stacks/after_setup_r717_test.go (7), web render + parity case.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
This commit is contained in:
2026-10-06 15:12:14 +02:00
parent 9c945688c0
commit 5b8656974b
13 changed files with 1080 additions and 39 deletions
+149 -35
View File
@@ -29,6 +29,26 @@ import (
// restarts.
//
// A command form (`service`, `command`, `success`, `env` names) follows after_install's argv-safe rules (R-713).
//
// R-717: an app whose switch lives in its own database (opengist, wishlist) is closed by `command` and reopened for
// the household's window by its twin:
//
// after_setup:
// service: app # shared by both commands, as is `user` and `args_env`
// command: [...] # CLOSES the switch; `success` must appear in its output
// success: "closed"
// open_command: [...] # OPENS it for the 15-minute window; `open_success` must appear in its output
// open_success: "opened"
//
// Where each runs: the window (OpenSignupWindow → liftNativeLock) runs `open_command` after the env lift; the loop
// (reconcileSignupBlocks, every 20 s and once at controller start) runs `command` again for every app whose state is
// not "applied" once no window runs — after the window, after a box restart, and after an app update
// (markNativeLockForReapply in verifyAndConclude). Fail closed: the state is marked "opening" BEFORE anything opens,
// so a crash mid-open leaves a state the loop closes; an `open_command` that fails closes the switch again at once and
// records `after_setup: {ok: false, step: open}` (the app page says the switch could not be opened); a close that fails
// keeps the state not-"applied", logs ERROR and is retried by the loop every nativeLockOpenRetry. A template with
// `command` but no `open_command` keeps today's window (env lift only) and logs once that the app's own switch cannot
// be reopened.
// Pinned by internal/stacks/after_setup_test.go.
// AfterSetupSpec is `.felhom.yml`'s `after_setup:`.
@@ -39,14 +59,23 @@ type AfterSetupSpec struct {
Args []string `yaml:"args_env,omitempty" json:"args_env,omitempty"` // deploy values a command may use
Command []string `yaml:"command,omitempty" json:"command,omitempty"`
Success string `yaml:"success,omitempty" json:"success,omitempty"`
// OpenCommand / OpenSuccess (R-717): the twin that opens the switch `command` closes, for the household's window.
OpenCommand []string `yaml:"open_command,omitempty" json:"open_command,omitempty"`
OpenSuccess string `yaml:"open_success,omitempty" json:"open_success,omitempty"`
}
// Native-lock states in SetupGateRecord.NativeLock.
const (
NativeLockApplied = "applied" // the app's own switch says closed
NativeLockLifted = "lifted" // the household's window: the switch is open again
// NativeLockOpening (R-717) is written BEFORE the window opens anything: a crash between the opening and its
// record leaves a state that is not "applied", so the loop closes it once the window has passed.
NativeLockOpening = "opening"
)
// afterSetupStepOpen marks an AfterInstallRecord written by a failed OPEN (the window), not a failed close.
const afterSetupStepOpen = "open"
// afterSetupUp starts the app from its stored app.yaml (a seam: tests never reach Docker).
func (m *Manager) afterSetupUp(name string) error {
if m.afterSetupUpFn != nil {
@@ -79,73 +108,158 @@ func (m *Manager) setNativeEnv(name, dir string, spec *AfterSetupSpec, lock bool
}
// applyNativeLock sets (lock=true) or lifts the app's own switch, then starts the app once when anything changed.
// Records the outcome. Safe to call again: an unchanged env starts nothing.
// Records the outcome. Safe to call again: an unchanged env starts nothing. A lift goes to liftNativeLock (R-717).
func (m *Manager) applyNativeLock(name string, lock bool, why string) error {
st, ok := m.GetStack(name)
if !ok || st.Meta.AfterSetup == nil {
return nil
}
if !lock {
return m.liftNativeLock(name, st, why)
}
spec := st.Meta.AfterSetup
dir := filepath.Dir(st.ComposePath)
record := func(ok bool, detail string) {
rec := &AfterInstallRecord{At: m.now().UTC().Format(time.RFC3339), OK: ok, Detail: truncateStr(detail, 300)}
state := NativeLockApplied
if !lock {
state = NativeLockLifted
}
m.mutateAppConfig(name, dir, "after_setup", func(cfg *AppConfig) bool {
cfg.AfterSetup = rec
if ok && cfg.SetupGate != nil {
cfg.SetupGate.NativeLock = state
}
return true
})
priorState := ""
if st.AppConfig != nil && st.AppConfig.SetupGate != nil {
priorState = st.AppConfig.SetupGate.NativeLock
}
var err error
// The switch works only if the app's INSTALLED compose reads the variable. An app installed before the template
// wired it (decision 49's apps) carries the old compose until its next update: say so, never report a lock that
// is not there. The address block still holds.
if len(spec.Env) > 0 && lock {
if len(spec.Env) > 0 {
if miss := composeMissingVars(st.ComposePath, spec.Env); len(miss) > 0 {
err = fmt.Errorf("the installed version of the app does not read %v yet — its own switch applies after its next update", miss)
m.logger.Printf("[WARN] [stacks] %s: %v", name, err)
record(false, err.Error())
m.recordNativeLock(name, dir, false, err.Error(), "", "")
return err
}
}
if len(spec.Env) > 0 {
if m.setNativeEnv(name, dir, spec, lock) {
if m.setNativeEnv(name, dir, spec, true) {
err = m.afterSetupUp(name)
}
}
if err == nil && lock && len(spec.Command) > 0 {
err = m.runAfterSetupCommand(name, dir, spec)
if err == nil && len(spec.Command) > 0 {
err = m.runAfterSetupCommand(name, dir, spec, spec.Command, spec.Success, "command")
}
if err != nil {
m.logger.Printf("[ERROR] [stacks] %s: the app's own sign-up switch could not be %s (%s): %v — the address block still holds", name, map[bool]string{true: "closed", false: "opened"}[lock], why, err)
record(false, err.Error())
if priorState == NativeLockLifted || priorState == NativeLockOpening {
// R-717: the household's window was (or may have been) opened — the app's own sign-up may still be OPEN.
m.logger.Printf("[ERROR] [stacks] %s: the app's own sign-up switch could NOT be closed again (%s): %v — sign-up inside the app may still be OPEN past the household's window; the address block holds and the loop retries every %s", name, why, err, nativeLockOpenRetry)
} else {
m.logger.Printf("[ERROR] [stacks] %s: the app's own sign-up switch could not be closed (%s): %v — the address block still holds", name, why, err)
}
m.recordNativeLock(name, dir, false, err.Error(), "", "")
return err
}
keys := make([]string, 0, len(spec.Env))
for k := range spec.Env {
keys = append(keys, k)
}
sort.Strings(keys)
m.logger.Printf("[INFO] [stacks] %s: the app's own sign-up switch %s (%s; env %v)", name, map[bool]string{true: "CLOSED", false: "opened for the household's window"}[lock], why, keys)
record(true, "")
m.logger.Printf("[INFO] [stacks] %s: the app's own sign-up switch CLOSED (%s; env %v, command %v)", name, why, sortedEnvKeys(spec.Env), len(spec.Command) > 0)
m.recordNativeLock(name, dir, true, "", "", NativeLockApplied)
return nil
}
// runAfterSetupCommand runs the command form once, with after_install's argv-safe expansion and success marker.
func (m *Manager) runAfterSetupCommand(name, dir string, spec *AfterSetupSpec) error {
if spec.Service == "" || spec.Success == "" {
return fmt.Errorf("after_setup command needs a service and a success marker")
// liftNativeLock is the household's window (R-717): the env keys go (one start) and the template's open_command runs.
// Fail closed: the state says "opening" before anything opens; an open that fails closes the switch again at once and
// records the failure with step "open" (the app page says it could not be opened). Only a full success records
// "lifted", which the loop closes again once the window has passed.
func (m *Manager) liftNativeLock(name string, st *Stack, why string) error {
spec := st.Meta.AfterSetup
dir := filepath.Dir(st.ComposePath)
if len(spec.Command) > 0 && len(spec.OpenCommand) == 0 {
if _, seen := m.nativeOpenMissingLogged.LoadOrStore(name, true); !seen {
m.logger.Printf("[WARN] [stacks] %s: the template closes the app's own sign-up switch with a command but has no open_command — the household's window cannot reopen it (only the address block opens)", name)
}
}
if len(spec.Env) == 0 && len(spec.OpenCommand) == 0 {
return nil // nothing of the app's own to open
}
m.mutateAppConfig(name, dir, "after_setup_opening", func(cfg *AppConfig) bool {
if cfg.SetupGate == nil {
return false
}
cfg.SetupGate.NativeLock = NativeLockOpening
return true
})
if c := LoadAppConfig(dir); c == nil || c.SetupGate == nil || c.SetupGate.NativeLock != NativeLockOpening {
err := fmt.Errorf("the record could not be marked before opening — the app's own switch stays closed")
m.logger.Printf("[ERROR] [stacks] %s: the app's own sign-up switch was NOT opened (%s): %v", name, why, err)
m.recordNativeLock(name, dir, false, err.Error(), afterSetupStepOpen, "")
return err
}
var err error
if len(spec.Env) > 0 && m.setNativeEnv(name, dir, spec, false) {
err = m.afterSetupUp(name)
}
if err == nil && len(spec.OpenCommand) > 0 {
err = m.runAfterSetupCommand(name, dir, spec, spec.OpenCommand, spec.OpenSuccess, "open_command")
}
if err != nil {
m.logger.Printf("[ERROR] [stacks] %s: the app's own sign-up switch could NOT be opened (%s): %v — closing it again; a new family member cannot sign up in the app itself", name, why, err)
detail := "could not be opened for the household's window: " + err.Error()
if cerr := m.applyNativeLock(name, true, "an opening that failed"); cerr != nil {
detail += "; closing it again failed too (the loop retries): " + cerr.Error()
}
m.recordNativeLock(name, dir, false, detail, afterSetupStepOpen, "")
return err
}
m.logger.Printf("[INFO] [stacks] %s: the app's own sign-up switch opened for the household's window (%s; env %v, open_command %v)", name, why, sortedEnvKeys(spec.Env), len(spec.OpenCommand) > 0)
m.recordNativeLock(name, dir, true, "", "", NativeLockLifted)
return nil
}
// recordNativeLock writes the after_setup record; state != "" also moves SetupGate.NativeLock.
func (m *Manager) recordNativeLock(name, dir string, ok bool, detail, step, state string) {
rec := &AfterInstallRecord{At: m.now().UTC().Format(time.RFC3339), OK: ok, Detail: truncateStr(detail, 300), Step: step}
m.mutateAppConfig(name, dir, "after_setup", func(cfg *AppConfig) bool {
cfg.AfterSetup = rec
if state != "" && cfg.SetupGate != nil {
cfg.SetupGate.NativeLock = state
}
return true
})
}
// markNativeLockForReapply (R-717) makes the loop run the close again after an app update: an update may bring a
// database whose switch is not the one the box set. NativeLock "" = "run once the app is up" (as after a restore).
func (m *Manager) markNativeLockForReapply(name, dir string) {
st, ok := m.GetStack(name)
if !ok || st.Meta.AfterSetup == nil {
return
}
marked := false
m.mutateAppConfig(name, dir, "after_setup_reapply", func(cfg *AppConfig) bool {
if cfg.SetupGate == nil || cfg.SetupGate.State != SetupGateOpen || cfg.SetupGate.NativeLock != NativeLockApplied {
return false // never set, or not applied: the loop already runs it
}
cfg.SetupGate.NativeLock = ""
marked = true
return true
})
if marked {
m.logger.Printf("[INFO] [stacks] %s: after the update the app's own sign-up switch is closed again by the loop", name)
}
}
func sortedEnvKeys(mp map[string]string) []string {
keys := make([]string, 0, len(mp))
for k := range mp {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
// runAfterSetupCommand runs one command of the command form (`command` or `open_command`) once, with after_install's
// argv-safe expansion and its success marker.
func (m *Manager) runAfterSetupCommand(name, dir string, spec *AfterSetupSpec, command []string, success, field string) error {
if spec.Service == "" || success == "" {
return fmt.Errorf("after_setup %s needs a service and a success marker", field)
}
cfg := LoadAppConfigDecrypted(dir, m.encKey)
if cfg == nil {
return fmt.Errorf("app.yaml unreadable")
}
cmd, err := expandAfterInstall(spec.Command, spec.Args, cfg.Env)
cmd, err := expandAfterInstall(command, spec.Args, cfg.Env)
if err != nil {
return err
}
@@ -156,8 +270,8 @@ func (m *Manager) runAfterSetupCommand(name, dir string, spec *AfterSetupSpec) e
args = append(args, spec.Service)
args = append(args, cmd...)
out, err := m.runInService(dir, args...)
if err != nil || !strings.Contains(out, spec.Success) {
return fmt.Errorf("after_setup command did not report %q (err %v)", spec.Success, err)
if err != nil || !strings.Contains(out, success) {
return fmt.Errorf("after_setup %s did not report %q (err %v)", field, success, err)
}
return nil
}