# Po profiles authoring contract

## Sources and shape

Po reads profile declarations in this order:

1. `~/.po/profiles.yaml`
2. `<repoRoot>/.po/profiles.yaml`

Plugins may also contribute in-memory profiles through `ProfileSources.register`. Session reads pass
`{ workspaceId }` to each source's `list(scope)`, so a source can show only the profiles that belong
to the session's workspace. File profiles are never filtered. See
[Plugin sources, readiness and defaults](#plugin-sources-readiness-and-defaults) for sources that load
asynchronously.
The current catalog shape is:

```yaml
profiles:
  roots: [agents/acme]
  entries:
    writer:
      persona: agents/special/writer
      env:
        BRAND: acme
        TONE: concise
  defaultProfile: writer
```

The document may contain only the `profiles` mapping. In catalog form, `profiles` may contain only
`roots`, `entries` and `defaultProfile`. Po still accepts the earlier flat form, where profile
names appear directly below `profiles`, but new configuration should use catalog form.

`defaultProfile` names the persona a run starts on when nothing else names one, the same way
`presets.yaml` declares `defaultPreset` and `domains.yaml` declares `defaultDomains`. A repository
declaration replaces a personal one. `po --profile <name>` overrides it for one run, and an
inherited `PO_PROFILE` wins so a nested run stays on the persona its parent chose. A
`defaultProfile` or `selection.profile` that names no file profile is not an error by itself: it is a
requested name that a plugin source may still deliver. The launch waits for the sources, at most ten
seconds in total, and when the name never appears it starts with no profile and shows one warning.
A value that is not a non-empty string still fails loading.

Every relative root or persona path resolves against the file that declares it. Repository paths
resolve from the repository root. Personal paths resolve from `~/.po`.

## Root discovery

Each `profiles.roots` value must resolve to an existing directory.

- If the root directly contains `profile.md`, `SOUL.md`, or `AGENTS.md`, the root is one profile.
  Its directory name is the profile name, and its children are not scanned.
- Otherwise, Po inspects only the root's direct-child directories. A child becomes a profile
  when it directly contains at least one persona file.
- Discovery does not recurse. Add another root or an explicit entry for a deeper persona.
- A discovered profile has an empty environment mapping unless its directory holds a `profile.yaml` sidecar.
- Unreadable candidates and candidates whose real path or persona files escape the configured root
  are ignored. An invalid configured root itself is an error.

### Shared settings: preset, domains and wake

Explicit entries, `profile.yaml` sidecars and plugin profile sources accept the same optional keys:

```yaml
preset: copilot # a preset name, checked by shape only
domains: [development] # up to 32 domain names, duplicates dropped
wake:
  period: 6h # m, h or d; 15m to 7d
  prompt: Check in on open work # optional, at most 4000 characters
```

Parsing injects no default: an absent key stays absent. `wake.period` becomes `wake.periodMs`. The
profile runtime snapshot carries a frozen copy as `settings`, replaced on every selection generation.
Ownership across plugins: Profile holds the prose playbook and check-in defaults, Task holds flexible daily routines and counters, Calendar holds wall-clock or cron-bound commitments, and Wake coordinates bot deadlines and nudges.

### Discovered `profile.yaml` sidecar

A discovered persona directory may hold a nonsecret `profile.yaml` sidecar, typically written by a
sync tool such as po-unsendbox:

```yaml
version: 1
env:
  BRAND: receiptnote
integration:
  provider: unsendbox
  # same shape as an explicit entry's integration
```

Only `version` (exactly `1`), `env`, `integration`, and scoped vault `secrets` are allowed. These are validated exactly like an
explicit entry. `env` cannot contain secret aliases in legacy or Liquid syntax. The sidecar must be a regular
file of at most 64 KiB inside the real persona directory; a symlink cannot escape it. A bad sidecar
skips only that profile and reports a diagnostic in `loadProfileCatalog(...).diagnostics`; the rest of
the catalog still loads. Diagnostics never echo sidecar values. Sync and async loaders behave the same.

## Explicit entries and path confinement

An explicit entry may contain only `persona`, `env`, optional `integration`, and optional vault `secrets`. `persona` is required, must be a non-empty
relative path, and must resolve to a directory containing readable persona content.

The persona must remain inside either:

- the `agents/` directory beside the declaring repository root or personal `.po` directory, or
- one of the `profiles.roots` directories declared in that same file.

Po checks both the lexical path and the real filesystem path. A persona-directory symlink cannot
escape an allowed root. Each resolved persona file must also remain inside the real persona
directory, so a file symlink cannot import instructions from outside it. Invalid explicit entries
fail loading instead of being skipped.

Persona content is assembled from non-empty files in this order:

1. `profile.md`
2. `SOUL.md`
3. `AGENTS.md`

## Nonsecret integration bindings

An explicit profile may bind one integration provider. The binding contains identifiers only,
never API keys, passwords, cookies, or resolved credential values:

```yaml
profiles:
  entries:
    worker:
      persona: agents/worker
      integration:
        provider: unsendbox
        organizationId: org-id
        mailboxId: mailbox-id
        credentialRef: local-auth-reference
        secrets:
          PASSWORD:
            credentialId: existing-credential-id
            field: password
            allowedOrigins: [https://login.example.com]
        browser:
          profileName: worker
          allowedOrigins: [https://login.example.com]
```

`provider`, `organizationId`, `mailboxId`, `credentialRef`, and `secrets` are required.
`credentialRef` identifies authentication supplied by the concrete integration outside profile
configuration. An empty `secrets` mapping is allowed. Each uppercase secret alias names an existing
credential and field (a field name, or `profileSecret:<ALIAS>` for provider-held profile secrets).

Each integration secret declares `purposes`, a nonempty unique subset of `browser`, `proxy`, `env`, and `input`, defaulting
to `[browser]`:

- `browser`: `{{ secrets.PASSWORD }}` is filled host-side by the browser, never profile `env`. It
  requires nonempty exact HTTP(S) `allowedOrigins`, without paths, wildcards, userinfo, or trailing
  slashes.
- `proxy`: named by `browser.proxySecret` and resolved host-side for the browser proxy only.
- `env`: injected only into workflow `run` steps that declare the alias, through `po/profile-secrets`.
- `input`: delivered only to an explicitly allowed native app through a trusted input boundary. Requires
  `allowedTargets`, a nonempty mapping of surface names to nonempty exact application-identifier lists,
  such as `{ios: [com.example.app], computer: [com.example.desktop]}`. Wildcards are refused. Browser,
  env and proxy are reserved and cannot be native surface names. Non-input aliases cannot set targets.

A secret without the `browser` purpose cannot list origins. The optional browser binding requires a
safe profile name, not a filesystem path, and its own nonempty exact `allowedOrigins`. Browser
policies combine configured origins with `PROFILE_SOCIAL_BROWSER_ORIGINS` from
`@agimon-ai/po-config/profiles`: exact HTTPS apex/www origins for X, Reddit, LinkedIn, Facebook,
Instagram, TikTok and YouTube, plus legacy Twitter origins and `https://accounts.google.com` for
YouTube sign-in. The effective browser origins must contain every browser-purpose secret origin.
These shared defaults never expand an individual secret's origins or purposes. They also apply to
persona-only browser policies. A browser binding may set `mode` (`playwright`, `extension`, or
`stealth`) and `proxySecret`, which must name a `proxy`-purpose secret. Unknown metadata is rejected.

The public `@agimon-ai/po-profile` API exposes the session-owned `po/profile-runtime` Cordis service.
Consumers declare that service as an injected dependency, use `requireProfileRuntime(context)`,
and attach exactly one concrete provider with `attachProvider(providerName, factory)`. The factory
receives deeply immutable binding metadata plus `{profileName, generation, signal}` and returns
`{resolveSecret(reference, signal), dispose()}`. The attachment returns an awaited cleanup operation.
Do not invoke `runtime.resolveSecret` from the factory: resolution is rejected until initialization
finishes. The runtime does not load provider SDKs or persist resolved values.

`runtime.resolveSecret(name, {origin, signal})` accepts a trusted actual target-frame origin from
the browser boundary, never a tool-supplied origin, and resolves `browser`-purpose aliases only.
`runtime.resolveProxySecret(signal)` is host-only and resolves `browser.proxySecret`. `ready()` rejects
if a configured provider is missing or failed. Session startup and new-turn admission both require
readiness. Profile changes and shutdown abort old generations before asynchronous provider cleanup;
late secret results are rejected rather than delivered to a replacement profile. Persona-only
profiles remain compatible. The concrete browser integration owns persistence and exclusive profile
leases.

Session secret delivery rereads current provider-backed alias metadata before resolution and again
before returning a value. New aliases become usable after the provider publishes them, without a
profile refresh, provider reconnection, selection generation change or browser tab closure. Removed
or changed aliases invalidate in-flight results. Provider, organization, mailbox and authentication
references must still match the selected identity. Browser launch identity, env and file-backed vault
aliases stay pinned until an explicit profile selection or refresh.

The global `po/profile-secrets` service serves jobs that run outside a session. Providers call
`registerProvider(provider, factory)`; workflow hosts call `resolveEnv({cwd, profile, names, signal})`.
Each call loads the profile catalog for `cwd`, requires the `env` purpose for every name, opens a fresh
provider connection, and disposes it before returning. Every failure is the same generic error. The
service is never exposed as a model tool. `redactSecrets(value, secrets)` and
`createSecretRedactionStream(secrets)` redact raw, JSON-escaped, and URL-encoded forms of resolved
values, including overlapping and chunk-split matches; use them before any output reaches a model.

## Vault aliases and Liquid input

Vault-backed aliases live at the profile level, independently of any integration provider:

```yaml
profiles:
  entries:
    worker:
      persona: agents/worker
      env:
        LOGIN_EMAIL: ops@example.com
      secrets:
        PASSWORD:
          vault: { namespace: logins, key: example, field: password }
          purposes: [browser, input]
          allowedOrigins: [https://login.example.com]
          allowedTargets:
            ios: [com.example.app]
            computer: [com.example.desktop]
```

The host reads only the configured vault entry. With `field`, only an own string property of that exact
name is accepted (no nested traversal); without it, the value itself must be a nonempty string. Vault
aliases support browser and input purposes, not proxy or workflow env. Provider and vault alias names
must not collide. The vault remains host-only with no secret-reading model namespace.

Input text may combine literals, `{{ env.LOGIN_EMAIL }}`, and `{{ secrets.PASSWORD }}`. `secret` is a
synonym for `secrets`, and legacy `${env.NAME}`, `${secret.NAME}`, and `${secrets.NAME}` remain supported.
The shared `@agimon-ai/po-core/inputTemplate` parser and LiquidJS renderer support interpolation only,
with at most 16 references and bounded input/output. Tags, filters, expressions, bracket/prototype access,
and malformed templates fail before resolving any credential. Resolved values are never rendered again.
`env` reads only this profile's declared nonsecret values, never arbitrary process or session environment.

`runtime.resolveInputSecret(name, {surface, target, signal})` is host-only. The surface must obtain the
actual app identity at its native boundary, recheck it after asynchronous resolution, and prevent values
from reaching output, traces, logs, recordings, and screenshots. Profile changes, shutdown and request
cancellation discard late results. Consumers must never return the resolved string to the model. New
surfaces reuse the shared parser/renderer and runtime method, not global argument interpolation or raw
vault reads. A tool-supplied target is never authorization evidence. Browser aliases retain their existing
actual-frame origin checks. An integration browser allowlist remains an additional restriction when set.

## Persona identity front-matter

A persona may open `profile.md` with a YAML front-matter block declaring who it is and how it
sounds. Only `profile.md` is read this way; `SOUL.md` and `AGENTS.md` are always prose.

```markdown
---
name: Rhea
icon: avatar.png
voice:
  voice: Karen
  rate: 175
---

You are Rhea, a blunt systems architect.
```

All three fields are optional. `name` replaces the profile's directory name in the cockpit,
`icon` is an image beside `profile.md`, and `voice` shadows `voice.autoCapture.tts` from
`config.yaml` per field: a persona setting only `rate` keeps the configured voice. The TTS `engine`
is never overridable, because it selects the synthesiser rather than the persona.

Because identity lives here rather than in `profiles.yaml`, it applies to profiles found by root
discovery as well as to explicit entries.

A block is only treated as identity when it is fenced on the very first line, closed, parses as a
YAML mapping, and declares at least one of `name`, `icon`, or `voice`. Anything else is left in the
persona text byte for byte, so a persona that legitimately opens with a horizontal rule is
unaffected. A recognised block is removed from the prompt: it describes the persona rather than
instructing it. A `profile.md` holding nothing but front-matter therefore has no persona text, and
the profile fails to load unless `SOUL.md` or `AGENTS.md` supplies it.

The icon is read once when the profile loads and travels to the cockpit as a `data:` URL, so no
file is served at request time. It must be a PNG, JPEG, GIF, or WebP, checked by content rather
than by file extension. SVG is refused because an SVG rendered in the cockpit executes script. The
icon must stay inside the persona directory under the same real-path rule as persona files, so a
symlink cannot smuggle a file out of it. An icon that is missing, unreadable, of another type, or
larger than 256 KiB once encoded is dropped: the persona keeps its name and the cockpit falls back
to the default avatar rather than failing the profile.

## Plugin sources, readiness and defaults

A plugin that holds profiles in memory registers a `ProfileSource` with `ProfileSources.register(id, source)`.
Besides the synchronous, cached `list(scope)`, a source may declare two optional hooks:

- `ready(scope, signal)` resolves when `list` reflects the source's first complete load for that scope and
  rejects when the load failed. The signal aborts when nobody waits any more, so shared background work
  must keep running.
- `defaultProfile(scope, signal)` returns the name a workspace starts with when nothing asked for a profile,
  or `undefined` for no opinion. Reject when the source holds a default it cannot honor.

A source without the hooks counts as immediately ready and offers no default. The registry waits for every
declared `ready` together and reports failures by source id only. It asks `defaultProfile` in registration
order: the first answer that is not `undefined` wins, and a source that rejects ends the search instead of
handing the decision to the next source. A file profile keeps a name a source also holds.
`readProfileSources(context, scope)` returns a view that reads every hook as that workspace.

`resolveInitialProfile(files, sources, { intent, scope, signal })` decides a session's first profile once.
`intent` is `{ kind: 'named', name }` for a requested name, `{ kind: 'unspecified' }` when nothing asked,
and `{ kind: 'none' }` for an explicit choice of no profile that no default overrides.

- A name that is already listed resolves at once and never waits.
- A missing name waits for source readiness. Every wait of one resolution shares a single ten second
  deadline; a hook that ignores its signal cannot hold the session back.
- A source default applies only to `unspecified` in a workspace with an id, and it must name a profile that
  is in that workspace's catalog. A default that is not listed yet waits for the sources under the same
  deadline before it is ruled out. An unlisted default never falls through to another source.
- A name that never arrives, a failing source, a timeout and an unlisted default all give a session with no
  profile and one warning (`timeout`, `missing`, `source-failed` or `invalid-default`). Only the owning
  session aborting rejects.

The result is an `InitialProfileOutcome` holding names only. A launcher that decides before the session
exists publishes it on the session context as `po/profile-initial-outcome` and builds the persona and
environment from the same decision. The session then applies that outcome without waiting again, checks the
name against the live catalog, and shows the warning once when it starts. A session launched without an
outcome resolves for itself: a saved name waits for its source, and a session with no profile consults
`defaultProfile` when its workspace is known. It cannot tell an explicit "no profile" from an absent choice, so
a launcher that wants no profile must publish an outcome. The decision it makes is published on the session
context too. Every applied selection, whoever asked for it, leaves one identity marker once the session has
started.

`GET /api/workspaces/<workspace>/plugins/profile/launch-profiles` lists what a launcher may offer before a
session exists: `{ profiles: [{ name, identity?: { name?, icon?, role?, contact? }, sourceId }], readiness }`,
where `sourceId` is `files` or a source id, and `readiness` is `unavailable` when a source failed or was not
ready within ten seconds. It never carries environment, persona text or paths, bindings, credential
references or secrets.

The owner-authenticated session API lives under
`/api/workspaces/<workspace>/sessions/<session>/plugins/profile`:

- `GET /current` returns `{ profile: string | null }` from the live selection.
- `GET /profiles` returns the same display-only catalog as the launch endpoint, but uses the session's
  repository root and admitted `HOME`, and the session workspace's sources. It waits up to ten seconds,
  keeps partial results on timeout or source failure, and may be requested again to discover late profiles.
- `PUT /current` accepts `{ profile: string | null }`; `null` explicitly clears the selection. A known name
  is accepted immediately. A missing name waits up to ten seconds and is checked again. The change uses
  the next tool boundary, so a busy session keeps the request pending until application completes.
  Success returns the actual applied `{ profile }`. Identity journaling follows the normal host selection
  path and is not published a second time by the API.

Invalid JSON or selection bodies return 400 `Invalid profile selection`. A name still missing after
successful readiness returns 404 `Unknown profile`. Incomplete readiness returns 503
`Profiles are not ready. Try again.` An integration admission failure returns 503
`Profile integration is unavailable. Restore its credential or choose another profile.` These sanitized
responses do not echo names or source errors. Profile configuration failure returns 500
`Profile configuration is unavailable`.

Native uses this API for the in-session Profile page. Only the core dispatch-gate 503 bodies
`Session selection is not ready.` and `Session selection changed before dispatch.` fall back to the
`/profile` recovery dialog: those responses occur before profile code runs. An admission failure does not
trigger recovery or replay. A request abort prevents application only before enqueue; an already queued
change may still apply after the caller leaves. Never automatically retry a failed or abandoned write.
The next live selection status is authoritative.

## Owner management reads

The owner-authenticated management reads are for a profile manager, not a launcher. They are read-only and
bounded, and they never carry an environment value, integration binding, credential reference, secret alias or
count, absolute path, or raw source error. Host: `/api/plugins/profile`. Workspace:
`/api/workspaces/<workspace>/plugins/profile`.

- `GET /management` returns `{ profiles, default, defaultRevision?, readiness }`. Each profile is `{ name,
  identity?, origin, sourceId, kind, isDefault, editableSections, readOnlyReason? }`. `origin` is `personal`,
  `repository` or `plugin`. `kind` is `discovered` (found under a configured root), `explicit` (listed in a
  `profiles.yaml`) or `contributed` (held by a plugin source). `default` is `{ name, from, available }` or
  `null`: a repository declaration replaces a personal one, a plugin default applies only in a workspace and only
  when no file declares one, and a declared default that nothing lists stays `available: false` instead of
  falling back to another profile. `defaultRevision`, host only, is the opaque revision of the personal
  `profiles.yaml`, or `absent` before it exists.
- `GET /management/profile?name=<name>` returns one profile: the same fields plus `voice`, `timezone`, `preset`,
  `domains`, `wake` as `{ periodMs, period, prompt? }` (`period` is the YAML form, such as `6h`), `envKeys` (names
  only), `persona` as `[{ file, text, truncated }]` and `revisions`. A missing, empty, repeated or oversized name
  is 400 `Invalid profile name`; an unknown one is 404 `Unknown profile`, and neither echoes the name.
- `persona[].file` is `profile.md`, `SOUL.md`, `AGENTS.md` or `Plugin persona`, never a path or a label a plugin
  chose. Each text is cut at 16 KiB and says so with `truncated`. A plugin persona omits the line that names its
  source.
- `editableSections` lists `identity`, `persona` and `settings`, and only for a personal definition: the server
  derives it from the layer, from each persona file's real path staying inside its directory, and from a
  supported settings file. A repository or plugin profile has none and a `readOnlyReason` (`repository`, `plugin`
  or `unsupported`). A `SOUL.md` over the cap is not offered for editing, so no editor starts from cut text.
- `revisions` holds one opaque revision for each editable section, of the one file it writes: `profile.md` for
  `identity`, `SOUL.md` for `persona`, and for `settings` the `profiles.yaml` that lists an explicit entry or the
  `profile.yaml` of a discovered one. A file that does not exist yet reads `absent`.

The launch catalog is unchanged.

## Owner management writes

Only the host mount accepts profile and default writes. They use the same remote `settings.write` step-up policy as preset changes.

Persona memory (`GET`/`POST`/`DELETE /management/memory`) and session status (`GET /management/status`) are served
at both mounts, each checked against its own catalog, so a repository profile listed only in a workspace has them
too. Memory is keyed by profile name alone, and workspace status lists only that workspace's sessions.

- `PUT /management/profile?name=<name>` accepts `{ section, revision, values }`. `identity` changes display name
  and voice; `persona` replaces the existing `SOUL.md` text; `settings` changes preset, domains, wake and timezone.
- `PUT /management/default` accepts `{ profile: string | null, revision }`. `null` removes the personal declaration.
- A successful save returns `{ revision }`. The server checks the expected revision and the actual target before
  atomically replacing a single file. A stale revision returns 409 without replaying the write. Reload the latest
  values before making another save. Edits affect future starts or profile reselection, not running sessions.
- New profile forms use `POST /profiles` with `createOnly: true`, which returns 409 for a taken alias. The existing
  coordinator onboarding rewrite is unchanged when that field is omitted.

## Precedence

Po resolves names in four passes, from lowest to highest precedence:

1. Personal root discoveries
2. Repository root discoveries
3. Personal explicit entries
4. Repository explicit entries

A later profile replaces an earlier profile with the same name. This means any explicit entry
overrides discovery, including a personal explicit entry replacing a repository discovery. A
repository explicit entry wins over a personal explicit entry. Unrelated names from all sources
remain available, and the final list is sorted by profile name.

A `profile.yaml` sidecar does not change precedence: a synced profile is still a discovery. Any
explicit entry with the same name, personal or repository, replaces it entirely, including its
integration. When moving a profile to sync, remove or rename the old explicit entry.

## Environment defaults and activation

Every `env` key maps to a nonsecret string. Secret alias expressions are rejected in `env`. Applying a profile writes only variables that are not already
exported by the caller. When switching profiles, Po removes a value contributed by the previous
profile only if that value has not since changed, then applies the next profile's defaults.

The `/profile` command resolves the named profile and executes the change through the session
transition coordinator. A profile change uses Pi reload so extensions re-read the environment.
Po assembles the persona into a private run-directory file, and the persona Pi entry appends
that content to the system prompt after reload.

Autonomous voice can switch profiles too. The `profile` voice capability lists the configured
personas and queues a switch, which arrives as `/profile --voice-switch-token=…`. The chosen name
travels in a TTL-bounded handoff rather than in the command text, so an edited transcript cannot be
turned into a switch to a different persona. A spoken switch therefore takes the same reload path
as the command, which is also what lets the new persona's voice take effect: the spoken voice is
read when autonomous voice activates.

## Verification

```sh
pnpm nx test @agimon-ai/po-config
pnpm nx typecheck @agimon-ai/po-config
pnpm nx test @agimon-ai/po-profile
pnpm nx typecheck @agimon-ai/po-profile
pnpm --filter @agimon-ai/po exec po --profile writer --explain
```

Use an actual parent session to smoke-test `/profile` when changing transition, environment, or
persona application behavior.
