Kongono v1.19 Documentation

Everything you need to build, test, secure, and scale modern PHP 8.5.13+ applications with zero Symfony runtime dependencies and zero mutable global state.

1. Quick Start

Requirements: PHP 8.5.13+ (ext-curl, ext-dom, ext-json, ext-mbstring, ext-pdo, ext-sodium) and Composer 2.x.

Create a New Project (Recommended)

composer create-project kongono/app my-app
cd my-app
composer dev

The installer automatically copies .env.example to .env and generates a 256-bit APP_KEY. Open:

  • App Home: http://127.0.0.1:8000/
  • Kongono Dev Studio: http://127.0.0.1:8000/_kongono
  • Operations Dashboard (when enabled): http://127.0.0.1:8000/_ops
  • Interactive OpenAPI 3.1 Explorer: http://127.0.0.1:8000/docs
  • Readiness Health Check: http://127.0.0.1:8000/health

Install into an Existing Project

composer require kongono/framework
php vendor/bin/kongo doctor

2. 11-Package Architecture

Kongono organizes the entire framework into 11 cohesive namespaces delivered in one lean package (kongono/framework) with only the 7 PSR interface packages in require, zero Symfony packages, 100% declare(strict_types=1), and zero mutable static properties.

NamespaceCore Components
Kongono\Core\Kernel, OperationScope, PSR-11 Container, pure-DI ClockInterface/SystemClock/FrozenClock, Fiber Async, Config, EnvLoader, Logger, MemoryCache/FileCache/RedisClient+RedisCache/CacheFactory, FeatureManager, NotificationDispatcher, Retry/CircuitBreaker, HealthCheck, Translator, Metrics/Tracer, SecretScrubber, ApplicationGraph
Kongono\Http\PSR-7/15 Request/Response/Cookie/UploadedFile, Live 2.5 (LiveMiddleware), Bridge (BridgeMiddleware, Response::page(), Response::adaptive()), Session + PRG flash, Router (O(1) + chunked PCRE2 AOT), zero-reflection App, StaticFilesMiddleware, CompressionMiddleware, HttpCacheMiddleware, IdempotencyMiddleware, EventBus/RedisEventBus SSE, OpenApiGenerator, /_kongono Dev Studio, /_ops OpsDashboardMiddleware, TestClient/TestResponse/TestUpload
Kongono\View\Compiled .kgn.html OPcache closure templates, context-aware XSS auto-escaping, @liveScript, @bridgeScript, @island, @safeHtml, @old/@error, @vite(...), layouts, <x-component> slots, @t(...), @json, warmCache(), production autoReload: false
Kongono\Validation\Attribute-driven DTO validation, nested DTOs, BackedEnum coercion, #[ArrayOf], RuleInterface, ValidatableDtoInterface, #[Date], #[Ip], #[NotIn], #[RequiredIf], #[Uuid], #[Between], #[Confirmed]
Kongono\Database\Parameterized QueryBuilder (soft deletes, forTenant(), PostgreSQL RowLevelSecurity, JOIN, whereGroup, upsert, RETURNING, paginate, getAs), BatchLoader (hasMany/belongsTo), QueryGuard, Factory, Schema/Blueprint (table/rename/softDeletes/foreignId), PdoConnection (auto-reconnect, stmt cache, nested SAVEPOINTs), DatabaseTestHelper, Migrator (--pretend, lint, fresh), PostgresFullTextSearch/MemorySearchEngine, Repository, SeederInterface
Kongono\Security\SessionAuth + #[Authenticated], revocable SHA-256 PersonalAccessToken (Memory/Cache/Pdo stores), PasswordResetBroker, EmailVerifier, LoginThrottler, RememberMeManager, WebAuthn PasskeyVerifier, MagicLinkAuth, PkceOAuthClient, AiThreatShieldMiddleware, Principal, Gate (policies + before()), #[Can], HtmlSanitizer, Argon2id PasswordHasher, HKDF Encryptor v2, RFC 6238 Totp, TokenSigner, SignedUrl, SSRF SafeHttpClient + SafeHttpClient::fake(), signed Webhooks
Kongono\Storage\Streaming putStream/getStream & copy/move across contained atomic LocalStorage, pure-PHP AWS SigV4 S3Storage (paginated ListObjectsV2, native server-side copy, presigned URLs), MemoryStorage, StorageDisks, StorageFactory, magic-byte UploadedFileStore, SignedLocalUrl
Kongono\Jobs\Queue, persistent/daemon Worker (multi-queue priority draining, JobMiddlewareInterface), DLQ listFailed/retryFailed/flushFailed, atomic uniqueKey dedup, parallel JobBatch + BatchDispatcher, durable Workflow, PostgresQueueDriver (FOR UPDATE SKIP LOCKED), Lua-atomic RedisQueueDriver, MemoryQueueDriver, cron Scheduler
Kongono\Mail\Mailer, SmtpTransport (STARTTLS), ResendTransport, LogTransport, MemoryTransport, MailNotificationChannel
Kongono\Ai\AiClient (OpenAI, Anthropic, Gemini, Groq, Ollama + live streaming), PromptGuard + UntrustedInput, EvalRunner, PgVectorStore (HNSW/GIN) + MemoryVectorStore, HybridSearch (RRF), KnowledgeBase, structured(), governed AgentPrincipal/RequiresApproval/AgentRunner, native McpServer
Kongono\Cli\Unified kongo CLI + Oshie, Chie, Hantei companions + 15-tool KongonoMcpFactory

3. Routing & PHP 8.5 Attributes

Register controllers with $app->controller(PostController::class) or fluent route closures via $app->routes(fn(Router $r) => ...). Parameter dispatch plans are compiled once per controller method (zero per-request reflection in persistent workers), with automatic DI for Request, Session, Principal, typed route params, Container services, and validated DTOs.

#[Prefix('/api/posts')]
final readonly class PostController
{
    #[Get('/', name: 'posts.index')]
    #[CacheControl(maxAge: 60, public: true, staleWhileRevalidate: 30)]
    public function index(): Response { ... }

    #[Get('/{id:\d+}', name: 'posts.show')]
    public function show(int $id): Response { ... }

    #[Post('/', name: 'posts.create')]
    #[Middleware(BearerAuthMiddleware::class)]
    #[Authenticated]
    #[Can('posts.write')]
    #[Idempotent(ttlSeconds: 3600)]
    public function store(CreatePostInput $input, Principal $principal): Response { ... }
}
AOT Compiled Router: Static routes dispatch in O(1) hash lookup; dynamic routes compile into chunked PCRE2 regexes via php vendor/bin/kongo optimize (var/cache/routes.compiled.php).

4. Compiled .kgn.html Views & Vite

Templates live in views/ and compile once into OPcache-friendly static PHP closures. All {{ $expr }} and @t(...) outputs are contextually HTML-escaped against XSS; use @safeHtml($richHtml) to sanitize user-authored markup via Kongono's built-in HTML5 HtmlSanitizer.

@extends('layouts/app')
@section('title', 'Dashboard')

@section('content')
  <h1>@t('dashboard.welcome', ['name' => $user->name])</h1>

  @unless ($archived)
    <x-card :title="$project->name">
      @forelse ($tasks as $task)
        <p>{{ $task->title }}</p>
      @empty
        <p>All caught up!</p>
      @endforelse
    </x-card>
  @endunless

  <script>window.__DATA__ = @json($payload);</script>
@endsection

In production persistent workers (FrankenPHP / RoadRunner), configure $app->views(autoReload: false) and run kongo optimize to keep compiled template closures hot in memory with zero filesystem checks. Bind $views->withVite(new ViteManifest($baseDir . '/public')) and drop @vite(['resources/css/app.css', 'resources/js/app.js']) into your layout for Vite dev HMR & hashed production manifests.

5. Kongono Live 2.5 & Bridge (React / Vue / Svelte)

Kongono Live 2.5 (Zero-Build, Strict-CSP Hypermedia)

Add LiveMiddleware and drop @liveScript in your layout for a ~3 KB runtime that requires zero npm build steps and zero unsafe-eval:

  • Keyed DOM Morphing & View Transitions: kgn-get, kgn-post, kgn-target, kgn-swap="morph", and automatic CSRF header forwarding.
  • Zero-eval() Cached-AST Signals: Reactive client state with safe arithmetic, ternary, and pipe expressions under strict Content-Security-Policy.
  • UX Primitives Built In: Speculative hover/visible prefetch, out-of-band multi-target updates (kgn-oob), persistent drafts & offline idempotent queue (k-persist), drag-and-drop ordering (kgn-sortable), optimistic UI, and live SSE streams (kgn-stream).

Kongono Bridge (React, Vue, Svelte & Hybrid Islands)

When a page needs a full JS component tree, scaffold Bridge with kongo bridge:init and generate TypeScript page/DTO definitions via kongo bridge:types. Return Response::page('Orders/Show', $props), embed hybrid islands inside .kgn.html templates with @island('Chart', $props), or serve HTML, Live fragments, Bridge pages, and JSON from a single controller via Response::adaptive().

6. Typed DTO Validation & HTML PRG Flash

Type-hint any readonly DTO in a controller method. Kongono validates JSON or form input, coerces scalars and BackedEnums, validates nested DTOs and typed arrays recursively, and returns 422 Unprocessable Content (or flashes secret-scrubbed @old() / @error() values on HTML PRG redirects).

final readonly class CreateTicketInput implements ValidatableDtoInterface
{
    /** @param list<string> $labels */
    public function __construct(
        #[Required, Uuid] public string $clientRequestId,
        #[Required, Min(3), Max(140)] public string $subject,
        #[Required, Email] public string $reporterEmail,
        #[Between(1, 5)] public int $severity,
        #[Date] public ?string $dueDate = null,
        #[Ip] public ?string $sourceIp = null,
        #[NotIn(['internal'])] public string $category = 'support',
        #[RequiredIf('severity', 5)] public ?string $escalationEmail = null,
        #[ArrayOf('string', min: 1, max: 5)] public array $labels = ['triage'],
    ) {}

    public function validateSelf(ValidationErrors $errors): void
    {
        // Custom cross-field validation; custom RuleInterface attributes also supported
    }
}

#[ArrayOf] automatically emits accurate array item schemas in OpenAPI 3.1, kongo sdk:generate, and kongo bridge:types.

7. HTTP Caching, Compression, SSE & Idempotency

  • HTTP Caching & 304: Decorate GET handlers with #[CacheControl(maxAge: 300, public: true, staleWhileRevalidate: 60)] for automatic weak ETag and 304 Not Modified handling.
  • Compression: Add new CompressionMiddleware() for automatic gzip/deflate encoding (safely skips streaming SSE & binary payloads).
  • Idempotency: Decorate mutating actions with #[Idempotent(ttlSeconds: 86400)] — retries with the same Idempotency-Key replay cleanly, while payload mismatches fail closed with 409 Conflict.
  • Real-Time SSE Pub/Sub: Publish events across single-node EventBus or multi-node RedisEventBus and stream replays honoring Last-Event-ID via Response::sse(...).

8. Database, Soft Deletes, BatchLoader & Migrations

Every value in QueryBuilder is bound via real PDO prepared statements (ATTR_EMULATE_PREPARES = false) with automatic reconnect and statement caching. Unscoped UPDATE/DELETE statements fail closed by default.

$db = PdoConnection::fromUrl(Config::env('DATABASE_URL'));
$db->onQuery(fn(string $sql, float $ms) => $inspector->recordQuery($sql, $ms));

// Tenant isolation + soft deletes + pagination + zero-N+1 BatchLoader
$page = $db->table('articles')
    ->forTenant($tenant)
    ->withoutTrashed()
    ->orderBy('created_at', 'DESC')
    ->paginate(page: 1, perPage: 20);

$authors = BatchLoader::belongsTo($db, 'users', 'id', $authorIds);
$comments = BatchLoader::hasMany($db, 'comments', 'article_id', $articleIds);

// Soft delete / query trash / restore
$db->table('articles')->where('id', '=', $id)->softDelete();
$trashed = $db->table('articles')->onlyTrashed()->getAs(ArticleDto::class);
$db->table('articles')->where('id', '=', $id)->restore();

Use Schema::create(), Schema::table(), Schema::rename(), and Blueprint helpers (uuid, json, decimal, foreignId, softDeletes), plus PostgreSQL RowLevelSecurity, NonTransactionalMigrationInterface (for CREATE INDEX CONCURRENTLY), QueryGuard for N+1 detection, and typed Factory::for() for seeds and tests.

php vendor/bin/kongo make:migration add_deleted_at_to_articles
php vendor/bin/kongo migrate --pretend      # Dry-run SQL preview without touching DB
php vendor/bin/kongo migrate:lint           # Zero-downtime lock/safety linter
php vendor/bin/kongo migrate
php vendor/bin/kongo migrate:fresh          # Guarded against production (requires --force)

10. Auth, PATs, Security & AI Threat Shield

  • Full Auth Stack (Zero Vendor Packages): SessionAuth + SessionAuthMiddleware + #[Authenticated], Gate policies & before() hooks, #[Can('ability')], revocable SHA-256 PersonalAccessToken (Memory/Cache/Pdo stores with automatic kgn_pat_ redaction in SecretScrubber), PasswordResetBroker, EmailVerifier, LoginThrottler, and split selector/validator RememberMeManager (revokes entire series on stolen-cookie detection).
  • Passwordless & MFA: Native WebAuthn/FIDO2 Passkeys (PasskeyVerifier ES256/Ed25519), single-use HMAC MagicLinkAuth, PKCE S256 PkceOAuthClient (GitHub/Google/OIDC), and RFC 6238 Totp + recovery codes.
  • Cryptography & Content Safety: Argon2id PasswordHasher, versioned HKDF Encryptor v2 (XChaCha20-Poly1305 AEAD + seamless key rotation), HTML5 HtmlSanitizer/@safeHtml, HMAC TokenSigner, and expiring SignedUrl.
  • SSRF & AI Attack Defense: DNS-pinned SafeHttpClient (blocks loopback/private/metadata IPs), signed WebhookDispatcher + #[VerifyWebhook], AiThreatShieldMiddleware (recon honeypots, hidden form traps, 404 burst auto-banning, compute budgets), and PromptGuard/UntrustedInput cryptographic Canary Token leakage blocking.

11. Storage, Queues, Batches, Workflows & Mail

  • Streaming Storage: Stream large files with putStream()/getStream() and native copy()/move() across contained atomic LocalStorage, pure-PHP AWS SigV4 S3Storage (paginated ListObjectsV2, native x-amz-copy-source, presigned URLs), and MemoryStorage. Add magic-byte UploadedFileStore, SignedLocalUrl, multi-disk StorageDisks, StorageFactory, and Response::download() / Response::fromStorage().
  • Queues, Priority & Dead-Letter Replay: PostgresQueueDriver (FOR UPDATE SKIP LOCKED + fencing tokens) and pure-PHP Lua-atomic RedisQueueDriver support multi-queue priority draining (Worker::run('critical,high,default')), atomic uniqueKey dedup, composable JobMiddlewareInterface, --daemon workers, and DLQ CLI commands (kongo queue:failed, queue:retry, queue:flush).
  • Parallel Batches & Durable Workflows: Fan-out/fan-in with JobBatch + BatchDispatcher (then/catch/finally callbacks on MemoryBatchStore or CacheBatchStore), or build multi-day durable Workflows with memoized $wf->step(), sleep(), and external waitForEvent()/signal().
  • Pure-PHP Redis & Mail: Zero-extension RedisClient (auto-reconnect, TLS, RESP2/RESP3) powers RedisCache, RedisEventBus, and RedisQueueDriver. Transactional Mailer ships with SmtpTransport (STARTTLS), ResendTransport, .kgn.html views, and NotificationDispatcher.

12. Testing: TestClient, Savepoints, Fakes & Clock

Kongono tests run with zero global mutable state — safe for parallel test runners and persistent workers alike:

// Fluent in-process HTTP, Live 2.5, Bridge & multipart testing
$client = (new TestClient($app))
    ->actingAs($principal)
    ->withStatefulCookies()
    ->followRedirects()
    ->withLive();

$client->postMultipart('/uploads', files: ['doc' => TestUpload::fakePdf('spec.pdf')])
    ->assertCreated()
    ->assertJsonPath('mime', 'application/pdf');

// Fast DB isolation using real transactions + nested SQL SAVEPOINTs
DatabaseTestHelper::inRollbackTransaction($db, function () use ($db): void {
    // Queries and nested $db->transaction() calls roll back cleanly on exit
});

// Pure-DI time travel & SSRF-enforcing outbound HTTP fake
$clock = FrozenClock::at('2026-11-22T09:00:00Z');
$clock->advanceSeconds(3600);
$http = SafeHttpClient::fake(['https://api.example.com/*' => ['status' => 200, 'body' => '{}']]);

13. AI SDK, Evals & 5-Line pgvector RAG

Set any one provider environment variable (OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, GROQ_API_KEY, or OLLAMA_HOST) and use one unified API across all five providers:

$ai = AiClient::fromEnv();

// 1. Live token streaming (OpenAI, Anthropic, Gemini, Groq & Ollama)
$ai->chatStream(
    new ChatRequest([Message::user('Summarize Kongono in 2 bullets')]),
    static function (string $delta): void { echo $delta; },
);

// 2. Validated structured DTO extraction + PromptGuard canary defense
$sentiment = $ai->structured($reviewText, SentimentDto::class);

// 3. 5-Line RAG with PostgreSQL pgvector (HNSW/GIN)
$kb = new KnowledgeBase($embedder, new PgVectorStore($db));
$kb->ingest('docs-1', $markdownText, ['product' => 'kongono']);
$answer = $kb->ask('How does key rotation work?', $ai);

Run php vendor/bin/kongo eval --redteam to execute Kongono's built-in 12-vector adversarial prompt-injection red-team suite and assert structured DTO accuracy, token limits, and latency budgets in CI.

14. Built-In AI Companions & 15-Tool MCP Server

Every Kongono app ships with three tool-equipped AI companions (live streaming, code/schema inspection, surgical patches, automatic AGENTS.md grounding, persistent local sessions, per-companion model routing with automatic provider failover, and hard KONGONO_AI_MAX_COST_USD caps) plus a capability-governed 15-tool JSON-RPC 2.0 MCP server:

php vendor/bin/kongo oshie --exercise routing                         # Grade hands-on Kongono exercises against your app
php vendor/bin/kongo oshie --progress                                 # Lesson & exercise progress + tailored recommendations
php vendor/bin/kongo oshie "Why is /api/notes slow?" --stream         # Live token streaming + token/cost telemetry footer
php vendor/bin/kongo chie "Add a /api/posts CRUD" --interactive       # Approve or skip each unified file diff [y/n/a/q]
php vendor/bin/kongo chie "Add a /api/posts CRUD" --apply --verify    # Multi-gate verify (syntax, PHPStan, tests, lint, audit)
php vendor/bin/kongo chie "Now add rate limiting" --continue          # Iterate on your last Chie plan
php vendor/bin/kongo hantei fix --apply --verify                      # Diagnose failure -> Chie patch -> re-verify
php vendor/bin/kongo hantei review --base=main --format=sarif         # CI-ready Kongono invariant & security diff review
php vendor/bin/kongo hantei watch --log=var/log/app.log               # Tail local error logs or failed queues live
php vendor/bin/kongo hantei queue-failed --queue=default              # Diagnose dead-lettered background jobs (secret-scrubbed)
php vendor/bin/kongo eval --companions                                # Oshie/Chie/Hantei zero-hallucination & safety evals
php vendor/bin/kongo mcp                                              # Start 15-tool stdio MCP server

Connect Antigravity, Cursor, Claude Code, or Codex via MCP

{
  "mcpServers": {
    "kongono": {
      "command": "php",
      "args": ["vendor/bin/kongo", "mcp"]
    }
  }
}

Exposed read-only, secret-scrubbed MCP tools (.env reads explicitly blocked): kongono_graph, kongono_openapi, kongono_sdk_generate, kongono_routes, kongono_inspect_schema, kongono_audit, kongono_eval, kongono_migrate_lint, kongono_test_route, kongono_deploy_preview, kongono_list_files, kongono_read_file, kongono_oshie_lesson, kongono_hantei_diagnose, and kongono_chie_preview.

15. /_ops Operations, Dev Studio & SDK Generator

  • Built-In Operations Dashboard (/_ops): Mount OpsDashboardMiddleware for a zero-npm, strict-CSP Live 2.5 control plane gated fail-closed by Gate abilities (ops.view for reads and 1-click Hantei DLQ diagnosis via POST /_ops/queues/diagnose, ops.manage for dead-letter retry/flush) — showing live queue depths, active JobBatch progress bars, HealthCheck status, Metrics::snapshot(), and recent request traces.
  • Kongono Dev Studio (/_kongono): Live request/SQL trace viewer, in-process time-travel replay (/_kongono/api/replay/{id}), 1-click Hantei trace diagnosis + PHPUnit 13 regression test export (POST /_kongono/api/hantei/trace/{id}), live SSE streaming for Oshie & Hantei (/_kongono/api/{oshie,hantei}/stream), ApplicationGraph inspector, and interactive Chie diff preview & MCP studio. Automatically returns 404 when APP_DEBUG=false.
  • Multi-Platform SDKs (kongo sdk:generate): Emit typed TypeScript, Swift 6, Kotlin, and Dart clients straight from your PHP 8.5 attribute routes and DTOs.
  • Feature Flags & Resilience: Deterministic percentage rollouts ($features->rollout('new_ui', 25) + #[Feature]), Retry, CircuitBreaker, GET /health, Prometheus GET /metrics, and Server-Timing headers via Tracer.

16. Production Deployment (FrankenPHP)

Generate hardened non-root read-only container blueprints with php vendor/bin/kongo deploy:init --domain=app.example.com or use the FrankenPHP persistent-worker Dockerfile, Caddyfile, and public/worker.php shipped in kongono/app:

docker build -t my-kongono-app .
docker run -p 8080:8080 --env-file .env.production my-kongono-app

Production checklist: enforce PHP ≥ 8.5.13, set APP_DEBUG=false and views(autoReload: false), run kongo optimize during image build, gate /_ops behind Gate policies, verify kongo audit --attack --strict and kongo migrate:lint in CI, rotate APP_KEY via Encryptor::$previousKeys, and point probes to /health.

17. Complete kongo CLI Reference

CommandDescription
kongo new <dir> [--starter=minimal|api|saas]Scaffold a new Kongono app (minimal, Bearer PAT + /_ops API, or full Live 2.5 + SessionAuth + PAT SaaS starter)
kongo auth:init [--mode=web|api|both] [--force]Scaffold zero-bloat SessionAuth + LoginThrottler + CSRF + Personal Access Token auth starter kit
kongo serve [--port=8000]Start local PHP 8.5 dev server
kongo tinker [--eval="expr"]Interactive PHP 8.5 REPL (or one-liner eval) with live $app & $container
kongo doctor / env:checkVerify PHP 8.5.13+, extensions, env keys, AI provider config & live app graph
kongo audit --attack --strictGraph-driven security audit + automated in-process red-team simulations
kongo eval [--redteam|--companions]Run AI DTO accuracy/budget evals, 12-vector red-team battery, or 6-check companion benchmark
kongo bridge:init / bridge:types / ui:addScaffold React/Vue/Svelte Bridge, emit TS route/DTO types, or add Live UI components
kongo skills:install [--target=agents|claude|both]Install the 5 bundled Kongono AI agent SKILL.md workflow recipes into .agents/skills and/or .claude/skills
kongo sdk:generate --lang=ts|swift|kotlin|dartGenerate typed web & mobile client SDKs straight from attribute routes and DTOs
kongo deploy:initGenerate hardened non-root FrankenPHP/Caddy/Docker deployment blueprints
kongo key:generateGenerate a cryptographically secure 256-bit APP_KEY
kongo optimize / cache:clearPrecompile views, AOT router, graph & OpenAPI caches (or clear caches)
kongo routes [--json] / graph / openapiInspect HTTP routes, live ApplicationGraph, or OpenAPI 3.1.0 JSON
kongo mcpRun read-only 15-tool JSON-RPC 2.0 MCP server over stdio
kongo migrate [--pretend] / rollback / status / lint / fresh / db:seedDry-run, lint, apply, roll back, reset (prod-guarded), and seed databases
kongo work [--daemon] / schedule:runRun persistent priority queue workers or execute due cron tasks
kongo queue:failed / queue:retry / queue:flushInspect, retry (single or --all), and clear dead-letter failed jobs
kongo make:controller|dto|migration|seeder|test|job|policy|middleware|factory|rule|mail|resourceDeterministic zero-AI PHP 8.5 single-file and full vertical-slice CRUD resource generators
kongo oshie / chie / hanteiBuilt-in AI tutor, project-aware builder, and debugger/test generator
kongo check / testRun full CS + PHPStan Level 9 Strict + PHPUnit 13 quality suite