package provision import ( "context" "errors" "strings" "amadan.net/oficina/alta/homeop" ) // Observation is what an adopted app's activation evidence takes from the // CARLOS half: the delivered version, the reviewed artifact's digest and // the environment binding. EnvironmentBinding is never printed or logged. type Observation struct { AppVersion, ArtifactDigest, EnvironmentBinding string } // Observer re-observes one adopted app immediately before its activation // and answers its evidence, or refuses with a fixed code. The engine // never activates an adopted app without it. The served alta has none. type Observer interface { Observe(ctx context.Context, app, teamSQID string) (Observation, error) } // ObserverRefusal is an Observer's refusal (adopt.Refusal): fixed codes, // which the activation parks with. Any other Observer error is a failed // read, retried on the next pass. type ObserverRefusal interface { error RefusalCodes() []string } // adoptionName is the existing team's display name (Paul, 2026-11-16). const adoptionName = "Oficina" // Existing-team adoption (Home implementation/existing-team-adoption.md) // runs in three plans, all under label oficina and the canonical tuple // (ConsumerID, PublicOrigin and PublicHost answer it for AdoptionLabel): // // - Plan A (StartAdoption): create-team with existing_team, owner-seed // and seed-team at that SQID, then each app's provision and register // (verified, nothing inserted). It ends done, awaiting-configuration. // - Plans B and C (ActivateAdopted): add-apps with existing_team, each // app's verify and activate under the existing-app policy, its // evidence from the Observer. // - DisableAdopted: an ordinary retire-apps window on the directory // alone, directory.disable-consumer and nothing else. // // None of them touches the console or an instance: the existing instances, // their environments and their keys are not Alta's. // adoptionSteps is an adoption run's per-app pipeline: Plan A, a // disable, or Plans B and C. func adoptionSteps(kind string) []string { switch kind { case homeop.KindCreateTeam: return []string{StepConsumer, StepRegister} case homeop.KindRetireApps: return []string{StepDisable} } return []string{StepVerify, StepActivate} } // StartAdoption opens Plan A for the canonical apps. existing_team is // the SQID the directory proposes now, read here; Home seeds the team at // it or not at all. func (e *Engine) StartAdoption(ctx context.Context, name, owner string) (int64, error) { if name != adoptionName { return 0, fail("name-not-oficina") } if !homeop.OwnerAddress(owner) { return 0, fail("owner-shape") } used, err := e.cfg.Store.LabelUsed(ctx, AdoptionLabel) if err != nil { return 0, err } if used { return 0, fail("label-used") } if _, o, _ := e.cfg.Home.Inspect(ctx, homeop.Credential); o != homeop.OK { return 0, fail("home-" + homeop.Credential + "-" + o.String()) } ins, o, _ := e.cfg.Home.Inspect(ctx, homeop.Directory) if o != homeop.OK { return 0, fail("home-" + homeop.Directory + "-" + o.String()) } if ins.Generation == nil || ins.TeamSQID == "" { return 0, fail("home-not-initialized") } apps := Slugs() if err := e.cfg.Store.CreateAdoption(ctx, name, owner, apps); err != nil { return 0, err } id, err := e.cfg.Store.NewAdoptionRun(ctx, homeop.KindCreateTeam, apps) if err != nil { return 0, err } e.cfg.Store.Audit(ctx, id, AdoptionLabel, "", "run-start", homeop.KindCreateTeam) return id, e.submitPlans(ctx, id, AdoptionLabel, name, owner, homeop.KindCreateTeam, apps, ins.TeamSQID) } // ContinueAdoption completes a Plan A whose team is seeded but whose // window closed before every app's consumer and register steps were done. // Home admits seeding under create-team alone, and provision and register // under add-apps too (internal/operator plan.go windowAdmits), so the // continuation's plan is add-apps on both roles, existing_team the stored // SQID, no owner, for exactly the apps still unregistered. The run is // Plan A's phase (create-team in Alta, no seed since the team is seeded): // done steps are skipped, a held request is replayed exactly, and it ends // awaiting-configuration. func (e *Engine) ContinueAdoption(ctx context.Context) (int64, error) { t, err := e.cfg.Store.Team(ctx, AdoptionLabel) if err != nil { return 0, fail("no-team") } if t.TeamSQID == "" { // Unseeded: Resubmit the Plan A run, whose create-team plan seeds. return 0, fail("team-not-seeded") } var missing []string for _, a := range Slugs() { if _, ok, err := e.cfg.Store.Done(ctx, AdoptionLabel, a, StepRegister); err != nil { return 0, err } else if !ok { missing = append(missing, a) } } if len(missing) == 0 { return 0, fail("plan-a-complete") } // A newly supported app may not have been in the original Plan A. // Record it locally too; AddAdoptionApps is idempotent on existing bindings. if err := e.cfg.Store.AddAdoptionApps(ctx, missing); err != nil { return 0, err } id, err := e.cfg.Store.NewAdoptionRun(ctx, homeop.KindCreateTeam, missing) if err != nil { return 0, err } e.cfg.Store.Audit(ctx, id, AdoptionLabel, "", "run-start", "continue-adoption") return id, e.submitPlans(ctx, id, AdoptionLabel, "", "", homeop.KindAddApps, missing, t.TeamSQID) } // ActivateAdopted opens Plan B or C: add-apps on both roles for apps // whose Plan A is done, existing_team the seeded team's SQID, no owner. func (e *Engine) ActivateAdopted(ctx context.Context, apps []string) (int64, error) { if e.cfg.Observer == nil { return 0, fail("no-observer") } if len(apps) == 0 { return 0, fail("no-apps") } sorted := SortApps(apps) if len(sorted) != len(apps) { return 0, fail("unknown-app") } t, err := e.cfg.Store.Team(ctx, AdoptionLabel) if err != nil { return 0, fail("no-team") } if t.TeamSQID == "" { return 0, fail("team-not-seeded") } for _, a := range sorted { if _, ok, err := e.cfg.Store.Done(ctx, AdoptionLabel, a, StepRegister); err != nil { return 0, err } else if !ok { return 0, fail("not-registered") } if _, ok, err := e.cfg.Store.Done(ctx, AdoptionLabel, a, StepDisable); err != nil { return 0, err } else if ok { return 0, fail("app-disabled") } if _, ok, err := e.cfg.Store.Done(ctx, AdoptionLabel, a, StepActivate); err != nil { return 0, err } else if ok { return 0, fail("app-active") } } id, err := e.cfg.Store.NewAdoptionRun(ctx, homeop.KindAddApps, sorted) if err != nil { return 0, err } e.cfg.Store.Audit(ctx, id, AdoptionLabel, "", "run-start", homeop.KindAddApps) return id, e.submitPlans(ctx, id, AdoptionLabel, "", "", homeop.KindAddApps, sorted, t.TeamSQID) } // DisableAdopted opens a retire-apps window on the directory alone for one // adopted app: directory.disable-consumer, the immediate incident response. // Its env-manifest consumer, instance and environment are untouched. // typed must equal the label. func (e *Engine) DisableAdopted(ctx context.Context, app, typed string) (int64, error) { if typed != AdoptionLabel { return 0, fail("label-mismatch") } if _, ok := AppBySlug(app); !ok { return 0, fail("unknown-app") } t, err := e.cfg.Store.Team(ctx, AdoptionLabel) if err != nil { return 0, fail("no-team") } if t.TeamSQID == "" { return 0, fail("team-not-seeded") } if _, ok, err := e.cfg.Store.Done(ctx, AdoptionLabel, app, StepConsumer); err != nil { return 0, err } else if !ok { return 0, fail("not-provisioned") } // Marked an adoption, so Advance takes it to the disable step alone, // never §9's retire, detach and delete. id, err := e.cfg.Store.newRun(ctx, homeop.KindRetireApps, AdoptionLabel, []string{app}, RunOptions{Profile: ProfileOutside}, true) if err != nil { return 0, err } e.cfg.Store.Audit(ctx, id, AdoptionLabel, "", "run-start", homeop.KindRetireApps) return id, e.submitPlans(ctx, id, AdoptionLabel, "", "", homeop.KindRetireApps, []string{app}, "") } // adoptedTeam is the SQID a fresh plan for adoption run r binds: the // directory's proposal for Plan A (unseeded), the seeded team's for // Plans B and C, none for a disable. func (e *Engine) adoptedTeam(ctx context.Context, r Run) (string, error) { switch r.Kind { case homeop.KindCreateTeam: ins, o, _ := e.cfg.Home.Inspect(ctx, homeop.Directory) if o != homeop.OK || ins.TeamSQID == "" { return "", fail("no-proposed-team") } return ins.TeamSQID, nil case homeop.KindAddApps: t, err := e.cfg.Store.Team(ctx, AdoptionLabel) return t.TeamSQID, err } return "", nil } // planExisting is the existing_team of the plan this run's window opened // for, from Alta's own signed copy of the directory's plan. func (e *Engine) planExisting(ctx context.Context, p *pass) (string, error) { subs, err := e.cfg.Store.Plans(ctx, p.run.PlanID) if err != nil { return "", err } // An absent row or dropped bytes read as no payload. raw, err := homeop.EnvelopePayload(subs[homeop.Directory].Signed) var plan homeop.Plan if err != nil || homeop.Decode(raw, &plan) != nil { return "", fail("plan-unreadable") } return plan.ExistingTeam, nil } // adoption is one Advance of an adoption run: the team's seed (Plan A // only), then each app's steps. A parked app does not hold the others // back; a failed one stops the run. func (e *Engine) adoption(ctx context.Context, p *pass) error { st := e.cfg.Store if p.team.TeamSQID == "" { // seed admits create-team only: Plans B and C need a seeded team. if err := e.seed(ctx, p); err != nil { return err } t, err := st.Team(ctx, p.run.Label) if err != nil { return err } p.team = t } // No recipe ever holds the owner here: the seed was the address's // last use. if _, held, err := st.Owner(ctx, p.run.Label); err != nil { return err } else if held { if err := st.ForgetOwner(ctx, p.run.Label); err != nil { return err } st.Audit(ctx, p.run.ID, p.run.Label, "", "owner-forgotten", "") } var first error for _, slug := range p.run.Apps { app, _ := AppBySlug(slug) if err := e.pipeline(ctx, p, app, adoptionSteps(p.run.Kind)); err != nil { if errors.Is(err, errCrash) { return err } var fl *Fail if errors.As(err, &fl) { return err } if first == nil { first = err } } } return first } // stepActivateAdopted is step 12 for an adopted app: the existing-app // policy, the canonical consumer and audience, the Observer's evidence, // started_at the recorded issued_at and completed_at now − Skew. A // request Alta already signed is replayed exactly and never rebuilt: its // observation was made once. func (e *Engine) stepActivateAdopted(ctx context.Context, p *pass, app App) error { st, label := e.cfg.Store, p.run.Label if e.cfg.Observer == nil { return fail("no-observer") } spec := opSpec{role: homeop.Directory, action: homeop.DirectoryActivate, label: label, app: app.Slug, purpose: "activate", reuse: true} if _, handled, err := e.replayHeld(ctx, spec); handled { if err != nil { return err } return e.record(ctx, p, app.Slug, StepActivate, map[string]any{"replayed": true}) } if err := e.needWindow(p, homeop.Directory); err != nil { return err } v, _, _ := st.Done(ctx, label, app.Slug, StepVerify) reg, _, _ := st.Done(ctx, label, app.Slug, StepRegister) _, cd, err := e.consumerData(ctx, p, app) if err != nil { return err } if num(v, "expires_at") <= e.now().Unix()+10 { // The attempt lapsed: verify again. _ = st.SetStep(ctx, label, app.Slug, StepVerify, "parked", "attempt-expired", nil) return park("attempt-expired") } obs, err := e.cfg.Observer.Observe(ctx, app.Slug, p.team.TeamSQID) if err != nil { var r ObserverRefusal if errors.As(err, &r) { return park("observe-" + strings.Join(r.RefusalCodes(), ",")) } if e.cfg.Debug != nil { e.cfg.Debug(err) } return park("observer-unavailable") } // What Home would refuse is never signed. if !activationVersion.MatchString(obs.AppVersion) || !homeop.CanonicalToken(obs.ArtifactDigest) || !homeop.CanonicalToken(obs.EnvironmentBinding) { return fail("observation-shape") } ev := homeop.ActivationEvidence{Version: 1, Policy: homeop.ExistingActivationPolicy, Attempt: str(v, "attempt"), Consumer: ConsumerID(label, app.Slug), TeamSQID: p.team.TeamSQID, App: app.Slug, Audience: PublicOrigin(label, app.Slug), Generation: str(cd, "generation"), RecordSequence: 1, RecordDigest: str(cd, "record_digest"), Epoch: num(cd, "epoch"), Owner: p.team.OwnerRef, AppVersion: obs.AppVersion, ArtifactDigest: obs.ArtifactDigest, EnvironmentBinding: obs.EnvironmentBinding, ManifestDigest: str(reg, "manifest_digest"), AliasHost: PublicHost(label, app.Slug), Started: num(v, "issued_at"), Completed: e.now().Unix() - homeop.Skew} spec.build = func(b homeop.InputBase) any { return homeop.ActivationInput{InputBase: b, Evidence: ev} } if _, err := e.op(ctx, spec); err != nil { if errors.Is(err, errOpRefused) { return fail("activate-refused") } return err } return e.record(ctx, p, app.Slug, StepActivate, map[string]any{"app_version": obs.AppVersion}) }