# Start a project

Status: Draft
Source: https://github.com/The-Focus-AI/standards/blob/main/handbook/project-setup.md
Relative links below resolve from handbook/project-setup.md.


Start in a reproducible cloud workspace. Read the project brief and existing
instructions before choosing tools or copying files. The baseline is input to
an agent, not a completed project and not an excuse to overwrite existing work.

## Choose what the project needs

Record the product, client boundary, runtime, package manager, deployment target,
required secrets, and checks. Use TypeScript and pnpm for new application work,
Clerk for sign-in, and Postgres for relational data unless an existing stack or
product requirement gives a reason to choose otherwise. Neon is the usual
Postgres host for Vercel apps. These are Focus defaults, not A2A protocol requirements.

Do not add a frontend framework, database, or Node application manifest to a
project that does not need one. Record consequential exceptions in its agent guide.

## Give an agent the brief

From this repository, emit a self-contained handoff:

```sh
scripts/setup-default-project.sh ../my-project --brief /path/to/brief.md --emit-prompt
```

This prints the brief, `setup-project` instructions, maintained baseline, and
skill restore helper. It creates no target files, installs nothing, and invokes
no agent. Keep secret values out of the brief. Use the output in the agent
session already doing the work.

To copy the baseline first:

```sh
scripts/setup-default-project.sh ../my-project --no-install
```

Existing files stay unchanged unless an operator explicitly requests `--force`.
The source is [templates/default-project](../templates/default-project/).
Generate the project-specific configuration from that baseline rather than
maintaining another template in prose.

## Adapt, then verify

1. Configure the [development tasks](development.md) for the actual stack.
2. Record [secret boundaries](secrets.md) before supplying credentials.
3. Restore the reviewed [skills](skills.md), preserving deliberate source choices.
4. Configure real CI and a [release record](release.md). Leave maturity unassessed
   until the project owner approves it.
5. Run install, lint, tests, and the production build/start path where applicable.
   Inspect the app in the cloud workspace, not through a service on somebody's laptop.

The copied lint, test, and deploy tasks deliberately fail until adapted.
Report missing application tests as a gap. Do not add unconditional-success
commands or fake tests to make the baseline green. Tool installation is not
proof of application behavior, external branch protection, or deployment.

For an existing repository, use [Update a project](update-project.md) instead.


---

# Update a project

Status: Draft
Source: https://github.com/The-Focus-AI/standards/blob/main/handbook/update-project.md
Relative links below resolve from handbook/update-project.md.


## Copy this prompt

```text
Update this repository using TheFocus.AI engineering handbook at https://standards.thefocus.ai (Markdown guide: https://standards.thefocus.ai/handbook/update-project.md; full Markdown bundle: https://standards.thefocus.ai/handbook.md; source repository: https://github.com/The-Focus-AI/standards).

Read https://standards.thefocus.ai/handbook/update-project.md and https://standards.thefocus.ai/handbook.md, and fetch https://github.com/The-Focus-AI/standards main safely to record the revision and compare templates/default-project/ and skills-lock.json. Inspect this repo's instructions, tooling, skills, secrets, auth, CI, and deployment against the relevant handbook Markdown pages (https://standards.thefocus.ai/handbook/<topic>.md). Ensure 1Password secrets use TheFocus.AI's company account (thefocusai.1password.com) and a dedicated project vault (<Client> - <Project> or <Client>), never a personal 1Password account (my.1password.com) or a Private/Personal/default vault. Treat Draft pages as recommendations unless this project adopted them. Preserve product behavior and documented exceptions.

Report concrete gaps, then implement the smallest safe fixes authorized by this request. Work in a reproducible cloud workspace. Run lint, tests, and relevant preview checks; report evidence and remaining decisions. Ask before changing credentials, production infrastructure, public contracts, or release policy. Do not ratify policy, merge, or deploy. Push or open PRs only when authorized.
```

## Audit before changing

1. Read the target's agent instructions, manifests, locks, tasks, and deployment
   configuration. Preserve existing work while fetching the handbook separately.
2. Read the published Markdown (`https://standards.thefocus.ai/handbook.md` or individual
   `.md` pages) alongside a fetched `main` revision from `The-Focus-AI/standards`, and
   record that commit SHA plus any explicitly included proposals. Do not treat an old
   local checkout or stale cache as the latest source.
3. Compare applicable topics: [development](development.md), [work](work.md),
   [secrets](secrets.md), [access](access.md), [sign-in](sign-in.md),
   [agent services](agent-services.md), [release](release.md), and [skills](skills.md).
4. Cite the file, command, or observation for each finding. Distinguish conforms,
   documented exception, adopted-policy gap, proposed improvement, and not applicable.
   An unknown is a verification gap, not success.

Do not replace a newer skill pin with an older default, discard project-specific
tasks, or require both same-name skill variants. Compare source, path, ref, and
content hash; the name alone does not identify the implementation.

## Fix and report

Group changes by independent risk. Keep credential provisioning, destructive
migrations, public-contract changes, and policy adoption behind their approval
boundaries. Use the maintained [baseline](../templates/default-project/) when
adding missing configuration, but adapt it to the actual application.

Record findings before editing; do not require a report-only PR unless the
project's workflow needs one. Follow [work and review](work.md) when delivering
issue-based work. Report commands/results, unknowns, and exact delivery state.
A local passing build is not a push, merge, deployment, or ratification.


---

# Develop in the cloud

Status: Draft
Source: https://github.com/The-Focus-AI/standards/blob/main/handbook/development.md
Relative links below resolve from handbook/development.md.


Use an Amp orb, Cursor cloud environment, or equivalent reproducible workspace.
A person's laptop is for review and personal authentication, not a required
database host or build server. Record genuine hardware or network exceptions
(such as native [macOS menu bar apps](../recipes/macos-menubar-app.md)) in the
project's agent instructions, with the supported verification path.

## Keep tooling in mise

Declare project runtimes and CLIs through `mise use`; pin the versions actually
tested. Do not depend on global npm, pip, or Homebrew installations. Use the
project's package manager and committed dependency lock. A failed frozen install
is an error to diagnose, not permission to retry without the lock.

```sh
mise trust
mise install
mise run install
```

Trust configuration only after reading it. Installation restores dependencies
and [locked skills](skills.md), not credentials or a person's login session.

## Give every repository the same entry points

| Task | Contract |
| --- | --- |
| `install` | Install from the reviewed lock and restore verified skills. Fail on incomplete restoration. |
| `dev` | Start the development workflow using repository-owned configuration. |
| `lint` | Run the actual static checks. Preserve their exit status. |
| `test` | Exercise observable behavior and fail on regression. An empty suite is not success. |
| `deploy` | Use the documented release path and explicit target, or fail with the non-deploying reason. A build is not a deployment. |

`mise run setup` is the one command that gets a checkout's secrets working, new
or existing: it makes sure a token that reads the project vault is in place and
checks that secrets resolve. Keep `secrets:check` for authorized resolution on its
own and `secrets:list` for declarations. Do not add a separate token-refresh task.
Keep credential/network checks out of offline lint and tests where feasible.

Inline mise shell tasks use POSIX `set -eu`. A task needing `pipefail` declares
a Bash shebang. Forward user arguments rather than silently dropping them.

## Commit workspace setup

Keep bootstrap, service definitions, required ports, and setup instructions in
the repository. Use the cloud platform's supervised service mechanism so
processes survive workspace lifecycle events. Publish the authenticated portal
or preview URL, not an inaccessible sandbox-local address.

Use the [default project configuration](../templates/default-project/) as the
starting point for agent instructions and CI. For pi, the maintained package
selection is [.pi/settings.json](../.pi/settings.json); do not copy a second
extension inventory into a guide. Keep sessions under ignored `.pi/sessions/`.

Check that a fresh workspace can install and run without your shell history,
personal authentication directory, or a token baked into its snapshot.


---

# Take work through review

Status: Draft
Source: https://github.com/The-Focus-AI/standards/blob/main/handbook/work.md
Relative links below resolve from handbook/work.md.


Use the repository's issue tracker. Record only tracker configuration and local
exceptions in its agent guide, not another copy of this workflow. GitHub Issues
is the default when available; local `docs/issues/` is an explicit fallback.

## Make the next action visible

| State | Meaning | Next transition |
| --- | --- | --- |
| No state label | Backlog; incomplete specification | A person or agent establishes readiness. Do not add a `backlog` label. |
| `ready` | Goal, background, acceptance criteria, verification plan, and non-goals are complete | Claim only if unassigned with no open dependencies. |
| `active` | One owner is implementing | Open a linked draft PR, or state the human decision that blocks progress. |
| `blocked` | Waiting on a person, access grant, or decision | Name who must do what before returning to ready. |
| `wontfix` | Deliberate decision not to do the work | Record why and what would reopen the decision, then close. |
| Closed | Implemented through the linked PR, or explicitly declined/duplicated | Keep the result and its reason traceable. |

An open issue has at most one state label. Record issue dependencies with native
blocking links, or a `Blocked by` section, not with the human-waiting label.
Specs and epics are planning items, not implementation work: use `type:spec`,
`type:epic`, or `wayfinder:map`, and link derived tickets to the spec.

Readiness is not permission to merge, deploy, spend, or change credentials.
A complete ticket with an unresolved product decision is not ready to implement.

## Claim before implementing

The eligible work is open, ready, unassigned, non-planning work with no open
blocker. Choose the issue worth doing now and say why; do not invent a priority
scoring scheme. Check existing issues before creating a duplicate.

1. Read the issue and every dependency again immediately before claiming.
2. Assign the owner, replace `ready` with `active`, and read back the result.
3. Yield if another owner holds the claim. Do not remove that owner's assignment.
4. If sessions share one tracker identity, use explicit session coordination.
   Sole assignment does not distinguish two sessions using the same account.

Comment on state changes with what happened and what happens next. One or two
sentences are enough. Never treat an unreadable dependency as a closed one.

## Open one reviewable change

Start from the current default branch. Name the branch `<issue-number>-<slug>`
and open one PR per implementation issue. If the work cannot fit, split the
issue before implementing. Use a closing reference such as `Closes #142`.

Put these sections in the PR description, in this order:

1. **Success criteria**: observable outcomes a reviewer can check.
2. **Why**: the problem and relevant constraints.
3. **What changed**: decisions worth reviewing, not a file-by-file diff summary.
4. **Evidence**: commands and results tied to each criterion; preview and images
   for visual changes, a short recording for interactions.

Keep the PR draft until ready. Distinguish a failure caused by the change from
a failure reproduced on the unchanged base. Neither permits ignoring a required
check. Reply when addressing review; do not force-push after human review.

## Keep approval independent

Do not approve and merge your own work. A person may grant bounded auto-merge
permission by applying `auto-merge` to the issue before implementation; required
checks still have to pass. Ticket readiness and product maturity do not imply
that permission. The [release gate](release.md) is a separate decision.

Merging the linked PR closes implemented work. A duplicate can be closed with a
link to the original and an explanation. A passing recovery notification alone
does not authorize closing the original issue.


---

# Handle secrets

Status: Draft
Source: https://github.com/The-Focus-AI/standards/blob/main/handbook/secrets.md
Relative links below resolve from handbook/secrets.md.


Use one dedicated project vault (`<Client> - <Project>` or `<Client>`) in
TheFocus.AI's company 1Password Business account (`thefocusai.1password.com`)
and a service account scoped to that vault. Never store project secrets,
service accounts, or bootstrap tokens in a personal 1Password account
(`my.1password.com`) or in built-in `Private`, `Personal`, `Employee`,
`Shared`, or `default` vaults.

The vault supplies development environments and previews; production values are
set where the deployment runs. `fnox.toml` declares references, not values. A
fnox profile selects values; it is not an access boundary or a deployment destination.

The vault, its service account, and the saved token belong to the company
account (`thefocusai.1password.com`). [Give and remove access](access.md) owns
who can reach them and what to rotate when that changes.

## Bootstrap without taking a person's identity

A person retrieves the project token through their individual seat in the
company 1Password account (`thefocusai.1password.com`, never a personal
`my.1password.com` account) and supplies `OP_SERVICE_ACCOUNT_TOKEN` through the
project's cloud secret settings. Do not request their password, Secret Key, or
login cache. Never save an injected token into a reusable image or snapshot.

Record the token item's location, recovery owner, scope, and receiving environments.
Recovery uses an authorized member's seat in `thefocusai.1password.com`. Save
the token in the project vault it unlocks, so one grant gives a developer both.

On a person's own machine, `mise run setup` fetches the token from
`thefocusai.1password.com` (`--account thefocusai.1password.com`) and writes it
to `.fnox/env`, a mode-600 ignored file. It refuses personal `my.1password.*`
accounts and built-in `Private`, `Personal`, `Employee`, `Shared`, or `default`
vaults, and is not a prerequisite for cloud injection. Setup checks that the
token actually reads the vault, not merely that one is present, and replaces
one that does not.

## Check before writing a credential file

Keep `.fnox/`, `.env`, `.env.*`, and project-specific credential files ignored.
Keep placeholder-only `.env.example` trackable. Preserve existing ignore rules.

For each intended path, run both checks before writing:

```sh
git check-ignore -q -- .fnox/env
git ls-files -- .fnox/env
```

The first must succeed; the second must print nothing. Repeat for every path,
not one representative. If a secret file is tracked, stop and report the path
without printing contents. Adding an ignore rule does not untrack or erase it.

## Separate runtime and administrative authority

Give the app only the credentials it needs. Bootstrap tokens, platform write
credentials, usage-report admin keys, and personal account sessions do not belong
in application profiles, model context, renderer HTML, command arguments, or logs.
Record an expiry and renewal owner for expiring credentials.

Sync from the project vault only to development and preview destinations. An
owner sets production values in the deployment platform directly, from the
provider that issued them; see [what stays out of the project vault](access.md#keep-production-out-of-the-project-vault).

Use a named sync target tying together project, destination, source profile,
credential environment names, and runtime-key allowlist. Dry-run first, apply
only with approval. Parse structured values; never split dotenv lines or pass
passwords through shell arguments. After an uncertain write, inspect remote
state before retrying. A multi-key sync is not an atomic transaction.

The [fnox procedure](../recipes/fnox.md) owns setup and the common sync behavior.
[Vercel](../recipes/vercel.md) and [GCP](../recipes/gcp.md) own destination details.

## Match production behavior in previews

Give previews the same integrations and configuration shape as production,
using the project vault's development and preview values. Separate vaults or
provider accounts for every environment are not the default requirement. Where
a preview can only work with a production value, record that exception in the
access map and use the narrowest role the provider offers.

Keep preview database writes off production. Isolate storage writes, webhooks,
and other harmful effects as needed. Record each configuration difference, its
reason, and what the preview cannot verify. This does not permit sharing OAuth
applications or credentials across clients; see [sign-in](sign-in.md).

After rotation, update every receiving environment, refresh affected processes,
verify actual access, then revoke old credentials. A presence check alone is
not evidence that a rotated token has the correct permissions.


---

# Give and remove access

Status: Draft
Source: https://github.com/The-Focus-AI/standards/blob/main/handbook/access.md
Relative links below resolve from handbook/access.md.


1Password exists to supply development environments: cloud workspaces, laptops,
and previews. Those credentials live in TheFocus.AI's company 1Password Business
account (`thefocusai.1password.com`), never in a person's personal account
(`my.1password.com`) or a personal vault. A person is granted access by joining
a group; a group is granted a vault. Nobody is added to a project vault by name.
Production values live where the deployment runs, not in a project vault.

[Handle secrets](secrets.md) owns how a credential is stored and delivered. This
page owns who may reach it, and what happens when that changes.

## Keep everything in the organization account

- Project vaults, their service accounts, and the saved bootstrap-token items all
  belong to the company account (`thefocusai.1password.com`). A personal account
  (`my.1password.com`) cannot have organization groups or shared recovery, so
  nothing stored there can be governed or recovered by a teammate.
- Name the company account in every interactive `op` command:
  `env -u OP_SERVICE_ACCOUNT_TOKEN op read --account thefocusai.1password.com ...`
  (do not combine `--account` or `OP_ACCOUNT` with `OP_SERVICE_ACCOUNT_TOKEN`).
  With both `thefocusai.1password.com` and `my.1password.com` signed in on a
  laptop, an unqualified `op` command silently uses whichever signed in last.
- An owner or administrator creates each service account. Members who are merely
  granted the create permission manage only their own service accounts [1], which
  leaves the organization dependent on that person.
- Save the bootstrap token as an item in its own project vault. One vault grant
  then gives a developer both the runtime values and the token, and removes both.
  A service account cannot be granted the built-in `Private`, `Personal`,
  `Employee`, or default `Shared` vault [2]; never keep project secrets there.

## Grant by client group

Create one group per client and one for internal work. Grant each project vault
to exactly one of them. This is the same boundary [sign-in](sign-in.md) draws for
OAuth applications: access to one client never implies access to another.

When a client serves clients of its own, the boundary is the end client. Give
each end client its own vault, service account, and group, and keep the
intermediary's own systems in a separate vault. A project that needs values from
two end clients is a sign that a shared value belongs in the intermediary's vault
or that the project should be split; do not widen one end client's vault to cover it.

Name each vault `<Client> - <Project>`, or just `<Client>` when the client has
one project. Each project has exactly one vault and one service account. Do not
create a vault per environment, and do not put the environment in an item name:
an item is titled with the variable it supplies.

| Role | Vault permission | Who |
| --- | --- | --- |
| Developer | View and copy | Members of the client group |
| Project owner | Edit and manage | One named person, plus the Owners group |
| Development environments | `read_items` | The project's service account |

Vault access is fixed when a service account is created and cannot be edited
later [1]. Changing what a project reads means issuing a new service account.

## Keep production out of the project vault

The project token is copied into every workspace that develops the project, so
it must not unlock anything that matters in production.

- The project vault holds development and preview values only. Where a provider
  offers separate development credentials, such as a Clerk development instance
  or a database branch, those are what the vault holds.
- An owner sets production values in the deployment platform. Access to them is
  a seat on that platform, recorded in the map.
- Administrative credentials, such as a database owner password or a migration
  role, do not belong in the project vault even when development needs the
  database. Give development a least-privilege role instead.
- Most production values can be re-issued by their provider and need no second
  copy. A value we generate ourselves and cannot re-issue without harm, such as a
  signing key or a push key, gets one recovery copy in an owner-only vault. No
  service account and no client group reads that vault.

When development and production must share one value, for example a single
shared database, record it in the map as an exception with the role's limits.
The value is then production-grade: rotate it when a developer leaves.

## Keep an access map

Keep one access map in a private repository. It records names and locations,
never values. Start from the [example map](../templates/access-map.example.md).

For each project it records the client group, vault, service account, where the
token item is saved, every environment that receives the token, where production
values live, each shared service the project uses, the owner, and the last
rotation date. For each person
it records their groups and their seat on each shared service.

The map is the checklist. A grant that is not in the map is drift: either record
it or remove it. Review the map against the providers' member lists on a schedule,
because nothing mechanical keeps a dashboard and a file in agreement.

## Separate human seats from machine credentials

On Vercel, Neon, Supabase, Clerk, GitHub, and cloud providers:

- A person signs in with their own seat on the organization's team, at the lowest
  role that lets them do the work. No shared logins and no personal tokens saved
  in a project vault.
- A machine credential is issued by the team or project, not from a person's own
  account, and is stored in the project vault. A key minted under a personal
  account stops working, or keeps working, when that person leaves.

## Add a person

1. Confirm which clients they work on. Invite them to the organization account
   and add them to those groups only.
2. For each project row in those groups, invite them to the listed shared
   services and repositories.
3. They run `mise run setup` in each project. A cloud workspace already has the
   token from its secret settings; on their own machine, setup fetches it from
   their seat in `thefocusai.1password.com`.
4. Record the person, their groups, and their seats in the map.

## Remove a person

Removing a grant stops future reads. It does not recall a value already copied:
a developer with view access could have read every item in the vault.

1. The same day, suspend the person in 1Password and remove every seat and
   repository grant in their rows of the map.
2. Rotate the bootstrap token of every project they could read, as below.
3. Rotate the underlying values marked rotate-on-departure in the map. That
   always includes any production-grade value the project vault held as a
   recorded exception. Other development values may wait for the scheduled
   rotation if the map says so. Production values set only in the deployment
   platform need rotation only if the person had a seat that could read them.
4. Find and re-issue anything that was created under their personal provider
   account.
5. Record the date and what was rotated. Delete the suspended account only after
   confirming no service account or item depends on it.

Moving a person off one client is the same procedure limited to that group.

## Rotate a service-account token

Rotation in the 1Password web interface issues a new token with the same vault
access and lets the old token expire immediately or after a short overlap [1].
Use the overlap for scheduled rotation and immediate expiry after a departure
or suspected exposure.

1. Rotate the token and save the new value over the token item in the vault.
2. Update every cloud secret setting listed in the map, and refresh the
   processes that hold the old value. Developers run `mise run setup` on their
   own machines; it replaces a token that no longer works.
3. Verify real access with `mise run secrets:check`; presence is not proof.
4. Confirm the old token has expired, then record the date in the map.

Changing which vaults a service account can read is not a rotation. Create a new
service account, deliver its token the same way, then revoke the old one.

## Sources and limits

Checked against 1Password's developer documentation on 2026-11-14. No rotation
was performed while writing this page. The documentation does not say what
happens to a service account when its creator is removed; verify that on a
disposable service account before relying on step 5 of removal.

[1] 1Password, *Manage service accounts*, `1password.dev/service-accounts/manage-service-accounts/`.

[2] 1Password, *Get started with service accounts*, `1password.dev/service-accounts/get-started/`.


---

# Isolate client sign-in

Status: Draft
Source: https://github.com/The-Focus-AI/standards/blob/main/handbook/sign-in.md
Relative links below resolve from handbook/sign-in.md.


Use a separate Clerk application for each client. Organizations and satellite
domains share a user pool; they do not replace this boundary.

Give each client its own Google OAuth application and Microsoft registration,
including client IDs and secrets, in every environment. Clerk's shared
development credentials do not satisfy that policy. One client's credentials
may serve its development, preview, and production environments where callback
support and permissions allow. Another client's credentials may not.

## Configure production deliberately

- Use a Clerk production instance for production and the client's own subdomain,
  not the organization's bare root domain.
- Leave Clerk DNS records unproxied so verification can complete.
- Configure Google publishing and Microsoft tenant support for the intended
  users. External client organizations need the appropriate multitenant registration.
- Record OAuth secret expiry and a renewal owner.
- Restrict signup and provision application permissions according to the client's
  access policy. A successful login alone does not grant specialist entitlement.

The [Clerk procedure](../recipes/clerk.md) includes the publishable-key diagnostic,
provider setup, and callback checks. Preview configuration follows the same
[parity and data-protection rules](secrets.md#match-production-behavior-in-previews).

## Treat OAuth clients as a different direction

When our product accesses a third-party or MCP authorization server, it is an
OAuth client rather than the sign-in provider. Use existing pre-registered
information first. Where supported, use Client ID Metadata Documents for new
registration; retain DCR only as a version-specific compatibility path.

The product owns its HTTPS client-identity URL on an organization-controlled
domain, with a path component and an exactly matching `client_id`. Keep it
reachable while granted consents remain live. Do not centralize every product's
client identity behind one unrelated registry site's deployment.

Store registration credentials keyed by the issuing authorization server and
do not reuse them across issuers. Refresh protocol-version claims against the
[MCP authorization specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization)
when implementing. OAuth registration is not native Clerk machine provisioning.

For backend-to-backend requests, select a [service access profile](service-access.md).
Do not put browser-session middleware in front of a machine-only API and assume
that a route-level bearer verifier can still run.


---

# Authorize service calls

Status: Draft
Source: https://github.com/The-Focus-AI/standards/blob/main/handbook/service-access.md
Relative links below resolve from handbook/service-access.md.


Browser sessions, native Clerk machine JWTs, OAuth access tokens, and administrative
API keys are not interchangeable. Enforce the declared profile across middleware
and the handler. Passing an exact machine method/path to its strict verifier is
not permission to exempt every API route. Browser pages retain session protection.

## Record the receiver contract

Name the issuer, verification keys or introspection, token class, permitted algorithms,
receiver audience, sender claim and allowlist, permissions, lifetime, and required
protected-header/payload claims. Missing configuration fails closed. A signature
from a trusted issuer alone is insufficient to distinguish token classes.

Choose authorization separately from authentication:

| Profile | Owner boundary | What it does not establish |
| --- | --- | --- |
| Machine-only service | Explicitly approved nonhuman workload, sender, receiver, and service permission | No per-human segregation or delegated user rights. Not the Workbench specialist profile. |
| Machine plus human | Independently verified human grant bound to the sender, then local entitlement | Signatures alone do not grant entitlement or operator authority. |
| Temporary demo | Separately approved exact credential, shared-demo owner, original expiry | No fallback after JWT/grant failure and no administrator rights. |

Check ownership on context, task, history, feedback, and interactive-view access.
Return the same not-found behavior for another owner's data as for missing data.
A changed identity mapping requires an entitlement and stored-owner migration.

## Require human delegation for Workbench specialists

Every Workbench invocation of an external specialist, including Specialist A and
Specialist B, carries both verified service identity and a signed, target-bound human
delegation grant. Public card discovery is not an invocation. This is the
owner-selected Workbench integration policy, not an A2A or MCP protocol rule.
Specialist B's revised receiver is under implementation; this policy is not a claim
that it has shipped. See the [dated evidence](../evidence/workbench-integration.md).

Derive the human subject from the verified server session. Verify the grant's
signature, trusted issuer, receiver audience, subject and lifetime independently
of the service credential. For the native Clerk profile, require
`human.azp === machine.sub`, using the actual verified machine token's `sub`,
not a registry alias or an unverified configured identity. A grant for one target
cannot authorize another specialist.

The receiver independently decides that human's entitlement under the verified
sender. It can refuse a correctly signed request. Missing, invalid, expired,
wrong-target or sender-mismatched grants fail without a shared-service or demo
downgrade. Workbench membership and coordinator authority do not enroll a user
or grant operator privileges. Machine-only access remains valid for explicitly
approved nonhuman workloads outside this integration, never as its fallback.

For the same user, sender and target, direct Workbench relay and coordinator-routed
calls preserve the same verified `(machine.sub, human.sub)` principal. Routing
can change task provenance, not signed authority. Task ids, parent-agent names,
context ids and recap text are attribution or input, not credentials. See
[conversation checks](conversations.md#verify-the-configured-paths).

## Bind credentials to the approved destination

Resolve the destination from trusted registry configuration, not a URL supplied
by the browser, model, or renderer. Before attaching credentials, check the
current target, identity binding, and policy revision. Keep service credentials
and human grants server-side.

Reject credential-bearing redirects rather than forwarding either credential
to the redirect target. A target change requires fresh policy resolution and
credentials bound to the approved destination, not reuse of the previous
request's headers. This applies to A2A dispatch and MCP tool or protected-resource
calls. Trusting a renderer does not waive destination checks.

## Issue native Clerk tokens without inventing an OAuth flow

The [Clerk API definition](https://github.com/clerk/openapi-specs/blob/94753d1d8a648806e4dc529beec8bb76daa13859/bapi/2026-08-20.yml)
requires a **machine secret** for
`POST https://api.clerk.com/v1/m2m_tokens`. The Workbench implementation sends
this JSON body and reads the response's `token` property:

```json
{
  "token_format": "jwt",
  "seconds_until_expiration": 300,
  "claims": { "scope": "bls:invoke" }
}
```

Use the profile's permission, such as `specialist:read`, rather than copying
`bls:invoke` to every service. Issue from the backend with a scoped machine
secret, not a Clerk administrative secret and not a browser-held credential.
This endpoint is not `/oauth/token`; its response is not `access_token`.

Clerk's configured **machine scopes** select allowed receiver machines. In the
recorded issuance experiment, those scopes produced JWT `aud`; setting custom
`claims.aud` did not. The custom `scope` string is an additional application
permission checked by the receiver. Inspect an actual issued token's verified
claims without logging the token before accepting a configuration.

The [inspected Workbench registry](../evidence/workbench-integration.md#service-profile-evidence)
supports both native `clerk-m2m` and a
separate OAuth `client-credentials` mechanism. A Client ID Metadata Document is
an OAuth client registration mechanism, not native Clerk machine provisioning.
The MCP registration order starts with existing pre-registered information,
then supported metadata documents, then the deprecated DCR compatibility path
([client sign-in and OAuth](sign-in.md)).

## Credential and authorization transitions

These tables describe this integration, not every possible authentication flow.
The caller owns issuance and caching; the provider owns verification, entitlement
and data ownership. Use the [state-machine index](agent-services.md#find-the-integration-state-machine)
for the adjacent registry, task, view, and release lifecycles. Desired guarantees
beyond these observations need a separate implementation and acceptance test.
Clerk's category, clock skew and grant lifetime caps are application-profile
details, not A2A or MCP mandates.

### Browser session

The session establishes who may request a new human grant, not whether a
specialist will authorize that human.

| Transition | Trigger, guard, owner and effect | Failure or recovery |
| --- | --- | --- |
| Signed out to signed in | Clerk sign-in establishes the session; Workbench derives the human subject from its verified server session | No session means no new delegated grant. Reauthenticate in the browser; never substitute request metadata or a machine subject. |
| Signed in to signed out | Logout or expiry ends the session used to issue new grants | Logout does not revoke an already signed grant. Its expiry and provider checks still govern acceptance. |

### Machine credential and token

Provisioning, the caller's cache, and the receiver's verification are separate
states. A cached token does not mean that the receiver accepted a request.

| Transition | Trigger, guard, owner and effect | Failure or recovery |
| --- | --- | --- |
| Unprovisioned to configured | Approved operator provisions sender and receiver, delivers a scoped secret, and records issuer, audience, sender, permission, TTL and credential reference | Stop on missing resources or access. Administrative credentials do not substitute for application credentials. [Preview parity](secrets.md#match-production-behavior-in-previews) still applies. |
| Empty or near-expiry cache to minting | Workbench `bearerFor` requests a new token when none is usable or it is within 30 seconds of expiry | Mint errors stop dispatch, with no old-token fallback. Repair issuance before a new attempt. |
| Minting to cached | Successful native mint returns `token` for the requested 300-second lifetime; Workbench caches it server-side by auth configuration | Changing the machine secret changes the cache key. Multiple processes have separate caches; a cached token still needs receiver verification. |
| Presented to verified or denied | Specialist checks the declared token class, signature, issuer, audience, sender, time and permission before constructing the machine principal | Invalid credentials, JWKS failures and missing configuration fail closed. Missing permission denies access. Workbench implements no automatic unauthorized retry or switch to another credential class. |

### Human delegation and entitlement

Each new request needs both credentials and the receiver's current authorization
decision. This is the selected Workbench policy; the inspected Specialist A behavior
below is not proof that Specialist B or every dispatch path already implements it.

| Transition | Trigger, guard, owner and effect | Failure or recovery |
| --- | --- | --- |
| Verified session to signed grant | Workbench signs a 300-second grant for the current human, pinned target and sender | A new grant requires a valid session and current target policy. No machine-only or demo fallback. |
| Paired credentials to bound principal | Receiver verifies the grant independently, then requires `human.azp === machine.sub`. Specialist A checks issuer, audience, signature and timestamps, with a 600-second maximum grant lifetime | Missing, invalid, expired, wrong-target or sender-mismatched grants fail before execution. A configured sender alias cannot replace the verified token subject. |
| Bound principal to authorized or denied | Specialist A finds the exact sender/human entitlement row and scopes task, context, history and feedback to its owner | Valid signatures without entitlement yield 403. No shadow user, automatic enrollment or operator privilege. Specialist B's revised acceptance remains pending. |
| Previously authorized to denied on a later check | Provider removes entitlement, policy disables the connection, or credentials expire | Deny the next applicable check. Removal is not known to stop in-flight work. Correct the cause through the owning operator, not by replaying under another identity. |

### Rotation and revocation limits

The issuer, Workbench operator, and provider own different controls. Secret
rotation changes future minting; it does not revoke all issued tokens. Clerk
JWTs are offline-verified and not individually revocable through its opaque-token
revocation API. Scope changes affect newly minted tokens. Immediate invalidation,
key overlap, and in-flight cancellation need a separately tested design.

Specialist A's native verifier requires `RS256`, the protected M2M category, a machine
`sub`, audience, application scope, and a maximum machine age and lifetime of
300 seconds. Its grant verifier accepts configured RSA or EC keys. Do not infer
that it enforces Specialist B's proposed `typ` check: the profiles and implementations
are distinct. When changing an issuer or identity claim, plan the entitlement
and stored-owner migration before switching the verifier.

The [ID-JAG draft](https://datatracker.ietf.org/doc/draft-ietf-oauth-identity-assertion-authz-grant/)
describes token exchange and redemption for an access
token. It does not describe Workbench's independently signed
`X-<Client>-Identity-Grant` header. Adoption would be a separate profile change.

## Preserve bounded demo access during cutover

The machine-auth cutover broke an original demo token that had not expired.
The recovery kept `AUTH_MODE=clerk-m2m` and added explicit coexistence instead
of weakening JWT verification. It also removed global operator access from that
legacy path: restoring the old privilege would expose other owners' analytics.
This recorded standalone demo path is not a Workbench connection profile. The
mandatory delegation policy does not select it or revoke it by implication.

| Transition | Guard, owner and effect | Recovery and approval boundary |
| --- | --- | --- |
| Disabled to coexistence enabled | Provider operator explicitly enables the approved legacy path; the primary machine profile remains active | Enabling coexistence is a separately approved access change, not an automatic rollback. |
| Eligible request to shared-demo access | Verifier requires `LEGACY_DEMO_ENABLED=true`, no identity-grant header, no JWT separator, exact SHA-256 digest match, and time before recorded expiry | The matching request owns only `shared-demo` data and has `operator=false`. Any failed guard stays on the strict path or is denied. |
| Invalid primary request to denied | Primary verifier rejects a wrong JWT, wrong grant or missing entitlement without selecting demo | Never catch a primary-profile failure and try the demo credential. |
| Enabled to expired | At the original cutoff, `2026-11-19T23:59:59Z`, the verifier denies demo access | Retirement owner removes the opt-in after checking outstanding users. This proposal does not extend that date or authorize deletion of saved history. |

## Agent and operator acceptance checks

Before changing code, write the profile and current state from evidence. Inspect
middleware, handler, issuance, registry and persistence together. Use fixtures
for negative tests, then an approved credential for a real route check. Keep
tokens and private keys out of logs, command arguments, renderer HTML and reports.
Agents can prepare code, tests and a provisioning plan in the cloud workspace;
operators approve production machines, grants, entitlements and cutover.

| Case | Observable acceptance criterion |
| --- | --- |
| Credential confusion | A trusted-issuer session/template JWT, OAuth token, administrative secret and opaque token each fail a native-M2M-only route. Wrong issuer, audience, category, sender, scope, expiry and overlong lifetime also fail. |
| Mandatory grant | Every Workbench external-specialist path rejects missing, invalid, expired and wrong-target human grants, even with a valid machine token. No model or tool execution, shared-service downgrade or demo retry follows. |
| Delegation binding | A valid machine A plus a valid grant bound to machine B fails. Test the actual token `sub` differing from a configured sender alias. Removing the exact entitlement denies the next request. |
| Direct and routed identity | For the same user, sender and target, direct relay and coordinator-routed calls resolve to the same verified principal and entitlement outcome. A second human remains distinct. |
| Provenance is not authority | Changing task, context, parent-agent or claimed-user metadata cannot change the verified principal, bypass a denied entitlement or replace a missing grant. |
| Credential destination | A credential-bearing A2A or MCP endpoint returns a redirect to a second test server. The caller rejects it and the second server receives neither credential. A changed registry target also rejects the old binding before dispatch; a browser-supplied replacement URL cannot override it. |
| Route boundary | Correct credentials reach a well-formed A2A response; no-token calls get the selected API auth error, not HTML. Session-protected pages and neighboring routes retain protection. |
| Delegated owner isolation | For delegated/per-human profiles such as Specialist A's sender/human pair, two humans under one machine and one human under two machines cannot read each other's context, task, history or feedback. Test the same context id under both owners. |
| Approved nonhuman workload | Outside Workbench specialist connections, a separately approved machine-only profile checks its service boundary without claiming per-human segregation. Its existence cannot enable a downgrade on a delegated route. |
| Cache and expiry | Test immediately before and at the refresh threshold and token expiry with a controlled clock. An issuance failure and an unauthorized response cause no second invocation. |
| Demo coexistence | The exact token works only before its unchanged expiry and without a grant. One changed byte, a JWT-shaped token, a grant-bearing request and an expired token never enter demo. Demo cannot use operator analytics. |


---

# Build an agent service

Status: Draft
Source: https://github.com/The-Focus-AI/standards/blob/main/handbook/agent-services.md
Relative links below resolve from handbook/agent-services.md.


A2A carries conversations. MCP exposes tools, resources, and interactive Apps.
Neither protocol decides who can access a client's data, which database to use,
or who may approve a release. Record the adopted protocol version, local
application profile, and policy choices separately.

## Find the integration state machine

These nine state machines describe the Workbench integration with external
specialists. They are separate lifecycles, not one shared status. A discovered
card can coexist with a denied invocation; a disconnected stream can coexist
with a running task. The linked tables own the transitions, guards, effects,
failures, and recovery rules. State labels describe behavior, not necessarily
literal database values or SDK enums.

| State machine | Who controls it | Question the transition table answers |
| --- | --- | --- |
| [Discovery and readiness](conversations.md#discovery-is-not-invocation-readiness) | Host card fetcher and acceptance runner | Did discovery succeed, or did an authenticated invocation pass? |
| [Registry and dispatch](conversations.md#registry-policy-and-dispatch) | Operator, policy store, and dispatcher | Does the current revision still permit this target and identity? |
| [Browser session](service-access.md#browser-session) | Clerk and host backend | Can the host establish a human for a new grant? |
| [Machine credential and token](service-access.md#machine-credential-and-token) | Operator, issuer, caller cache, and receiver | Can the caller mint a token, and does the receiver accept it? |
| [Human delegation and entitlement](service-access.md#human-delegation-and-entitlement) | Grant issuer and receiving specialist | Is the human bound to this sender and allowed this operation? |
| [Bounded demo access](service-access.md#preserve-bounded-demo-access-during-cutover) | Provider operator and verifier | Does the separate, approved demo path still permit access? |
| [A2A task and transport](conversations.md#conversations-tasks-and-transport) | Provider task store and caller recovery code | Is the task finished, paused, or merely no longer observable? |
| [MCP view and snapshot](mcp-apps.md#view-transitions) | Host bridge, view store, and provider | Does the action restore a snapshot, call a tool, or update future-turn context? |
| [Cutover and recovery](release.md#integration-cutover-and-recovery) | Release owner and approved operator | Can this code, schema, and identity configuration receive traffic or roll back? |

## Read transitions without inventing guarantees

A transition needs an event, a guard that permits it, and an owner that applies
its effects. A failed guard follows the stated failure path, not a weaker
authorization profile. Recovery can be a supported read, reauthentication,
configuration repair, or an operator decision; it is not automatically a retry.

Keep each statement's basis explicit:

- Protocol requirements apply to the named version and supported operations.
- Inspected behavior is bounded to the revisions in the [source record](../evidence/workbench-integration.md),
  not a claim about today's deployment.
- Selected policy states what this integration requires, including a human grant
  on every Workbench specialist call. Implementation acceptance remains separate.
- Proposed gates, such as live-probe enablement, are not implemented guarantees
  or release approval.

Before changing a transition, name its guard and failure outcome in the change
description. Exercise both an allowed transition and a rejected one using the
owning page's acceptance checks. Record unsupported recovery operations and
unverified deployment behavior instead of marking them passed. These tables are
an operational description, not an exhaustive protocol model or a formal proof.

## Put responsibility on the owning service

A specialist owns its model loop, guardrails, data, and persisted state. The host
owns its registry, dispatch policy, and host-user session. They communicate
through authenticated interfaces, not imports of another service's code or
queries against its database.

Workbench uses registry-derived specialist calls and keeps credentials on the
server. Its resident agent also uses the A2A relay; its repository forbids a
private chat route. That is Workbench's application architecture, not an A2A
requirement on every vendor.

## Use one definition through the adapters

| Concern | Focus default | Verification |
| --- | --- | --- |
| Tool shape | A name, description, input schema, and execution handler in one `ToolSpec` | Validate public inputs at the boundary. |
| Tool catalog | Derive model and MCP tool exposure from that definition | No divergent second schema or handler. |
| Refusal | Structured result with a stable reason, not an ambiguous successful string | Tests distinguish denial from empty data and execution failure. |
| Citation | Structured provenance tied to the returned result | Source identifiers survive every adapter. |
| System prompt | One canonical prompt; generate or compare any runtime mirror | A changed prompt cannot leave the runtime on stale instructions. |
| Persistence | Postgres task/session state with verified-owner scoping | Restart, missing configuration, failed writes, and cross-owner reads are tested. |
| Model entry point | One `runAgent` used by conversational adapters | An MCP rendering action does not implicitly invoke the model. |

The client's onboarding packet
defines its own refusal/citation Parts and extensions. Use those types when
adopting that contract; do not claim they are universal A2A fields. A vendor's
framework, model, database, and cloud remain implementation choices.

## Persist at the selected owner boundary

Derive the owner from verified identities, not request metadata. Workbench
external specialists use the [required human-delegation profile](service-access.md#require-human-delegation-for-workbench-specialists),
including on coordinator-routed calls. The receiver authorizes the sender and
human independently of task provenance. A machine-only profile is an option
for explicitly approved nonhuman workloads outside that integration; it scopes
data to the authorized service and does not segregate humans.
Check context/task ownership on every operation. Do not rely on an SDK's
default anonymous owner to isolate callers.

Await required writes before terminal success, or use an explicitly supported
durable completion mechanism. Do not silently fire and forget persistence.
Production fails closed without its database; in-memory state is an explicit
mock mode. Apply migrations before traffic shifts, not on application boot.

## Implement only the contract you advertise

Publish a card whose interfaces, versions, streaming, security, and extensions
match the actual endpoint. A native Clerk bearer profile must not advertise an
invented OAuth token endpoint. Use one handler for supported dialects, and make
unsupported operations explicit rather than retrying through another dialect.

The [server recipe](../recipes/a2a-server.md) gives the versioned layout and event
ordering. Test task-before-update and artifact-before-terminal ordering only
on task-producing paths; a standalone Message need not create a task.

The [component lifecycle evidence](../evidence/component-lifecycle.md) covers
local resource ownership behind these interfaces. It is not a protocol contract.


---

# Run an agent conversation

Status: Draft
Source: https://github.com/The-Focus-AI/standards/blob/main/handbook/conversations.md
Relative links below resolve from handbook/conversations.md.


A public card is discovery, not proof of authenticated invocation. Record the
configured protocol dialect and the operations both caller and provider support.
The implementation examples below were inspected on 2026-11-07; they do not
establish live acceptance. [Source record](../evidence/workbench-integration.md).
Use the [state-machine index](agent-services.md#find-the-integration-state-machine)
to find the credential, view, and release lifecycles that surround a conversation.

## Discovery is not invocation readiness

Track card freshness, configuration enablement, and invocation evidence
separately. None is a substitute for the others. The acceptance states below
are a proposed way to record readiness, not an implemented enablement gate.

| Transition | Guard, owner and recorded effect | Failure or recovery |
| --- | --- | --- |
| Unknown or expired card to discovered | Workbench fetches and parses the public AgentCard. Cache uses `max-age` minus `Age`, capped at 300 seconds; no freshness permission means no cache | Expiry evicts the old entry. Fetch/parse errors are discovery failures, not failed token validation or permission revocation. |
| Configuration disabled to enabled | Operator provides credentials and the selected policy; managed enablement checks configuration blockers | A green discovery dot and an enabled record still do not prove an authenticated operation. Specialist B's public card succeeded while invocation was blocked. |
| Enabled to invocation-verified, proposed acceptance gate | Approved harness exercises positive and negative calls through the deployed route; record target, code, policy, profile, operation, timestamp and result | Changed target/profile/revision invalidates that evidence. Readiness lifetime and whether the UI toggle blocks on a probe remain design decisions; current enablement has no live-probe gate. |
| Verified to failed or unverified acceptance | A new acceptance call fails, or the recorded target/profile/revision changes | Keep the card and configuration results separate. Repair the failing path and run new acceptance checks; do not reuse the old success as proof. |

## Registry policy and dispatch

At Workbench `c302e20`, these revision controls apply to entries opting into
`identityPolicy: "admin"`; other registry configurations do not acquire those
controls implicitly. `WORKBENCH_AGENTS` replaces the whole fleet, not one row.

| Transition | Guard, owner and recorded effect | Failure or recovery |
| --- | --- | --- |
| Absent or disabled to enabled | Authorized operator saves expected revision with valid configuration; `savePolicy` increments revision and commits policy plus audit together | Compare-and-swap conflict returns 409; reload and reassess instead of overwriting. A failed transaction saves neither policy nor audit. |
| Enabled to suppressed | `resolvePolicy` sees missing/disabled policy, blockers or mismatched target binding | New resolution returns no managed agent. Restore configuration and explicitly save/review a new policy; no legacy fallback. |
| Resolved to dispatched | `agentHeaders` re-resolves the managed entry and checks revision, URL and identity before minting headers | Changed or disabled policy blocks this dispatch. It does not cancel an already dispatched call. |
| Configuration changed | Binding includes slug, JSON-RPC URL, dialect, machine identity/scope and signer identity; OAuth binding also includes token URL | Machine secret is not in this policy binding, although token cache keys include auth configuration. Rotation is not equivalent to policy revision or immediate revocation. |

The selected [Workbench delegation policy](service-access.md#require-human-delegation-for-workbench-specialists)
requires both credentials on every external-specialist dispatch, beyond these
inspected registry controls. Direct relay and coordinator-routed requests to
the same specialist retain the same verified sender and human. A coordinator
task or parent-agent label records provenance; it cannot replace the human
grant, change its subject or supply entitlement. Reject missing delegation
before dispatch and at the receiver. Existing fixture results do not establish
that every path already enforces this policy.

The dispatcher also owns [credential destination checks](service-access.md#bind-credentials-to-the-approved-destination).
A redirect or changed target is not permission to forward the minted headers.

## Conversations, tasks and transport

These A2A v1.0 concepts are protocol-defined. The caller's recovery support and
the provider's stored history are separate implementation facts. Full normative
wire details remain in the [A2A specification](https://a2a-protocol.org/v1.0.0/specification/).

### Task state belongs to the provider

Active tasks are submitted or working. Input-required and auth-required tasks
are interrupted, not terminal. Completed, failed, rejected, and canceled tasks
are terminal. A standalone Message has no task lifecycle.

| Transition | Guard, owner and effect | Failure or recovery |
| --- | --- | --- |
| New turn to Message or new Task | Caller creates a fresh message id; server can return a standalone Message or create its own task id | An accepted Message need not create a task. A client-supplied context is used only by prior agreement; otherwise retain the server-issued context. |
| Active to terminal | Provider publishes applicable task progress and artifacts, then a completed, failed, rejected or canceled state | Persist results under the verified owner. Transient stream events are not a reliable durable record. Not every task must pass through every active state. |
| Working to input-required or auth-required | Provider pauses for input or authorization; an authorized continuation addresses the unfinished task | Interrupted is not terminal. Resume only through implemented operations; never interpret this state as permission to bypass auth. |
| Interrupted to working | Required input or authorization arrives through a supported continuation; provider resumes the unfinished task. Negotiated out-of-band authorization can permit resumption without another message | If either side lacks continuation support, report that limit. A new send is not an automatic recovery path. |
| Terminal task remains terminal; next turn starts separately | Caller sends a new message id and no terminal task id; server starts a new task or Message. Input history follows the configured profile described below | Terminal tasks do not restart. Workbench retains a child context per conversation/specialist; provider checks the selected profile's ownership boundary even if another caller reuses the id. |
| Cancellation requested to confirmed or refused | Caller invokes supported cancellation; server acknowledges its actual outcome | A local Stop button is not remote cancellation. A terminal or noncancelable task can refuse; unsupported operations stay explicit. |

### Transport state belongs to the caller

Attached, disconnected with unknown outcome, and recovered observation describe
what the caller knows. A broken connection does not change the provider's task
to failed, canceled, or input-required.

| Transition | Guard, owner and effect | Failure or recovery |
| --- | --- | --- |
| Attached to observed pause or terminal result | Provider reports an interrupted or terminal state; caller records it even if the stream then closes | An observed input-required or auth-required state is a known pause, not an unknown transport failure. Follow its supported continuation path. |
| Attached stream to disconnected/unknown | Client loses transport without observing an interrupted or terminal result | Preserve task/context ids. Poll `GetTask` or subscribe only when implemented; an abort does not establish cancellation. Do not resend the question to discover the result. |
| Known task to recovered observation | Authorized caller reads a persisted task snapshot when both caller and provider support that operation | Specialist A supports polling, rejects live resubscription and has no successful cancellation path at the inspected revision. Workbench `askSpecialist` rejects a noncompleted SDK task with “do not repeat the request” and has no polling/resume loop. Its direct transport's `reconnectToStream` returns `null`. |
| Unknown outcome remains unresolved | No supported read/resume path exists, or its result is unavailable | Caller reports uncertainty with known ids for operator reconciliation. Lack of observation does not authorize replay or prove cancellation. |

### A new turn is not a task retry

Workbench `c302e20` has distinct input-history paths. Its direct
`A2AChatTransport` sends only the latest user text for configured `v1` and
`a2a-0.3` dialects. For the legacy specialist-specific dialect, `composeOutboundText` instead sends a
`<conversation-so-far>` recap followed by the current question. The recap contains
up to eight prior user/assistant text turns, capped at 1,500 characters each.
This is an explicit compatibility path for the stateless legacy receiver, not
A2A history persistence. The transport sends no `taskId` and uses the supplied
new-turn `messageId` or generates a UUID. The server-side `askSpecialist` client
forwards its supplied question without calling this recap composer. Keep these
paths distinct in tests; a shared `contextId` does not give them identical history.

A2A makes `GetTask` idempotent but only permits, rather than guarantees, send
deduplication by message id. No general exactly-once, automatic resume, lost-event
replay or cancellation guarantee follows from using the SDK.

## Verify the configured paths

Confirm the unauthenticated call returns an auth failure, not just a malformed
JSON-RPC error. Then run the service's authenticated integration harness with
the service identity and human grant required by its selected profile. For
Workbench external specialists both are mandatory on direct and routed paths. Keep
credentials in the secret store/environment, not command arguments or logs.
Record the configured dialect and the operations advertised and supported by
both caller and provider. Exercise blocking calls, streaming, same-context
follow-ups and post-completion `GetTask` only for supported paths. Test each
dialect the integration configures; do not assume both v1 and v0.3 are supported.
For unsupported operations or dialects, record an explicit unsupported outcome,
not a successful check or an implicit retry through another path. Test owner
isolation under the selected authorization profile. See the packet's
acceptance checklist.

| Case | Observable acceptance criterion |
| --- | --- |
| Discovery without access | Valid public card plus missing/invalid invocation credentials never reports invocation-verified. |
| Registry race | Two saves at one revision produce one success and one conflict; policy/audit stay atomic. Disable or target rebind prevents the next managed dispatch. |
| Delegated dispatch | Direct and coordinator-routed Workbench calls carry a target-bound grant for the same human, bound to the actual machine `sub`. Missing or mismatched grants and denied human entitlements stop execution on both paths. Altering task provenance cannot change this result. |
| Next-turn identity | New turns use distinct message ids, retain the authorized context where supported and never address a completed task id. New Task results have distinct task ids; standalone Messages need not create tasks. Test isolation at the selected profile's owner boundary. |
| SDK-profile input | Workbench's direct `v1`/`a2a-0.3` transport sends only the latest user text. The server-side specialist client forwards the supplied question without adding a recap. |
| Legacy Specialist B direct input | A follow-up contains the current question plus the delimited, capped recap described above. It does not reopen a completed task or establish server-side history. Keep this compatibility assertion separate from the SDK-profile test. |
| Known pause | Observe input-required or auth-required before the stream closes. Retain that task state; continue only through supported operations, without reporting unknown failure or bypassing auth. |
| Interrupted send | Drop the stream after task acceptance. Recover by a supported read or report the missing client capability; no duplicate send or false cancellation success. |

Credential tests live in [Service access](service-access.md); view checks in
[MCP Apps](mcp-apps.md). Plan cutover and rollback under [Release](release.md).


---

# Host interactive agent views

Status: Draft
Source: https://github.com/The-Focus-AI/standards/blob/main/handbook/mcp-apps.md
Relative links below resolve from handbook/mcp-apps.md.



A2A owns the conversation. A provider can additionally publish MCP tools and
resources for interactive results. The provider owns its domain data and renderer;
the host owns authorization and placement. A pure-A2A agent needs no MCP route.

The inspected Workbench pins MCP Apps **2026-01-26**, ext-apps **2.0.4** and MCP
client/core/server **2.4.0**. Apps extension version, base MCP transport version,
SDK version and A2A dialect are distinct. Record them separately and use the
selected SDK's Streamable HTTP transport. Do not rename legacy `text/html+mcp`
tiles to Apps resources or assume the legacy renderer implements this handshake.

## Protocol and application boundaries

| Contract | What it defines |
| --- | --- |
| Stable MCP Apps | `io.modelcontextprotocol/ui`, tool `_meta.ui.resourceUri`, `ui://` resource discovery with `resources/read`, MIME `text/html;profile=mcp-app`, app visibility and initialization messages |
| Workbench A2A association | `urn:<client>:workbench:mcp-apps:1` advertises a same-origin MCP endpoint; `application/vnd.<client>.mcp-app+json` associates a saved answer with `viewId`, tool, arguments, resource and result |
| Workbench permissions | Same owning provider/resource, app-visible tools, `readOnlyHint: true`; no mutating tools, sampling, conversational `ui/message`, arbitrary resources or external-link handler |
| Workbench persistence | Current arguments, result, revision and selected text context in `mcp_app_views`; original answer remains unchanged |

No official A2A-to-Apps association was found in the inspected upstream specs.
The two client-namespaced identifiers are local contracts, not standards-defined names.
Generic MCP hosts discover the UI resource from the provider tool without that
A2A association. Read-only hints describe tools; they do not enforce data access.

The host resolves associations from the signed-in user's stored transcript,
checking provider origin and machine-client binding. It does not accept a
browser-supplied endpoint, HTML document or substitute result. Historical answers
without an acceptable binding stay readable but cannot invoke an app.
Apply the same [credential destination checks](service-access.md#bind-credentials-to-the-approved-destination)
to MCP requests; a trusted starting endpoint does not authorize redirecting its
credentials elsewhere.

Under the selected [Workbench delegation policy](service-access.md#require-human-delegation-for-workbench-specialists),
provider tool and protected-resource calls on the user's behalf also carry the
service identity and target-bound human grant. The receiver can deny that
human independently. A saved result or task-origin label is not signed authority.
This is a required policy check, not a claim that the inspected implementation
or Specialist B's revised receiver has passed it.

## The trusted-renderer exception is local policy

The stable web-host specification requires a different-origin intermediate
sandbox and enforced resource CSP. The Workbench owner explicitly chose to trust
registered agent renderers. Workbench uses direct opaque-origin `srcdoc` with
`sandbox="allow-scripts"`, without `allow-same-origin`, a separate sandbox service
or enforced network CSP. Renderer code can send displayed data to outside
services. This is an approved local exception, not full stable MCP Apps
host-security conformance and not a universal recommendation.

The exception does not expose backend credentials or waive user, target, tool,
resource, result and revision checks. Adding untrusted renderers or extending the
exception to another host needs a new policy decision. A provider resource can
still work in a host that implements the full standard security contract.

## View transitions

The following states describe the inspected Workbench implementation. Saved
snapshots and concurrency control are its application contract, not standard
durable widget state. Provider compatibility remains an integration test.
The [state-machine index](agent-services.md#find-the-integration-state-machine)
links the separate credential, conversation, and release lifecycles.

The host controls closed, resolving, initializing, ready, updating, and uncertain
view states. A committed snapshot revision is stored data, not a new model turn.
Restoring or refreshing a view returns it to ready; neither reopens the original
A2A task or changes its answer.

| Transition | Trigger, guard and owner | Failure or recovery |
| --- | --- | --- |
| Closed to resolving | User opens a saved result; host verifies transcript ownership and binding, current registry policy, same-origin endpoint and matching app-visible tool | Missing, disabled, rebound or inaccessible result is denied. Keep the original text answer. |
| Resolving to initializing | Host reads the matching `ui://` resource with the Apps MIME, connects the bridge before loading HTML, then waits for `ui/initialize` and `ui/notifications/initialized` | Missing resource, invalid MIME or handshake timeout shows an error. Close/reopen retries resource loading, not the original analysis. |
| Initialized to ready | Host sends tool input before tool result, using a saved snapshot or the original result | Check whether updated renderer code can read old snapshots; old-renderer retention is not established. A cached result does not justify skipping current authorization. |
| Ready to updating | Explicit refresh or selection requests an allowed tool for the same resource; host locks the view row and checks expected revision before calling the provider | Stale revision yields 409 before tool execution. This is a new provider call, not restoration of the snapshot. No automatic call retry. |
| Updating to ready | Successful provider call and persistence save arguments/result, increment revision and clear stale selected context | Provider `isError` retains old state. The original answer stays unchanged. Failure after possible execution follows the uncertain path below. |
| Ready to ready with new context revision | App sends supported text `ui/update-model-context`; host saves it at the next revision | No model turn starts. Latest authorized text is added as untrusted selected data on the next user turn, not as system instructions or replayed chat history. |
| Closed through resolving and initializing to ready | Reopen loads current snapshot and re-resolves the renderer resource | No tool execution occurs on reopen. Resource reads still use the provider. Unsubmitted in-memory selections are not restored. |
| Updating to uncertain | Network or persistence fails after a provider call may have executed | Reopen to reconcile saved state before choosing an action. A database rollback cannot undo the provider call; do not promise exactly-once behavior. |
| Open to closed | User closes, component unmounts or navigation removes the view; host aborts its browser request and closes the bridge | Abort is not proof of provider cancellation. Current cleanup does not establish full protocol teardown conformance. |

## Acceptance checks

| Case | Observable acceptance criterion |
| --- | --- |
| MCP ownership | Wrong provider, tool, resource, user, result binding or revision fails. With successful provider responses, two updates competing at one revision produce one commit and one 409 before the second call. A failed call can leave that revision reusable, so this is not deduplication of failed attempts. |
| Provider delegation | Tool and protected-resource calls carry both credentials for the current authorized human and target. Missing or invalid grants and denied entitlements fail without shared-service downgrade; saved snapshots and task provenance cannot authorize a new call. |
| Snapshot versus refresh | Reopen preserves the saved result without a tool call. Explicit refresh makes a provider call; a changed result updates the view, not the original answer. |
| Model context | Selection sends no new A2A turn. The next user turn carries the latest authorized text context; renderer HTML and resource code never enter model history. |
| Failure after provider execution | Simulate failed response/persistence after a provider call. Show uncertainty and no automatic retry; reopening reflects whatever snapshot actually committed. |
| Renderer policy | Verify opaque-origin parent isolation and server-side credentials without claiming outbound network blocking. Record the owner-approved exception, not full host-security conformance. |

[Source revisions and limits](../evidence/workbench-integration.md).
Use [Release](release.md) for rollback and approval.


---

# Verify and release

Status: Draft
Source: https://github.com/The-Focus-AI/standards/blob/main/handbook/release.md
Relative links below resolve from handbook/release.md.


Run the repository's real lint and test tasks in CI on each PR and default-branch
push. Classify checks as blocking or advisory; make only blocking checks required
in branch protection. Tests cannot depend on a person's laptop. Use disposable
services, fixtures, or approved scoped credentials.

## Keep one release record

Use `docs/testing.md` with five sections: Checks, Preview verification, Benchmarks
and thresholds, Sign-off gates, and Alerting. Record actual checks, evidence,
owners, and gaps. `N/A` means inapplicable, not unconfigured.

The [default testing record](../templates/default-project/docs/testing.md) and
[CI procedure](../recipes/ci.md) provide working starting points. Copying a
workflow does not configure branch protection or prove that CI ran.

## Verify what will run

For web changes, publish a PR preview URL as a status/check on the exact head
commit. Run smoke or end-to-end checks against that preview before review.
When the platform cannot provide one, document the limitation and exercise the
candidate's production build/start path in the cloud workspace. State the
deployment behavior that remains unverified.

Inspect representative UI states and widths. Include screenshots for appearance
and a recording for interaction. For data/model behavior, record dataset,
metric, committed baseline, measured score, and commit; fail on regression.
Confidence thresholds for accepting output without review need benchmark
evidence and a person's approval, not an arbitrary constant.

Keep previews [production-like without production writes](secrets.md#match-production-behavior-in-previews).
No separate staging environment is required.

## Name who can release

The project owner records maturity, approval date, and rationale in `AGENTS.md`.
Missing maturity is unassessed, not an implicit `alpha`.

| Maturity | Verification | Approval |
| --- | --- | --- |
| `alpha` | Lint, tests, changed-workflow smoke test, known gaps | Owner may explicitly delegate bounded, reversible releases. |
| `client-testing` | Alpha checks plus client scenarios and representative data | Named owner accepts client-visible changes; record agreed client acceptance. |
| `production` | Regression, relevant auth/isolation/migration checks, candidate smoke test, recovery path | Recorded release approval and operational recovery owner. |

Maturity never waives security or grants merge/deploy authority. An agent can
collect evidence, but cannot supply the person's required approval. The
[review gate](work.md#keep-approval-independent) remains separate.

## Deploy the approved candidate

Build and deploy through the recorded CI path. Name the platform project,
environment, region/team where relevant, runtime identity, and artifact revision.
Do not rely on an ambient CLI target. Serialize releases to a destination;
do not cancel a half-finished deployment to start another.

## Integration cutover and recovery

This proposed release state machine applies to the combined code, schema, and
identity configuration, not code alone. It does not grant deployment or access
approval. The [state-machine index](agent-services.md#find-the-integration-state-machine)
links the request and view lifecycles affected by a cutover.

| Transition | Guard, owner and effect | Failure and recovery |
| --- | --- | --- |
| Planned to candidate verified | Engineer records code, schema, identity mapping and rollback compatibility; CI and cloud checks exercise that candidate | Fixture interoperability is not genuine issuance or deployed acceptance. Missing evidence stays an open gate. |
| Candidate verified to schema and configuration ready | Approved operator verifies target, backup and recovery, applies compatible schema, and confirms required credential and entitlement setup | Apply migrations separately from application boot and before readers. A failed migration, missing grant or absent provisioning stops promotion. |
| Ready to deployed, not accepted | Release owner authorizes the recorded code and registry cutover; pipeline publishes that candidate | Check runtime health and actual authenticated paths separately from discovery. Build success is not acceptance. |
| Deployed to accepted | Recorded acceptance gate passes on the deployed candidate, including direct and routed identity, negative auth cases, next turns and saved views | A failed gate blocks acceptance. The owner chooses repair or rollback; never mark blocked checks passed. |
| Deployed or accepted to dispatch paused | On failed acceptance or an incident, operator blocks new dispatch under the recovery plan and records known task/context ids | Pausing dispatch does not cancel in-flight work. Reconcile its actual outcome through supported reads or operator investigation; do not replay blindly. |
| Paused to rolled back or repaired | Owner selects a tested compatible code, schema and identity configuration; operator restores it while dispatch remains paused | Keep additive schema and saved history unless a separate migration is approved. Rollback does not undo data writes, grants or secret sync, or revoke issued tokens. |
| Rolled back or repaired to deployed, not accepted | Operator verifies compatibility and obtains approval for bounded acceptance traffic | Repeat the affected acceptance checks before general dispatch resumes. No rollback by disabling auth or restoring demo operator privileges. |

Workbench `c302e20` follow-up turns query `mcp_app_views` even when no view opens.
Apply and verify that schema before deploying code that reads it. Test a text-only
follow-up as well as view reopen; hiding the view UI does not remove the schema
dependency. The [source record](../evidence/workbench-integration.md#conversation-and-view-sources)
pins the implementation, not a current deployment.

For integration cutovers, preserve valid existing access only through a separately
approved, bounded coexistence profile. Never retry a failed machine/JWT/grant
request as a demo identity. Test stored contexts and snapshots against the chosen
rollback pair before release. See [service access](service-access.md).

| Recovery check | Observable acceptance criterion |
| --- | --- |
| Schema before readers | A failed or missing migration blocks the candidate's traffic. With the approved schema, text-only follow-ups and saved-view reopen both work. |
| Dispatch pause | New specialist calls stop, while an already accepted task is tracked separately. The operator records whether its outcome is known or unresolved, without claiming cancellation. |
| Compatible rollback | The selected old-code/new-schema pair can read retained contexts and snapshots. Code rollback neither drops additive schema/history nor weakens authorization. |
| Resume gate | Approved acceptance calls pass for the restored revision before general dispatch resumes. A public card alone cannot pass this gate. |

Platform procedures: [Vercel](../recipes/vercel.md), [GCP](../recipes/gcp.md),
[macOS menu bar apps](../recipes/macos-menubar-app.md), and the dated
[Gaia runtime record](../evidence/gaia-runtime.md).

## Route failures back to work

Default-branch blocking failures, failed deployments, and scheduled-check failures
need an issue or a link to an existing issue. Deduplicate with a stable
`<!-- fp:scope:target:rule -->` marker, not a run timestamp. Record first/latest
occurrence, classification, and run/log links.

Notify the project's named Slack channel with the issue link. Repeat failures
belong in its existing thread; route human replies and recovery evidence back
to the issue. A raw automated failure stays backlog until actionable under
[the work workflow](work.md). Recovery alone is not permission to close it.


---

# Install and maintain skills

Status: Draft
Source: https://github.com/The-Focus-AI/standards/blob/main/handbook/skills.md
Relative links below resolve from handbook/skills.md.


The site catalog is generated from [skills-lock.json](../skills-lock.json) and
the owned `skills/` directories. It distinguishes installed defaults from
optional capabilities, groups external sources, and exposes the actual paths
and revisions. Do not maintain another inventory in prose.

The smaller default keeps the external selection plus `setup-project` and
`work-next-issue`. Presentation, brand, and research capabilities remain optional.
`pptx-decks` owns deck mechanics; `focus-ai-brand` supplies optional brand tokens.
Neither requires installing the other for an unrelated project.

## Restore the reviewed selection

Use the mise-pinned skills CLI, not an unpinned `npx` command or manually copied
skill folders. The root and default-project locks stay identical.

```sh
mise run install
node scripts/restore-skills.mjs --check
node scripts/restore-skills.mjs --validate-lock
```

The restore helper installs in a temporary directory, verifies canonical paths,
full commit refs, inventory, and installed-byte hashes, then replaces the managed
directory. It never rewrites the project lock. It refuses unknown existing skills
instead of deleting them and rejects concurrent wrapper runs. Inspect an abandoned
guard before removal. This is not a sandbox for untrusted code or a power-loss-safe
transaction, and it does not lock out someone running the raw CLI concurrently.

The pinned skills 1.7.4 behavior was checked on 2026-10-30:

- `experimental_install` is the raw restore command; `install` aliases `add`.
- Raw restore does not enforce `computedHash`; unknown frozen flags do not help.
  Exit zero can still leave an incomplete restore. Use the helper.
- `skills check` dispatches to a mutating update. It is not a read-only audit.
- `skills update --project -y` checks recorded refs, so immutable pins do not
  advance to latest. Unscoped named updates can also touch global skills.
- `skills remove NAME -y` removes the project files and lock entry. Agent-specific
  removal retains shared content while another agent uses it.

## Update deliberately

1. Read upstream changes and select a reviewed published full commit SHA.
2. Run `skills add` from that immutable source with explicit skill names and agent.
3. Review source, `skillPath`, ref, and hash changes; run the restore checks.
4. Update the consuming lock only after the source is published. Local edits to
   an owned skill do not change the installed version pinned to an earlier commit.

Never run bare `skills add cursor/plugins -y` or `skills add mattpocock/skills -y`.
They include capabilities outside the selected set. For pstack, use its canonical
`pstack/skills/` tree, not same-name harness adapters.

## Resolve same-name skills explicitly

The lock stores one entry per name. `tdd` and `teach` default to Matt Pocock's
feature-testing and teaching-workspace implementations. Pstack's alternatives
provide focused regression testing and how/why explanations. Choose one installed
source; do not invent alias keys that upstream restoration cannot resolve.

To read the alternative without changing the lock:

```bash
set -euo pipefail
PSTACK_REF=$(jq -er '.skills["poteto-mode"].ref' skills-lock.json)
[[ "$PSTACK_REF" =~ ^[0-9a-f]{40}$ ]]
skills use "https://github.com/cursor/plugins/tree/$PSTACK_REF/pstack/skills" --skill tdd
```

`skills use` emits the prompt, not supporting resources or plugins. Read resources
at the same revision. Cursor-specific plugins, agents, and Bugbot/Automations
remain separate dependencies; skip unsupported steps explicitly in other hosts.

## Maintain an owned skill

Keep `skills/<name>/SKILL.md` with matching kebab-case name and a description that
says what it does and when to use it. Preserve bundled resources and attribution
in [VENDORED.md](../skills/VENDORED.md). Names are the installable identities;
there is no second numbering scheme.

Run `mise run skills:check`. Read command/server declarations before adopting an
external skill, and verify behavior rather than treating installation as proof.

CLI source: [skills 1.7.4](https://github.com/vercel-labs/skills/tree/a80e4c9d12d607631249d4d7d059f835d4b2f13a).
The [restore helper](../scripts/restore-skills.mjs) and its tests encode the
additional checks this inventory relies on.


---

# Maintain the handbook

Status: Draft
Source: https://github.com/The-Focus-AI/standards/blob/main/handbook/maintaining.md
Relative links below resolve from handbook/maintaining.md.


Write for the task a reader needs to complete. Put the default, scope, exceptions,
failure/recovery behavior, and verification together. Link to a topic instead
of repeating its rules in a guide, skill, template, and standard.

## Authority stays explicit

| Status | Meaning |
| --- | --- |
| Draft | Proposed guidance. Not an organization-wide obligation unless a project explicitly adopts it. |
| In force | A person approved this policy; record `approved-by` and `approved-on`. Agents cannot grant this status. |
| Reference | A procedure or capability, not independent policy. |
| Evidence | A dated observation with sources and limits, not a claim about current deployments. |

This redesign changes organization, not approval. Existing proposed policies
remain Draft. A team can adopt a named page revision for a project and record
that decision locally. Protocol requirements apply only to implementations
claiming that version; local application profiles and policy exceptions do not
become protocol requirements.

## Keep pages small and findable

- `handbook/` owns task-oriented guidance. Add a page to `handbook/navigation.json`
  under the reader's task, not under its document type.
- `recipes/` holds longer platform-specific commands linked from their owner topic.
- `evidence/` holds dated implementation observations worth retaining.
- `skills/` holds installable skills. Keep their CLI-owned frontmatter and record
  attribution in `skills/VENDORED.md`. Generate the catalog from the lock and source.
- `templates/` and `scripts/` are executable starting points, not a second policy book.
- [CHANGELOG.md](../CHANGELOG.md) records substantive additions and revisions as
  newest-first `## YYYY-MM-DD — Title` sections with links to the affected pages.
  The build renders `changelog.html` and the RSS 2.0 feed `feed.xml` for Focus.AI
  Labs and other subscribers; omit typo and formatting fixes.

Use meaningful filenames and links. There are no document numbers, clause-number
registries, duplicate reference lists, or replacement-pointer paperwork. Git
retains removed material. Keep a dated evidence page only when a current decision
needs it, not to preserve every old plan.

Each published Markdown page declares `title`, `summary`, and `status` in
frontmatter. Evidence also declares `checked` as a real ISO calendar date.
Record source revisions and what was actually run in its body. A fresh edit date
is not a new verification date. Attribution is not inferred from repository ownership.

## Check the result

```sh
mise run lint
mise run test
mise run handbook:build
```

The build validates metadata, navigation coverage, and local links before writing.
The catalog derives selected sources/revisions from `skills-lock.json`; it does
not imply all optional skills or upstream dependencies are installed.

Inspect the rendered desktop and narrow layouts after visual changes. Mechanical
checks catch broken structure, not conflicting advice or unsafe commands.


---

# Build an A2A server

Status: Reference
Source: https://github.com/The-Focus-AI/standards/blob/main/recipes/a2a-server.md
Relative links below resolve from recipes/a2a-server.md.


This recipe retains the SDK 1.3.0 implementation guidance checked on 2026-10-21.
Use [Agent services](../handbook/agent-services.md) for the proposed defaults,
[Service access](../handbook/service-access.md) for authentication, and the
[conversation lifecycle](../handbook/conversations.md) for runtime behavior.

For a Workbench external specialist, apply the
[required human-delegation profile](../handbook/service-access.md#require-human-delegation-for-workbench-specialists)
before the executor runs. Verify service identity and the target-bound human
grant, bind `human.azp` to the actual verified `machine.sub`, then check the
receiver's human entitlement. Exercise direct and coordinator-routed calls with
the same principal. Task provenance is not authority; a missing or invalid grant
never falls back to shared-service access. Specialist B's revised receiver still
needs implementation and acceptance evidence for this contract.

## Server layout

```text
app/
├── agent/
│   ├── loop.ts                 ← runAgent(): the one entry point (handbook/agent-services.md)
│   ├── system-prompt.md        ← canonical prompt; verify any runtime mirror
│   ├── tools/                  ← one ToolSpec per file, one barrel
│   └── a2a/executor.ts         ← AgentExecutor: runAgent events → A2A events
├── app/
│   ├── .well-known/agent-card.json/route.ts   ← public card
│   ├── api/health/route.ts                    ← public health
│   ├── api/a2a/jsonrpc/route.ts               ← authenticated JSON-RPC
│   └── api/mcp/route.ts                       ← optional, for tiles
├── lib/{db,auth,env}.ts        ← pool, token verification, env parsing
└── __tests__/
```

**One `runAgent`, one set of tools.** Each tool is one `ToolSpec`. The model
tool and the MCP tool are both derived from it (`handbook/agent-services.md`). The A2A executor
and the MCP route both import the same catalog. Conversational requests call
`runAgent` with the verified caller and a `surface` tag. MCP rendering interactions
call authorized tools without implicitly starting a model turn. A chat UI sends its
requests to your own A2A endpoint. Do not add a separate chat route for it:
`handbook/agent-services.md` permits one if it calls the same entry point, but on the
Workbench a private route is forbidden.

When adopting the client's onboarding packet,
refusals and citations are typed Parts. Its media types are
`application/vnd.<client>.refusal+json` and
`application/vnd.<client>.citations+json`, declared under the extension URIs at
`https://<client-standards-host>/ext/…/v1`. Use these shared types for citations
and refusals rather than replacing them with per-project types. Domain output
can have its own media type alongside the shared provenance Parts.

## Persistence: Postgres, owned and isolated

The Focus default in [Agent services](../handbook/agent-services.md) uses Postgres
sessions. It is not an A2A requirement. This setup has two parts:

1. **A2A task state** in the SDK's `DatabaseTaskStore`
   (`@a2a-js/sdk/server/database`, new in 1.3.0). It holds task snapshots,
   status, history and artifacts, so follow-ups, `GetTask` and polling keep
   working when instances are recycled. Apply migrations as a deploy step, not
   at boot. Run `a2a-db upgrade` under `fnox exec`, so the CLI reads
   `DATABASE_URL` from the environment. Do not pass `--url` with credentials in it.
2. **A session log** that the agent owns: conversation, user turn, assistant
   turn, and each tool call with arguments, output, citation and refusal rule as
   `jsonb`. This log is what turns a silent tool bug into a SQL query.

Ownership and isolation:

- Record the verified owner on every row: the selected service principal and,
  for delegated profiles, the human subject. The machine claim is issuer-specific;
  `sub`, `azp` and `client_id` are not interchangeable. Read the agreed identity
  from verified tokens, never the request body. Changing that mapping needs a
  migration for existing entitlements and history. Never create shadow users.
- Look up a context or task by owner as well as by id. A caller asking for
  another owner's task gets the same "not found" response as a missing task.
  The SDK's built-in stores scope by tenant and owner from `context.user`;
  without a verified user, callers share the `unknown` owner. Populate the
  verified principal through the user builder. Custom stores need their own
  scoping. Test cross-owner access even when using the built-in store.
- Await the writes. Do not fire and forget. A serverless instance can freeze
  after the response, so wait for the write before the terminal event, or use
  the platform's `waitUntil`. A failed write is logged with the context id, not
  hidden.
- In production, the server refuses to start without `DATABASE_URL`. An
  in-memory fallback is for local mock mode only.
- Each environment has its own database. Preview never writes to production
  (`handbook/secrets.md`).

## Endpoints

| Route | Auth | Purpose |
| --- | --- | --- |
| `GET /api/health` | public | Uptime; reports no secrets or config |
| `GET /.well-known/agent-card.json` | public | AgentCard (RFC 8615); respects `A2A-Version`, sets `Vary: A2A-Version` and cache headers |
| `POST /api/a2a/jsonrpc` | Selected service credential profile | A2A v1.0 + v0.3 where implemented |
| Advertised MCP endpoint, e.g. `/mcp` or `/api/mcp` | Selected service credential profile | Optional; expose only the HTTP methods the selected transport implements |
| `/api/cron/*` | `CRON_SECRET` | Optional scheduled jobs |

### The card

Build the card from the same tool catalog. Skill ids match tool names. It
contains `supportedInterfaces[]` with the JSON-RPC URL built from `APP_URL`,
the interface's `protocolVersion: "1.0"`, `capabilities.streaming: true`, the packet's
extensions, `securitySchemes` naming the OAuth issuer's token URL and scopes,
and skill `examples` for the probe to use. Field shapes are in the
[A2A v1.0 specification](https://a2a-protocol.org/v1.0.0/specification/) and the
packet. They are not repeated here.

Use that OAuth description only for an actual OAuth flow. Native Clerk M2M uses
the declared HTTP bearer profile instead. A card's security declaration describes
the service; it neither issues credentials nor proves an invocation succeeds.

### The JSON-RPC wire (SDK 1.3)

| | v1.0 | Legacy v0.3 |
| --- | --- | --- |
| Selected by | PascalCase method, sent with `A2A-Version: 1.0` | slash-separated method; omitted version header uses the SDK's 0.3 default |
| Methods | `SendMessage`, `SendStreamingMessage`, `GetTask`, `CancelTask`, `SubscribeToTask`, … | `message/send`, `message/stream`, `tasks/get`, `tasks/cancel`, `tasks/resubscribe` |
| Result / stream payload | one of `task`, `message`, `statusUpdate`, `artifactUpdate` | objects discriminated by `kind` |
| Task states | `TASK_STATE_SUBMITTED`, `TASK_STATE_WORKING`, `TASK_STATE_COMPLETED`, `TASK_STATE_FAILED`, … | `submitted`, `working`, `completed`, `failed`, … (plus a computed `final`) |

When both dialects are required, wire them through one `DefaultRequestHandler`. Configure
`legacyCompat: { enabled: true }` on the JSON-RPC transport and card handlers,
not on `DefaultRequestHandler`. The SDK picks the dialect per request, and
your executor only sees v1 types. Use the SDK's own documents and samples,
versioned with the code:

- [Migration guide v0.3 → v1.0](https://github.com/a2aproject/a2a-js/blob/v1.3.0/docs/migration-guide.md)
- [v0.3 compatibility guide](https://github.com/a2aproject/a2a-js/blob/v1.3.0/docs/compatibility-v0_3.md)
  and the runnable `compat-v1-server` sample
- [Persistent stores and migrations](https://github.com/a2aproject/a2a-js/blob/v1.3.0/docs/persistent-stores.md)
- [CHANGELOG](https://github.com/a2aproject/a2a-js/blob/v1.3.0/CHANGELOG.md)

### Event order in a task-producing executor

- Publish a `task` first. The server rejects a stream that opens with a status
  or artifact update. A2A also permits a standalone Message result; for a
  durable task workflow, return a Task from blocking `SendMessage` too.
- Stream `statusUpdate` (`TASK_STATE_WORKING`) and `artifactUpdate` events as
  work progresses. Keep Part order as produced.
- Publish all artifacts, including citation and refusal Parts, **before** the
  terminal status. Put the reply text on the terminal status's `status.message`.
  v1 has no `final` flag; the terminal state closes the stream.
- A refusal is a successful completion that carries a refusal Part. It is not a
  JSON-RPC error.
- After a terminal task, an SDK-profile follow-up sends the new turn with a fresh
  `messageId`, the same authorized `contextId`, and no old `taskId`. An unfinished
  task awaiting input can instead receive a message addressed to that task if
  the implementation supports it. Context history is an application persistence
  contract, not guaranteed by the existence of a context id. Workbench's legacy
  Specialist B direct transport additionally sends a bounded recap; see
  [conversation behavior](../handbook/conversations.md#conversations-tasks-and-transport).
- On disconnection, preserve the known task id and use supported `GetTask` reads.
  Polling is an available recovery operation, not proof that every caller has
  implemented it. Workbench's `askSpecialist` does not poll or resume.
- If you do not support an operation, say so. Set `pushNotifications: false` on
  the card. Have `CancelTask`/`SubscribeToTask` return the SDK's
  unsupported-operation error until they really work. Do not advertise a
  capability and then fail it.


---

# Configure CI and failure routing

Status: Reference
Source: https://github.com/The-Focus-AI/standards/blob/main/recipes/ci.md
Relative links below resolve from recipes/ci.md.


The approval and verification defaults live in [Release](../handbook/release.md).
Adapt these examples to the project; a copied workflow does not configure
external permissions, branch protection, or alert delivery.

## `docs/testing.md` contract (`handbook/release.md`)

Every repository carries `docs/testing.md` with five required level-two
headings (`## Checks`, `## Preview verification`, `## Benchmarks and thresholds`,
`## Sign-off gates`, `## Alerting`). Mark a section `N/A` when it does not apply.

Copy `templates/default-project/docs/testing.md` and fill in the project's
actual checks, evidence, and approvers. That is the maintained generic template.
Set project thresholds from evidence and explicit approval, not copied numbers.

Use the owner-approved maturity recorded in `AGENTS.md` to select the release
profile in `handbook/release.md`; keep the actual checks and approval record in
`docs/testing.md`. The handbook owns the profiles, not this walkthrough. Missing
maturity is an assessment gap, not an implicit `alpha` or permission to release.

No separate staging environment is required. Verify the release candidate in
preview, or document the cloud build/start alternative for a platform without
previews ([release guidance](../handbook/release.md)), then record the release approval. Preview
behavior follows production by default (`handbook/secrets.md`).

Failure reporting starts issues in backlog with `automated` and, where relevant,
`bug`. A person or agent may add `ready` after assessing specification completeness
under `handbook/work.md`; a raw failure event does not establish readiness.

An agent auditing a repository checks `docs/testing.md` with:

```sh
for h in "## Checks" "## Preview verification" "## Benchmarks and thresholds" "## Sign-off gates" "## Alerting"; do
  grep -Fxq "$h" docs/testing.md || { echo "missing heading: $h"; exit 1; }
done
```

## CI on pull requests (`handbook/release.md`)

`.github/workflows/ci.yml` runs `mise run lint` and `mise run test` against a
disposable service container so CI never depends on laptop state:

```yaml
name: ci
on:
  pull_request:
  push:
    branches: [main]
concurrency:
  group: ci-${{ github.ref }}
  cancel-in-progress: true
jobs:
  check:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_HOST_AUTH_METHOD: trust
          POSTGRES_DB: test
        ports: ["5432:5432"]
        options: >-
          --health-cmd "pg_isready -U postgres"
          --health-interval 5s --health-retries 10
    env:
      DATABASE_URL: postgresql://postgres@127.0.0.1:5432/test
    steps:
      - uses: actions/checkout@v4
      - uses: jdx/mise-action@v2
      - run: mise run install
      - run: mise run lint
      - run: mise run test
```

Mark `check` as required in branch protection; keep advisory jobs non-required
(`handbook/release.md`).

## Preview status and end-to-end verification (`handbook/release.md`)

`.github/workflows/preview.yml` triggers on `deployment_status`, runs Playwright
against the preview URL, and publishes the result as `context=preview/e2e` on
the head commit SHA. This is an adaptation example, not a verified drop-in
workflow: declare Playwright in the project lock and configure the protected
`preview-verification` environment before enabling it. Its approval gate must
review the candidate code before it receives a bypass secret or write token;
the environment name alone creates no protection. Restrict preview destinations
to the project's platform hostnames, not an arbitrary event-supplied URL.

```yaml
name: preview
on: deployment_status
jobs:
  e2e:
    if: >-
      github.event.deployment_status.state == 'success' &&
      github.event.deployment.environment != 'Production'
    runs-on: ubuntu-latest
    environment: preview-verification
    permissions:
      contents: read
      statuses: write
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.deployment.sha }}
      - uses: jdx/mise-action@v2
      - run: mise run install
      - run: npx --no-install playwright install --with-deps chromium
      - run: npx --no-install playwright test
        env:
          BASE_URL: ${{ github.event.deployment_status.environment_url }}
          VERCEL_AUTOMATION_BYPASS_SECRET: ${{ secrets.VERCEL_AUTOMATION_BYPASS_SECRET }}
      - if: always()
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          gh api "repos/${{ github.repository }}/statuses/${{ github.event.deployment.sha }}" \
            -f state="${{ job.status == 'success' && 'success' || 'failure' }}" \
            -f context="preview/e2e" \
            -f description="Playwright against preview (${{ job.status }})" \
            -f target_url="${{ github.event.deployment_status.environment_url }}"
```

An agent preparing PR evidence reads the preview status directly from the commit:

```sh
SHA="$(git rev-parse HEAD)"
gh api "repos/:owner/:repo/commits/$SHA/status" \
  --jq '.statuses[] | select(.context == "preview/e2e") | {state, target_url, description}'
```

## Failure → Issue → Slack → Route-back (`handbook/release.md`)

This is an implementation outline, **not installed automation**. The former
shell snippets used search's first hit as identity and accepted Slack HTTP 200
as success; neither establishes correct delivery. Keep one tested integration
in the consuming repository rather than copying partial scripts from this guide.

### Open or update a deduplicated issue (`handbook/release.md`)

Every automated issue carries `<!-- fp:<scope>:<target>:<rule> -->` on line 1 of
its body. The reporter handles failed default-branch and scheduled blocking checks:

1. Read all open `automated` issues, paginating the API, and compare the **exact
   first-line marker**. Search text is a discovery aid, not an identity check.
2. Serialize writers for the same repository/fingerprint, then recheck before
   creating. A list followed by a create is not atomic; if multiple matches
   already exist, report them for reconciliation rather than choosing one silently.
3. Comment with the timestamp and run URL on the existing issue, or create one
   with `automated`/`bug`, check classification, ref/SHA, first/latest occurrence,
   and run URL. Do not apply `ready` from a failure event alone.
4. Propagate API errors and retain the failed notification for retry. Do not
   confuse reporter success with recovery of the original check.

### Post or thread in Slack (`handbook/release.md`)

Keep the exact issue-to-thread mapping
`<!-- slack:channel=<channel-id>;ts=<thread_ts> -->`; read every comment when
the mapping lives in comments. Match **both channel and timestamp**, not just
the first timestamp found. Existing mappings receive replies; an absent mapping
requires a new root message and persistence of the returned channel/timestamp.

Check both HTTP status and JSON `ok === true` before recording delivery. Slack's
[`chat.postMessage` documentation](https://docs.slack.dev/reference/methods/chat.postMessage/)
returns `ok: false` for application errors and defines `thread_ts` for replies
(checked 2026-10-30). Validate the returned channel and timestamp; never persist
`null` as a thread. Supply the bot token through the runtime's secret handling,
not a logged command argument. Reconcile an ambiguous timeout before retrying a
message creation; otherwise a retry can create a second thread.

### Route Slack replies and resolving matches back (`handbook/release.md`)

Verify incoming Slack event authenticity, deduplicate event IDs, ignore bot
echoes, and resolve the exact channel/thread mapping before posting a reply to
the issue. Treat message text as data, not instructions to the reporter.

A subsequent successful run of the same fingerprint, or a merged linked fix,
adds a recovery comment with its run URL to both surfaces. It does not silently
close an implementation issue before its fix merges. See the explicit duplicate
exception in `handbook/work.md` rather than treating every recovery as that exception.

Before claiming the loop works, exercise repeated and concurrent failures,
near-match fingerprints, pagination, Slack `ok: false`, ambiguous timeouts,
replayed events, and recovery in an authorized test repository/channel. None of
those external integrations is configured or verified merely by this outline.


---

# Configure Clerk and social sign-in

Status: Reference
Source: https://github.com/The-Focus-AI/standards/blob/main/recipes/clerk.md
Relative links below resolve from recipes/clerk.md.


Policy lives in [Client sign-in](../handbook/sign-in.md). This recipe preserves
the original provider walkthrough and its stated verification dates.

## Always run a production instance in production

- **Never ship a development instance to production.** A dev instance
  (`pk_test_…`, Frontend API on `*.clerk.accounts.dev`) defaults to Clerk's
  _shared_ OAuth credentials, has stricter rate limits, and sends email from
  `accounts.dev`. It is for local dev only; the shared OAuth defaults are not
  the client-specific configuration described in `handbook/sign-in.md`.
- Production uses `pk_live_…` / `sk_live_…` on your own custom domain.
- Sanity-check which instance a deployment uses by decoding the publishable key
  (the payload is base64 of the Frontend API host followed by `$`):

  ```bash
  node <<'JS'
  const key = process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY ?? "";
  const match = key.match(/^pk_(live|test)_([A-Za-z0-9+/]+={0,2})$/);
  if (!match) throw new Error("Expected a Clerk publishable key (pk_live_ or pk_test_)");
  const decoded = Buffer.from(match[2], "base64").toString("utf8");
  if (Buffer.from(decoded).toString("base64").replace(/=+$/, "") !== match[2].replace(/=+$/, "") ||
      !/^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9-]+\$$/i.test(decoded)) {
    throw new Error("Invalid publishable-key host payload");
  }
  console.log(`${match[1] === "live" ? "production" : "development"}: ${decoded.slice(0, -1)}`);
  JS
  ```

This diagnostic checks key shape and identifies the instance type; it does not
test sign-in, OAuth ownership, or origin isolation. The decoder was checked
2026-10-30 against Clerk's [key implementation](https://github.com/clerk/javascript/blob/main/packages/shared/src/keys.ts)
with synthetic live/test keys and invalid inputs. It prints only type and host.

## Per-client production setup (repeat for each client)

1. Create the application, then **Create production instance** (clone dev — note
   SSO connections, integrations, and Paths do NOT copy and must be re-added).
2. Set the instance domain to the client subdomain, e.g. `thp.thefocus.ai`.
3. Add the CNAME records from the Clerk **Domains** page. Standard set (hosts
   shown relative to the `thefocus.ai` zone, for the `thp` subdomain):

   ```text
   clerk.thp              CNAME  frontend-api.clerk.services      # Frontend API
   accounts.thp           CNAME  accounts.clerk.services          # Account Portal
   clkmail.thp            CNAME  mail.<token>.clerk.services       # email
   clk._domainkey.thp     CNAME  dkim1.<token>.clerk.services      # DKIM
   clk2._domainkey.thp    CNAME  dkim2.<token>.clerk.services      # DKIM
   ```

4. **Cloudflare: set every Clerk record to "DNS only" (grey cloud).** A proxied
   (orange-cloud) record fails Clerk's domain/SSL verification.
5. Put `pk_live_…` / `sk_live_…` in that client's hosting env (each client is
   its own Vercel project). The #1 prod mistake is forgetting to swap the keys.
6. Add that client's social OAuth credentials (see "Social OAuth" below) and
   re-point webhooks to the production instance.
7. Lock origins in middleware so a token from one client is rejected by another:

   ```ts
   // middleware.ts (per project)
   import { clerkMiddleware } from "@clerk/nextjs/server";
   export default clerkMiddleware({ authorizedParties: ["https://thp.thefocus.ai"] });
   ```

8. Deploy certificates in the Dashboard (DNS can take up to 48h to propagate).

## Social OAuth (Google + Microsoft)

Clerk supplies _shared_ OAuth credentials by default for development instances;
production instances require custom credentials. That vendor convenience is
not a compliant client-specific setup under `handbook/sign-in.md`. Configure **Use
custom credentials** with the client's own provider registration in development
as well as production. A sign-in that works with Clerk's shared defaults has not
tested the client's OAuth configuration.

For each instance and provider, **copy the exact redirect URI from the Clerk
Dashboard** (SSO Connections → provider → _Use custom credentials_). Production
examples look like the following; these two clients' callbacks belong in
different provider applications, not one shared registration:

```text
https://clerk.thp.thefocus.ai/v1/oauth_callback        # THP OAuth app only
https://clerk.habitats.thefocus.ai/v1/oauth_callback   # Habitats OAuth app only
```

### Per-client OAuth applications and credentials

Under `handbook/sign-in.md`, each client gets its own Google OAuth application and
Microsoft app registration for the providers it uses, with client IDs and
secrets that are never copied into another client's Clerk application. This is
the isolation boundary even when clients share a root domain, consent-screen
branding, or the team administering their provider accounts.

- Separate Clerk applications isolate user pools. Separate provider
  applications additionally keep consent, credentials, rotation, and revocation
  within one client's boundary; different branding is not a prerequisite.
- Multiple redirect URIs can belong to one client's application: development,
  preview, and production can reuse that client's registration and credentials
  where supported and appropriately scoped (`handbook/secrets.md`). Each callback and
  origin belongs to that client, never another client.
- Store credentials in the client's project vault (`handbook/secrets.md`), and record
  their owner and renewal date where they expire (`handbook/secrets.md`). Within-client
  reuse means coordinating rotation across that client's environments, not
  across the whole client fleet.

### Google setup (repeat for each client)

1. In this client's Clerk application, open each instance being configured:
   **SSO Connections → Google** → enable + **Use custom credentials** → copy
   its Redirect URI.
2. In Google Cloud Console, select or create a project dedicated to this
   client. Configure its **OAuth consent screen / Google Auth Platform** with
   the client's app name and **External** audience. Set **Authorized domains**
   for the client's URLs (`thefocus.ai` for the THP example); a shared parent
   domain is not a reason to share the OAuth application. **Publish to "In
   production"** before production use (`handbook/sign-in.md`), completing any Google
   verification required for the app's branding or scopes.
3. **Credentials → OAuth client ID → Web application**:
   - Name the OAuth client for this client project.
   - Authorized JavaScript origins: `https://thp.thefocus.ai`, plus the origins
     used by this same client's other environments as needed.
   - Authorized redirect URIs: add the exact Clerk Redirect URIs collected for
     this client, not callbacks from other clients.
4. Save Client ID + Secret in this client's project vault, then enter them into
   **Use custom credentials** in only this client's Clerk instances and save.

### Microsoft / Entra ID setup (repeat for each client)

1. In this client's Clerk application, open each instance being configured:
   **SSO Connections → Microsoft** → enable + **Use custom credentials** → copy
   its Redirect URI.
2. Azure → Microsoft Entra ID → **App registrations → New registration**:
   - Name this registration for the client; use a separate registration for
     every other client.
   - **Supported account types: "Accounts in any organizational directory
     (multitenant) and personal Microsoft accounts."** Required so external
     orgs (e.g. a client's tenant) can sign in. Clerk uses the `common` tenant.
     Multitenant describes who can sign in, not permission to share this
     registration across our client projects.
   - Redirect URI: platform **Web**, enter this client's Clerk Redirect URI.
     Add callbacks for other environments of this same client in the
     registration's **Authentication** settings as needed.
3. **Certificates & secrets → New client secret** → copy the Value. Note the
   expiry (≤24mo), record the renewal owner, and set a rotation reminder —
   expired secrets silently break Microsoft login.
4. **Token configuration**: add the `email` optional claim.
5. Save Application (client) ID + secret Value in this client's project vault,
   then enter them into **Use custom credentials** in only this client's Clerk
   instances and save. The secret **Value**, not the Secret ID, is the credential.

### Check the client boundary

Compare provider application/client IDs across clients: they differ. Review
each registration's callbacks and origins: none belongs to another client.
Then test each enabled provider from this client's Clerk Account Portal in
each configured environment, confirming the expected client application and
successful callback. A check against development defaults does not substitute
for this test.

## Access control per client

- Restrict self-signup to the client's email domain in
  **Dashboard → Configure → Restrictions → Allowlist** (per application, so
  policies never leak between clients).
- Pair with app-side provisioning that grants tool access on first sign-in for
  the client's domain.

## OAuth setup references

Checked for this OAuth credential setup update on 2026-10-29; the rest of the
Clerk configuration walkthrough was not reverified in this update. Consult the
provider guides for current dashboard labels and additional connection settings.

- [Clerk: social OAuth](https://clerk.com/docs/nextjs/guides/configure/auth-strategies/social-connections/overview).
- [Clerk: Google](https://clerk.com/docs/guides/configure/auth-strategies/social-connections/google).
- [Clerk: Microsoft](https://clerk.com/docs/guides/configure/auth-strategies/social-connections/microsoft).
- [Google: manage OAuth clients](https://support.google.com/cloud/answer/6158849).
- [Google: manage OAuth app branding](https://support.google.com/cloud/answer/15549049).
- [Microsoft: redirect URIs](https://learn.microsoft.com/en-us/entra/identity-platform/how-to-add-redirect-uri).


---

# Configure fnox and secret delivery

Status: Reference
Source: https://github.com/The-Focus-AI/standards/blob/main/recipes/fnox.md
Relative links below resolve from recipes/fnox.md.


Follow the [secret-handling guidance](../handbook/secrets.md) before setup.

A reference for setting up isolated, auditable secret management on any project.
Goals:

1. **Project isolation in the company account** — each project's secrets live in
   its own dedicated vault (`<Client> - <Project>` or `<Client>`) inside
   TheFocus.AI's company 1Password Business account (`thefocusai.1password.com`),
   accessed by a service account scoped to that vault. Never use a personal
   1Password account (`my.1password.com`) or built-in `Private`, `Personal`,
   `Employee`, `Shared`, or `default` vaults.
2. **1Password is the source of truth for development and preview values** — production
   values are set in the deployment platform by an owner. The scoped bootstrap token enters through
   cloud secret settings; application credentials resolve through fnox. Platform
   write credentials belong only in authorized sync jobs, not the application.
   Nothing is committed or baked into a reusable image. A local token file is an exception.
3. **Control where every key comes from** — `fnox.toml` maps each runtime variable to
   a provider/vault/item; a sync target maps only the runtime keys its application needs.
4. **Usage visibility** — secret descriptions can point to billing dashboards.
   Administrative usage-report credentials stay outside application runtime profiles.

## Concepts

- **fnox** resolves variables from providers; it is a router, not a vault or API proxy.
- **1Password service account** is a non-human identity scoped to selected vaults.
  Its `OP_SERVICE_ACCOUNT_TOKEN` is a bootstrap credential, not an application key.
- **fnox profile** selects source declarations and overrides. It does not select a
  deployment destination or prove that the injected identity has the correct scope.
- **Sync target** names the platform project, destination, source profile, credential
  environment names, and runtime allowlist together. Preview and Production may use
  the **same profile and runtime keys**; differences need a reason, not just different names.

Deployment procedures have one owner: **`recipes/vercel.md` for Vercel**, **`recipes/gcp.md` for GCP**.
This guide owns bootstrap, fnox semantics, and the common sync contract.

## One-time per-project setup

### Install tools (via mise)

Work in the project's cloud workspace (`handbook/development.md`). Declare fnox and the
1Password CLI in its mise configuration; use `mise use` when adding tools.
The maintained versions are in `templates/default-project/mise.toml`.

Run `mise trust` and `mise install` for the tools, then `mise run install` for
project dependencies. fnox needs `op` on PATH, but an injected service-account
token does not need desktop integration or a person's interactive login.
Installation of `op` 2.41.1 through mise and its service-account command help
were checked on 2026-10-29; no real credentials were resolved [1].

For the sync implementation below, use Node 22 or newer and pin a tested fnox
release with named-key export support through mise. The source checked here is
**fnox v1.45.0** [2], not an assertion that older releases accept the same flags.

> **Interactive shells.** Optional mise/fnox activation can resolve application
> values when entering a project. For zsh, put activation in `~/.zshrc` rather
> than only `~/.zprofile`:
>
> ```bash
> eval "$(mise activate zsh)"
> command -v fnox >/dev/null 2>&1 && eval "$(fnox activate zsh)"
> ```
>
> Activation is for interactive app work, not a prerequisite for sync. For a
> command without activation, use `fnox --profile runtime exec -- <command>`.
> Keep administrative keys out of the runtime profile. Inspect the selected
> profile rather than assuming that every declared key is safe to inject.

The cloud platform injects `OP_SERVICE_ACCOUNT_TOKEN`; mise does not retrieve it.
Check presence without printing even part of a value:

```bash
test -n "${OP_SERVICE_ACCOUNT_TOKEN:-}" && echo "Bootstrap token is present"
fnox --profile runtime exec -- sh -c 'test -n "$ANTHROPIC_API_KEY"'
```

The second command resolves real secrets: run it only in an authorized workspace.
Presence alone is not proof of vault access or correct scope.

### Create the dedicated vault in the company account

Always pass `--account thefocusai.1password.com` (and unset any ambient
`OP_SERVICE_ACCOUNT_TOKEN`) on interactive `op` commands. A laptop signed in to
both `thefocusai.1password.com` and a personal `my.1password.com` account
otherwise creates resources in whichever account signed in last:

```bash
env -u OP_SERVICE_ACCOUNT_TOKEN op vault create "<Client> - <Project>" \
  --account thefocusai.1password.com --icon vault-door \
  --description "Secrets for <project>; managed by fnox"
```

### Retrieve and inject the scoped bootstrap token

A person uses their individual seat in the company 1Password account
(`thefocusai.1password.com`, never a personal `my.1password.com` account) to
retrieve the project's saved service-account token. If it does not exist, an
authorized owner or administrator creates it in `thefocusai.1password.com` and
saves the result in the project vault:

```bash
env -u OP_SERVICE_ACCOUNT_TOKEN op service-account create "<project>-sa" \
  --account thefocusai.1password.com \
  --vault "<Client> - <Project>:read_items"
```

Use `write_items` only for an authorized secret-management workflow, not merely
to run the app. The command displays the token once: keep its output out of
agent transcripts and save it through 1Password's secure UI.

Add the token as `OP_SERVICE_ACCOUNT_TOKEN` in each authorized cloud environment's
secret settings. In Amp, prefer project scope; a personal Amp secret applies
across that person's orbs and is not equivalent to retrieving a project token
with a personal 1Password identity. Cursor environment secrets apply to every
repository using that environment; choose the environment boundary accordingly
(`handbook/development.md`).

Record the token item's location, owner, vault scope, and receiving environments,
not its value. Recovery uses the person's 1Password access, not the lost token;
there is no universal same-vault or different-vault rule (`handbook/secrets.md`).
Never supply the person's account password, Secret Key, or login-session cache
to the agent, and never bake the token into an image or snapshot.

For a documented local-development exception only, `.fnox/env` is a gitignored
dotenv file with mode 600, loaded by mise's `_.file` directive. It is not needed
for cloud injection. Run the agent-instruction secret-file preflight before
creating it; do not copy an injected cloud token there.

### Ignore coverage

```text
.fnox/
.env
.env.*
!.env.example
```

The full template and `AGENTS.md` preflight own ignore coverage. Check each
intended secret path for both ignore coverage and existing Git tracking before
writing; patterns do not protect already tracked files.

### Initialize fnox

```bash
fnox provider add op 1password
# Edit fnox.toml: replace vault = "default" with vault = "<Client> - <Project>".
```

`fnox provider add` writes `vault = "default"` as a placeholder: always replace
it with the dedicated company project vault (`<Client> - <Project>` or
`<Client>`), never `"default"`, `"Private"`, `"Personal"`, `"Employee"`, or
`"Shared"`. Do **not** set `account = "thefocusai.1password.com"` inside
`[providers.op]`: fnox forwards `--account` to `op read`, which conflicts with
`OP_SERVICE_ACCOUNT_TOKEN`, whereas the scoped service-account token already
binds resolution exclusively to `thefocusai.1password.com` and its granted vault.

Example declarations (references, not secret values):

```toml
[providers.op]
type = "1password"
vault = "<Client> - <Project>"

[secrets.ANTHROPIC_API_KEY]
provider = "op"
value = "ANTHROPIC_API_KEY"
description = "Anthropic — https://console.anthropic.com/settings/billing"

[secrets.CLERK_SECRET_KEY]
provider = "op"
value = "CLERK_SECRET_KEY"

[secrets.NEXT_PUBLIC_CLERK_SIGN_IN_URL]
default = "/sign-in"

[secrets.OPTIONAL_FUTURE_KEY]
provider = "op"
value = "OPTIONAL_FUTURE_KEY"
if_missing = "ignore"

# An explicit profile can inherit the shared top-level declarations.
[profiles.runtime]
```

1Password item title = `value` is a convention, not an implicit lookup: include
the `value` reference. fnox's schema rejects arbitrary custom fields; put
dashboard URLs in `description`, not a custom `dashboard` or `usage_api` field.
Keep unprovisioned keys out of sync allowlists until they are required and issued.

### Import existing values (one-time migration)

The 1Password provider reads item references; `fnox set`/`import` are not a
substitute for creating those items. Use 1Password's secure UI for a small
import or a separately reviewed importer for the source format. Then add the
provider/item references to `fnox.toml`.

The former `while IFS='=' read ...` loop was not a dotenv parser: quotes,
multiline values and comments could be stored incorrectly. It also passed
passwords in process arguments and printed `FAILED` without failing the job.
It is intentionally not retained as an executable migration recipe. Do not
paste replacement secrets into shell commands or transcripts.

After checking ignore/untracked status, verify the required keys through the
app or an authorized `fnox check`, then remove only the now-disposable plaintext
source. A successful check that ignores an unprovisioned key does not verify it.

### Wire up application and operations tasks

With fnox activation, ordinary `package.json` commands inherit the selected
application environment. Without activation, wrap the application command in
`fnox --profile runtime exec -- ...`.

```json
{
  "scripts": {
    "dev": "pnpm --filter web dev",
    "build": "pnpm --filter web build",
    "start": "pnpm --filter web start"
  }
}
```

To run a workspace binary rather than a package script, use
`pnpm --filter web exec tsx ...`, not `pnpm --filter web tsx ...`.

Use the maintained `setup` task in `templates/default-project/mise.toml`. It is
the one command that gets a checkout ready, and it is safe to run again at any time:

- If the token in the environment can read the project vault, it changes nothing.
- If there is no token, or the token no longer reads the vault, it fetches the
  saved token from `thefocusai.1password.com` (`--account thefocusai.1password.com`)
  and writes the ignored, mode-600 `.fnox/env`, after checking that git ignores
  and does not track it. It refuses personal `my.1password.*` accounts and
  built-in `Private`, `Personal`, `Employee`, `Shared`, or `default` vaults.
- If neither works, it says what to fix: the cloud secret setting, or the
  person's sign-in and group membership in `thefocusai.1password.com`.

It then checks that every declared secret resolves. `OP_ACCOUNT_HOST` defaults
to `thefocusai.1password.com`; set the project vault (`OP_VAULT`) and the token
item's title (`OP_TOKEN_ITEM`) when adapting it to a project.
The other secret tasks are:

```toml
[tasks."secrets:check"]
description = "Verify declared required secrets resolve cleanly"
run = "fnox check"

[tasks."secrets:list"]
description = "List declared secrets and their sources without resolving values"
run = "fnox list"
```

After rotation, update the receiving cloud secret settings and refresh the
workspace processes using that platform's supported mechanism. On a person's own
machine, `mise run setup` notices the old token no longer works and replaces it;
there is no separate refresh task. It cannot update a cloud secret setting.

## Multi-environment (development / preview / production)

`handbook/secrets.md` makes production behavior the default for preview. Start from the
same configuration and integrations, then record only the differences needed
for deployment constraints or to prevent harmful side effects. A project vault
and suitably scoped runtime keys can be shared; a separate vault, account, or
key for every environment is not the default requirement.

Profiles select intended values; they do not have to select different vaults.
Keep preview writes off the production database (`handbook/secrets.md`), and record
each difference and its testing limits in the environment matrix. For example,
retain shared provider keys but override database references in a preview profile:

```toml
[profiles.preview.secrets.DATABASE_URL]
provider = "op"
value = "DATABASE_URL_PREVIEW"

[profiles.production.secrets.DATABASE_URL]
provider = "op"
value = "DATABASE_URL_PRODUCTION"
```

For hard isolation, the earlier separate-vault layout remains an option:

```toml
[profiles.dev.providers.op]
type = "1password"
vault = "<Project> - Dev"

[profiles.prod.providers.op]
type = "1password"
vault = "<Project> - Prod"
```

That layout needs separately scoped service-account tokens. A profile alone
is not an access boundary. The deployment target selects both profile and token
environment name; Vercel/runtime GSM mirrors receive neither bootstrap token.

### Verified fnox semantics

Source inspection at v1.45.0 [2–4] establishes:

- `--profile` takes precedence over `FNOX_PROFILE`; absent selection falls back
  to settings/default. `default` means the top-level config, not `[profiles.default]`.
- Named profiles inherit top-level secret/provider declarations, then overlay
  their own. Missing profiles fail. Sharing declarations does not prove that
  different vaults contain all the same items.
- `export --format json KEY ...` exports **only the named keys** as strings in
  `.secrets`, with `.metadata.profile` and `.metadata.total_secrets`. It can
  resolve referenced dependencies internally, but does not export those dependencies.
- The output is not a flat object and not a stream of `KEY=value` lines. JSON
  decoding preserves quotes, newlines, backslashes and JSON-valued strings.
- fnox's export `--dry-run` is **not** a no-resolution mode. The wrapper's
  default dry-run does not call fnox at all.
- `as_file = true` exports temporary-file paths, not contents. It is unsupported
  by this sync tool; configure runtime values as inline strings.

Use `fnox --profile NAME list` to inspect declared key names without resolving
them. Do not export the whole vault just to compare key sets. Authorized CI
checks select their profile explicitly and use only that profile's scoped token.

## Common sync contract

The replacement for the withdrawn bulk-sync snippets is
[`scripts/sync-secrets.mjs`](../scripts/sync-secrets.mjs), with
[`templates/secret-sync.example.json`](../templates/secret-sync.example.json).
Copy the script and adapt the JSON in a consuming project; the platform guides
own commands and provider setup. This repository itself does not need provider
credentials to run the offline tests.

The JSON maps a named target to:

- `platform`, `projectId`, and (Vercel) `teamId` and `environment`;
- `tokenEnv`: the injected platform credential's **environment name**, never its value;
- `source.config`: fnox file path relative to the JSON file;
- `source.profile` and `source.tokenEnv`: an explicit profile and the injected
  project-vault token's environment name;
- `keys`: a nonempty mapping of fnox runtime keys to destination environment
  names (Vercel) or pre-existing secret IDs (GCP).

The example deliberately shares profile `runtime` and runtime keys between
Preview and Production. It omits databases: add only the justified overrides
for a preview branch before allowing preview writes. Delete unused example
targets and replace project/team placeholders before applying.

**Safety behavior:**

- No default target. Without `--apply`, the script validates configuration and
  prints key/destination names; no credentials are read, no secrets resolved,
  and no provider requests made.
- An ambient `FNOX_PROFILE` mismatch fails even in dry-run. Unset it or choose
  the intended target; the child always receives an explicit `--profile`.
- The child has an isolated global fnox config/state directory, no daemon, and
  no ambient application variables or platform credentials. Only the selected
  project token is mapped to `OP_SERVICE_ACCOUNT_TOKEN`.
- Review the fnox file **and its imports**: use direct 1Password references and
  intentional non-secret defaults, not fallback values masking provider failures,
  sync caches, file-valued secrets, or administrative credentials renamed as runtime keys.
  This is not a TOML policy engine or sandbox for untrusted project configuration.
- Only allowlisted keys are requested; missing/extra keys, wrong profile metadata,
  invalid JSON, empty/non-string values, NUL and invalid Unicode fail before writes.
  Empty values are intentionally unsupported, not silently treated as deletion.
- Known admin/bootstrap/control-plane names, configured credential names and
  recognizable admin/bootstrap values are rejected. Name checks cannot identify
  every provider's master key: human review of key permissions remains necessary.
- Values stay in captured stdout and HTTPS request bodies, not shell arguments,
  generated env files, or logs. Provider bodies and subprocess error text are not
  printed. Keep shell tracing and external HTTP/debug tracing disabled too.
- Writes are sequential and **not atomic**. First failure stops later writes and
  exits nonzero, reporting confirmed destinations and the possibly applied current
  write. No deletion, rollback, automatic retry, or deployment is performed.
  Inspect provider state after partial or uncertain completion before retrying.
- Serialize sync jobs per destination and avoid concurrent dashboard edits.
  A dry-run validates a plan, not credentials, remote state, or runtime behavior.

## Onboarding a teammate

[Give and remove access](../handbook/access.md) owns groups, shared-service seats,
offboarding, and rotation. These steps cover only the workspace.

1. Open the repository in an Amp orb, Cursor cloud environment, or equivalent
   reproducible workspace. Its committed bootstrap installs the tools and dependencies.
2. Add the person to the project's group in `thefocusai.1password.com`. In a
   cloud workspace the project's secret settings already supply the token; if
   they do not, the person retrieves it from their seat in
   `thefocusai.1password.com` (never a personal `my.1password.com` account) and
   enters it there.
3. Run `mise run setup`. It confirms the token reads the vault, fetching it on
   the person's own machine if needed, then checks that secrets resolve. Resolve
   application secrets through fnox activation or `fnox exec --`, as in step 1
   above, then run `mise run dev`.
4. Review the app through the workspace portal or deployment preview. A teammate
   should not need your laptop, shell configuration, or local database.

During token rotation, update every recorded receiving environment, verify access,
and revoke the old service account. Do not treat successful presence checks as
verification that the new token has the right scope.

## Tracking key usage

fnox is a router, not a proxy: it cannot measure API usage. Store dashboard URLs
in secret descriptions and use the provider's billing dashboard. For automated
usage checks, run a separate authorized operational job with administrative
credentials and provider-supported reporting APIs; keep those keys out of app
profiles and sync allowlists. Use an HTTP library rather than passing bearer
values as `curl` arguments. The older unverified balance snippets are not a
runtime-secret deployment recipe.

Per-request attribution needs a proxy or instrumentation layer, for example
LiteLLM, Helicone, or an application-owned usage meter. That is separate from
secret storage and delivery.

## Security checklist

- [ ] Vault, service account, and saved token live in `thefocusai.1password.com`,
  never `my.1password.com` or `Private`/`Personal`/`Employee`/`Shared`/`default` vaults.
- [ ] Service account scoped to one project vault; review `op vault list` using
  the already injected token, not a token literal in the command.
- [ ] Secret-file preflight confirms intended paths are ignored and untracked.
- [ ] Only required runtime keys appear in each allowlist; credential scope reviewed.
- [ ] Preview shares production behavior; justified differences and testing limits recorded.
- [ ] Preview cannot write to the production database.
- [ ] Rotation owner, expiry, token location, and receiving environments recorded.
- [ ] Provider target/inventory reviewed after sync; runtime smoke check after deployment.
- [ ] An authorized member can recover the saved token through their seat in `thefocusai.1password.com`.
- [ ] No bootstrap token or personal session persisted into a shared image/snapshot.

## Verification and references

On 2026-10-30, fnox source and primary provider API documentation were read and
the Node tests exercised simulated fnox and HTTP adapters, including failure paths.
Run `node --test tests/test-secret-sync.mjs` offline. No real secret resolution,
provider credential validation, live write, or deployment was performed. Before
adoption, an authorized operator still verifies the pinned tools, IAM scopes,
provider behavior on a disposable target, then the application's runtime behavior.

[1] [fnox 1Password provider](https://fnox.jdx.dev/providers/1password),
checked 2026-10-29, plus `op service-account create --help` from mise-installed
`op` 2.41.1. Cloud secret scope/snapshot references remain in `handbook/development.md`.

[2] fnox v1.45.0,
[named-key export and JSON metadata](https://github.com/jdx/fnox/blob/48f328bbdb726b527dca0328bc52da30557d0dbd/src/commands/export.rs#L29-L200).

[3] fnox v1.45.0,
[profile selection and merging](https://github.com/jdx/fnox/blob/48f328bbdb726b527dca0328bc52da30557d0dbd/crates/fnox-core/src/config.rs),
and [CLI flags](https://github.com/jdx/fnox/blob/48f328bbdb726b527dca0328bc52da30557d0dbd/src/commands/mod.rs#L80-L133).

[4] fnox v1.45.0,
[resolution/fallback behavior](https://github.com/jdx/fnox/blob/48f328bbdb726b527dca0328bc52da30557d0dbd/crates/fnox-core/src/secret_resolver.rs#L700-L772).


---

# Deploy on GCP

Status: Reference
Source: https://github.com/The-Focus-AI/standards/blob/main/recipes/gcp.md
Relative links below resolve from recipes/gcp.md.


Follow [release guidance](../handbook/release.md) before changing a deployment.

Canonical pattern for deploying and operating Focus projects on Google Cloud.
Reference implementations:

| Project | Runtime | Pattern |
| --- | --- | --- |
| **foundtain-creek** (Fountain Creek) | Cloud Run (+ Scheduler, GCS, Secret Manager) | Named gcloud config + project-local ADC + `mise` deploy tasks |
| **qbsync** | App Engine (+ cron) | Isolated gcloud config `qb-to-sheets` + fnox at deploy time |

This recipe owns GCP secret delivery. The [fnox procedure](fnox.md) owns
bootstrap concepts and the sync contract. For Vercel apps see [Vercel deployment](vercel.md).

For the **habitats / Umwelten agent runtime** (GCE VM, Docker-out-of-Docker,
self-hosted GitHub runner, no PR previews on GCP), see `evidence/gaia-runtime.md` —
that CD shape does not apply to Cloud Run.

## Defaults

| Concern | Standard |
| --- | --- |
| CLI | `gcloud` pinned via mise — not Homebrew for project tooling |
| Project isolation | One **named gcloud configuration** per GCP project / client |
| Shell activation | Set `CLOUDSDK_ACTIVE_CONFIG_NAME` (and related vars) in **`mise.toml` `[env]`** |
| Deploy commands | Explicit `--project` and `--region` in mise tasks (never rely on “whatever is active”) |
| User auth | `mise run auth` → `gcloud auth login` + Application Default Credentials |
| Automation | Prefer **service account impersonation** or Workload Identity; avoid downloaded SA key JSON when org policy allows |
| App secrets | 1Password → fnox in an authorized cloud job → **Secret Manager**; Cloud Run binds secret references, not values |
| Preferred compute for new services | **Cloud Run** (source deploy or image). Use App Engine when the existing project already standardized on it (qbsync). Agent orchestration that needs a host Docker daemon → `evidence/gaia-runtime.md`. |

## Mental model

gcloud config precedence (highest wins):

1. Command-line flags (`--project`, `--region`)
2. Environment variables (`CLOUDSDK_CORE_PROJECT`, `CLOUDSDK_ACTIVE_CONFIG_NAME`, …)
3. Active named configuration
4. Default configuration

Treat named configurations as profiles. The failure mode to prevent is deploying
to the wrong project. Make context automatic in the repo (mise `[env]`) and
still pass `--project` / `--region` in every deploy task.

## Project-local mise setup

### Tools and env

Pin tested `gcloud` and fnox versions through mise (the sync source contract
checked here is fnox v1.45.0; `recipes/fnox.md` records its limits). Configure the
non-secret project context separately:

```toml
[env]
CLOUDSDK_ACTIVE_CONFIG_NAME = "foundtaincreek"   # or qb-to-sheets, client-acme, …
GOOGLE_CLOUD_PROJECT = "foundtaincreek"
GOOGLE_CLOUD_REGION = "us-central1"
# Optional: project-local ADC so libraries don't depend on ~/.config/gcloud
# GOOGLE_APPLICATION_CREDENTIALS = "{{config_root}}/.adc.json"
```

Add `.adc.json` (if used) to `.gitignore`. Do **not** commit credential files.

### Create and authenticate a named configuration

```bash
# One-time (also encapsulate as mise run auth — see fountain creek / qbsync)
gcloud config configurations create foundtaincreek
gcloud config configurations activate foundtaincreek
gcloud config set project foundtaincreek
gcloud config set compute/region us-central1
gcloud auth login
gcloud auth application-default login
```

qbsync pattern — isolate without touching the user’s default config:

```bash
export CLOUDSDK_ACTIVE_CONFIG_NAME=qb-to-sheets
# Create once; if it already exists, inspect it rather than suppressing errors.
gcloud config configurations create qb-to-sheets
gcloud auth login
gcloud auth application-default login
```

Fountain Creek additionally copies ADC into a **project-local** `.adc.json` and
patches `quota_project_id`, so libraries use repo-scoped credentials via mise
`GOOGLE_APPLICATION_CREDENTIALS`. Prefer that when multiple GCP projects are
open on one machine.

### Required mise tasks

| Task | Purpose |
| --- | --- |
| `mise run auth` | Login + ADC (+ create named config if missing) |
| `mise run auth-status` | Show active config, project, ADC path / quota project |
| `mise run deploy` or `deploy-<service>` | Deploy with explicit `--project` / `--region` |
| `mise run watch-logs` / log helpers | Tail Cloud Run or App Engine logs for this project |

Optional but useful: `auth-revoke`, `enable-apis`, `deploy-all`, Scheduler setup
tasks (see foundtain-creek `mise.toml`).

## Cloud Run (Fountain Creek pattern)

Use for HTTP services, webhooks, workers triggered by Eventarc/Scheduler.
Run production builds/deploys in CI (`handbook/release.md`); `--source .` below is
Cloud Build input, not authorization to release an unreviewed workspace.

```bash
gcloud run deploy SERVICE \
  --source . \
  --project "$GOOGLE_CLOUD_PROJECT" \
  --region "$GOOGLE_CLOUD_REGION" \
  --set-env-vars "GCS_BUCKET=…,NON_SECRET=…" \
  --set-secrets "NOTION_API_KEY=notion-api-key:latest,…" \
  --memory 512Mi \
  --timeout 300s
  # --allow-unauthenticated   # only for public webhooks/front doors
  # --no-allow-unauthenticated  # default for internal APIs
```

Conventions:

- One mise task per service (`deploy-invoice-parse`, …); `deploy-all` depends on them.
- Non-secrets via `--set-env-vars`; secrets via **Secret Manager** + `--set-secrets`.
- Public only when required (Notion/Xero OAuth callbacks, public dashboards).
- Polling / periodic work: **Cloud Scheduler** → Cloud Run with OIDC to the
  runtime service account (see `setup-drive-watcher-scheduler` in foundtain-creek).
- Prefer `--source .` for small Node/Python services; use Artifact Registry images
  when build is heavy or multi-service.

### Secrets on Cloud Run

Two patterns; this is their platform owner. Bootstrap, profile semantics and
runtime-key allowlists are in `recipes/fnox.md`. Both keep 1Password authoritative.

| Pattern | When | How |
| --- | --- | --- |
| **A — fnox at start** | A deliberate runtime dependency on 1Password is acceptable | GSM holds the scoped bootstrap token; a verified image runs fnox before the app |
| **B — GSM mirrors 1P** | Prefer native runtime delivery, no 1P call at cold start | Authorized job syncs allowlisted values; Cloud Run binds numeric GSM versions |

Pattern B is the default here. Pattern A does not have a measured latency claim
or a ready-to-use runtime image in this corpus; validate it for the application.
Fountain Creek's original examples use native Secret Manager bindings. qbsync's
legacy App Engine deploy-time configuration is a separate path, not evidence
that Cloud Run needs fnox in the runtime image.

#### Pattern B: sync runtime values to existing GSM secrets

1. Copy `scripts/sync-secrets.mjs` and adapt `templates/secret-sync.example.json`
   as `secret-sync.json` at the consuming repo root. Keep only relevant GCP
   targets. Pin Node/fnox through mise as described in `recipes/fnox.md`.
2. Set each target's explicit GCP `projectId` and `keys` mapping (fnox runtime
   key → secret ID). The example uses separate preview/production GCP projects
   but the same `runtime` source profile and provider keys. A single project
   with distinct secret IDs/services is also possible. Separate projects are an
   isolation choice, not a requirement to duplicate all runtime credentials.
3. Provision secret containers separately through reviewed infrastructure or
   the console, with the intended replication/residency policy. The sync tool
   adds versions only: a missing secret fails, never triggers auto-creation.
4. Grant the sync identity **Secret Manager Secret Version Adder**
   (`roles/secretmanager.secretVersionAdder`) on only those secret resources [3].
   It does not need value-read, deletion or project-admin permissions. Give
   the Cloud Run runtime identity **Secret Accessor** on its required secrets,
   not the sync role. Document both identities and the project/resource scope.
5. An authorized CI job uses Workload Identity Federation or impersonation to
   obtain a short-lived OAuth access token with the `cloud-platform` scope and
   inject it as the target's `tokenEnv` (for example `GCP_PREVIEW_ACCESS_TOKEN`).
   The separate `source.tokenEnv` holds the project-vault bootstrap token.
   The script never discovers ADC, an active gcloud project, or a personal login.
   It cannot prove a token's IAM scope offline; verify the issuing identity and
   grants when provisioning the job. Do not commit or log either token.
6. Review the dry-run plan, then explicitly apply from the authorized job.

```bash
node scripts/sync-secrets.mjs --config secret-sync.json --target gcp-preview
# After plan review and authorization:
node scripts/sync-secrets.mjs --config secret-sync.json --target gcp-preview --apply
```

Expose that command as a forwarding `gcp:sync` mise task in the consuming
project, retaining mandatory `--target` and optional `--apply`. No target is
selected by ambient gcloud configuration or `FNOX_PROFILE`.

The supported REST write [1] is
`POST https://secretmanager.googleapis.com/v1/projects/PROJECT/secrets/SECRET:addVersion`.
The script sends `payload.data` as base64 of the exact UTF-8 string in an HTTPS
JSON body [2]. Quotes, embedded JSON and trailing newlines are preserved, not
shell-decoded or trimmed. Values above 64 KiB fail before any writes. Regional
Secret Manager endpoints are outside this implementation's scope.

The CLI alternative `gcloud secrets versions add SECRET --data-file=-` supports
stdin and fails for a missing container [5]; the maintained script uses REST,
not a shell loop. Neither credential values nor payloads are command arguments.

Each successful call creates a **new version**, even for an unchanged value.
Capture the printed version resource names in the release evidence. First failure
stops later writes and exits nonzero with confirmed destinations; the current
write may have landed. There is no transaction, rollback, pruning or automatic
retry. Inspect versions/audit records before retrying, since retries can add
duplicate versions. A partial sync is not a successful release.

#### Bind and verify the versions

Use the confirmed numeric version for each environment-variable binding [4].
`latest` can leave old and new instances with different values across starts;
adding a version alone does not refresh a running app. For example, from the
approved CI deployment job, with non-secret identifiers set explicitly:

```bash
gcloud run deploy "$SERVICE" \
  --configuration "$GCLOUD_CONFIGURATION" \
  --project "$GCP_PROJECT_ID" \
  --region "$GCP_REGION" \
  --impersonate-service-account "$DEPLOY_SERVICE_ACCOUNT" \
  --service-account "$RUNTIME_SERVICE_ACCOUNT" \
  --image "$CI_IMAGE_DIGEST" \
  --update-secrets "CLERK_SECRET_KEY=app-clerk-secret-key:${CLERK_SECRET_VERSION}"
```

The flag contains secret **references**, not values. `--update-secrets` retains
unrelated bindings; `--set-secrets` replaces the binding set, so the latter is
appropriate only when the full intended set is supplied. Verify the new revision's
bindings and runtime behavior without printing secret data. Runtime bindings do
not inject build-time variables into a previously built image.

#### Pattern A: fnox at container start

The container has fnox installed through the repository's mise configuration and
an explicitly selected runtime-only profile. Build and verify that image in CI;
there is no supported `https://fnox.jdx.dev/install.sh` recipe here. Its entrypoint
shape is `fnox --profile runtime exec -- <app>`.

A person retrieves the project-scoped bootstrap token from 1Password and enters
it into the intended project's GSM secret through secure cloud secret settings
(`handbook/secrets.md`). This is a bootstrap operation, **not** a runtime allowlist entry:
the sync tool intentionally refuses `OP_SERVICE_ACCOUNT_TOKEN`.

Grant the runtime identity Secret Accessor only on that bootstrap secret and bind
its numeric version to `OP_SERVICE_ACCOUNT_TOKEN` using the same explicit
project/region/identity deploy pattern above. fnox then resolves application values
at startup. The runtime now holds a vault-reading credential and depends on
1Password/network availability; assess that wider blast radius before choosing A.
On rotation, update the token/value upstream and deploy a new revision, then verify.

For GKE, the analogous delivery is a reviewed Secret Manager CSI integration or
External Secrets Operator plus a pod secret reference. For Compute Engine, use
the VM identity with Secret Manager access; if an operational design requires a
systemd `EnvironmentFile`, protect its ownership/mode and lifecycle rather than
treating `/etc/fnox/token` as disposable. Those adapters are not tested by this
Cloud Run/GSM sync implementation.

## App Engine (qbsync pattern)

Use when the project is already on App Engine (cron + Flask, etc.).

```toml
[tasks.deploy]
run = '''
set -euo pipefail
export CLOUDSDK_ACTIVE_CONFIG_NAME=qb-to-sheets
# stage any generated data the app bundle needs
fnox exec -- ./deploy steering_house app --quiet
./deploy steering_house cron --quiet
'''
```

Conventions:

- Isolated config name matching the GCP project (e.g. `qb-to-sheets`).
- `mise run deploy` is the only supported ship path; document data-staging steps
  so generated JSON is included in the App Engine bundle.
- Logs: `gcloud app logs tail --project=…` behind `mise run watch-logs`.

## Multi-project / multi-client machines

1. One named configuration per GCP project (`client-acme-prod`, `foundtaincreek`, …).
2. Each repo sets `CLOUDSDK_ACTIVE_CONFIG_NAME` in its own `mise.toml`.
3. Deploy scripts always pass `--project` / `--region`.
4. Prefer **service account impersonation** over SA key files:

   ```bash
   gcloud run deploy my-service \
     --source . \
     --project "$GOOGLE_CLOUD_PROJECT" \
     --region "$GOOGLE_CLOUD_REGION" \
     --impersonate-service-account=deploy-sa@PROJECT.iam.gserviceaccount.com
   ```

5. CI: GitHub Actions + **Workload Identity Federation** (no keys). See the
   multi-project report references.

Do **not** use direnv as the primary switcher in new projects — mise `[env]` is
the org standard. The older report mentions direnv; treat that as background
research only.

## Auth troubleshooting

If `gcloud run deploy` prompts **"Reauthentication required"** on macOS, the
password is usually a **Keychain** passphrase or Google reauth — not a GCP API
key. Prefer:

1. Re-run `mise run auth` / ADC refresh.
2. Cloud Shell deploy when local Keychain is blocked.
3. CI + Workload Identity for unattended deploys.

Avoid downloading SA JSON keys when org policy
`iam.disableServiceAccountKeyCreation` is on (common). Fountain Creek’s
`docs/gcloud-auth.md` documents the Keychain case in detail — keep that
project-local; this standard prefers impersonation / WIF / Cloud Shell.

## Anti-patterns

- Deploying without verifying project (`gcloud config get-value project` or
  explicit `--project`).
- Homebrew / global gcloud as the only install — pin via mise in the project.
- Shared “default” gcloud config for every client repo.
- Long-lived service account key files in the repo or home directory when
  impersonation/WIF is available.
- Putting secret values in `--set-env-vars` instead of Secret Manager / fnox.
- Assuming ADC (`application-default login`) and `gcloud auth login` are the
  same — client libraries need ADC; the CLI uses its own credentials.
- Hardcoding another client’s project ID in a shared script without an env override.

## New GCP project checklist

- [ ] GCP project created; billing and required APIs enabled (`mise run enable-apis`)
- [ ] Named gcloud configuration; `CLOUDSDK_ACTIVE_CONFIG_NAME` in `mise.toml`
- [ ] `gcloud` (and `fnox` if needed) in `[tools]`; `mise run auth` / `auth-status`
- [ ] `.adc.json` / key files gitignored
- [ ] Deploy tasks with explicit `--project` and `--region`
- [ ] Secrets in 1Password + Secret Manager (or documented fnox-at-start pattern)
- [ ] Log/tail tasks for the chosen runtime (Cloud Run or App Engine)
- [ ] Scheduler / Eventarc wired if the design needs polling or GCS triggers
- [ ] Smoke deploy + `gcloud run services list` / App Engine versions check

## Where the source material lives

| Source | Role |
| --- | --- |
| `foundtain-creek/reports/2026-02-02-gcloud-cloud-run-multi-project.md` | Original research; retained in this repository's Git history |
| `foundtain-creek/mise.toml` + `docs/gcloud-*.md` | Cloud Run + auth tasks |
| `qbsync/mise.toml` | App Engine + isolated config + fnox deploy |
| `recipes/fnox.md` | Bootstrap, fnox semantics and common sync contract; GCP procedures stay here |

## Verification and primary sources

Checked 2026-10-30: reachable Google API/CLI documentation and offline simulated
fnox/transport tests (`node --test tests/test-secret-sync.mjs`). No real credential
read, provider write, IAM change or deployment was performed. The existing
application-specific deploy wrappers above were not executed. Before adoption,
an authorized operator verifies a disposable target, identity scope, version
creation and runtime delivery; simulated tests do not establish live IAM access.

[1] Google Cloud, [Secret Manager addVersion](https://cloud.google.com/secret-manager/docs/reference/rest/v1/projects.secrets/addVersion).

[2] Google Cloud, [SecretPayload encoding and size](https://cloud.google.com/secret-manager/docs/reference/rest/v1/SecretPayload).

[3] Google Cloud, [Secret Manager IAM roles and resource scope](https://cloud.google.com/secret-manager/docs/access-control).

[4] Google Cloud, [Cloud Run secret bindings and version pinning](https://cloud.google.com/run/docs/configuring/services/secrets).

[5] Google Cloud, [gcloud secrets versions add](https://cloud.google.com/sdk/gcloud/reference/secrets/versions/add).


---

# Generate the agent Dockerfile

Status: Reference
Source: https://github.com/The-Focus-AI/standards/blob/main/recipes/generate-dockerfile.md
Relative links below resolve from recipes/generate-dockerfile.md.


Produce a `Dockerfile` that packages this standards repo into a containerized
development environment. The image provides a ready-to-use `/standards` with
all tooling available after `mise install`. `/app` is left empty as a sandbox
for whatever project the user scaffolds with `skills/setup-project/SKILL.md`.

The Dockerfile is the only artifact — write the file, do not explain.

## Constraints (hard requirements — do not deviate)

### Base image and user

- **`debian:stable-slim`** as the base image.
- Create a non-root user named **`agent`** with home at `/home/agent`.
- Switch to `USER agent` as soon as the user is created and **never switch back
  to root**. Use `COPY --chown=agent:agent` when copying files.
- Create `/standards` and `/app` directories, both owned by `agent`. `/app` is
  left **completely empty** — no mise.toml, no .gitignore, no tools, no config.
  It is a blank sandbox for the user's project.

### System packages

Install these packages (and only these) via `apt-get`:
`curl`, `ca-certificates`, `git`, `tmux`, `unzip`, `build-essential`.

Do **not** install **GitHub CLI** (`gh`) via `apt-get` or an apt repository.

Do NOT install zsh. Bash is the only shell.

### mise

- `mise` is the primary tooling dependency baked into the image. **GitHub CLI**
  (`gh`) is the only exception and must be installed through project-scoped
  `mise use gh@latest`. Everything else (Node, pi, fnox, firecrawl-cli, etc.)
  flows from `mise install` inside `/standards` at runtime.
- Install mise via `curl https://mise.run | sh` as the `agent` user. This lands
  the binary at `/home/agent/.local/bin/mise`. Add `/home/agent/.local/bin` to
  `PATH` via ENV.
- **Do NOT run `mise install` at build time.** The user runs it manually.
- **Do run `mise trust /standards` at build time** so the user doesn't hit a
  trust prompt at runtime.
- Install **GitHub CLI** (`gh`) via project-scoped mise after copying
  `/standards`: `cd /standards && mise use gh@latest`. This may update the
  repo's mise config in the image; do not use apt for `gh`.
- **NEVER use `mise -g` (global).** All mise operations are project-scoped.

### Shell activation

Write mise activation to **both** `.bashrc` and `.bash_profile` so it works
whether the user runs `docker run ... bash` (non-login) or `docker run ...`
(login shell via CMD).

```bash
eval "$($HOME/.local/bin/mise activate bash)"
```

### tmux

Bake a minimal `~/.tmux.conf` (required by the pi-tmux extension):

```tmux
set -g mouse on
set -g extended-keys on
set -g extended-keys-format csi-u
```

### Git config

Set default identity so git operations work immediately:

```bash
git config --global user.name "TheFocus.AI"
git config --global user.email "agent@thefocus.ai"
```

### /standards

- `COPY --chown=agent:agent . /standards` to put the entire standards repo
  into the image.
- Do NOT set a WORKDIR — the CMD determines the working directory.

### CMD

```dockerfile
CMD ["/bin/bash", "-l"]
```

## Runtime contract (document in Dockerfile comments at the top)

The generated Dockerfile must include comments at the top documenting:

1. **Provenance:** `Generated from recipes/generate-dockerfile.md.`
   `Do not hand-edit; edit the prompt and regenerate with mise run generate:dockerfile.`
2. **Build:** `docker build -t focus-ai-standards-agent .`
3. **Run in a cloud workspace:**
   `docker run -it --rm --env OPENAI_API_KEY --env OP_SERVICE_ACCOUNT_TOKEN focus-ai-standards-agent`
   These names forward already-injected, project-scoped credentials only when needed.
   Use the selected model provider's variable instead of `OPENAI_API_KEY` if different.
4. **First steps inside the container:**

   ```bash
   cd /standards
   mise install
   mise run install
   pi -p "$(cat skills/setup-project/SKILL.md)"   # supply a project brief; target /app
   ```

5. A person retrieves the project-scoped bootstrap token through their seat in
   TheFocus.AI's company 1Password account (`thefocusai.1password.com`, never a
   personal `my.1password.com` account) and injects it through cloud secret
   settings. Do not mount personal authentication directories (`~/.pi`,
   `~/.config`, `~/.ssh`, or a 1Password session), persist tokens, or bake
   credentials into the image. Installation and offline checks do not need those
   runtime credentials.
6. Sessions are ephemeral (lost when the container exits). Store durable project
   work in an approved workspace, not a personal auth-directory mount.

## What NOT to do

- Do NOT install zsh or configure `.zshrc`.
- Do NOT create `/app/mise.toml` or any file inside `/app`.
- Do NOT install fnox, 1Password CLI, or configure secrets.
- Do NOT run `mise install` at build time.
- Do NOT install pi extensions (`pi install`). The `/standards/.pi/settings.json`
  declares them and pi auto-installs missing packages on startup.
- Do NOT install skills (`npx skills add`). They live in the standards repo
  and the user's project installs its own.
- Do NOT set up systemd, linger, or `loginctl`.
- Do NOT switch back to root after `USER agent`.
- Do NOT use `mise -g` (global install).


---

# Build and release single-file macOS menu bar apps

Status: Reference
Source: https://github.com/The-Focus-AI/standards/blob/main/recipes/macos-menubar-app.md
Relative links below resolve from recipes/macos-menubar-app.md.


Native macOS menu bar utilities need hardware, WindowServer, and TCC permissions
that Linux cloud containers cannot exercise. Record that local/macOS runner
exception in the project's `AGENTS.md` ([development](../handbook/development.md))
and follow the approval and release gates in [release](../handbook/release.md).

## Keep one Swift source file, two execution modes

Keep each utility in a single `<app>.swift` file with `#!/usr/bin/env swift` at line 1
and zero external Swift Package Manager dependencies (`Cocoa`, `Foundation`,
`SwiftUI`, `CoreBluetooth`, `CoreLocation`, `CoreWLAN`, `CoreServices`, `MapKit`).

- **Script mode (`./app.swift`)**: fast iteration without Xcode or `.xcodeproj` state.
- **Bundle mode (`AppName.app`)**: required for distribution, Login Items, and
  per-app TCC permissions (`Bluetooth`, `Location`, Wi-Fi SSID access). Running raw
  `./app.swift` borrows the parent terminal's TCC identity instead of the app's.

Separate pure data models, parsers, layout math, and state machines from `AppKit`
controllers, and place a single `// MARK: - Main Entry Point` marker immediately
before `NSApplication` startup so headless CLI flags and unit tests can bypass UI
boot cleanly.

## Support headless CLI inspection and runtime version truth

GUI menu bar apps are opaque to CI and remote debugging unless they expose text
entry points. Implement at least `--version` and `--dump-menu` in every utility,
and flush `stdout` (`fflush(stdout)`) after log lines so piped processes do not
lose buffered output when terminated.

Read the version string from `Bundle.main.infoDictionary` rather than hardcoding a
second constant in Swift:

```swift
func appVersionText() -> String {
    let info = Bundle.main.infoDictionary
    let short = (info?["CFBundleShortVersionString"] as? String)?
        .trimmingCharacters(in: .whitespacesAndNewlines)
    let build = (info?["CFBundleVersion"] as? String)?
        .trimmingCharacters(in: .whitespacesAndNewlines)
    guard let short, !short.isEmpty else { return "development build" }
    guard let build, !build.isEmpty else { return short }
    return "\(short) (\(build))"
}
```

Display `<AppName> \(appVersionText())` as a disabled `NSMenuItem` directly above
`Quit <AppName>` (`⌘Q`), and render the real `NSMenu` off-screen for `--dump-menu`:

```swift
func printMenuDump(title: String, menu: NSMenu) {
    print("TITLE: \(title)")
    for item in menu.items {
        if item.isSeparatorItem {
            print("  ---")
        } else {
            let text = item.attributedTitle?.string ?? item.title
            let checked = item.state == .on ? " [checked]" : ""
            print("  \(text)\(checked)")
        }
    }
    fflush(stdout)
}
```

Recommended CLI flags for hardware/network monitors:

- `--version` / `-V`: print `<AppName> <short> (<build>)` and exit `0`.
- `--dump-menu`: populate the real `NSMenu`, print items as text, and exit `0`.
- `--once`: take one reading/probe, print `key=value` output, and exit `0` (or `1` on timeout).
- `--quit`: post a quit notification on `DistributedNotificationCenter` and terminate
  running instances matched via `NSRunningApplication.runningApplications(withBundleIdentifier:)`.

## Handle `LSUIElement` menu bar UX edge cases

Menu bar apps run with `LSUIElement = true` and `app.setActivationPolicy(.accessory)`
(no Dock icon). Handle four macOS behaviors explicitly:

1. **Finder reopen**: double-clicking an already-running `LSUIElement` app in Finder
   does nothing by default, making the app appear broken. Implement
   `applicationShouldHandleReopen` to open the main window or pop the status menu:

   ```swift
   func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
       statusItem?.button?.performClick(nil)
       return true
   }
   ```

2. **MacBook camera notch occlusion**: on crowded menu bars, macOS places new
   `NSStatusItem`s underneath the camera housing where they are invisible. Check
   visibility ~1.5s after launch and surface a window if occluded:

   ```swift
   if let screen = NSScreen.main,
      let left = screen.auxiliaryTopLeftArea,
      let right = screen.auxiliaryTopRightArea,
      let frame = statusItem?.button?.window?.frame {
       let notchGap = NSRect(
           x: left.maxX, y: left.minY,
           width: max(0, right.minX - left.maxX), height: left.height
       )
       if notchGap.width > 0, frame.intersects(notchGap) {
           showMainWindow()
       }
   }
   ```

3. **RunLoop modes while the menu is open**: `Timer.scheduledTimer` schedules on
   `.default` mode, which pauses while an `NSMenu` is open (`NSEventTrackingRunLoopMode`).
   Register live timers and `FSEventStream`s on `.common` / `commonModes`:

   ```swift
   RunLoop.main.add(timer, forMode: .common)
   ```

4. **Subprocess timeouts off the main thread**: never call `Timer.scheduledTimer`
   inside `DispatchQueue.global().async` — global GCD threads have no active RunLoop,
   so the timer never fires. Use a `DispatchWorkItem` with `asyncAfter` and cancel it
   after `task.waitUntilExit()`, and resolve Homebrew tools across both
   `/opt/homebrew/bin` (Apple Silicon) and `/usr/local/bin` (Intel).

## Keep storage outside iCloud Drive and guard polling

- **Store app data in `~/Library/Application Support/<AppName>/`**: never write
  high-frequency logs or caches to `~/Documents` or `~/Desktop`. Those folders are
  commonly backed by iCloud Drive (`bird`), which evicts files to cloud-only stubs
  and triggers TCC prompts or multi-second main-thread hangs on read.
- **Keep file I/O off the main thread**: parse and append logs on a dedicated serial
  `DispatchQueue`, caching parsed records keyed by `(fileSize, contentModificationDate)`.
- **Prevent overlapping probes**: guard periodic network or CLI checks with an
  `inFlight` boolean and an incrementing `generation` counter so stale callbacks are
  discarded after state resets or Wi-Fi transitions.
- **Prefer passive BLE over active GATT connections**: when reading BLE sensors that
  broadcast advertisements, scan passively (`CBCentralManagerOptionShowPowerAlertKey: false`
  with an explicit in-menu radio/permission state) and connect only on user-initiated
  history syncs.
- **Render missing data honestly**: break chart/map polylines across time gaps and
  right-align sparse sample strips instead of stretching two samples across the full
  width.

## Unit test single-file Swift without Xcode

Strip everything from `// MARK: - Main Entry Point` downward with `sed`, append a
test harness, and compile with `swiftc`. This runs in seconds on both developer Macs
and GitHub Actions `macos-latest` runners:

```sh
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
TEST_DIR="$(mktemp -d "${TMPDIR:-/tmp}/app-tests.XXXXXX")"
trap 'rm -rf "$TEST_DIR"' EXIT

sed '/\/\/ MARK: - Main Entry Point/,$d' app.swift > "$TEST_DIR/main.swift"
cat tests/checks.swift >> "$TEST_DIR/main.swift"

CLANG_MODULE_CACHE_PATH="$TEST_DIR/modulecache" \
  swiftc -O "$TEST_DIR/main.swift" -o "$TEST_DIR/checks"
"$TEST_DIR/checks" "$@"
```

## Generate `.icns` icons reproducibly from code

Check in a deterministic `make_icon.py` alongside `AppIcon.icns` so icons can be
tweaked and regenerated without binary design files:

1. Render artwork at `4096x4096` in RGBA using Python `Pillow`.
2. Draw semi-transparent highlights or shadows onto separate `Image.new("RGBA", ...)`
   layers and composite with `art.alpha_composite(layer)` — drawing `alpha < 255`
   shapes directly onto an opaque `RGBA` canvas with `ImageDraw` overwrites
   destination alpha and punches transparent holes in the icon.
3. Apply a macOS squircle mask (`824/1024` canvas ratio, ~22.5% corner radius),
   downsample with `Image.Resampling.LANCZOS` into the 10 standard `.iconset` PNG
   sizes (`icon_16x16.png` through `icon_512x512@2x.png`), and convert via native
   `iconutil`:

```sh
python3 make_icon.py   # writes icon-1024.png + AppIcon.icns via iconutil -c icns
```

## Package universal `.app` bundles and publish releases

Use reverse-DNS Bundle IDs (`ai.thefocus.<slug>`), compile universal binaries
(`arm64` + `x86_64`) via `swiftc` + `lipo`, validate `Info.plist` with `plutil -lint`,
and archive with `ditto -c -k --keepParent` (never plain `zip`, which strips bundle
extended attributes and breaks signatures):

```sh
#!/usr/bin/env bash
set -euo pipefail

APP_NAME="${APP_NAME:?}"
BUNDLE_ID="${BUNDLE_ID:?}"
SOURCE_FILE="${SOURCE_FILE:?}"
VERSION="${VERSION:-1.0.0}"
BUILD_NUMBER="${BUILD_NUMBER:-1}"
MIN_MACOS="${MIN_MACOS:-12.0}"
CODESIGN_IDENTITY="${CODESIGN_IDENTITY:--}"

BUNDLE_DIR="${APP_NAME}.app"
BIN="${BUNDLE_DIR}/Contents/MacOS/${APP_NAME}"
BUILD_TMP="$(mktemp -d "${TMPDIR:-/tmp}/${APP_NAME}-build.XXXXXX")"
trap 'rm -rf "${BUILD_TMP}"' EXIT

rm -rf "${BUNDLE_DIR}"
mkdir -p "${BUNDLE_DIR}/Contents/MacOS" "${BUNDLE_DIR}/Contents/Resources" "${BUILD_TMP}/modulecache"

compile_arch() {
  swiftc -O -module-cache-path "${BUILD_TMP}/modulecache" \
    -target "$1-apple-macosx${MIN_MACOS}" "${SOURCE_FILE}" -o "$2"
}

if compile_arch arm64 "${BUILD_TMP}/arm64" && compile_arch x86_64 "${BUILD_TMP}/x86_64"; then
  lipo -create "${BUILD_TMP}/arm64" "${BUILD_TMP}/x86_64" -output "${BIN}"
else
  compile_arch "$(uname -m)" "${BIN}"
fi

[ -f AppIcon.icns ] && cp AppIcon.icns "${BUNDLE_DIR}/Contents/Resources/AppIcon.icns"

cat > "${BUNDLE_DIR}/Contents/Info.plist" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>CFBundleExecutable</key><string>${APP_NAME}</string>
  <key>CFBundleIdentifier</key><string>${BUNDLE_ID}</string>
  <key>CFBundleName</key><string>${APP_NAME}</string>
  <key>CFBundlePackageType</key><string>APPL</string>
  <key>CFBundleShortVersionString</key><string>${VERSION}</string>
  <key>CFBundleVersion</key><string>${BUILD_NUMBER}</string>
  <key>LSMinimumSystemVersion</key><string>${MIN_MACOS}</string>
  <key>LSUIElement</key><true/>
  <key>NSHighResolutionCapable</key><true/>
  <key>CFBundleIconFile</key><string>AppIcon</string>
</dict>
</plist>
EOF

plutil -lint "${BUNDLE_DIR}/Contents/Info.plist" >/dev/null

if [ "${CODESIGN_IDENTITY}" = "-" ]; then
  codesign --force --deep --sign - "${BUNDLE_DIR}"
else
  codesign --force --deep --options runtime --timestamp --sign "${CODESIGN_IDENTITY}" "${BUNDLE_DIR}"
fi
codesign --verify --deep --strict "${BUNDLE_DIR}"

ditto -c -k --keepParent "${BUNDLE_DIR}" "${APP_NAME}-${VERSION}.zip"
shasum -a 256 "${APP_NAME}-${VERSION}.zip" > "SHA256SUMS-${VERSION}.txt"
```

### Signing tiers: ad-hoc vs Developer ID notarization

- **Internal or alpha tools (`CODESIGN_IDENTITY="-"`)**: ad-hoc signing gives macOS
  TCC a stable code structure without requiring Apple Developer certificates in CI.
  Document the one-time Gatekeeper quarantine removal in release notes:

  ```sh
  xattr -dr com.apple.quarantine /Applications/<AppName>.app
  ```

- **External or client distribution**: sign with a `Developer ID Application`
  certificate (`--options runtime --timestamp`), submit the `ditto` `.zip` with
  `xcrun notarytool submit --wait`, staple the ticket to `<AppName>.app` via
  `xcrun stapler staple`, and re-create the distributable `.zip` with `ditto`.

### Per-app tag releases in a multi-app repository

When several single-file utilities share one repository, tag each app independently
as `<app>-v<version>` (for single-app repositories, `v<version>` is sufficient) and
verify slices, signatures, and `--version` on `macos-latest` before publishing:

```yaml
name: release
on:
  push:
    tags: ["*-v[0-9]*"]
permissions:
  contents: write
jobs:
  release:
    runs-on: macos-latest
    steps:
      - uses: actions/checkout@v4
      - name: Build, verify, and publish
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          TAG="${GITHUB_REF_NAME}"
          APP="${TAG%-v*}"
          VERSION="${TAG##*-v}"
          [ -f "${APP}/tests/run.sh" ] && bash "${APP}/tests/run.sh"
          VERSION="${VERSION}" BUILD_NUMBER="${GITHUB_RUN_NUMBER}" bash "${APP}/package.sh"
          for BUNDLE in "${APP}"/*.app; do
            BIN="${BUNDLE}/Contents/MacOS/$(basename "${BUNDLE}" .app)"
            lipo -archs "${BIN}"
            codesign --verify --deep --strict "${BUNDLE}"
            "${BIN}" --version
          done
          (cd "${APP}" && shasum -a 256 ./*-"${VERSION}.zip" > "SHA256SUMS-${VERSION}.txt")
          gh release create "${TAG}" "${APP}"/*-"${VERSION}.zip" "${APP}/SHA256SUMS-${VERSION}.txt" \
            --title "${APP} v${VERSION}" --generate-notes
```


---

# Deploy on Vercel

Status: Reference
Source: https://github.com/The-Focus-AI/standards/blob/main/recipes/vercel.md
Relative links below resolve from recipes/vercel.md.


Follow [release guidance](../handbook/release.md) before changing a deployment.

Canonical pattern for Next.js apps on Vercel with GitHub previews, fnox-backed
secrets, Neon, Vercel Blob, and Clerk. Reference implementation: the **habitats**
repo (Next.js, fnox, Neon + Blob + Clerk). The maintained sync implementation
is this repository's `scripts/sync-secrets.mjs`, not the former bulk-export task.

For remote-server / pi / tmux setup see `handbook/development.md`. For Clerk domain and
OAuth rules see `recipes/clerk.md`. For the full fnox playbook see
`recipes/fnox.md`. For CI, testing against previews, and
failure notification see `handbook/release.md` and
`recipes/ci.md`.

## Defaults

| Concern | Standard |
| --- | --- |
| Host | Vercel (GitHub integration) |
| Production branch | `main` → Production deployment |
| Other branches / PRs | Preview deployments (`*.vercel.app`) |
| Database | Neon Postgres (`DATABASE_URL` pooled + `DATABASE_URL_UNPOOLED` when needed) |
| Object storage | Vercel Blob (`BLOB_READ_WRITE_TOKEN`) |
| Auth | Clerk — production-equivalent flows in Preview; production instance in Production; dev instance for local work |
| Secrets | 1Password vault → fnox → `mise run vercel:sync` → Vercel env store |
| Runtime on Vercel | Native Vercel env vars only — **do not** run fnox in the Vercel build or serverless runtime |

## One-time project setup

### GitHub + Vercel

1. Create a Vercel project linked to the GitHub repo.
2. **Settings → Git → Production Branch** = `main`.
3. Leave Preview Deployments enabled for non-`main` branches and pull requests.
4. If the Next app is not at the repo root (e.g. `app/` or `web/`):
   - **Settings → General → Root Directory** = that folder.
   - Enable including source files outside the root when using a pnpm workspace.
5. Pin `npm:vercel` through mise; run `mise install`.
6. Link the intended project/team explicitly using the pinned CLI's project and
   scope options. Keep `.vercel/` gitignored; verify its project/team IDs against
   the committed sync target before using CLI deployment tasks.

### `vercel.json`

Commit a minimal config next to the Next app (adjust path for monorepos):

```json
{
  "$schema": "https://openapi.vercel.sh/vercel.json",
  "framework": "nextjs"
}
```

Add `crons` only when the app needs them. Cron handlers must verify
`Authorization: Bearer $CRON_SECRET` and stay on the public middleware allowlist.

### Required mise tools and tasks

Pin Vercel CLI, Node and fnox via mise. `recipes/fnox.md` owns bootstrap, source-profile
semantics and the common sync contract. Configure the following consuming-project
tasks; they are not deployment tasks for this standards website:

| Task | Purpose |
| --- | --- |
| `mise run setup` | Get a checkout ready: a token that reads the project vault, then a secrets check (`recipes/fnox.md`) |
| `mise run secrets:check` / `secrets:list` | Resolve required keys / list declarations without values |
| **`mise run vercel:sync`** | Run `node scripts/sync-secrets.mjs --config secret-sync.json`; forward explicit `--target` and optional `--apply` |
| `mise run vercel:deploy` | Trigger the approved CI/Git production deployment for the recorded project/team |
| `mise run vercel:preview` | Trigger the recorded project's preview build; not a production release |

#### Configure and review the target

1. Copy `scripts/sync-secrets.mjs` and adapt `templates/secret-sync.example.json`
   as `secret-sync.json` at the consuming repo root. Keep only its Vercel targets.
2. Replace `prj_REPLACE` and `team_REPLACE` with IDs verified in project/team
   settings. Each target explicitly selects `preview`, `production`, or
   `development`; there is no default production destination.
3. Review each `keys` mapping and fnox source file/profile. Shared profile
   `runtime` and shared keys are intentional in the example. Add database and
   URL overrides only where required; do not export every key in the vault.
4. Create an expiring **project-scoped** Vercel access token [3], with an owner
   and renewal date. Inject it into the authorized sync job as `VERCEL_SYNC_TOKEN`
   (or the configured `tokenEnv`), alongside the source's project-vault token.
   Team scope is broader, not equivalent. Do not use a full-account token by default.
5. Run the offline tests, inspect dry-run output, then authorize writes. Do not
   run sync inside `fnox exec` or a shell hook that resolves secrets before dry-run.

The direct commands, before adding the forwarding mise task, are:

```bash
node scripts/sync-secrets.mjs --config secret-sync.json --target vercel-preview
# Authorized writes only after reviewing the plan:
node scripts/sync-secrets.mjs --config secret-sync.json --target vercel-preview --apply
node scripts/sync-secrets.mjs --config secret-sync.json --target vercel-production --apply
```

The script uses `GET /v10/projects/{projectId}/env?teamId=...&decrypt=false`
for a preflight inventory [1], then one
`POST /v10/projects/{projectId}/env?teamId=...&upsert=true` per key [2].
Each body contains one explicit target scope; values travel as JSON in HTTPS,
never `--value` arguments. There is no remove-before-add window. A `201` alone
is insufficient: the tool also checks `failed` and the returned key/scope/type.

All scopes use `type: sensitive` and `visibility: secret`. Vercel's current
Config/Secret documentation [4] explicitly allows Secrets in Development,
reversing the older Preview/Production-only restriction. Secret values are
write-only; an empty/redacted pull is **not** proof that a value was stored
empty or that it is correct. Confirm behavior in a newly built deployment.

Vercel's optional **Separate Production Secret Values** team policy can forbid
sharing a value between Production and other scopes [4]. Shared runtime keys
remain this guide's default where permitted. If that policy is enabled, the
write fails rather than silently switching source or weakening visibility;
document the provider constraint and obtain approval for the needed mapping.

For managed keys, preflight refuses shared multi-scope records, branch/custom
overrides, duplicate entries, integration-owned records, and incomplete inventories.
Review and separate those records deliberately before adopting this tool; do not
delete an old value as part of a blind retry. This implementation manages ordinary
scope-wide variables, not custom environments or branch-specific overrides.
Serialize jobs and avoid dashboard edits while syncing: preflight is not a lock.

On failure, stop the deploy. Confirmed earlier writes remain; the current write
may have landed despite a timeout or invalid response. Inspect remote state
before retrying. The script does not roll back, delete unrelated variables,
retry automatically, or claim all-or-nothing behavior.

### fnox.toml

Declare every runtime env var the app needs. Item title in 1Password = env var
name. Non-secrets may use `default = "..."`.

Minimum set for a typical app:

| Env var | Role |
| --- | --- |
| `DATABASE_URL` | Neon **pooled** connection string |
| `DATABASE_URL_UNPOOLED` | Neon **direct** URL (migrations, LISTEN/NOTIFY, session features) |
| `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` | Clerk publishable key |
| `CLERK_SECRET_KEY` | Clerk secret key |
| `CLERK_WEBHOOK_SECRET` | Svix signing secret (if webhooks are used) |
| `BLOB_READ_WRITE_TOKEN` | Vercel Blob read/write token |
| `CRON_SECRET` | Bearer for Vercel Cron (if crons exist) |
| `NEXT_PUBLIC_APP_URL` | Canonical public URL for the environment |

Optional but common: `AI_GATEWAY_API_KEY`, app-specific secrets, JWT template
name as a fnox `default`.

Keep a committed `.env.example` that lists the same keys with comments for
local / Preview / Production — no real values.

## Environment matrix

Vercel has three scopes. Map them deliberately, starting Preview from the
production configuration rather than a reduced development configuration:

| | Local / Development | Preview (PR / branch) | Production |
| --- | --- | --- | --- |
| Trigger | `pnpm dev` / `vercel dev` | Push to non-`main` or open PR | Push to `main` (or `vercel:deploy`) |
| Sync target | Add explicit `vercel-development` target if needed | `--target vercel-preview` | `--target vercel-production` |
| 1Password | Project vault or isolated dev source | Shared project vault; isolated source only where needed | Project vault |
| Neon | Dev branch or local | Staging / preview branch | Prod branch |
| Clerk | Dev instance `pk_test_` / `sk_test_` | Production-equivalent auth; document provider/domain constraints | **Production instance** `pk_live_` / `sk_live_` |
| Blob | Dev store token | Same integration; isolate writes that could harm production objects | Prod store token |
| `NEXT_PUBLIC_APP_URL` | `http://localhost:3000` | Preview URL or branch alias | Custom domain |
| `CLERK_AUTHORIZED_PARTIES` | Local origin | Approved preview origin or stable alias; same origin checks | Locked to the prod origin |

**Parity, with explicit exceptions:** `handbook/secrets.md` makes production behavior
the default, not separate keys. Shared runtime credentials are appropriate when
their permissions suit both targets; keep preview writes off the
production database. Record each differing setting, its reason, and what the
preview cannot verify. The sync task selects sources and allowed keys explicitly;
the destination flag alone does not establish that mapping.

## GitHub branch previews

1. Connect the repo in the Vercel dashboard (Git integration).
2. Every push to a non-production branch and every PR gets a Preview deployment
   built with the **Preview** env scope.
3. After changing Preview secrets: dry-run, then
   `mise run vercel:sync -- --target vercel-preview --apply`; redeploy to pick up values.
4. `NEXT_PUBLIC_*` vars are baked at **build** time. Changing them requires a
   new deployment through the recorded project's CI/Git pipeline.
5. Allow preview origins where the framework requires it (e.g. Next server
   actions `allowedOrigins` including `*.vercel.app`).

## Neon

- The **Neon ↔ Vercel** integration can provision pooled/direct connections.
  Give each variable one delivery owner: either record an integration-managed
  exception or transfer it deliberately to the 1Password-backed sync mapping.
  Do not have the integration and this script overwrite each other's values.
- App queries: pooled URL. Migrations / LISTEN / session features: unpooled.
- Preview isolation: a Neon **branch** (or separate project) whose connection
  strings are mapped to the Preview Vercel scope; this does not require a
  separate vault. Keep schema and database behavior aligned with production,
  apart from the change under test.
- Run migrations through an authorized cloud operational job against the explicit
  target URL, after any required approval. Do not depend on a laptop or use a
  Vercel build as an implicit destructive-migration step.

Map the migration job's explicit fnox profile to the intended direct database
reference and execute its migration command through fnox. Keep tracing disabled;
never print the connection string as a diagnostic.

## Vercel Blob

1. Create a Blob store in the Vercel project (or reuse per-environment stores).
2. Put `BLOB_READ_WRITE_TOKEN` in the matching 1Password vault.
3. Sync with `vercel:sync` for each env scope that needs storage.
4. Prefer **private** blobs; serve through authenticated app routes (signed URL
   or stream), not public world-readable URLs for client data.
5. Health checks should report whether the blob token is present (boolean), not
   the token value.

## Clerk: production and preview

Instance setup and the **publishable-key diagnostic** live in `recipes/clerk.md`; use
that diagnostic for both live and test keys rather than a live-prefix-only decoder.
A development instance still
uses client-specific OAuth applications under `handbook/sign-in.md`; Preview aims to
exercise production authentication under `handbook/secrets.md`, not inherit development
shortcuts automatically.

| | Preview | Production |
| --- | --- | --- |
| Instance / keys | Select a supported preview domain/instance setup; share runtime keys where appropriate | **Production** instance on the client custom domain; `pk_live_…` / `sk_live_…` |
| Social OAuth | Same providers and client-specific setup as production | This client's Google/Microsoft apps; never another client's (see `recipes/clerk.md`) |
| Domains | Configure the actual preview origin and callback URLs; document required differences | Custom domain + Clerk CNAMEs (DNS-only / grey cloud on Cloudflare) |
| `authorizedParties` | Approved preview origin or stable branch alias; retain origin checks | Lock to `https://<prod-host>` |
| Webhooks | Same events and handlers at the preview endpoint; isolate harmful downstream effects | Prod URL + `CLERK_WEBHOOK_SECRET` in Production scope |
| Middleware | Same auth checks and public-route exceptions; no silent auth bypass | Public: sign-in/up, health, cron, webhooks; never put `DEV_AUTH_BYPASS` in Production |

Verify Clerk's supported domains and redirects before selecting shared keys;
do not assume copying live keys makes an arbitrary preview URL work. If a
provider constraint requires a development-only fallback, document what it
leaves unverified. Clerk's shared development OAuth credentials do not satisfy
the client-isolation rule, even when a login succeeds.

**Never** put `pk_test_` / `sk_test_` in Vercel Production. The #1 prod outage
pattern is shipping the dev instance to the live domain.

Practical sync model:

1. Map shared runtime keys and justified overrides to each Vercel scope.
2. Keep preview database writes on a separate branch; scope Blob writes and
   webhook effects so testing cannot damage production data.
3. `mise run vercel:sync -- --target vercel-preview` reviews that mapping without resolving values.
4. Select `vercel-production` explicitly for production; add `--apply` only after approval.

A shared project vault is compatible with this model. A blind export of its
contents is not: sync only each target's required keys (`handbook/secrets.md`).

## Daily operations

For production, record the verified candidate and required release approval
before triggering the CI deployment (`handbook/release.md`). No separate staging
environment is required; a Git-triggered release still has that gate.

```bash
# Rotate the value through 1Password's secure UI, not shell arguments.
# Review then apply the explicit production target.
mise run vercel:sync -- --target vercel-production
mise run vercel:sync -- --target vercel-production --apply
# Trigger the approved CI/Git deployment for this project.
# Review key names/scopes in the project's dashboard, then smoke-test.
curl --fail --silent --show-error "https://<host>/api/health"
```

An inventory confirms names and scopes, not that values work. Test actual
database/auth/storage operations without exposing credentials in logs.

## Troubleshooting

| Symptom | Check |
| --- | --- |
| `No Next.js version detected` | Root Directory points at the Next.js app, not the monorepo root |
| `No Output Directory named public` | Framework Preset is Next.js; minimal `vercel.json` is next to the app |
| Empty-looking sensitive value on pull | Sensitive values are write-only; verify a rebuilt app rather than replacing them with empty strings |
| Quotes/newlines corrupted | Use the maintained JSON-based sync, not shell/dotenv line splitting |
| Profile mismatch | Unset the ambient `FNOX_PROFILE` or choose the matching named target; do not change only the destination |

Do not install fnox in the Vercel build or store only its bootstrap token there.
Native environment delivery avoids a 1Password request at every cold start;
already-deployed functions do not depend on a later sync succeeding.

## Health and cron

- Expose `/api/health` (or equivalent) that reports booleans for DB / Blob /
  Clerk config without leaking secrets.
- Cron routes: declare in `vercel.json`, protect with `CRON_SECRET`, exclude
  from Clerk auth.
- Long jobs: set `maxDuration` / Fluid Compute as needed; document in the app.

## Anti-patterns

- Manual dashboard-only secrets with no fnox / 1Password source of truth.
- `fnox exec` (or installing fnox) as the Vercel build command.
- Dev Clerk keys in Production; live keys committed to `.env` or the repo.
- One Neon database shared by Preview and Production with write access from both.
- Syncing the entire monorepo vault into a Vercel project that only needs a
  subset (review `vercel env ls` after sync).
- Changing `NEXT_PUBLIC_*` and expecting running deployments to pick it up
  without a rebuild.
- Relying on Supabase-as-default for new Focus projects — prefer Neon unless
  the client already standardized on Supabase (document the exception).

## New project checklist

- [ ] Vercel project linked to GitHub; Production branch `main`; Preview on
- [ ] Root Directory + `vercel.json` `"framework": "nextjs"`
- [ ] `npm:vercel` in mise; `vercel link`; `.vercel/` gitignored
- [ ] Dedicated 1Password vault(s); `fnox.toml`; `mise run setup`
- [ ] `vercel:sync` / `vercel:deploy` / `vercel:preview` tasks
- [ ] Neon: pooled + unpooled URLs; Preview branch planned
- [ ] Blob token(s) in fnox
- [ ] Clerk: production instance in Production; production-equivalent auth in Preview
- [ ] Preview configuration differences have a reason and documented testing limits
- [ ] `.env.example` matches fnox keys; health endpoint exists
- [ ] Explicit sync target reviewed and applied; deployed runtime and key/scope inventory verified
- [ ] Custom domain + Clerk DNS per `recipes/clerk.md` when going live

## Verification and primary sources

Checked 2026-10-30: reachable primary API documentation and offline simulated
adapter tests (`node --test tests/test-secret-sync.mjs`). No real provider
credential was read, no live write or deployment was performed, and these
tests do not establish live permission or account-specific API behavior.
Before adoption, an authorized operator verifies a disposable project, exact
scope isolation, sensitive-variable behavior, and runtime delivery.

[1] Vercel, [environment inventory API](https://vercel.com/docs/rest-api/projects/retrieve-the-environment-variables-of-a-project-by-id-or-name).

[2] Vercel, [create/upsert environment variables](https://vercel.com/docs/rest-api/projects/create-one-or-more-environment-variables).

[3] Vercel, [access token scope and expiry](https://vercel.com/docs/accounts/access-tokens).

[4] Vercel, [Config/Secret variables and separation policy](https://vercel.com/docs/environment-variables/sensitive-environment-variables).


---

# Component lifecycle reference

Status: Evidence
Checked: 2026-08-27
Source: https://github.com/The-Focus-AI/standards/blob/main/evidence/component-lifecycle.md
Relative links below resolve from evidence/component-lifecycle.md.


> `@umwelten/substrate` is the reference implementation. The lifecycle principles apply to any
> pluggable system that must add, remove and replace behavior without leaving partial state behind.

A pluggable system is more than dynamic import. It needs a lifecycle that makes every installation
reversible, activates a component only when its dependencies are present, and replaces code without
breaking the working version when a new module cannot load. The same model applies to browser
panels, server integrations, agent tools and long-lived resources.

`@umwelten/substrate` provides an isomorphic, zero-dependency reference: contexts own effects,
service keys connect providers to consumers, component specs describe activation, fibers represent
mounted instances, and `Loader` reconciles a host manifest. The package is currently a private
workspace package in The-Focus-AI/umwelten; treat the examples as the present repository API rather
than a published compatibility promise.

## The lifecycle model

A component is a declarative spec, not a singleton object. Mounting creates a fiber with its own
owner context. The fiber activates when every injected service is available and receives a committed
view of those exact service values. Withdrawing one dependency deactivates the fiber; providing it
again creates a fresh activation. Explicit unmount is different: it is permanent and idempotent.

```ts
import {
  createContext,
  Loader,
  mount,
  serviceKey,
  type ComponentSpec,
} from "@umwelten/substrate";

interface Database {
  subscribe(onRow: (row: unknown) => void): () => void;
}

const database = serviceKey<Database>("database");
const events: string[] = [];

const results: ComponentSpec<{ query: string }> = {
  name: "results",
  inject: [database],
  apply(ctx, view, config) {
    const db = view.get(database);

    ctx.effect(() => {
      const unsubscribe = db.subscribe((row) => {
        events.push(`${config.query}:${String(row)}`);
      });
      return unsubscribe;
    });

    events.push("active");
    return () => events.push("inactive");
  },
};

const root = createContext();
const fiber = mount(root, results, { query: "open invoices" });
await fiber.settled();
console.assert(!fiber.active && fiber.missing[0] === database);

const withdrawDatabase = root.provide(database, myDatabase);
await fiber.settled();
console.assert(fiber.active);

await withdrawDatabase();
await fiber.settled();
console.assert(!fiber.active);

root.provide(database, replacementDatabase);
await fiber.settled();
console.assert(fiber.active);

await fiber.unmount();
await fiber.unmount(); // Permanent and idempotent; it cannot reactivate.
await root.dispose();
```

Read injected services from the committed `view`, not with a new `ctx.get()`. The view keeps setup
and teardown tied to the same values even while a provider is leaving. A realm permits one provider
for a service key at a time; withdrawing it first allows another value to take its place.

Transitions on one fiber serialize. If a dependency disappears during an asynchronous `apply`, the
activation finishes against its committed view and deactivation follows; setup and teardown do not
interleave into a half-mounted fiber. A failed activation reverses partial effects, leaves the fiber
inactive and records the failure in `fiber.error`. Use `await fiber.settled()` whenever following
work depends on the current transition being complete.

## Reversible effects and ownership

Everything installed during activation needs an inverse: event listeners, timers, service
provisions, subscriptions, child mounts and backend registrations. `ctx.effect(callback)` runs the
callback immediately and tracks its returned inverse. `apply` may also return an inverse. Both may
be asynchronous.

Cleanup is LIFO. The inverse returned by `apply` is registered after effects created inside `apply`,
so it runs first, followed by `ctx.effect` inverses in reverse registration order. Cleanup continues
after an inverse fails and reports one error or an aggregate rather than abandoning the remaining
recovery.

Mount a child on the activation context when its lifetime belongs to that activation:

```ts
const child: ComponentSpec = {
  name: "child",
  apply() {
    events.push("child up");
    return () => events.push("child down");
  },
};

const parent: ComponentSpec = {
  name: "parent",
  inject: [database],
  apply(ctx) {
    mount(ctx, child);
    events.push("parent up");
    return () => events.push("parent down");
  },
};
```

Deactivating or unmounting the parent cascades through children owned by that activation. Child
teardown completes before parent teardown; sibling effects and child contexts otherwise follow LIFO
order. Disposing the context on which a fiber was mounted also unmounts it.

The general principle is ownership: install an effect on the narrowest context that completely owns
its lifetime. Then dependency loss, manifest removal, hot replacement and process shutdown all use
the same recovery path.

## Isolation realms

Context children ordinarily share a root service registry. `isolate(key)` gives one subtree a fresh
realm for that key while other keys continue to resolve normally. Descendants inherit the nearest
override. A named realm lets separate subtrees intentionally share one isolated binding.

```ts
const tenantA = root.child();
tenantA.isolate(database); // Install before provide, declare or mount.
tenantA.provide(database, tenantADatabase);
mount(tenantA, results, { query: "tenant A invoices" });

const tenantB = root.child();
tenantB.isolate(database, "tenant-b");
tenantB.provide(database, tenantBDatabase);
mount(tenantB, results, { query: "tenant B invoices" });
```

Providers and declarations capture their resolved realms when created, so isolation is configured
before provisioning or mounting; changing an override does not migrate existing bindings. Changes
in one realm notify only declarations bound to that realm, and an isolated declaration does not fall
back to the default provider.

This is dependency-resolution isolation, not a security boundary. Components in one JavaScript
process remain trusted code with the process's authority. Use a process boundary or sandboxed iframe
for untrusted UI, and enforce authorization at the host that crosses that boundary.

## Manifest reconciliation and hot replacement

The host owns file watching and manifest polling. `Loader` owns keyed reconciliation and component
lifecycle. Entries have stable, unique `id` values and either a module `url` or an inline
`component`; `config` and `disabled` control realization.

```ts
const loader = new Loader(root);

await loader.apply([
  { id: "results", url: "/components/results.js", config: { query: "open" } },
  { id: "status", component: statusComponent },
  { id: "debug", url: "/components/debug.js", disabled: true },
]);

await loader.reload("results");

for (const entry of loader.entries()) {
  console.log(entry.id, entry.generation, entry.fiber?.active, entry.error);
}
```

`apply()` first retires IDs absent from the desired manifest, then adds or reconciles desired
entries in order. Unchanged entries preserve the same fiber. Added entries mount and settle;
disabled entries remain known without a fiber; removed entries dispose their per-entry context and
settle teardown. A changed URL, config, disabled flag or inline component is retired and then
realized. Entry IDs therefore need to be unique even though the current Loader does not reject
duplicates itself.

Hot replacement of a URL entry uses `reload(id)`, which is deliberately import-before-retire:

```text
import and validate generation N+1
  ├─ failure → record error; keep generation N mounted
  └─ success → settle unmount of N; mount and settle N+1
```

The replacement module must default-export a component spec. A failed import or invalid export
advances the generation for the next cache-busting URL, records the error, and resolves while the old
fiber remains active. This is transactional protection for import and export validation. Once import
succeeds, a later teardown or activation failure does not roll back to the old fiber. Inline
`reload()` and manifest changes handled by `apply()` are retire-before-realize, not transactional hot
replacement.

Loader work within one `apply()` or `reload()` call is sequential and awaits fiber settlement. The
Loader has no global mutex, so the host serializes calls rather than starting overlapping polls or
reloads. A typical host compares its own manifest version or file modification time, calls
`loader.apply(entries)`, then awaits `loader.reload(id)` for changed URL entries. `version` is host
metadata, not a current Loader `Entry` field.

These distinctions preserve the useful guarantee without overstating it: broken code discovered at
import time leaves the working component active; arbitrary replacement failures are not fully
rollback-safe.

## Local composition and wire projection

Within one trusted runtime, components, services and effects compose as local typed values. A server
component can own a database pool, provide a narrow service to dependent server components, and let
dependency draining stop consumers before pool cleanup:

```ts
const databaseProvider: ComponentSpec = {
  name: "database-provider",
  async apply(ctx) {
    const pool = await openPool(process.env.DATABASE_URL!);
    ctx.effect(() => () => pool.end());
    ctx.provide(database, {
      subscribe: (onRow) => subscribeToRows(pool, onRow),
    });
  },
};
```

That composition stops at a process or trust boundary. A browser component projects to an MCP-UI
`ui://` resource; it does not receive the server context, service keys, database credentials, pool
or agent handle. Its sandboxed iframe emits declarative UI actions. A trusted host authenticates and
authorizes them, validates inputs, and brokers them to typed MCP tools/resources or A2A conversation
actions. Protocol data crosses back, not backend objects.

```text
browser component → trusted host → typed MCP tool/resource → server component → database
                                  └→ A2A conversation action → agent
```

A2A and MCP are wire projections of capabilities owned by the local runtime. They neither create nor
own local component fibers; their registrations should instead be reversible effects of the server
component that owns the underlying resource.

### Proposed capability contract

The full-stack direction is for browser components to declare named capabilities and for a
server-side component to register narrow MCP tools/resources during `apply`, then unregister them
and close long-lived resources during teardown.

This registry and browser declaration are **proposed application contracts, not current
`@umwelten/substrate` APIs**. The package currently exports lifecycle and service primitives, not
`declareCapability`, an MCP registry, or automatic browser-to-service bindings. An application-owned
contract could eventually look like this:

```ts
// Browser-safe manifest: names only, never credentials or handles.
const invoicePanel = {
  capabilities: ["invoices.list", "conversation.ask"],
};

// Trusted server process: illustrative app-owned registry.
const mcpRegistry = serviceKey<AppMcpRegistry>("app:mcp-registry");

const invoiceBackend: ComponentSpec = {
  inject: [mcpRegistry],
  async apply(ctx, view) {
    const pool = await openPool(process.env.DATABASE_URL!);
    ctx.effect(() => () => pool.end());
    ctx.effect(() => view.get(mcpRegistry).registerTool({
      name: "invoices.list",
      input: ListInvoicesSchema,
      run: (input) => listInvoices(pool, input),
    }));
  },
};
```

Each resource has its own inverse registered immediately after acquisition.
If tool registration throws, the activation still closes the pool. If tool
unregistration rejects during teardown, context cleanup still attempts the pool
inverse; combining both into one callback would skip it after the first rejection.

The trusted host resolves `invoices.list` to that MCP tool and `conversation.ask` to an A2A action
only after authorization. The browser knows neither implementation.

## Reference implementation sources

The API and lifecycle details in this guide were checked against public `main` in
The-Focus-AI/umwelten:

- [`component.ts`](https://github.com/The-Focus-AI/umwelten/blob/main/packages/substrate/src/component.ts)
  and its [tests](https://github.com/The-Focus-AI/umwelten/blob/main/packages/substrate/src/component.test.ts)
- [`context.ts`](https://github.com/The-Focus-AI/umwelten/blob/main/packages/substrate/src/context.ts),
  [`services.ts`](https://github.com/The-Focus-AI/umwelten/blob/main/packages/substrate/src/services.ts),
  and the [isolation tests](https://github.com/The-Focus-AI/umwelten/blob/main/packages/substrate/src/isolation.test.ts)
- [`loader.ts`](https://github.com/The-Focus-AI/umwelten/blob/main/packages/substrate/src/loader.ts), its
  [tests](https://github.com/The-Focus-AI/umwelten/blob/main/packages/substrate/src/loader.test.ts),
  and the [HMR example](https://github.com/The-Focus-AI/umwelten/blob/main/packages/substrate/examples/hmr.ts)
- [ADR 0032](https://github.com/The-Focus-AI/umwelten/blob/main/docs/adr/0032-components-project-onto-the-wire-as-ui-resources.md)
  for the accepted but not yet implemented wire-projection direction

For the MCP route and A2A backend pattern that carries those projections, see
[`handbook/agent-services.md`](../handbook/agent-services.md).


---

# Gaia runtime deployment record

Status: Evidence
Checked: 2026-07-25
Source: https://github.com/The-Focus-AI/standards/blob/main/evidence/gaia-runtime.md
Relative links below resolve from evidence/gaia-runtime.md.


This is a dated implementation record. Use [release guidance](../handbook/release.md)
for current proposed gates and verify the deployed configuration before acting.

Deployment pattern for the **habitats / Umwelten agent runtime plane**: a
long-lived **GCE VM** running Docker, Gaia (orchestrator), and sibling habitat
containers. Reference: **umwelten** (`deploy/gaia/`, `.github/workflows/deploy-gaia.yml`)
and ops notes in `umwelten/docs/guide/operating-production.md`.

This is **not** the Cloud Run / App Engine standard. For those see
`recipes/gcp.md`. For the habitats SaaS control plane (previews, env sync)
see `recipes/vercel.md`.

## When to use this pattern

Use GCE + Gaia when the workload needs:

- A **Docker daemon** on the host (Gaia spawns sibling containers — Docker-out-of-Docker)
- **Persistent per-habitat volumes** (tokens, local state) that must survive recreates
- **Wildcard subdomains** (`*.habitats.thefocus.ai`) terminated on the host
- Long-running agent processes, not request/response Cloud Run functions

Do **not** use this for:

- Stateless HTTP APIs → Cloud Run (`recipes/gcp.md`)
- Next.js SaaS with PR previews → Vercel (`recipes/vercel.md`)
- Gaia itself on Cloud Run — rejected today (needs Docker socket, volumes, sibling networking)

## Three deploy loops (do not mix them)

| Loop | What changes | Trigger | Blast radius |
| --- | --- | --- | --- |
| **1. Platform** | Gaia, base images, tool sets, `deploy/gaia/` | Push to `umwelten` `main` (path-filtered) → self-hosted runner → `redeploy.sh` | Whole fleet: rebuilds images, recreates Gaia, cycles **running** habitats (~10 min) |
| **2. One agent** | Habitat repo logic (`config.json`, tools, stimulus) | Push to the agent repo → Gaia `rebuild <id>` (`git pull` + `mise install` + `pnpm install --prod`) | That habitat only |
| **3. SaaS** | habitats.thefocus.ai UI / API | Push to `habitats` → Vercel | Control plane only; **does not** rebuild GCE agents |

PR previews exist on **loop 3 (Vercel)** only. Loops 1–2 have **no** branch/PR
preview environment on GCP today.

## Host topology

| Piece | Convention |
| --- | --- |
| Compute | GCE VM (e.g. `gaia-host`), Debian + Docker Engine + compose |
| Size | Start ≥ `e2-standard-4` / 100 GB disk when hosting multiple habitats; 4 GB swap |
| SSH | **IAP only** — no public SSH |
| Ingress | caddy-docker-proxy on `gaia-net`; Gaia not published raw on the host |
| Domains | `GAIA_HOSTNAME` + `GAIA_BASE_DOMAIN`; DNS `*.<base>`; habitat default `<id>.<base>` |
| Naming | Gaia container `gaia`; children `gaia-<id>`; volumes `gaia-<id>-data` |
| gcloud | Named config in umwelten `mise.toml` (`CLOUDSDK_ACTIVE_CONFIG_NAME = "habitats"`) |
| Secrets | Host `deploy/gaia/.env` (0600, gitignored); Gaia master vault on disk; child bindings via Gaia API — **not** Vercel Preview env |

Startup hardening: idempotent `deploy/gcp/*-startup.sh` (swap, Docker, gcplogs,
Ops Agent). Logging: Docker `gcplogs` driver + `docker logs` on the host.
Backups: scheduled disk snapshots covering Gaia data and Docker volumes.

## Auto-deploy (platform loop)

### How it works

1. Merge to `umwelten` `main` touching `packages/**`, `examples/**`, `deploy/gaia/**`,
   lockfiles, or the workflow file.
2. GitHub Actions job `runs-on: [self-hosted, gaia]` executes **on the prod VM**.
3. Workflow sets `GAIA_ENV_FILE` to the host’s canonical `.env` (secrets stay on disk).
4. `deploy/gaia/redeploy.sh` builds images **on the host**, recreates Gaia, waits
   for `/health`, then stop/start each **running** habitat via the Gaia API.
5. Deliberately stopped habitats stay stopped. Named volumes persist.

Manual equivalent: SSH via IAP and run `redeploy.sh`, or `workflow_dispatch`.

### Hard rules for the self-hosted runner

- **Push to the default branch only.** Never attach this runner to `pull_request`
  — the repo is public and the runner controls the production Docker socket.
- Require approval for workflows from forks.
- Path-filter the workflow so unrelated docs/PRs do not cycle the fleet.
- `concurrency` group for deploys with `cancel-in-progress: false` (don’t interrupt
  a half-finished redeploy).
- Runner user needs Docker group access; treat runner registration as a production
  credential (rotate if leaked; systemd `Restart=always` watchdog recommended).

This CD shape **does not transfer to Cloud Run**. Cloud Run has no host Docker
socket and no “build on the prod box” step. Future Cloud Run / Cloud Build work
is a different pipeline (build in Cloud Build → Artifact Registry → pull on host
or deploy a service) — document that separately when it ships.

## Previews: what exists vs what does not

| Surface | Preview? | How |
| --- | --- | --- |
| habitats SaaS | Yes | Vercel Preview env + `mise run vercel:sync -- --env preview` |
| Gaia / habitats on GCE | **No** | Every platform merge hits production |
| Cloud Build PR images | **Not implemented** | Planned (umwelten migration Phase 4 / Stage 2) |

No separate staging host is required. Following [release guidance](../handbook/release.md),
test the control-plane UI against Preview Vercel and exercise the exact
agent-fleet candidate's build/start checks in a disposable cloud workspace.
Record the commands, results, runtime limitations, and release approval before
merging a change that will deploy to production. The existing ~10 minute
production cycle is deployment behavior, not a substitute for that evidence.
This review aligns the procedure; it does not verify that the live Gaia workflow
has these gates configured.

## Agent (habitat) lifecycle

Repo-backed habitats only going forward:

```text
config.json      # id metadata, toolsDir, stimulusFile, requiredSecrets
STIMULUS.md
tools/<name>/    # TOOL.md + handler.ts
src/
package.json     # runtime deps; boot installs with --prod
mise.toml        # pin node/pnpm
```

1. Secrets → Gaia master vault (`POST /api/secrets`), never into git.
2. `create_habitat` with `gitUrl` + `secretBindings`; hostname defaults to
   `<id>.<GAIA_BASE_DOMAIN>`.
3. `start_habitat` → check `/health`; attach in SaaS with the **child** API key
   (never Gaia’s master key).
4. Later deploys = agent-repo push + Gaia `rebuild <id>` (loop 2).

Gaia is the only holder of GitHub credentials (GitHub App on an explicit
allowlist). See umwelten ADR / operating-production for the App layout.

## Secrets and credentials

| Secret | Where it lives |
| --- | --- |
| Compose / host config (`GAIA_API_KEY`, hostnames, …) | `deploy/gaia/.env` on the VM |
| Provider keys, Twitter tokens, per-agent DB URLs | Gaia master vault → bound into child `secrets.json` |
| GitHub App private key | On gaia-host only |
| SaaS Clerk / Neon / Blob | habitats Vercel + fnox — **separate plane** |

Do not sync Vercel Preview secrets onto the GCE host. Do not put prod Gaia keys
in the SaaS Preview vault.

## Anti-patterns

- Wiring the prod self-hosted runner to `pull_request` or `pull_request_target`.
- Expecting Cloud Run “branch previews” for Gaia/habitats.
- Building images on a laptop and `docker save` into prod as the normal path
  (use the on-host redeploy or future Artifact Registry pull).
- Exposing Gaia’s raw port publicly; always go through caddy + API key.
- Wiping habitat Docker volumes casually (rotated OAuth tokens live there).
- Mixing loops: changing SaaS Preview env and assuming agents rebuilt.
- Putting Gaia’s master API key into the habitats SaaS client.

## Planned next (not standard yet)

Documented in umwelten migration reports — **do not treat as current practice**:

1. **Cloud Build → Artifact Registry** so the host **pulls** tags instead of
   `docker build` on the pet VM (decouples CD from runner disk/RAM).
2. Optional **staging Gaia host** if we need a non-prod runtime plane.
3. Longer term: GKE / Cloud Run Instances if orchestration requirements change.

When Stage 2 lands, add a short subsection here or a sibling doc; keep this file
focused on the live GCE + self-hosted runner pattern.

## Checklist (new Gaia host)

- [ ] GCE VM, IAP SSH, Docker Engine, disk + swap sized for the fleet
- [ ] Wildcard DNS + caddy-docker-proxy; Gaia only on `gaia-net`
- [ ] `deploy/gaia/.env` from `.env.example`; mode 0600; not in git
- [ ] Self-hosted runner registered with labels `self-hosted`, `gaia`
- [ ] `deploy-gaia.yml`: `main` + path filters only; no `pull_request`
- [ ] `GAIA_ENV_FILE` points at host `.env`; smoke `redeploy.sh`
- [ ] Uptime check on Gaia `/health`; memory/disk alerts
- [ ] Disk snapshot schedule; document restore
- [ ] Named gcloud config in the umwelten repo `mise.toml`
- [ ] Team knows the three deploy loops and which repo to push

## Related docs

| Doc | Role |
| --- | --- |
| `recipes/gcp.md` | Cloud Run / App Engine / gcloud configs |
| `recipes/vercel.md` | habitats SaaS previews and fnox→Vercel sync |
| umwelten `deploy/gaia/README.md` | Host runbook |
| umwelten `docs/guide/operating-production.md` | Day-to-day fleet ops |
| umwelten `reports/2026-07-10-gaia-on-gcp-deployment-strategy.md` | Why not Cloud Run |


---

# Workbench, Specialist A, and Specialist B integration

Status: Evidence
Checked: 2026-11-07
Source: https://github.com/The-Focus-AI/standards/blob/main/evidence/workbench-integration.md
Relative links below resolve from evidence/workbench-integration.md.


## Service profiles

This record supports [service access](../handbook/service-access.md), checked against source on
2026-11-07. It distinguishes inspected behavior, reported candidate tests and
the owner's subsequent connection-policy decision.
It does not provision accounts, grant access or certify a deployment. The
earlier social-sign-in walkthrough retains its own verification dates.

The owner subsequently required that a human grant always pass through the
Workbench connection so Specialist A, Specialist B and other specialists can identify and
potentially refuse that human. The private coordinating record
supersedes the earlier Specialist B machine-only selection. The required profile is
now [service identity plus bound human delegation](../handbook/service-access.md#require-human-delegation-for-workbench-specialists)
for every Workbench external-specialist invocation. The Specialist B owner is revising
the receiver; this records a requirement, not shipped enforcement.

Choose a credential mechanism and an authorization profile separately. Clerk
native M2M JWTs, OAuth client-credentials access tokens, browser sessions and
administrative API keys are not interchangeable. The presence of a Clerk secret
proves neither that a machine exists nor that an application token can be issued.
Keep every client's OAuth applications isolated under `handbook/sign-in.md`; the
machine examples do not change that boundary.

| Profile | Verified identity and permission | Evidence and limits |
| --- | --- | --- |
| Browser session | Clerk human session for this client application | Browser routes retain session protection. Sign-in does not grant specialist entitlement. |
| Specialist A machine plus human | Native Clerk machine JWT plus independently signed Workbench grant; local entitlement for `(machine.sub, human.sub)` | Implemented at Specialist A `074330` (source A2 below). Fixed issuers are part of the identity boundary. The owner hash is SHA-256 of the JSON pair; it is not a protocol identifier. Initial integration entitlement was `operator=false`, not an administrator grant. |
| Specialist B selected delegated profile | Verified service identity plus target-bound human grant, `human.azp === machine.sub`, and receiver-owned human entitlement | Owner-required replacement for the machine-only candidate (A6). Missing or invalid grants cannot downgrade to shared-service access. Revised implementation, genuine issuance and deployed acceptance are not verified here. |
| Superseded Specialist B machine-only candidate | Trusted Specialist B issuer, receiver `aud`, allowed sender and `specialist:read`; rejected human-grant headers | Historical candidate and fixture evidence only. It is no longer the selected Workbench profile and does not satisfy the new requirement. |
| Specialist A temporary legacy demo | Exact existing opaque token, separate `shared-demo` owner, original expiry, no grant header | Implemented coexistence path, not the default machine profile. `operator=false`; old standalone operator authority is not restored. See [demo cutover](../handbook/service-access.md#preserve-bounded-demo-access-during-cutover). |

## Trace middleware before choosing a verifier

At Specialist B `9e763e4` (A3), `auth.protect()` runs before the
route's bearer verifier. The public card passes that middleware, but machine
invocation does not. The inspected Clerk Next.js **7.4.3** package defaults
`protect()` to session tokens and rejects other token classes. A coordinating
production check reported HTTP 200 for the card and Clerk protect-rewrite HTML
404 for a no-token POST. It also reported registry auth `none`, zero configured
machines and OAuth applications, and no verified reusable application token.
Those observations are dated evidence, not a fresh account inventory in this
documentation task. See the integration record in A6.

The earlier machine-only candidate passed only `POST /api/a2a/jsonrpc` through
browser-session protection to a strict route verifier. Ordinary browser routes
retained session protection. That candidate checked `RS256`, `typ: JWT`, native protected-header
`cat: cl_…`, trusted issuer, receiver audience, exact sender allowlist,
integer `iat`/`exp` with at most 300 seconds of lifetime, and top-level
`scope` containing `specialist:read`. Its five-second skew included
optional `nbf` checks. Its configuration names were `CLERK_DOMAIN`,
`SPECIALIST_A2A_CALLER_ID` and `SPECIALIST_A2A_AUDIENCE`.
The category value comes from the observed native Clerk token profile, not from
A2A or MCP; the skew is also a local choice. That candidate returned 403 for a
human-grant header and removed the assumed OAuth client-credentials endpoint.
Rejecting all grants is incompatible with the new selected profile; retaining
the machine verifier alone does not complete the revised receiver.

The implementer reported five interoperability fixture tests using the published
Workbench `c302e20` registry, `agentHeaders`, `askSpecialist` and direct relay
against that earlier Specialist B middleware, verifier, route and adapter. They covered
blocking and streaming calls, same-context/new-message follow-ups, native mint
caching, and wrong-scope 403 and wrong-audience 401 responses without a model call.
The fixtures replaced Clerk minting and JWKS, the model, host session lookup and
conversation persistence. Receiver/card/browser checks and a sandbox production
build also reportedly passed. These results were not rerun here. They establish
reported local interoperability for the superseded profile, not acceptance of
mandatory human delegation or a deployment.

The owner authorized M2M setup and assigned it to the laptop operator in the
coordinating thread. Provisioning completion and genuine issuance are not verified
here. That setup authorization does not approve publication, ratification or
deployment. The revised grant verifier, human entitlement policy, persisted-owner
mapping and deployed direct/routed acceptance remain separate verification work.
Direct and routed tests must prove the same verified sender/human principal, not
merely the presence of provenance fields. Broad-suite failures and their comparison
with the unchanged base remain in the implementation record, not a claim that all
Specialist B tests pass.

For acceptance, send a well-formed A2A request through the real middleware and
handler. Inspect status, content type and response semantics. An HTML 404 or
sign-in redirect is not the expected API authentication response, and a 400
parser error is not proof that authorization worked. Test the exact supported
method and path, other methods, adjacent API paths and normal browser routes.

## Service-profile evidence

Source inspection on 2026-11-07 confirmed the code paths below and refreshed
Clerk documentation. No credentials were resolved and no production calls or
account changes were made in this documentation task. The later owner requirement
above is policy evidence, not a new source or production verification. Specialist B's
revised candidate remains subject to its implementation report and live acceptance.

- A1. Workbench `c302e20` (private client repository):
  `app/lib/registry.ts`, `identity.ts`, `agent-auth.ts` and `agent-policy.ts`.
- A2. Specialist A `074330` (private client repository):
  `src/auth.ts`, `src/store.ts` and `app/api/session/route.ts`.
- A3. Specialist B `9e763e4` (private client repository):
  `app/middleware.ts`, `app/agent/auth/clerkJwt.ts` and `app/app/api/a2a/jsonrpc/route.ts`.
- A4. [Clerk Next.js 7.4.3 package](https://registry.npmjs.org/@clerk/nextjs/-/nextjs-7.4.3.tgz),
  `dist/esm/server/protect.js`; [current auth reference](https://clerk.com/docs/reference/nextjs/app-router/auth).
- A5. [Clerk OpenAPI](https://github.com/clerk/openapi-specs/blob/94753d1d8a648806e4dc529beec8bb76daa13859/bapi/2026-08-20.yml)
  and [M2M lifecycle](https://clerk.com/docs/guides/development/machine-auth/m2m-tokens).
- A6. Coordinating evidence and owner decisions (private coordinating record);
  Specialist B implementation, not production acceptance (private coordinating record).

## Conversation and view sources

- **2026-11-07** — Agent-authored integration proposal, source inspection only.
  Standards base fetched and fast-forward checked at `1b55f96`; no local work was
  present and remote `main` was already at that revision. Credential evidence
  and Specialist B's candidate are recorded above. Additional sources:
  - Workbench `c302e20` (private client repository):
    `app/lib/agent-card.ts`, `agent-policy.ts`, `agent-auth.ts`, `a2a/client.ts`,
    `a2a/transport.ts`, `mcp-app-contract.ts`, `mcp-apps.ts`, `app/components/mcp-app-tile.tsx`,
    `app/docs/mcp-apps.md` and `app/package.json`.
  - Specialist A `074330` (private client repository):
    `src/auth.ts`, `src/a2a.ts`, `src/store.ts`. This pin proves source behavior,
    not a fresh deployment or the later MCP candidate's release.
  - [A2A v1.0.0 source](https://github.com/a2aproject/A2A/tree/173695755607e884aa9acf8ce4feed90e32727a1):
    `docs/specification.md` and `docs/topics/life-of-a-task.md`, especially task
    immutability, context, idempotency and interrupted streams.
  - [Stable MCP Apps 2026-01-26](https://github.com/modelcontextprotocol/ext-apps/blob/19256f52cad5517ba8272581ed2e11d6a81273d5/specification/2026-01-26/apps.mdx):
    discovery, visibility, initialization, future-turn context, sandbox and CSP.
    Durable restoration is listed as a future extension, not a present guarantee.
  - Owner decisions and coordinating evidence (private coordinating record):
    direct trusted-renderer exception, reported production observations, and
    unresolved provider release and signed-in integration acceptance.
