# AI Agent Workflow Runbook

## 1. Purpose

This document defines how to implement the update server with sequential AI agents.

The workflow is designed for:

- one human operator who launches agents one by one;
- one implementation agent per stage;
- one validation agent after each stage;
- file-based handoff instead of direct agent-to-agent chat.

## 2. Source Of Truth

Every implementation agent must read these files before starting:

- `/Users/delete/projects/update_server/PRODUCT_SPEC.md`
- `/Users/delete/projects/update_server/IMPLEMENTATION_PLAN.md`
- `/Users/delete/projects/update_server/DEVELOPMENT_WORKFLOW.md`
- `/Users/delete/projects/update_server/docs/agents/WORKFLOW.md`

Every agent must also read the latest handoff and validation files if they exist.

## 3. Fixed Technical Decisions

These decisions are considered fixed unless the human operator explicitly changes them.

- Language: Go
- Router: `chi`
- Database: `SQLite`
- HTML strategy: server-rendered HTML templates
- Artifact storage: local filesystem
- Deployment shape: app container behind Caddy or Nginx
- Web auth: session-based authentication
- Client auth: `Authorization: Bearer <api_key>`
- API key access modes:
  - `all_projects`
  - `project_allow_list`
  - `project_deny_list`
  - `tag_allow_list`
  - `tag_deny_list`
- One API key must use exactly one scope mode at a time
- Projects support tags from day one
- Security is mandatory, not optional

## 4. Shared Workspace Rules

All code lives in the main repository.

Agents should use these implementation paths:

- `/Users/delete/projects/update_server/cmd/server`
- `/Users/delete/projects/update_server/internal`
- `/Users/delete/projects/update_server/web`
- `/Users/delete/projects/update_server/migrations`

Agents must use these coordination paths:

- handoffs: `/Users/delete/projects/update_server/docs/agents/handoffs`
- validations: `/Users/delete/projects/update_server/docs/agents/validation`

If an agent needs to communicate something to the next agent, it must do so through:

- code changes;
- a handoff file;
- updates to spec or implementation docs if architecture changed.

Agents should not rely on hidden memory or previous chat state.

## 5. Handoff Protocol

After finishing work, every implementation agent must create a handoff file:

- naming format: `NN-agent-name.md`
- example: `01-foundation.md`

Each handoff file should be saved in:

- `/Users/delete/projects/update_server/docs/agents/handoffs`

The handoff file must include:

- scope of work;
- files changed;
- migrations added or changed;
- endpoints added or changed;
- tests or commands run;
- known limitations;
- exact next recommended step.

Use this template:

- `/Users/delete/projects/update_server/docs/agents/HANDOFF_TEMPLATE.md`

## 6. Validation Protocol

After each implementation agent finishes, run a validation agent before moving to the next stage.

The validation agent should:

- read the current agent section in this file;
- read the latest handoff file;
- inspect code changes;
- run relevant tests or checks;
- produce a validation report.

Validation files should be saved in:

- `/Users/delete/projects/update_server/docs/agents/validation`

Use this template:

- `/Users/delete/projects/update_server/docs/agents/VALIDATION_TEMPLATE.md`

Validation result must end in one of these statuses:

- `APPROVED`
- `CHANGES_REQUIRED`

Do not launch the next implementation agent until the previous stage is `APPROVED`.

## 7. Agent Count

Recommended sequence:

- 7 implementation agents
- 1 validation agent role used after every stage

The validation agent can be the same AI system reused every time.

## 8. Agent 01 - Foundation

### Mission

Set up the repository skeleton and the minimum runnable Go application.

### Ownership

This agent owns:

- Go module initialization
- basic app boot
- config loading
- HTTP router setup
- health endpoint
- base middleware wiring
- template bootstrapping
- initial developer commands

### Deliverables

This agent must produce:

- runnable server entrypoint
- config package
- base router with route groups
- health endpoint
- base HTML layout structure
- initial project structure under `cmd`, `internal`, and `web`

### Out Of Scope

This agent must not implement:

- business logic
- database schema
- authentication flows
- release upload
- API keys

### Acceptance Criteria

- the app starts successfully;
- a health endpoint responds;
- the code structure matches the implementation plan;
- the project is ready for migrations and feature modules.

## 9. Agent 02 - Database And Migrations

### Mission

Create the data model, migrations, and database access foundation.

### Ownership

This agent owns:

- migration setup
- database connection layer
- schema design
- repository or query layer foundation

### Deliverables

This agent must implement tables for:

- `users`
- `projects`
- `tags`
- `project_tags`
- `releases`
- `api_keys`
- `api_key_project_access`
- `api_key_tag_access`
- `sessions` if needed
- `audit_logs` if included in the first pass

### Out Of Scope

This agent must not implement:

- login UI
- upload endpoints
- full business workflows

### Acceptance Criteria

- migrations can be applied cleanly;
- schema matches the spec;
- access tables support project and tag based key scopes;
- database layer is ready for the next agents.

## 10. Agent 03 - Authentication And Admin Sessions

### Mission

Implement admin authentication and session management.

### Ownership

This agent owns:

- admin bootstrap user creation
- password hashing
- login and logout flow
- session middleware
- role checks foundation

### Deliverables

This agent must produce:

- login form and login handler
- session creation and invalidation
- protected admin route group
- admin bootstrap from environment or setup logic

### Out Of Scope

This agent must not implement:

- project management
- release upload
- API key logic

### Acceptance Criteria

- admin can log in and log out;
- protected routes are actually protected;
- passwords are hashed securely;
- session handling works reliably.

## 11. Agent 04 - Projects, Tags, And Releases

### Mission

Implement core product data management: projects, project tags, and release upload metadata flow.

### Ownership

This agent owns:

- project CRUD
- tag CRUD
- attach or detach tags from projects
- release metadata handling
- artifact storage abstraction
- upload flow and checksum generation

### Deliverables

This agent must produce:

- project create, edit, list, archive flow
- tag create, edit, list flow
- project-tag assignment
- release upload service
- artifact persistence on disk
- checksum capture

### Out Of Scope

This agent must not implement:

- API key access logic
- external client update endpoints

### Acceptance Criteria

- admin can manage projects and tags;
- admin can upload a release to a project;
- release metadata is stored in the database;
- artifact files are stored outside the public web root.

## 12. Agent 05 - API Keys And Access Control

### Mission

Implement API key generation, hashing, permissions, and scope evaluation.

### Ownership

This agent owns:

- secure API key generation
- API key hashing and lookup
- permission flags
- access scope evaluation
- project allow or deny list rules
- tag allow or deny list rules

### Deliverables

This agent must produce:

- API key creation flow
- one-time key reveal behavior
- key activation and revocation
- permission middleware for API key routes
- project and tag access resolution logic

### Out Of Scope

This agent must not implement:

- final UI polish
- deployment hardening

### Acceptance Criteria

- API keys are stored hashed;
- only authorized projects are visible to a given key;
- allow-list and deny-list logic works for projects and tags;
- disabled or expired keys are rejected.

## 13. Agent 06 - Client API And Admin UI

### Mission

Implement the usable product experience for admins and client applications.

### Ownership

This agent owns:

- admin pages for projects, tags, releases, and API keys
- client-facing update endpoints
- latest-release lookup
- release metadata endpoint
- authenticated download endpoint

### Deliverables

This agent must produce:

- admin pages that cover the main flows
- client endpoint to list accessible projects
- client endpoint to get latest release metadata
- client endpoint to download a release

### Out Of Scope

This agent must not implement:

- deep security hardening beyond local route protection
- production reverse proxy setup

### Acceptance Criteria

- an admin can complete the full product flow from the browser;
- a client can authenticate with a bearer API key;
- a client can discover and download only authorized updates.

## 14. Agent 07 - Security And Deployment Hardening

### Mission

Make the system safe and deployable on an internet-facing server.

### Ownership

This agent owns:

- security headers
- rate limiting
- request timeouts
- CSRF finishing pass
- safer cookie settings
- reverse proxy examples
- Docker and deployment finishing pass
- backup and operational notes

### Deliverables

This agent must produce:

- hardened HTTP server settings
- production-ready container setup
- Caddy or Nginx example configuration
- deployment notes for Proxmox
- security review fixes that fit the current architecture

### Out Of Scope

This agent must not redesign the product or data model unless a critical security issue requires it.

### Acceptance Criteria

- the service is ready to run behind HTTPS;
- admin and client traffic have sane security defaults;
- artifacts are not directly exposed;
- deployment instructions are complete enough for first production rollout.

## 15. Validation Agent Role

### Mission

Review each completed stage before the next implementation agent starts.

### Required Checks

The validation agent should verify:

- scope completion;
- obvious regressions;
- schema or route mismatches;
- missing tests;
- unsafe behavior;
- contradictions with the spec.

### Output

The validation agent must write one validation file per stage and finish with:

- `APPROVED`
- or `CHANGES_REQUIRED`

## 16. Operator Guide For Human User

Этот раздел специально для тебя, на русском.

### Общая схема запуска

Запускаешь агентов строго по порядку:

1. `Agent 01 - Foundation`
2. `Validator`
3. `Agent 02 - Database And Migrations`
4. `Validator`
5. `Agent 03 - Authentication And Admin Sessions`
6. `Validator`
7. `Agent 04 - Projects, Tags, And Releases`
8. `Validator`
9. `Agent 05 - API Keys And Access Control`
10. `Validator`
11. `Agent 06 - Client API And Admin UI`
12. `Validator`
13. `Agent 07 - Security And Deployment Hardening`
14. `Final Validator`

### Как запускать каждый этап

Для каждого нового агента даёшь ему один и тот же базовый контекст:

- прочитать `PRODUCT_SPEC.md`
- прочитать `IMPLEMENTATION_PLAN.md`
- прочитать `DEVELOPMENT_WORKFLOW.md`
- прочитать `docs/agents/WORKFLOW.md`
- прочитать последний handoff-файл
- прочитать последний validation-файл, если он есть

После этого говоришь агенту работать только в рамках его секции из этого runbook.

### Что требовать от каждого агента

После завершения этапа агент обязан:

- внести код;
- если нужно, обновить документацию;
- создать handoff-файл в `docs/agents/handoffs`;
- перечислить, что сделано;
- перечислить, что не сделано;
- указать, что должен делать следующий агент.

### Когда запускать валидатора

Валидатора запускаешь после каждого агента.

Ему даёшь задачу:

- прочитать соответствующую секцию агента из `docs/agents/WORKFLOW.md`;
- прочитать свежий handoff;
- проверить код;
- проверить, не нарушена ли спецификация;
- выдать `APPROVED` или `CHANGES_REQUIRED`;
- сохранить отчёт в `docs/agents/validation`.

### Если валидатор нашёл проблемы

Если статус `CHANGES_REQUIRED`, то:

1. не переходишь к следующему агенту;
2. запускаешь того же самого агента повторно;
3. даёшь ему его прошлый handoff и validation report;
4. просишь закрыть замечания;
5. снова запускаешь валидатора.

### Когда использовать меня как валидатора

Меня лучше использовать:

- после каждого крупного этапа;
- перед миграциями базы;
- перед этапом security hardening;
- перед первым Docker/deploy;
- перед выкладкой на Proxmox.

### Практически удобный режим

Самый удобный режим для тебя такой:

1. локально на Mac запускаешь первого агента;
2. проверяешь, что handoff-файл создался;
3. зовёшь меня как валидатора;
4. после `APPROVED` запускаешь следующего агента;
5. когда дойдёшь до конца, только потом собираешь контейнер и переносишь на Proxmox.

### Главный принцип

Следующий агент никогда не стартует без handoff от прошлого и без validation report.

Это защитит тебя от хаоса, повторной работы и скрытых поломок между этапами.
