Metadata-Version: 2.4
Name: zarch
Version: 0.2.0
Summary: Z-Arch Runtime Library
License: Copyright © 2026 RAM Cloud Code LLC
        
        This license applies only to the Z-Arch Runtime Library (the "Software")
        and does not extend to any other component of the Z-Arch platform.
        
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this Software except in compliance with the License.
        You may obtain a copy of the License at:
        
            http://www.apache.org/licenses/LICENSE-2.0
            
        
                                         Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Classifier: License :: OSI Approved :: Apache Software License
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pyjwt==2.11.0
Requires-Dist: cryptography==46.0.3
Requires-Dist: quart==0.21.0
Requires-Dist: google-auth[aiohttp]==2.56.3
Requires-Dist: httpx==0.28.1
Dynamic: license-file

# Z-Arch Runtime Library

Z-Arch Runtime Library (`zarch`) provides the authentication primitives (`ZArchAuth`) used by services running within the Z-Arch architecture. It exposes a stable Python API for minting and handling encrypted session cookies, service-to-service trust, and the `ZArchExtension` interface with lifecycle hooks used during bootstrap and deployment workflows with the [Z-Arch CLI](https://zarch.ramcloudcode.com).


## Quick Start: `ZArchAuth`

Create a session service with `ZArchAuth`:
```python
from zarch import ZArchAuth

auth = ZArchAuth()

# Session service entrypoint.
# In a standard Z-Arch deployment, the gateway validates JWT + session cookie
# before protected traffic reaches your business services.
app = auth.session.start()
```
- `ZArchAuth.session.start()` starts an asynchronous Quart server
- runs the session service endpoints (`/session`, `/session/login`, `/session/logout`, `/session/verify`)
- adds optional session hooks for revocation, backend session control, additional validation requirements, and `/session` response enrichment

Common deployment pattern:
- Keep the session service separate from business services.
- Let Z-Arch Gateway enforce end-user auth; app services focus on business logic.
- Use `await ZArchAuth.s2s.sign(...)` and `ZArchAuth.s2s.verify(...)` for internal service trust.

## `ZArchAuth` API Reference

`ZArchAuth` exposes authentication functionality through two namespaces:

```python
from zarch import ZArchAuth

auth = ZArchAuth()

auth.session
auth.s2s
```

### `auth.session.start()`

`ZArchAuth.session.start()` starts an asynchronous Quart server and returns its application instance.

```python
app = auth.session.start()
```

The returned application exposes the standard Z-Arch session endpoints:

* `GET /session`
* `POST /session/login`
* `POST /session/logout`
* `POST /session/verify`
* `GET /session/health`

**Returns**

| Type          | Description                                              |
| ------------- | -------------------------------------------------------- |
| `quart.Quart` | Initialized asynchronous session service application.    |

---

### Session hook decorators

Register hooks with `@auth.session.on_login`, `@auth.session.on_logout`, `@auth.session.on_verify`, or `@auth.session.on_session`. Hook functions may be synchronous or asynchronous and only need to declare the available named parameters they use.

```python
@auth.session.on_verify
async def verify(sid, uid):
    return await session_store.is_valid(sid, uid)
```

Asynchronous hooks are awaited. Synchronous hooks run in a worker thread to avoid blocking Quart's event loop. A hook accepting `**kwargs` receives all parameters available for that event.

| Decorator | Available parameters | Return value |
| --- | --- | --- |
| `auth.session.on_login` | `sid`, `uid`, `tenant`, `iat`, `exp` | Ignored |
| `auth.session.on_logout` | `sid`, `uid`, `tenant` | Ignored |
| `auth.session.on_verify` | `sid`, `uid`, `tenant`, `iat`, `exp` | `True` when valid; `False` denies |
| `auth.session.on_session` | `uid`, `email`, `tenant`, `sid`, `iat`, `exp`, `claims` | `dict` to merge into the response, or `None` |

When `on_verify` is registered, it must return exactly `True` or `False`; any other value raises `TypeError`. When it is not registered, verification uses the stateless fallback and allows a cryptographically valid session.

Parameter meanings:

| Parameter | Description |
| --------- | ----------- |
| `sid` | Session identifier. For `on_session`, this is `None` when no valid session cookie is available. |
| `uid` | Authenticated user identifier. |
| `tenant` | Tenant identifier, or `None`. |
| `iat` | Session issued-at Unix timestamp. For `on_session`, this may be `None`. |
| `exp` | Session expiration Unix timestamp. For `on_session`, this may be `None`. |
| `email` | User email address, or `None`; available to `on_session` only. |
| `claims` | Decoded user-info claims; available to `on_session` only. |

### `auth.session.register_hook(hook_name, callback)`

Programmatically register a synchronous or asynchronous hook. This API remains available as an alternative to decorators and applies the same named-parameter filtering.

| Parameter   | Type     | Description                                                                                                      |
| ----------- | -------- | ---------------------------------------------------------------------------------------------------------------- |
| `hook_name` | `str`    | One of `on_login`, `on_logout`, `on_verify`, or `on_session`.                                                    |
| `callback`  | callable | Hook function; it may declare any subset of the selected hook's available named parameters.                     |

---

### `auth.session.verify(cookie_val, expect_uid=None, expect_tenant=None, stateful_session=None, session_service_url=None)`

Asynchronously decrypt and validate a Z-Arch encrypted session cookie. This method must be awaited.

In standard Z-Arch deployments, cryptographic session cookie verification is performed at the gateway. When stateful verification is enabled, the session service is also queried to determine whether the session remains valid via the `on_verify` hook. Only use `ZArchAuth.session.verify(...)` directly in application code for non-standard topologies. Normal use cases should never need to verify session cookies manually. 

```python
claims = await auth.session.verify(
    cookie_val,
    expect_uid="123",
)
```

**Parameters**

| Parameter             | Type          | Required    | Description                                                                              |
| --------------------- | ------------- | ----------- | ---------------------------------------------------------------------------------------- |
| `cookie_val`          | `str`         | Yes         | Raw encrypted Z-Arch session cookie value.                                               |
| `expect_uid`          | `str \| None` | No          | Expected user ID. Verification fails if provided and it does not match the cookie.       |
| `expect_tenant`       | `str \| None` | No          | Expected tenant ID. Verification fails if provided and it does not match the cookie.     |
| `stateful_session`    | `str \| None` | No          | Set to `"TRUE"` to perform authoritative state verification through the session service. |
| `session_service_url` | `str \| None` | Conditional | Base URL of the session service. Required when `stateful_session="TRUE"`.                |

**Returns**

A `dict` containing the verified session payload, including:

```python
{
    "sid": ...,
    "uid": ...,
    "tenant": ...,
    "iat": ...,
    "exp": ...,
    "v": ...
}
```

**Raises**

`ValueError` if the cookie is missing, invalid, tampered with, expired, does not satisfy expected identity constraints, or fails stateful verification.

---

### `auth.s2s.sign(req, target, url="")`

Asynchronously authorize an outbound request to another Z-Arch service. This method must be awaited.

The method adds a short-lived Z-Arch S2S JWT to the request as:

```text
x-zarch-s2s-token: <token>
```

On GCP, when `url` is supplied, it also adds a Google OIDC identity token using:

```text
X-Serverless-Authorization: Bearer <token>
```

```python
await auth.s2s.sign(
    req,
    target="orders",
    url="https://orders-abc-uc.a.run.app",
)
```

**Parameters**

| Parameter | Type   | Required | Description                                                                                                                               |
| --------- | ------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `req`     | object | Yes      | Outbound HTTP request object. It must expose a mutable `headers` attribute supporting header assignment with `req.headers[name] = value`. |
| `target`  | `str`  | Yes      | Z-Arch service ID of the intended downstream service. The target must be permitted by this service's build-derived S2S policy.            |
| `url`     | `str`  | No       | Base URL of the upstream service. On GCP, this is used as the audience when minting the Google OIDC identity token.                       |

The `req` parameter is intentionally framework and HTTP-client agnostic. Any request-like object satisfying the documented `headers` interface may be used.

**Raises**

`PermissionError` if the requested `target` is not authorized by the service's `S2S_ALLOWED_TARGETS` policy.

---

### `auth.s2s.verify(req)`

Verify the Z-Arch S2S credentials on an inbound request.

The method reads the `x-zarch-s2s-token` request header and validates the token's signature, issuer, audience, expiration, freshness, and deployment-derived trust policy.

```python
claims = auth.s2s.verify(request)
```

**Parameters**

| Parameter | Type   | Required | Description                                                                                                    |
| --------- | ------ | -------- | -------------------------------------------------------------------------------------------------------------- |
| `req`     | object | Yes      | Inbound HTTP request object. It must expose a `headers` attribute supporting `req.headers.get(name, default)`. |

The request object does not need to be a Quart request. Any framework or request implementation exposing the required `headers` interface is compatible.

Examples include request objects from Quart, FastAPI/Starlette, and other libraries with equivalent header access semantics.

**Returns**

A `dict` containing the verified S2S JWT claims:

```python
{
    "iss": ...,
    "aud": ...,
    "iat": ...,
    "exp": ...,
    "typ": "zarch/s2s",
    "v": 1,
}
```

**Raises**

`PermissionError` when the S2S token is missing, malformed, expired, signed by an unknown or invalid issuer, addressed to the wrong service, or outside the allowed freshness bounds.

## Usage & Examples
### Session

Session cookies are stateless by default. If no hooks are registered, cryptographic cookie validation is enough and `/session/verify` defaults to valid after payload checks.

To enable stateful behavior (revocation, server-side deny lists, tenant-specific controls) and enrich the `/session` response, decorate the hooks needed by your session service. Each hook may declare only the available parameters it uses.

Any dict returned by `on_session` is merged after the default `uid`/`email`/`tenant` fields, so matching keys override the built-in values.

For `on_session`, `sid`, `iat`, and `exp` come from the current encrypted session cookie when it is available and valid; otherwise they are `None`.

Real-world pattern:
- hash `sid` before storage
- persist session records on login
- mark `revoked_at` on logout (idempotent)
- deny in `on_verify` when revoked, missing, or expired
- decorate `/session` with app-specific profile metadata when needed

```python
from zarch import ZArchAuth
from google.cloud import firestore
from datetime import datetime, timezone
import hashlib
import time

auth = ZArchAuth()
db = firestore.AsyncClient()

def _hash_sid(sid: str) -> str:
    return hashlib.sha256(sid.encode()).hexdigest()

@auth.session.on_login
async def on_login(sid: str, uid: str, tenant: str | None, iat: int, exp: int) -> None:
    await db.collection("zarch_sessions").document(_hash_sid(sid)).set({
        "uid": uid,
        "tenant": tenant,
        "created_at": datetime.fromtimestamp(iat, tz=timezone.utc),
        "expires_at": datetime.fromtimestamp(exp, tz=timezone.utc),
        "revoked_at": None,
    })

@auth.session.on_logout
async def on_logout(sid: str) -> None:
    await db.collection("zarch_sessions").document(_hash_sid(sid)).set({
        "revoked_at": datetime.now(tz=timezone.utc),
    }, merge=True)

@auth.session.on_verify
async def on_verify(sid: str) -> bool:
    doc = await db.collection("zarch_sessions").document(_hash_sid(sid)).get()
    if not doc.exists:
        return False

    data = doc.to_dict()
    if data.get("revoked_at") is not None:
        return False
        
    expires_at = data.get("expires_at")
    return bool(expires_at and expires_at.timestamp() >= time.time())

@auth.session.on_session
async def on_session(
    uid: str,
    email: str | None,
    sid: str | None,
    claims: dict,
) -> dict | None:
    return {
        "display_name": claims.get("name") or email or uid,
        "has_active_session": bool(sid),
    }

app = auth.session.start()
```

### S2S

`ZArchAuth.s2s` exists so internal calls are explicitly authorized at the application-policy layer, not just network-reachable.

When you await `auth.s2s.sign(req, target, url=...)`:
- Z-Arch always adds `x-zarch-s2s-token: <jwt>` (short-lived Ed25519 JWT with `iss`, `aud`, `iat`, `exp`, `typ`).
- On GCP (`ZARCH_PLATFORM=gcp`) and when `url` is provided, it also adds `X-Serverless-Authorization: Bearer <google-id-token>`.

Why both are used in GCP deployments:
- The Google ID token is the stronger platform authentication mechanism (Cloud Run/IAM identity boundary).
- The Z-Arch token is a service-authorization policy mechanism (enforces caller identity, audience, and Z-Arch trust graph rules).
- Using both gives layered control: Google proves caller identity to the platform, Z-Arch enforces project policy at the service layer.

The Z-Arch token can also be used by itself in non-GCP or non-IAM topologies. In that mode, services still get signed caller identity and audience/policy checks without requiring Google-authenticated services.

#### Request Object Compatibility:

`ZArchAuth.s2s` is framework-agnostic and accepts request-like objects through a minimal interface:

* `await auth.s2s.sign(req, ...)` requires an object with a mutable `headers` attribute supporting header assignment.
* `auth.s2s.verify(req)` requires an object with a `headers` attribute supporting `.get(name, default)`.

This allows S2S authentication to work with request objects from Quart, FastAPI/Starlette, `httpx`, and other libraries that expose compatible headers.


Caller example (adds both headers on GCP):

```python
import httpx
from zarch import ZArchAuth

auth = ZArchAuth()

async def call_orders_service() -> dict:
    req = httpx.Request(
        "POST",
        "https://orders-abc-uc.a.run.app/internal/create",
        json={"sku": "A-100", "qty": 1},
    )

    # Always injects x-zarch-s2s-token.
    # On GCP + url provided, also injects X-Serverless-Authorization: Bearer <google-id-token>.
    await auth.s2s.sign(req, target="orders", url="https://orders-abc-uc.a.run.app")

    async with httpx.AsyncClient(timeout=30) as client:
        response = await client.send(req)
        response.raise_for_status()
        return response.json()
```

Receiver example (verifies Z-Arch policy token):

```python
from quart import Quart, jsonify, request
from zarch import ZArchAuth

app = Quart(__name__)
auth = ZArchAuth()

@app.post("/internal/create")
async def create_order():
    # Verifies x-zarch-s2s-token signature, audience, issuer trust, and freshness.
    claims = auth.s2s.verify(request)
    caller_service = claims["iss"]

    # Cloud Run IAM / Google token auth (if enabled) is evaluated by platform/gateway.
    return jsonify({"ok": True, "caller": caller_service}), 200
```

S2S verification data is deployment-derived and local at runtime:
- `SERVICE_ID`: current service identity.
- `S2S_PUBLIC_KEYS_JSON`: trusted caller public keys by service ID.
- `S2S_ALLOWED_TARGETS`: mint-time policy for where this service may call.

---
## Security Model Summary

- Session cookies are encrypted and stateless by default; stateful controls are added explicitly via `on_login`, `on_logout`, and `on_verify` hooks, while `/session` response enrichment is opt-in via `on_session`.
- In the intended Z-Arch platform flow, gateway/session components handle end-user auth so application services do not need to implement cookie auth logic directly.
- `ZArchAuth.s2s.sign(...)` and `ZArchAuth.s2s.verify(...)` enforce short-lived signed service-to-service trust with explicit caller/target validation.
- Auth helpers fail closed: invalid, expired, tampered, or unauthorized credentials raise errors that should map to `401`/`403`.
- Secret material (cookie encryption keys, S2S keys, API credentials) should come from secure secret management and never be hardcoded or logged.

---

# Z-Arch Extensions: Project Context Interface

This document describes the **extension-facing interface** exposed to extensions through the `project_context` argument passed into lifecycle hooks. This is the stable API extensions should use. It is intentionally narrow, safe, and versioned by Z-Arch.

If you are authoring an extension, you should **only** access functionality via `project_context` (not internal modules).

---

## Quick Start

A minimal extension looks like:

```python
from typing import Any, Dict
from zarch.extensions.base import ZArchExtension

class Extension(ZArchExtension):
    def claim(self, extension_name: str, extension_block: Dict[str, Any]) -> bool:
        return extension_block.get("type") == "example"

    async def post_service_deploy(self, project_context, extension_configuration: Dict[str, Any]) -> None:
        project_context.log("Hello from my extension!")
```

The `project_context` object is your primary tool. It provides:
- project metadata (project ID, region, repo path)
- config accessors
- safe prompt helpers
- GCP helpers (secrets, service URLs, env vars, service accounts)
- GitHub and Cloudflare helpers

Lifecycle hooks are async. Await async `project_context` helpers such as `gcloud`, Secret Manager, Cloud Run service metadata, connected-repo lookup, and Cloudflare operations. Logging, config accessors, prompts, and `github()` are synchronous.

---

## Lifecycle Hooks (from `ZArchExtension`)

Extensions can implement any subset of these methods. Hook methods must be defined with `async def`; Z-Arch rejects synchronous hook implementations. Each hook receives `project_context` and the extension-specific configuration block.

### `claim(extension_name, extension_block) -> bool`
Return `True` if your extension should handle this extension block in `zarch.yaml`.

**Example**
```python
    def claim(self, extension_name: str, extension_block: Dict[str, Any]) -> bool:
        return extension_block.get("type") == "my-extension"
```

### `pre_project_bootstrap(project_context, extension_configuration)`
Runs before initial project bootstrap, but after prompting and repo cloning.

**Example**
```python
    async def pre_project_bootstrap(self, project_context, extension_configuration):
        project_context.log("Preparing custom bootstrap")
```

### `post_project_bootstrap(project_context, extension_configuration)`
Runs after initial project bootstrap.

**Example**
```python
    async def post_project_bootstrap(self, project_context, extension_configuration):
        domain = project_context.config_get("domain")
        project_context.log(f"Project domain is {domain}")
```


### `pre_service_deploy(project_context, extension_configuration)`
Runs before a Cloud Run service is deployed.

**Example**
```python
    async def pre_service_deploy(self, project_context, extension_configuration):
        project_context.log("Preparing service deployment")
```

### `post_service_ensureSA(project_context, extension_configuration)`
Runs immediately after the service runtime service account has been ensured/created.

**Example**
```python
    async def post_service_ensureSA(self, project_context, extension_configuration):
        event = project_context.get_event_data() or {}
        sa = ((event.get("payload") or {}).get("service_account") or {}).get("email")
        project_context.log(f"Service SA ready: {sa}")
```

### `post_service_deploy(project_context, extension_configuration)`
Runs after a Cloud Run service has been deployed.

**Example**
```python
    async def post_service_deploy(self, project_context, extension_configuration):
        project_context.log("Service deployed successfully")
```

### `pre_gateway_deploy(project_context, extension_configuration)`
Runs before the Z-Arch gateway is deployed.

**Example**
```python
    async def pre_gateway_deploy(self, project_context, extension_configuration):
        project_context.log("Preparing gateway deployment")
```

### `post_gateway_ensureSA(project_context, extension_configuration)`
Runs immediately after the gateway service account has been ensured/created.

**Example**
```python
    async def post_gateway_ensureSA(self, project_context, extension_configuration):
        payload = (project_context.get_event_data() or {}).get("payload") or {}
        project_context.log(f"Gateway SA: {payload.get('service_account', {}).get('email')}")
```

### `post_gateway_deploy(project_context, extension_configuration)`
Runs after the Z-Arch gateway has been deployed.

**Example**
```python
    async def post_gateway_deploy(self, project_context, extension_configuration):
        project_context.log("Gateway deployed successfully")
```

### `pre_job_deploy(project_context, extension_configuration)`
Runs before a Cloud Run job is deployed.

**Example**
```python
    async def pre_job_deploy(self, project_context, extension_configuration):
        project_context.log("Preparing job deployment")
```

### `post_job_ensureSA(project_context, extension_configuration)`
Runs immediately after the job runtime service account has been ensured/created.

**Example**
```python
    async def post_job_ensureSA(self, project_context, extension_configuration):
        payload = (project_context.get_event_data() or {}).get("payload") or {}
        project_context.log(f"Job SA: {payload.get('service_account', {}).get('email')}")
```

### `post_job_deploy(project_context, extension_configuration)`
Runs after a Cloud Run job has been deployed.

**Example**
```python
    async def post_job_deploy(self, project_context, extension_configuration):
        job_id = project_context.config_get("jobs[0].id")
        project_context.log(f"Job {job_id} deployed successfully")
```

### `pre_scheduler_deploy(project_context, extension_configuration)`
Runs before a Cloud Scheduler job is deployed.

**Example**
```python
    async def pre_scheduler_deploy(self, project_context, extension_configuration):
        project_context.log("Preparing scheduler deployment")
```

### `post_scheduler_ensureSA(project_context, extension_configuration)`
Runs immediately after the scheduler service account has been ensured/created.

**Example**
```python
    async def post_scheduler_ensureSA(self, project_context, extension_configuration):
        payload = (project_context.get_event_data() or {}).get("payload") or {}
        principal = payload.get("principal", {}).get("id")
        project_context.log(f"Scheduler principal with SA ready: {principal}")
```

### `post_scheduler_deploy(project_context, extension_configuration)`
Runs after a Cloud Scheduler job has been deployed.

**Example**
```python
    async def post_scheduler_deploy(self, project_context, extension_configuration):
        scheduler_id = project_context.config_get("schedulers[0].id")
        project_context.log(f"Scheduler {scheduler_id} deployed successfully")
```

### `pre_topic_deploy(project_context, extension_configuration)`
Runs before a Pub/Sub topic is deployed.

**Example**
```python
    async def pre_topic_deploy(self, project_context, extension_configuration):
        project_context.log("Preparing topic deployment")
```

### `post_topic_deploy(project_context, extension_configuration)`
Runs after a Pub/Sub topic has been deployed.

**Example**
```python
    async def post_topic_deploy(self, project_context, extension_configuration):
        topic_id = project_context.config_get("topics[0].id")
        project_context.log(f"Topic {topic_id} deployed successfully")
```

## Hook Payload Matrix

Lifecycle event payloads are additive schema-v1 summaries. Use `.get(...)` and tolerate unknown keys.

| Hook | Key payload fields (summary) |
| --- | --- |
| `pre_project_bootstrap` | `project_id`, `module`, `principal`, `repo`, `create_gcp_project`, `regions`, `domain`, `edge_proxy`, `userbase` |
| `post_project_bootstrap` | `status`, `repo`, `domain`, `edge_proxy`, `userbase`, `clients`, `control_plane_ready`, `gateway_deployed` |
| `pre_service_deploy` | `principal`, `resource_type`, `source`, `endpoint`, `flags`, `routes`, `targets`, `env`, `schema`, `control_plane_args` (wrapper) |
| `post_service_ensureSA` | `principal`, `service_account`, `resource_type`, `source`, `endpoint`, `flags`, `targets`, `routes`, `env`, `schema` |
| `post_service_deploy` | `deployment`, `inbound_callers`, `outbound_targets`, `s2s`, `env`, `endpoint`, `targets` |
| `pre_gateway_deploy` | `principal`, `rotate_session_key`, `min_instance`, `auth_profile`, `session`, `trial_mode`, `control_plane_args` (wrapper) |
| `post_gateway_ensureSA` | `principal`, `service_account`, `rotate_session_key`, `min_instance`, `auth_profile`, `session`, `trial_mode` |
| `post_gateway_deploy` | `deployment`, `gateway`, `session`, `s2s`, `env` |
| `pre_job_deploy` | `principal`, `source`, `flags`, `targets`, `env`, `control_plane_args` (wrapper) |
| `post_job_ensureSA` | `principal`, `service_account`, `source`, `targets`, `flags`, `env` |
| `post_job_deploy` | `deployment`, `targets`, `target_summary`, `s2s`, `env` |
| `pre_scheduler_deploy` | `principal`, `schedule_mode`, `schedule`, `timezone`, `paused`, `targets`, `target_count` |
| `post_scheduler_ensureSA` | `principal`, `service_account`, `schedule_mode`, `schedule`, `timezone`, `paused`, `targets`, `target_count` |
| `post_scheduler_deploy` | `service_account`, `schedule_mode`, `schedule`, `timezone`, `paused`, `targets`, `target_summary`, `created_scheduler_job_ids` |
| `pre_topic_deploy` | `principal`, `subscribers`, `subscriber_ids`, `subscriber_count`, `publisher_candidates`, `publisher_candidate_count` |
| `post_topic_deploy` | `principal`, `subscribers`, `subscriber_ids`, `subscriber_count`, `publishers`, `publisher_ids`, `publisher_count` |

All payloads avoid secret values (for example: env var values, session keys, gateway URL/suffix secrets).

## Manual Hook Triggering

Use the CLI to manually dispatch lifecycle hooks for configured extensions:

```bash
zarch ext trigger pre_service_deploy
zarch ext trigger post_service_ensureSA --extension my-extension
zarch ext trigger post_service_deploy --extension my-extension
zarch ext trigger post_gateway_deploy --extension audit --extension cache
```

- `hook_name` must be one of the lifecycle hooks defined by `ZArchExtension`.
- `--extension` is optional and can be repeated. Values must match extension block names under `extensions:` in `zarch.yaml`.
- Without `--extension`, all configured extension blocks are considered, and only installed extensions that claim those blocks are invoked.
- Dispatch follows the normal hook execution policy (`local` vs `remote`) used by live deployments.
- Manual dispatches include minimal event metadata where `source` is `"manual"` and `payload.extension_names` lists any explicitly selected extension blocks.

---

## `project_context` Interface

The sections below describe **all available attributes and methods** exposed to extensions. Use them as the primary API surface.

### Core Attributes

These attributes represent the current project state in a safe, read-only form.

- `project_context.id` (str)
  - The active GCP project ID.
  - Example: `"my-gcp-project"`

  **Example**
  ```python
  project_id = project_context.id
  project_context.log(f"Deploying project {project_id}")
  ```

- `project_context.region` (str)
  - The active region for this deployment run.
  - Example: `"us-east1"`

  **Example**
  ```python
  region = project_context.region
  project_context.log(f"Active region: {region}")
  ```

- `project_context.project_root_path` (`pathlib.Path`)
  - Absolute path to the project root directory.

  **Example**
  ```python
  root = project_context.project_root_path
  project_context.log(f"Root path: {root}")
  ```

- `project_context.non_interactive` (bool)
  - True if Z-Arch is running in non-interactive mode.

  **Example**
  ```python
  if project_context.non_interactive:
      project_context.log("Running non-interactively")
  ```

- `project_context.config` (`zarch_cli.helpers.config.Config`)
  - The loaded Z-Arch config object.
  - Most extensions should use the `config_get`, `config_set`, and `config_save` helpers instead of accessing `config` directly.

  **Example**
  ```python
  cfg = project_context.config
  project_context.log(f"Config loaded from: {cfg.root}")
  ```

### Event Metadata

#### `get_event_data() -> dict[str, Any] | None`
Read optional metadata for the lifecycle hook currently being dispatched.

- This may be `None` when metadata is unavailable.
- Keys are additive and may grow over time; extensions should tolerate unknown keys.
- Known envelope fields include:
  - `schema_version` (integer)
  - `source` (`"live"` or `"manual"`)
  - `hook` (hook name)
  - `timestamp` (UTC ISO-8601)
  - `resource` (e.g. kind/id/region)
  - `payload` (hook-specific details, may be empty)

**Example**
```python
event = project_context.get_event_data() or {}
payload = event.get("payload") or {}
principal = payload.get("principal") or {}
service_account = payload.get("service_account") or {}

project_context.log(
    f"Hook={event.get('hook')} principal={principal.get('kind')}:{principal.get('id')} "
    f"sa={service_account.get('email')}"
)
```

---

### Logging

#### `log(message: str, level: str | None = None) -> None`
Write a styled message to the Z-Arch console.

- `level` is optional and used only to tag the message (e.g. "INFO", "WARN").

**Example**
```python
project_context.log("Preparing extension steps", level="info")
```

---

### Command Execution

#### `async run_command(command_parts: list[str]) -> tuple[str, int]`
Run a local shell command. Returns `(stdout, exit_code)`.

**Example**
```python
out, code = await project_context.run_command(["echo", "hello"])
if code == 0:
    project_context.log(out.strip())
```

#### `async gcloud(command_parts: list[str]) -> tuple[str, int]`
Run a `gcloud` command using the embedded or system `gcloud` binary.
Returns `(stdout, exit_code)`.

**Example**
```python
out, code = await project_context.gcloud(["projects", "list", "--format=value(projectId)"])
if code == 0:
    project_context.log("Projects:\n" + out)
```

---

### Config Access

#### `config_get(key: str, default: Any = None) -> Any`
Fetch a config value using dotted path notation.

**Example**
```python
domain = project_context.config_get("domain", "")
project_context.log(f"Domain: {domain}")
```

#### `config_set(key: str, value: Any) -> None`
Set a config value in memory (does not write to disk).

**Example**
```python
project_context.config_set("gateway.session.stateful", False)
```

#### `config_save() -> None`
Persist config changes to `zarch.yaml`.

**Example**
```python
project_context.config_set("gateway.session.stateful", False)
project_context.config_save()
```

---

### Prompts

These are safe wrappers around Z-Arch’s prompt system.

#### `ask(message: str, default: str | None = None, required: bool = True, validate: Callable | None = None) -> str`
Prompt the user for a string value.

**Example**
```python
name = project_context.ask("What is the service name?", default="session")
```

#### `choice(message: str, choices: list[str], default: str | None = None, sub_prompt: str = "") -> str`
Prompt the user to select a single option.

**Example**
```python
region = project_context.choice("Select region", ["us-east1", "us-west1"], default="us-east1")
```

#### `multichoice(message: str, choices: list[str], default: list[str] | None = None, sub_prompt: str = "(space to toggle, enter to confirm)") -> list[str]`
Prompt the user to select multiple options.

**Example**
```python
features = project_context.multichoice("Enable features", ["cdn", "auth", "logging"])
```

#### `yes_no(message: str, default: bool = True, sub_prompt: str = "") -> bool`
Prompt the user for a yes/no response.

**Example**
```python
confirm = project_context.yes_no("Proceed with cleanup?", default=False)
```

#### `review_and_confirm() -> None`
Render the config and ask the user to confirm. Useful before sensitive operations.

**Example**
```python
project_context.review_and_confirm()
```

---

### GCP Helpers

These helpers wrap common GCP operations and automatically use the project context’s `id` and `region` where applicable.

#### `async ensure_service_account(service_account_name: str, display_name: str | None = None) -> str`
Ensure a service account exists, creating it if missing.

- `service_account_name` can be either a full email (`name@project.iam.gserviceaccount.com`) or just the short name.
- If `display_name` is omitted, Z-Arch derives it from the service account name.

**Example**
```python
sa = await project_context.ensure_service_account("zarch-ext")
project_context.log(f"Service account: {sa}")
```

#### `async secret_exists(secret_name: str) -> bool`
Check if a Secret Manager secret exists in the current project.

**Example**
```python
if not await project_context.secret_exists("my-secret"):
    project_context.log("Secret does not exist")
```

#### `async store_secret(secret_name: str, secret_value: str) -> None`
Create or update a Secret Manager secret with a new version.

**Example**
```python
await project_context.store_secret("my-secret", "super-secure-token")
```

#### `async get_secret(secret_name: str) -> str`
Fetch the latest version of a Secret Manager secret.

**Example**
```python
token = await project_context.get_secret("my-secret")
```

#### `async get_service_url(service_name: str) -> str`
Fetch the Cloud Run service URL for a named service in the current region.

**Example**
```python
session_url = await project_context.get_service_url("session")
project_context.log(f"Session URL: {session_url}")
```

#### `async get_env_var(service_name: str, env_var_key: str) -> str`
Read a specific environment variable from a deployed service or function.

**Example**
```python
public_key = await project_context.get_env_var("zarch-gateway", "S2S_PUBLIC_KEY")
```

#### `async set_env_vars(service_name: str, env_vars: dict[str, str]) -> None`
Set or update environment variables on a deployed service or function.

**Example**
```python
await project_context.set_env_vars("session", {"SESSION_TTL": "1209600"})
```

---

### GitHub

#### `github()`
Return an authenticated GitHub client (PyGitHub-style client used internally by Z-Arch).

**Example**
```python
gh = project_context.github()
user = gh.get_user()
project_context.log(f"GitHub user: {user.login}")
```

#### `async get_connected_repo() -> tuple[str, str]`
Return the connected repo fullname and branch as `("owner/repo", "branch")`.

**Example**
```python
repo, branch = await project_context.get_connected_repo()
project_context.log(f"Connected repo: {repo} ({branch})")
```

---

### Cloudflare

These helpers manage Cloudflare workers and pages as used by Z-Arch.

#### `async update_edge_proxy(project_name: str | None = None) -> None`
Update the edge proxy worker for the project.

- If `project_name` is omitted, it is inferred from the connected repo name.

**Example**
```python
await project_context.update_edge_proxy()
```

#### `async set_edge_proxy_envs(env_vars: dict[str, str], project_name: str | None = None) -> bool`
Set environment variables on the edge proxy worker.

- Returns `True` on success, `False` on failure.

**Example**
```python
ok = await project_context.set_edge_proxy_envs({"API_VERSION": "v1"})
if not ok:
    project_context.log("Failed to update edge envs", level="warn")
```

#### `async deploy_cf_worker(script_name: str, repo_root_dir: str, repo_full: str | None = None, branch: str | None = None, domain: str | None = None) -> None`
Deploy a Cloudflare Worker from the connected repo.

- `script_name`: Worker script identifier
- `repo_root_dir`: Root path in the repo to deploy
- `repo_full`: Optional `owner/repo` override
- `branch`: Optional branch override
- `domain`: Optional custom domain

**Example**
```python
await project_context.deploy_cf_worker(
    script_name="my-worker",
    repo_root_dir="services/edge",
    branch="main",
)
```

#### `async set_worker_route(script_name: str, domain: str, route: str = "/api/*") -> None`
Attach a route to a worker script.

**Example**
```python
await project_context.set_worker_route("my-worker", "example.com", "/api/*")
```

#### `async deploy_cf_pages(domain: str, project_name: str | None = None, repo_full: str | None = None, branch: str | None = None) -> None`
Deploy a Cloudflare Pages project from the connected repo.

**Example**
```python
await project_context.deploy_cf_pages("example.com")
```

---

## End-to-End Example

A realistic extension that uses multiple helpers:

```python
from typing import Any, Dict
from zarch.extensions.base import ZArchExtension

class Extension(ZArchExtension):
    def claim(self, extension_name: str, extension_block: Dict[str, Any]) -> bool:
        return extension_block.get("type") == "my-ext"

    async def post_service_deploy(self, project_context, extension_configuration: Dict[str, Any]) -> None:
        project_context.log("Post-deploy hook starting")

        # Read config
        domain = project_context.config_get("domain", "")
        if not domain:
            project_context.log("No domain configured", level="warn")
            return

        # Ensure a secret exists
        if not await project_context.secret_exists("edge-api-key"):
            await project_context.store_secret("edge-api-key", "replace-me")

        # Update edge proxy envs
        await project_context.set_edge_proxy_envs({"API_VERSION": "v1"})

        # Deploy pages site
        await project_context.deploy_cf_pages(domain)

        project_context.log("Post-deploy hook complete")
```

---

## zarch.yaml
```yaml
    extensions:
      {extension_name}:
        type: "{extension_name}"
        required_roles: []
        config:
          example_key: example_value
```
Add each extention to zarch.yaml or it will not run even if it is installed. The extension block is a dictionary of objects keyed by each extension's name. `type` is the extension's name. Include all GCP IAM roles that are required by the service account that will run the extension in the `required_roles` list. Values in `config:` are available to the extension code at runtime. 

---

## Notes and Best Practices

- Prefer `config_get`/`config_set` over accessing `project_context.config` directly.
- Use `log()` for all extension output to stay consistent with Z-Arch UX.
- Avoid raw shell calls unless absolutely necessary; use provided helpers first.
- Never log secrets or gateway URL suffixes.

If you need additional helpers, consider filing a request rather than importing internal modules directly.

---

## License

Apache License 2.0. See `LICENSE`.
Copyright © 2026 [RAM Cloud Code LLC](https://ramcloudcode.com)
