I read this as an advisory architecture investigation - I’ll trace authority from candidate creation through activation, capability issuance, transport, gateway, coaching, and tests, then compare minimal external-authority designs and recommend exact seams without editing files.


I read this as an advisory architecture investigation - I surveyed the Task26 qualification, activation, capability, nutrition, gateway, transport, receipt, and test paths and recommend a minimal external filesystem authority with lock-based TOCTOU control.

## Recommendation

Use an **operator-owned local filesystem authority**, separate from every candidate bundle and profile:

```text
/etc/hermes/task26-authority-pin.json       # immutable operator pin
/var/lib/hermes/task26-authority/
  genesis.json                              # immutable identity
  authority.lock                            # shared/exclusive flock
  registry.json                             # mutable hash-chained registry
  qualification-ledger.json                 # mutable paired ledger
```

Expose it through one injectable `CandidateAuthoritySource` interface. Production uses a read-only `FileCandidateAuthoritySource`; Golden and unit tests use an in-memory implementation.

This is the smallest design satisfying all requirements. Do not add a database, event bus, distributed consensus, or remote signing service for this single-host pilot.

## Current architecture and flaw

The current Task26 authority is qualification evidence, not runtime authority:

- `gateway/platforms/task26_candidate_authority.py`
  - `append_candidate_authority()` writes paired v1 registry/ledger files beneath any caller-supplied root.
  - `verify_candidate_authority()` verifies chains and current/revoked status.
  - There is no source identity, pinned genesis, freshness limit, process lock, or production-root distinction.
- `scripts/source_golden_path.py`
  - Calls `append_candidate_authority(profile, ...)` only at the end of the Golden lifecycle.
  - The lifecycle has already activated a customer, issued a capability, and exercised transport before qualification exists.
- `scripts/verify_source_golden_path.py`
  - Calls `verify_candidate_authority(root, candidate)` only as an offline verifier.
- `gateway/platforms/task26_final_state.py`
  - Copies `candidate-authority/registry.json` and `qualification-ledger.json` into the sealed candidate.
  - Rehydration compares the immutable copied heads, so it proves historical qualification but cannot observe later revocation.
- No production activation, capability, or transport module imports `verify_candidate_authority()`.

Runtime paths therefore trust only immutable or profile-local candidate pins:

- `dualcoach_tasks21_25_controller.launch_controller()` validates manifest, profile, wheel, and service state, but not current candidate authority.
- It currently starts the service before writing the launch authorization.
- `dualcoach_tasks21_25_controller.issue_delivery_capability()` trusts the launch receipt and profile hash.
- `dualcoach_activation_cutover.activate_customer_cutover()` trusts deployment and membership evidence but not current candidate authority.
- `NutritionCoachingCoordinator.issue_delivery_capability()` accepts any syntactically valid `DeliveryLaunchAuthorization`.
- `NutritionCoachingCoordinator.validate_delivery_transport()` verifies customer, route, approval, expiry, and one-use state, but only checks that candidate fields look like SHA-256 values.
- `AdaptiveOperatorService._issue()` and `AdaptiveOperatorCapability` bind owner/config/registry/consent/activation state, but no Task26 candidate authority.
- `AdaptiveNutritionCoordinator.activate_latest()` and `deliver_latest_once()` do not consult Task26 authority.
- `TelegramCustomerTransport`, scheduled delivery, reminders, activation notices, legacy draft delivery, and onboarding publications all revalidate customer/profile authority, but not the current Task26 candidate.

A copied one-event bundle therefore remains sufficient forever.

## Viable designs

### A. External filesystem authority with a shared transport lock — recommended

The runtime reads the operator-owned registry and ledger under `flock(LOCK_SH)`. Operator qualification, affirmation, and revocation append under `LOCK_EX`.

For the final transport check, the runtime retains the shared lock through the provider invocation. Therefore:

- A revocation committed before the final check prevents transport.
- A revocation writer arriving during transport waits.
- The transport is linearized before that revocation, eliminating the check/send gap.

Trade-offs:

- Lowest implementation and migration cost.
- Excellent offline testability.
- No network dependency.
- POSIX/local-filesystem coupling.
- A slow provider call delays revocation commit, so transport calls must have bounded timeouts.
- A crash between paired registry/ledger replacements fails closed and needs operator repair.

### B. Authority broker that owns transport permits

A small local daemon verifies candidate authority and either:

1. proxies the provider send itself, or
2. grants and atomically consumes a transport permit while serializing revocations.

Trade-offs:

- Stronger isolation if the gateway account must not read or write operator files.
- Better multi-host evolution.
- More deployment units, IPC authentication, availability failure modes, protocol testing, and Golden harness work.
- A permit-only broker still has a TOCTOU gap unless it owns transport or retains a lease through provider I/O.

This does not pay for itself in the current single-host Task26 architecture.

A signed snapshot feed without locking or broker-owned transport is not sufficient: signatures authenticate state but do not close the revocation/check/send race.

## External authority schema

### Operator pin

`task26-authority-pin-v1` must be supplied independently, preferably through a systemd credential or root/operator-owned file:

```json
{
  "schema": "task26-authority-pin-v1",
  "source_id": "<64 hex>",
  "genesis_sha256": "<64 hex>",
  "authority_root": "/var/lib/hermes/task26-authority",
  "max_event_age_seconds": 86400,
  "allowed_clock_skew_seconds": 60
}
```

The pin loader must reject:

- Relative or symlinked paths.
- A root beneath the profile, package, wheelhouse, launch-receipt directory, or candidate bundle.
- Bundle v1 schemas.
- Wrong source ID or genesis hash.
- Unsafe ownership/modes.
- Missing lock, registry, ledger, or genesis files.

### Genesis

```json
{
  "schema": "task26-runtime-authority-genesis-v1",
  "source_id": "<64 hex>",
  "created_at_utc": "...",
  "operator_domain": "dualcoach-production",
  "generation": 1
}
```

The independently supplied pin contains the hash of these canonical bytes.

### Registry event

```json
{
  "sequence": 7,
  "source_id": "<64 hex>",
  "genesis_sha256": "<64 hex>",
  "previous_sha256": "<registry event head>",
  "ledger_predecessor_sha256": "<ledger row head>",
  "action": "qualify|affirm|revoke",
  "candidate_digest": "<64 hex>",
  "historical_pass_digest": "<64 hex>",
  "committed_at_utc": "...",
  "valid_until_utc": "...",
  "reason": "...",
  "event_sha256": "<hash of preceding fields>"
}
```

Rules:

- `qualify` selects one current candidate.
- `affirm` may refresh only the currently selected, non-revoked candidate.
- `revoke` requires an earlier qualification and permanently invalidates that digest.
- A revoked digest cannot be requalified.
- Qualification of a successor makes the predecessor non-current.
- `valid_until_utc` cannot exceed the maximum period allowed by the pinned policy.

### Registry and ledger documents

Both documents bind:

- `source_id`
- `genesis_sha256`
- `event_count`
- their own head
- the paired document’s head
- current candidate
- permanent revoked digest set
- canonical document hash

The paired ledger row mirrors event sequence, action, candidate, timestamps, and event hash. Registry and ledger counts must be equal and nonzero.

### Runtime snapshot

Every accepted check returns:

```json
{
  "schema": "task26-runtime-authority-snapshot-v1",
  "source_id": "<64 hex>",
  "genesis_sha256": "<64 hex>",
  "candidate_digest": "<64 hex>",
  "registry_head_sha256": "<64 hex>",
  "ledger_head_sha256": "<64 hex>",
  "event_count": 7,
  "committed_at_utc": "...",
  "valid_until_utc": "...",
  "snapshot_sha256": "<64 hex>"
}
```

This exact object is embedded in launch authorizations, activation receipts, capabilities, reservations, and local provider receipts.

## Runtime interface and TOCTOU semantics

Add `gateway/platforms/task26_runtime_authority.py` with approximately:

```python
class CandidateAuthoritySource(Protocol):
    @contextmanager
    def authorize(
        self,
        candidate_digest: str,
        *,
        stage: AuthorityStage,
        predecessor: AuthoritySnapshot | None = None,
    ) -> Iterator[AuthoritySnapshot]: ...
```

Stages:

- `service_activation`
- `customer_activation`
- `adaptive_activation`
- `capability_issue`
- `transport`

`authorize()` must:

1. Acquire the source shared lock.
2. Re-read and fully verify genesis, registry, ledger, document hashes, both chains, counts, and cross-heads.
3. Match the independently pinned source ID and genesis.
4. Reject unavailable or expired authority.
5. Require the requested digest to be the current non-revoked candidate.
6. If given a predecessor snapshot, prove its heads occur at its exact event count and that every later event is only an `affirm` of the same continuously current candidate.
7. Yield the latest snapshot while retaining the lock.

For activation and capability issuance, retain the lock until the durable local mutation commits. For transport, retain it through the bounded provider call.

This permits harmless authority affirmations between stages while rejecting rollback, revocation, successor selection, truncation, or source substitution.

## Exact implementation seams

### Historical bundle authority

- `gateway/platforms/task26_candidate_authority.py`
  - Keep v1 as historical qualification evidence only.
  - Rename documentation and result keys to make that explicit.
  - Do not let production instantiate a runtime source from this root.
- `scripts/source_golden_path.py::run`
  - Use an injected deterministic Golden authority source while exercising the offline lifecycle.
  - Append historical PASS evidence only after the Golden contract completes.
- `scripts/verify_source_golden_path.py::verify`
  - Continue checking historical bundle evidence.
  - Add an assertion that the bundled v1 root is rejected by the production source loader.
- `gateway/platforms/task26_final_state.py`
  - Rename sealed `authority` metadata to `historical_candidate_authority`.
  - Update `TRUST_BOUNDARY`: mutable production authority comes from the independently pinned external source, not sealed bytes.

### Gateway startup and service activation

- `gateway/run.py::GatewayRunner.start`
  - When production nutrition coaching is enabled, require a runtime launch authorization and authority pin.
  - Check `service_activation` immediately before connecting the production adapter.
  - Fail startup for that production surface if authority is absent, stale, revoked, or mismatched.
- `gateway/run.py::_create_adapter`
  - Pass the source and runtime candidate authorization into `TelegramAdapter`.
- `gateway/platforms/dualcoach_tasks21_25_controller.py::launch_controller`
  - Check current authority for the manifest candidate.
  - Write the authority-bound launch authorization before starting the service.
  - Keep the shared authority lock through receipt persistence and `_start_service()`.
- `_deployed_candidate_matches`
  - Also require the service unit to expose independently configured authority-pin and launch-authorization paths.
- `hermes_cli/gateway.py::generate_systemd_unit`
  - For the dedicated production profile, provide these as systemd credentials or operator-owned absolute paths; do not derive them from the candidate/profile.

### Customer activation

- `gateway/platforms/dualcoach_activation_cutover.py::activate_customer_cutover`
  - Derive candidate identity from the validated deployment receipt.
  - Acquire `customer_activation` authority before `admin.activate_customer()`.
  - Retain it through `_finalize_membership_activation_binding()` and `_activate_bootstrap()`.
  - Add the snapshot to `ActivationCutoverResult`.
- `_finalize_membership_activation_binding`
  - Bind the snapshot into the activation-binding journal row.
- Profile-wheel source corresponding to installed `checkin_cli/customer_admin.py`:
  - `ActivationResult`
  - `_activate_customer_locked`
  - `_build_activation_audit_record`
  - `_require_committed_activation_receipt`
  - Include and validate the Task26 authority snapshot in the prepared/committed activation journal and audit receipt.
  - Do not edit installed `site-packages`; rebuild the profile wheel.

### Capability issuance

- `dualcoach_tasks21_25_controller.issue_delivery_capability`
  - Recheck `capability_issue` immediately before writing `draft-deliveries.json`.
  - Bind the latest snapshot into `bindings`.
- `nutrition_coaching.py::DeliveryLaunchAuthorization`
  - Add the launch authority snapshot.
- `NutritionCoachingCoordinator.__init__`
  - Require the runtime candidate identity and `CandidateAuthoritySource` in production.
- `NutritionCoachingCoordinator.issue_delivery_capability`
  - Recheck under the source lock immediately before the delivery-ledger write.
  - Bind the issue snapshot into `DraftDeliveryCapability.bindings`.
- `AdaptiveOperatorService._issue`
  - Recheck before `_append_row_unlocked`.
  - Add authority fields to `_ADAPTIVE_SESSION_IMMUTABLE_FIELDS`, the session row, and `AdaptiveOperatorCapability`.
- `AdaptiveNutritionCoordinator._validate_capability_session`
  - Verify source/genesis, continuity, candidate, heads, and count against the live source.

### Activation of adaptive plans

- `AdaptiveNutritionCoordinator.activate_latest`
  - Recheck `adaptive_activation` from the operator capability immediately before the prepared transition.
  - Retain the source lock through overlay, epoch, receipt, and committed-transition writes.
  - Add the snapshot to `prepared_payload`, `receipt_payload`, and `adaptive_plan_activated`.

### Final transport boundary

- `NutritionCoachingCoordinator.claim_delivery_transport`
  - Return a claim containing the issued authority snapshot, not only an opaque digest.
- `TelegramAdapter._handle_nutrition_draft_callback`
  - After claim consumption and immediately before `_send_nutrition_topic`, enter a `transport` authorization context.
  - On rejection, persist a provider-not-started terminal state rather than “unknown provider outcome.”
- `TelegramCustomerTransport._send_customer`
  - Resolve the exact consumed delivery row and issued snapshot, then retain transport authority through the strict sender.
- `TelegramCustomerTransport.send_adaptive_customer`
  - Read the authority snapshot from the immutable adaptive reservation.
  - Recheck it under the external lock and retain the lock through `strict_sender`.
- `AdaptiveNutritionCoordinator.deliver_latest_once`
  - Add the issue snapshot to `delivery_attempt_started`.
  - Add the transport snapshot to `delivery_attempt_consumed`, provider receipt, delivered, and sent-audited rows.
- `TelegramAdapter._send_nutrition_topic`
  - Make this the final non-bypassable gate for all nutrition Telegram I/O, including onboarding publications.
  - It should consume an expected snapshot when the operation has a capability/reservation and return an authorized receipt wrapper carrying the transport snapshot.
- `telegram_nutrition_onboarding_runtime_publication_transport.py::_send_publication`
  - Bind the returned snapshot into `GatewayOnboardingPublicationOutbox` claim and receipt rows.
- `telegram_activation_notice.py::ActivationNoticeReceipt` and `ActivationNoticeStore.mark_sending`
  - Add issue and transport authority snapshots.
- `TelegramAdapter._send_missing_checkin_reminder`
- `TelegramAdapter._drain_activation_completion_notices`
- `TelegramAdapter._send_nutrition_coaching_tick`
  - Bind authority when provider authority is issued.
  - Pass that snapshot into the final send.
  - If it changed or was revoked, record a provider-not-started terminal outcome.
- Profile-wheel `checkin_cli/customer_schedule.py`
  - Extend `ScheduledDeliveryReceipt`, `_build_row`, `_validate_schedule_row_shape`, `reserve_*`, and `mark_customer_task_sending` with candidate-authority snapshots.

Every local receipt should distinguish:

```json
{
  "candidate_authority_issued": { "...": "..." },
  "candidate_authority_transport": { "...": "..." }
}
```

The Telegram provider’s opaque message ID remains unchanged; the local durable receipt binds that ID to these snapshots.

## Minimal tests

1. Valid external source returns the expected source ID, heads, count, and candidate.
2. Missing files, stale `valid_until`, wrong source/genesis, candidate mismatch, revocation, chain tampering, count mismatch, and bundle-local v1 roots all fail.
3. Customer activation failure leaves the registry disabled and bootstrap in `AWAITING_ACTIVATION`.
4. Service launch under revoked authority never invokes `_start_service`.
5. Revocation after launch but before draft/adaptive capability issuance writes no capability.
6. Revocation after capability issuance but before legacy draft transport invokes no sender and records provider-not-started.
7. The same race for adaptive transport yields `delivery_preflight_rejected` and no strict sender.
8. Scheduled delivery and activation-notice reservations bind authority and stop before provider I/O after revocation.
9. Lock-order integration: collect ordered events showing transport exits before an exclusive revocation commit; use barriers/events and bounded joins, never sleeps.
10. Offline source and installed Golden paths use a deterministic injected authority and assert that the immutable copied authority is never accepted as production authority.

## Migration order

1. Treat all existing bundled v1 authority as historical evidence only.
2. Implement and test the external v2 source and deterministic fake source.
3. Extend profile-wheel activation and scheduled-receipt schemas to carry authority snapshots.
4. Extend gateway launch, capability, adaptive, and transport schemas while still reading old receipts only for reconciliation.
5. Provision a new external genesis and operator pin outside the profile and candidate.
6. Import the existing PASS as an explicit operator migration qualification event; do not copy the candidate’s self-contained registry as authority.
7. Build and qualify a successor candidate containing the runtime enforcement.
8. Generate a fresh authority-bound launch authorization and restart the dedicated service.
9. Reject all legacy pending capabilities/reservations lacking authority fields. Existing uncertain/sending attempts remain terminal and are never retried.
10. Enable future customer/adaptive activation only through the new checks.

## Boundaries and risks

- This recommendation assumes Task26 governs the DualCoach/nutrition production surface, not unrelated generic Hermes messaging.
- The filesystem must be local and all authority writers must honor the same lock.
- The gateway process should have read/lock access but no write access to genesis, registry, or ledger. If it runs under the same writable operator account, the broker design is stronger.
- A provider call already linearized before revocation cannot be undone. The shared lock guarantees the revocation commits after that call, not that already-started external I/O can be recalled.
- Freshness requires periodic operator `affirm` events. If affirmation stops, production fails closed.
- Paired-file crash inconsistency is intentionally fail-closed; automatic distributed recovery is unnecessary here.

No files were edited and no live, service, provider, or network actions were performed.