# Add Equipo to the existing Oficina team

Implementer: Codex GPT-6-Astra. Approved scope: Equipo's 2026-11-20
native Oficina ID spec, E4. This runbook is for Paul on the Mac holding
Alta's existing operator configuration and state. No commands here were
executed against production with writes during implementation.

## Prerequisites

- Land and deploy the reviewed Home `native/equipo-in-directory` change to
  **both** `oficina` and `oficina-id`; verify their `X-Carlos-Version`.
- Land this Alta change and build `make adopt` on the operator Mac.
  Before deleting Home's source branch after a squash merge, re-pin Alta's
  test-only `homecompat` module to the Home merge commit and pass `make ci`.
- The separately implemented Equipo adoption contract below must be
  deployed at `https://equipo.oficina.works`, with its existing instance,
  storage and access policy preserved. Its native exchange must also be
  deployed before testing native sign-in.
- Configure Equipo's existing Oficina ID integration **before** capturing
  the adoption baseline: `EQUIPO_HOME_ISSUER=https://id.oficina.works`,
  `EQUIPO_HOME_CONSUMER_ID=equipo`, `EQUIPO_HOME_KEYS_BASE64` containing the
  pinned Home public key map, and `EQUIPO_HOME_DEK_BASE64` containing its
  persistent 32-byte key. Use the Equipo rollout for this step: preserve an
  existing DEK, never regenerate it. The key map is a base64-encoded JSON
  object mapping key IDs to encoded public keys (`connect/config.go`).
- Use a current CARLOS CLI with `services` and `db query`. Reuse the same
  Alta config, state path, operator key and pins. Do not initialize again
  or run keygen. Alta's web process must not run concurrently with the
  adoption runner; both own the same signed streams.
- Calendar's Plan B must still be active in the existing journal. The
  runner checks this again before Equipo activation.

Read-only observations on 2026-11-20, 14:42–14:49 UTC: Home served
`5e5ebe54f4c4eacfb6aa053919c91ebce0d05af8`; its default
`HOME_CONSUMERS_BASE64` had ten entries, neither `equipo` nor its canonical
origin. `/authorize?consumer=equipo&nonce=AAAAAAAAAAAAAAAAAAAAAA` answered
400, with the identical Docs control answering 303. Equipo served
`b6c76de2`, its operations path returned its generic API 401, and
`/auth/start` redirected locally to `/signin`. The default Equipo env and
secret-name listings contained none of the four `EQUIPO_HOME_*` keys.
These are observations of that deployment, not evidence of a later release
or of other config layers. Current live sign-in is a prerequisite, not
something `alta-adopt configure` installs.

## 1. Verify and register the canonical consumer

Native assert and web authorize read the same effective registry. This
public check creates no login session and prints no cookie/token:

```sh
curl -sS -o /dev/null -w 'Equipo consumer HTTP %{http_code}\n' \
  'https://id.oficina.works/authorize?consumer=equipo&nonce=AAAAAAAAAAAAAAAAAAAAAA'
curl -sS -o /dev/null -w 'Docs control HTTP %{http_code}\n' \
  'https://id.oficina.works/authorize?consumer=docs&nonce=AAAAAAAAAAAAAAAAAAAAAA'
```

Expected: both 303. A 400 for Equipo with a 303 control means the consumer
ID is not registered. A 303 establishes ID admission; the following manifest
inspection establishes its exact origin. Canonical adoption requires the
**env** registration. Its `credential.register-consumer` verifies this
binding and returns the manifest digest; it never inserts a duplicate table
row. A table-only registration needs a separately reviewed reconciliation,
not another registration on top of it.

Check the replica for an ID/origin collision (read-only, current CLI):

```sh
carlos db query --account oficina --app oficina-id \
  "SELECT consumer_id,origin,state FROM consumers WHERE consumer_id='equipo' OR origin='https://equipo.oficina.works'"
```

Expected: no rows. If a row exists, stop; adding the same ID or origin to
the env manifest would make Home refuse boot.

On an otherwise unchanged deployment, Paul runs this to preserve the live
manifest and add the exact binding. It reads only the public manifest from
`carlos env list`, refuses an unexpected format or conflicting binding, and
prints no credentials. Do not run concurrently with another manifest edit.

```sh
python3 - <<'PY'
import base64, json, subprocess
from pathlib import Path
base = ['carlos', 'env']
args = ['--account', 'oficina', '--app', 'oficina-id']
text = subprocess.check_output(base + ['list'] + args, text=True)
values = dict(line.split(None, 1) for line in text.splitlines()
              if line.startswith(('HOME_CONSUMERS ', 'HOME_CONSUMERS_BASE64 ')))
assert set(values) == {'HOME_CONSUMERS_BASE64'}, 'Inspect manifest format before changing it'
manifest = json.loads(base64.b64decode(values['HOME_CONSUMERS_BASE64'], validate=True))
origin = 'https://equipo.oficina.works'
assert isinstance(manifest, dict) and 0 < len(manifest) <= 16
assert all(isinstance(k, str) and isinstance(v, str) for k, v in manifest.items())
assert manifest.get('equipo', origin) == origin, 'Equipo has a different origin'
assert all(k == 'equipo' or v != origin for k, v in manifest.items()), 'Origin has another ID'
if manifest.get('equipo') == origin:
    print('Equipo already has the exact canonical env registration')
else:
    assert len(manifest) < 16, 'Env registry is full'
    backup = Path.home() / '.oficina-id-consumers-before-equipo.b64'
    with backup.open('x', encoding='ascii') as saved:
        saved.write(values['HOME_CONSUMERS_BASE64'] + '\n')
    backup.chmod(0o600)
    manifest['equipo'] = origin
    encoded = base64.b64encode(json.dumps(manifest, separators=(',', ':')).encode()).decode()
    subprocess.run(base + ['set'] + args + ['HOME_CONSUMERS_BASE64=' + encoded], check=True)
    print('Added equipo -> https://equipo.oficina.works; restart the credential service')
PY
carlos restart --account oficina --app oficina-id
curl --fail --silent --show-error -D - https://id.oficina.works/healthz
```

Expected health: 200 and `X-Carlos-Version` naming the reviewed Home release.
The backup is public consumer metadata; the exclusive create prevents
overwriting the previous manifest. If it already exists, inspect it before
another attempt. Keep it until health and consumer checks pass.

If this manifest change makes the credential service unhealthy, restore the
saved value immediately (only if no intervening manifest edit occurred),
restart, and check health before investigating. This rolls back the manifest
change, not an adoption or deployment:

```sh
python3 - <<'PY'
import base64, json, subprocess
from pathlib import Path
old = (Path.home() / '.oficina-id-consumers-before-equipo.b64').read_text().strip()
assert isinstance(json.loads(base64.b64decode(old, validate=True)), dict)
subprocess.run(['carlos', 'env', 'set', '--account', 'oficina', '--app',
                'oficina-id', 'HOME_CONSUMERS_BASE64=' + old], check=True)
PY
carlos restart --account oficina --app oficina-id
curl --fail --silent --show-error -D - https://id.oficina.works/healthz
```

On success, re-run the two public checks. Expected: Equipo and Docs both 303 after the
process restarts. Home's native `assert` then accepts exactly
`https://equipo.oficina.works`, with no port, slash, suffix or case variants.
A complete native check still needs a real device grant and the deployed
Equipo exchange; the public check alone is not a native end-to-end test.

## 2. Build and select the existing operator state

After both branches are reviewed and landed, run in the Alta checkout on
the operator Mac (no live Alta server is required):

```sh
git fetch origin
git switch main
git pull --ff-only
make adopt
bash
read -r -p 'Absolute path to the EXISTING alta-adopt config: ' ALTA_CONFIG
read -r -p 'Absolute path to the existing short-lived CARLOS Admin token file: ' ALTA_TOKEN_FILE
read -r -p 'Reviewed Equipo release name (X-Carlos-Version): ' EQUIPO_RELEASE
ALTA_ADOPT="$PWD/releases/alta-adopt"
"$ALTA_ADOPT" version
"$ALTA_ADOPT" status --config "$ALTA_CONFIG"
```

Keep this Bash shell for the commands below. The token file must contain
only the token, as the existing adoption setup requires. It is passed on FD
3, never exported or stored in Alta's config/state. If its credential has
expired, mint a fresh short-lived Admin credential using the existing
operator procedure (`carlos services create --account oficina --role admin
oficina-adoption`); keep its token out of command history. Revoke it after
this session, as the original adoption runbook requires.

Expected status: the `oficina` team is seeded, the original six apps'
register steps are done, calendar has completed activation, and Equipo has
no steps yet. No `oficina` run may be `planned`, `running` or `parked`:
finish or resolve it before opening another Plan A, which supersedes an
unfinished run. If Equipo is already registered, skip Plan A below. If it is
already active, stop here: no repeat adoption is needed.

Add the reviewed release's digest to `artifacts`, preserving every other
config field, including the state path and keys. This is the SHA-256 of the
**release name**, without a newline, not the binary's hash:

```sh
python3 - "$ALTA_CONFIG" "$EQUIPO_RELEASE" <<'PY'
import hashlib, json, os, pathlib, stat, sys, tempfile
p = pathlib.Path(sys.argv[1])
st = p.stat()
assert stat.S_ISREG(st.st_mode) and stat.S_IMODE(st.st_mode) == 0o600 and st.st_uid == os.getuid()
cfg = json.loads(p.read_text())
cfg.setdefault('artifacts', {})['equipo'] = hashlib.sha256(sys.argv[2].encode()).hexdigest()
fd, tmp = tempfile.mkstemp(dir=p.parent, prefix='.equipo-config-')
try:
    with os.fdopen(fd, 'w') as f:
        json.dump(cfg, f, indent=2)
        f.write('\n')
    os.replace(tmp, p)
finally:
    if os.path.exists(tmp): os.unlink(tmp)
print('Equipo reviewed release recorded; keys and state path preserved')
PY
"$ALTA_ADOPT" preflight --config "$ALTA_CONFIG" --app equipo \
  --carlos-token-fd 3 3<"$ALTA_TOKEN_FILE"
```

Expected: `equipo: ready`. No write. Missing Home identity, inherited keys
on other instances, team-mode config, unreviewed release, or an unexpected
operations response stops the run. Fix the reported cause, never remove the
gate or edit the journal. All Equipo config and release preparation belongs
before the first `configure`, which captures an immutable baseline.
An unscoped `preflight` now includes Equipo and will refuse until its
separate contract is deployed; use the explicit `--app equipo` above.

## 3. Register Equipo against the already seeded team

```sh
"$ALTA_ADOPT" plan-a --config "$ALTA_CONFIG"
"$ALTA_ADOPT" plan-a --config "$ALTA_CONFIG" --apply
```

Expected dry run: continuation of Plan A for **equipo only**. The applied
command prints a run ID and both confirmation URLs. It binds the existing
SQID and registers missing apps; it does not seed a second team. If other
apps are listed, inspect the existing state before applying.

Open `https://oficina.works/operator/confirm`, then
`https://id.oficina.works/operator/confirm` in the system browser. Confirm
with a fresh passkey; compare the plan prefix on both pages. Both must name
Equipo and the existing team SQID. Complete each plan/confirmation/advance
within its 15-minute window. No owner retyping or re-seeding is needed for
this continuation.

```sh
read -r -p 'Registration run ID printed by plan-a: ' EQUIPO_REGISTER_RUN
"$ALTA_ADOPT" advance --config "$ALTA_CONFIG" --run "$EQUIPO_REGISTER_RUN" --apply
"$ALTA_ADOPT" status --config "$ALTA_CONFIG"
```

Expected: run `done awaiting-configuration`; Equipo provision and register
steps done, directory row pending, existing team and registrations retained.
Wait for any previous confirmation window to expire before opening another
plan; never alter the clock or state to bypass `plan-open`.

## 4. Configure and activate Equipo

```sh
"$ALTA_ADOPT" configure --config "$ALTA_CONFIG" --app equipo \
  --carlos-token-fd 3 3<"$ALTA_TOKEN_FILE"
"$ALTA_ADOPT" configure --config "$ALTA_CONFIG" --app equipo --apply \
  --carlos-token-fd 3 3<"$ALTA_TOKEN_FILE"
```

Dry run names the two agent keys and their write layer. Apply writes them
conditionally, restarts **only the canonical Equipo host**, waits for the
agent-access challenge, and records the delivery check. Expected ending:
`Delivery check recorded.` The release must stay the reviewed release.

```sh
"$ALTA_ADOPT" activate --config "$ALTA_CONFIG" --apps equipo \
  --carlos-token-fd 3 3<"$ALTA_TOKEN_FILE"
"$ALTA_ADOPT" activate --config "$ALTA_CONFIG" --apps equipo --apply \
  --carlos-token-fd 3 3<"$ALTA_TOKEN_FILE"
```

Expected dry run: `equipo: ready`. Apply prints a **new** run ID. Confirm on
both Home pages again, for Equipo and the same existing SQID and plan prefix.
Then:

```sh
read -r -p 'Activation run ID printed by activate: ' EQUIPO_ACTIVATE_RUN
"$ALTA_ADOPT" advance --config "$ALTA_CONFIG" --run "$EQUIPO_ACTIVATE_RUN" --apply \
  --carlos-token-fd 3 3<"$ALTA_TOKEN_FILE"
"$ALTA_ADOPT" status --config "$ALTA_CONFIG"
carlos db query --account oficina --app oficina \
  "SELECT t.label,i.app,i.origin,i.consumer_id,i.state FROM team_instances i JOIN teams t ON t.id=i.team_id WHERE t.label='oficina' AND i.app='equipo'"
```

Expected: activation run `done`, verify and activate steps done, and exactly
`oficina | equipo | https://equipo.oficina.works | equipo | live` on the
replica once caught up. A roster member's native `/api/native/teams` includes
`{"app":"equipo","origin":"https://equipo.oficina.works","consumer_id":"equipo"}`.
Equipo native lists Oficina and signs in after its separate native build is
installed. Removed members and non-live instances remain excluded.
Back up the state database with the existing procedure and revoke the
session's Admin credential. Do not downgrade the journal or delete rows.

## Contract the separate Equipo session must implement

Reference inspected at [Docs commit 7de2d40](https://amadan.net/oficina/docs/commit/7de2d40c1c77a8b43544a4b47c7806411eafd65f):
[agent access source](https://amadan.net/oficina/docs?ref=main&path=internal/docs/agent_access.go),
[config wiring](https://amadan.net/oficina/docs?ref=main&path=cmd/docs/main.go),
and `amadan.net/oficina/agent-access.git` (`http.go`, `remote.go`, registry
and principal types). Docs pins `8ed8ba826000` at that revision. The file
links follow main; reproduce the exact inspected implementation locally with:

```sh
git -C /Users/paulcampbell/amadan.net/oficina/docs show \
  7de2d40c1c77a8b43544a4b47c7806411eafd65f:internal/docs/agent_access.go
```

1. Read `EQUIPO_AGENT_ISSUER` and `EQUIPO_AGENT_TEAM` together. Both absent
   leaves agent access disabled; partial/malformed config refuses boot.
   Require valid Home identity config. Issuer is
   `https://connect.oficina.works`; team is the Home directory **SQID**, not
   `oficina`, an Equipo database team ID, or a hostname. If a separate team
   mode is configured, the binding must agree; Alta adoption itself refuses
   `EQUIPO_TEAM_*` keys and does not enable team mode.
2. Mount agent routes ahead of Equipo's device/session authentication
   middleware. `GET /api/v1/operations` takes no body. With no valid bearer,
   answer **401**, `Cache-Control: no-store`, `Content-Type: application/json`,
   exactly one `WWW-Authenticate: Bearer` (parameters are permitted), and
   exactly `{"error":{"code":"unauthenticated","message":"Connect to Oficina first."}}`.
   The message may be another nonempty string. No request ID, copy key,
   wrapper fields, redirect, extra JSON value, or generic API 401 shape.
3. Use agent-access's delegated `Authorization: Bearer <token>` contract,
   not an Equipo device credential. `NewRemoteVerifier(agentIssuer,
   equipoOrigin+"/api/v1", homeIssuer)` checks online at
   `POST https://connect.oficina.works/api/v1/credential`, forwarding the
   bearer and JSON `{"resource":"https://equipo.oficina.works/api/v1"}`.
   It requires matching returned resource and identity issuer, plus a
   nonempty subject and grant. Do not hand-roll a permissive substitute.
   Resolve the Home person locally and enforce Equipo's current membership
   and permissions, including revocation, as Docs' `prepareMode` does.
4. With an authorized bearer, return 200 `{"operations":[...]}` with
   descriptors filtered to the principal's team/scopes. Actual invocation
   is `POST /api/v1/operations/{name}`, `Content-Type: application/json`,
   raw operation arguments including the exact team SQID, with the same
   bearer verification and current permissions. Use the shared registry's
   schema/size checks, and Docs' permission/revocation recheck for writes.
   Operation names and which Equipo actions to expose belong to that
   session's approved contract. A fake public list added only to satisfy
   Alta is not an integration.
5. Keep `/healthz` at 200 and `/api/version` at the stamped version, with
   `X-Carlos-Version` naming the same release (Alta `SameRelease` accepts
   the existing git-describe/short-hash pair). No redirects on these probes.
6. If `EQUIPO_HOME_ISSUER` or `EQUIPO_HOME_CONSUMER_ID` are stored as secrets,
   `GET /auth/start` must directly return 302/303 to Home's exact
   `/authorize?consumer=equipo&nonce=...`; Alta never follows it. Plain env
   values are read from effective config instead. The normal app should
   actually sign in with the same issuer/consumer in either case.

Alta sends no bearer in its probes. For Equipo, like Calls and Slides, it
requires the pre-configuration generic API **401** to change to the exact
agent-access **401** above. An unauthenticated 200 is refused for these apps.
`adopt/delivery.go` (`shape`, `BaselineOps`, `Delivered`) implements this;
`adopt/observer.go` checks baseline/write/after/delivery-check evidence,
calendar's active canary, reviewed release digest, unchanged instance and
storage identity, every preserved config digest/source/layer, exact agent
keys, and Home identity. `configure` writes only the two agent keys, so all
Home credentials and unrelated config must be prepared before its baseline.
