Guidance for AI agents (including Claude Code) working in this repository.
rennf93/guard-agent-php (https://github.com/Guard-Core/guard-agent-php) is the PHP telemetry agent for the guard-core ecosystem. It buffers security events, performance metrics, and agent status in memory (optionally persisted to Redis for crash recovery) and ships them to the Guard Core App ingestion API with at-least-once delivery semantics: nothing acknowledged is lost, nothing unacknowledged is forgotten.
- Composer package
rennf93/guard-agent-php, typelibrary, license MIT. Noversionfield in composer.json (the laravel-guard/symfony-guard convention); versions come from git tags and are reported to the server asagent_versionfromRenzoFranceschini\GuardAgent\Version::VERSION(3.2.4at the time of writing, in lockstep with the Python agent; 3.2.4 is not tagged yet). - This package contains NO security logic. It reports what a host adapter already decided; detection, rate limiting, bans, and verdicts all live in guard-core (and guard-core-php).
- PHP
^8.2. Requiresext-jsonandext-curlonly. Redis persistence works with zero extra dependencies through a built-in RESP2 stream client;ext-redisandpredis/predisadapters are provided and listed undersuggest. - Autoload is PSR-4:
RenzoFranceschini\GuardAgent\maps tosrc/. Every file isdeclare(strict_types=1). There is no PSR-7/PSR-15 anything: this is a client library, not middleware. - The semantic source of truth is the Python guard-agent (guard_agent/), with the TypeScript (guardagent src/) and Go (guard-agent-go) ports as two verified mappings. The wire contract is defined by guard-core-app's ingestion API (
backend/guard-core-api/guard_core_api/api/routers/telemetry_router.py).
guard-coreis the engine library; the framework adapters (fastapi-guard, flaskapi-guard, djapi-guard, tornadoapi-guard) wire it into frameworks;guard-agent(Python), guardagent (TS), guard-agent-rs (Rust), and guard-agent-go (Go) are the sibling telemetry agents;guard-core-appis the SaaS this agent reports to.- The ingestion contract, verified against guard-core-api source:
POST {endpoint}/api/v1/events,/api/v1/metrics,/api/v1/status.- Headers:
X-API-Key(required),X-Project-Id(optional),X-Agent-Install-Id(install tracking, telemetry_router.py:194),User-Agent(guard-agent-php/<version>,Version::USER_AGENT), optionalX-Payload-Signature. - Bodies above
compressionThresholdbytes are gzipped withContent-Encoding: gzip. The server'sGzipRequestMiddlewareinflates the body BEFORE the router runs. X-Payload-Signature: v1=<hex>where<hex>is HMAC-SHA256 over the UNCOMPRESSED body bytes:_verify_signature_or_warn(telemetry_router.py:110-126) hashesrequest.body()after the middleware already decompressed it, so the signature must always cover the plain JSON bytes. The Python agent signs the same uncompressed bytes (_transport_dispatch.py:108-126), as do the TS and Rust agents.413when the decompressed body exceeds 262144 bytes (services/payload_size_guard.py);429carriesRetry-After;200withsuccess: falseor non-emptyerrors[]is a partial failure.
- This package does NOT import guard-core-php, any framework, or any composer dependency. Guard adapters that need telemetry embed this agent directly.
All of src/, namespace RenzoFranceschini\GuardAgent:
GuardAgent.php: the client.__construct(AgentConfig|array $config, ?TransportInterface $transport = null)(the second parameter is the test seam).start()/stop()/close()lifecycle (start idempotent and may throw; stop idempotent and never throws);sendEvent()/sendMetric()ingest path (never throw, normalize + redact + buffer);flushBuffer()(never throws);tick()andflushIfNeeded()(host-driven loop, see Runtime model below);getDynamicRules()(TTL-cached rules fetch, never throws);getStatus()/getStats()/healthCheck(). Per-kind failure streaks with backoff gates (eventsRetryAfter/metricsRetryAfter),flushConsecutiveFailures/statusConsecutiveFailures/rulesConsecutiveFailuresloop counters,lastStatusPushOk,rulesFetched/cachedRules/rulesLastUpdate.Config/AgentConfig.php: readonly resolved config (camelCase, mirroring the TS port naming; defaults identical to the Python agent).Config/AgentConfigResolver.php:resolve(array $input)(accepts camelCase and snake_case keys),validate()(returns the error list),normalizeEndpoint()(strips trailing slashes and a legacy/api/v1suffix with a one-time warning, mirroring guard_agent/models.py:176-205).Config/BufferOverflowPolicy.php:drop/block/raiseenum.Config/RedisConfig.php: url, keyPrefix (guard:agent), password, db, commandTimeoutMs (5000).EventBuffer/EventBuffer.php: per-kind bounded queues withSplObjectStoragekey maps; overflow policies;flushEventsWithKeys()/flushMetricsWithKeys()/requeueEventsInMemory()/requeueMetricsInMemory()(front requeue, tail eviction returns the evicted keys);confirmEventRedisKeys()/confirmMetricRedisKeys();persistPending()(writes unkeyed buffered items, TTL 3600; never called from add; run byflushBuffer()after the send, byflushIfNeeded()when no flush is due, and byGuardAgent::persistAtShutdown()from a shutdown function registered once ininitializeRedis());initializeRedis()reloads persisted items at startup;clearBuffer();atHighWatermark().Transport/HttpTransport.php: cURL implementation ofTransportInterface. Retry loop (retryAttempts + 1tries, localRateLimiter100/60,CircuitBreaker5 failures/60s), response classification, gzip compression,SignerHMAC, 413 split-or-drop, permanent-rejection drops,RetryAfterparsing (default 60s, honored up to 300s),BatchId, response-body summaries.Transport/TransportInterface.php: the seam (sendEvents/sendMetrics/sendStatusreturn bool; true = accepted or intentionally dropped, false = transient, caller requeues;fetchDynamicRules()returns?DynamicRulesand never throws).getWithRetry()implements the GET path forGET /api/v1/ruleswith the same retry/circuit-breaker/Retry-After machinery as the POST loop (mirrors_get_with_retry,_transport_send.py:238-289).Transport/CircuitBreaker.php,Transport/RateLimiter.php,Transport/Signer.php.Persistence/RedisClientInterface.php: the client seam (ping/get/set/delete/keys/close).Persistence/StreamRedisClient.php: dependency-free RESP2 client overstream_socket_client(PING, AUTH, SELECT, GET, SET EX, DEL, KEYS; command timeout viastream_set_timeout).Persistence/PredisRedisClient.phpandPersistence/ExtRedisClient.php: optional adapters over injected\Predis\ClientInterface-shaped and\Redisinstances.Persistence/RedisHandler.php: namespaced facade ({keyPrefix}:{namespace}:{short}) with the Go port's fail-open policy: 3 consecutive write failures pause writes for 30s.Model/SecurityEvent.php,Model/SecurityMetric.php,Model/AgentStatus.php: readonly wire models withnormalize()(camelCase or snake_case input,InvalidEventExceptionon bad input) andtoWire()(snake_case, ISO-8601 UTC with milliseconds).Model/KnownTypes.php: the advisory event-type list and the enforced metric-type list.Model/DynamicRules.php: the SaaS rules surface (mirrors DynamicRules, guard_agent/models.py:250-324, snake_case wire keys with camelCase properties,normalize()raisingInvalidRulesException;ttldrives the client cache,blocked_cloud_providersdeduped like the Python set,ge=1enforced only on theauto_ban_*fields).Model/WireFormat.php: timestamp parsing (DateTimeInterface, epoch SECONDS, or parseable string) andisoUtc().Install/InstallId.php: file-backed install ID at~/.guard-agent/install-id(override parameter, uuid v4, all filesystem failures warn and fall back to an in-memory UUID).Log/AgentLogger.phpinterface +Log/DefaultAgentLogger.php(streams in CLI SAPI,error_login web SAPI;GUARD_AGENT_DEBUGenables debug).Utils/:Json(Python-json.dumps-compatible bytes: unescaped slashes, escaped non-ASCII;SerializationException),Backoff(base * 2^attemptcapped),RetryAfter,BatchId,Uuid(v4 without ext-uuid),HeadersRedactor(recursive[REDACTED]with a JSON-string scan, depth cap 10),ResponseSummary,ErrorHook(stagestransport_send/encryption/flush_events/flush_metrics; a throwing hook is caught and logged).Exception/:GuardAgentExceptionbase withConfigException,BufferFullException,InvalidEventException,SerializationException,InvalidRulesException,RateLimitedException(carriesretryAfterSeconds),PermanentClientException(400/404/422;statusCode+detail),PayloadTooLargeException(413, extends PermanentClientException, so both are circuit-breaker exempt),RedisException.examples/basic_usage/: minimal wiring demonstration (engineonBlockpayload toSecurityEvent, agent from env, host-driventick()loop, final flush on shutdown;basic_usage.php+README.md).mkdocs.yml: mkdocs-material site definition (docs/ sources).docs/: documentation site sources:index.md,usage.md,configuration.md.
Runtime model (deliberate PHP deviation, documented in the README): PHP has no background threads, so the flush and status loops of the Python/TS/Go agents are host-driven. start() only marks the agent running, loads crash-recovery state, and initializes the transport. tick() is the loop body: it flushes when the high-watermark or flush interval triggers, pushes a status report when the status interval elapses, and refreshes the dynamic rules when the dynamic rule interval elapses (mirroring _rules_loop; a null refresh counts a consecutive rules loop failure like the other loops). Long-running workers call tick() from their own loop (pcntl-free, no signal handlers); request-scoped apps call flushBuffer() from kernel.terminate / register_shutdown_function. Under the block overflow policy the buffer invokes the agent's flush inline while waiting (the one opt-in exception to failure isolation), because in single-threaded PHP nothing else can free the space.
Neither former "dropped" entry remains: project_encryption_key is implemented (see Encryption\PayloadEncryptor) and the /api/v1/rules dynamic-rules surface is implemented (Model/DynamicRules.php, HttpTransport::fetchDynamicRules(), the tick-driven rules refresh with dynamicRuleInterval).
Key invariants an agent must preserve when editing:
- The handshake is always drain, then send, then confirm (delete persisted records) or requeue at the FRONT in the original order; under buffer pressure during requeue the TAIL (newest items) is evicted and its records confirmed.
- The HMAC signature covers the UNCOMPRESSED JSON body even when the wire bytes are gzipped; the server verifies after decompression. Any change here must update the pinned HMAC vector and the mock server together.
- The host-facing methods (
sendEvent,sendMetric,flushBuffer,tick,getStatus,getStats,healthCheck,stop) never throw into the host path; every failure is a log line plus a counter. Onlystart()may throw. - Per-kind state (queues, failure streaks, backoff gates) stays independent: one kind failing must never stall the other.
- Redis failures are fail-open: log, count, keep going (plus the 30s write cooldown after 3 consecutive write failures).
- Community workflows (
issue-link,stale,sync-labels) stay byte-identical to the Go family's (gin-guard and siblings);greetings,summary, andlabeler/labelscarry repo-specific text (agent subsystems, not adapter middleware) and must not drift in structure.
This machine has NO php and NO composer binary. Run everything through Docker (php:8.2-cli / php:8.3-cli / php:8.4-cli for tests, composer:2 for composer), or let CI execute. The host Redis on 6379 is reachable from containers as host.docker.internal.
docker run --rm -v "$PWD":/app -w /app composer:2 composer install --no-interaction --no-progress
docker run --rm -v "$PWD":/app -w /app -e REDIS_HOST=0 php:8.3-cli php bin/test_agent.php # unit-only
docker run --rm -v "$PWD":/app -w /app -e REDIS_HOST=host.docker.internal php:8.3-cli php bin/test_agent.php # full
docker run --rm -v "$PWD":/app -w /app composer:2 composer validate --strict
The CI-verified path (from .github/workflows/ci.yml): checkout, shivammathur/setup-php from the matrix (8.2/8.3/8.4, mbstring extension, coverage none), composer install --no-interaction --no-progress, the php -l sweep, then REDIS_HOST=127.0.0.1 php bin/test_agent.php and php bin/test_shutdown.php against a redis:7-alpine service on port 6379, plus a composer audit job.
Every field except apiKey is optional; AgentConfigResolver::resolve() fills defaults, validates, and throws ConfigException listing every problem. Both camelCase and snake_case keys are accepted.
| Field | Default | Constraint |
|---|---|---|
apiKey |
required | at least 10 characters; sent as X-API-Key |
endpoint |
https://api.guard-core.com |
http/https URL; trailing /api/v1 stripped with a one-time warning |
projectId |
null | sent as X-Project-Id and as batch project_id (falls back to "default" on the wire) |
bufferSize |
100 | per-kind in-memory capacity, > 0 |
flushInterval |
30 (s) | > 0; time-based flush trigger and per-kind backoff base |
dynamicRuleInterval |
300 (s) | >= 60; dynamic-rules poll cadence (tick-driven refresh) |
statusInterval |
300 (s) | >= 60; status report cadence |
highWatermarkRatio |
0.8 | in (0, 1]; occupancy fraction that triggers an early flush |
maxConcurrentFlushes |
1 | >= 1; bounds re-entrant flushes (single-threaded PHP: effectively a re-entrancy guard) |
bufferOverflowPolicy |
drop |
drop (evict oldest) / block (drain inline + poll) / raise |
enableMetrics / enableEvents |
true | false disables that ingest kind entirely |
retryAttempts |
3 | transport retries per batch (total tries = attempts + 1), >= 0 |
timeout |
30 (s) | per-request cURL timeout, > 0 |
backoffFactor |
1.0 | transport retry backoff base, capped at 60s |
sensitiveHeaders |
authorization, proxy-authorization, cookie, x-api-key | redacted from metadata/tags at ingest and again at the transport boundary |
maxPayloadSize |
1024 | advisory truncate helper for adapter metadata |
guardVersion / guardCoreVersion |
null | reported in every batch for server-side attribution |
compressionEnabled |
true | gzip above compressionThreshold |
compressionThreshold |
1024 (bytes) | >= 0 |
installId |
null | overrides the file-backed install ID |
installIdPath |
~/.guard-agent/install-id |
override the cache file location |
payloadSigningSecret |
null | enables X-Payload-Signature over the UNCOMPRESSED body |
onError |
null | Closure(string $stage, Throwable $error, array $context): void, never allowed to throw |
logger |
DefaultAgentLogger | any AgentLogger implementation |
redis |
null | RedisConfig array: url (redis:// or rediss://), keyPrefix, password, db, commandTimeoutMs |
- Failure isolation:
sendEvent,sendMetric,flushBuffer,tick,getStatus,getStats,healthCheck, andstopnever throw into the host path; every failure is a log line plus a counter. Onlystart()may throw, and only the standaloneEventBuffersurfacesBufferFullException(the agent swallows it under theraisepolicy). Theblockpolicy is the one documented, opt-in blocking exception. - At-least-once handshake: drain (keys aligned with items) -> send -> on success confirm (delete Redis records); on failure requeue at the FRONT in original order, retain Redis records, arm the per-kind gate for
min(flushInterval * 2^(streak - 1), 300)seconds. Under pressure the requeue evicts the TAIL (newest items) and the caller confirms those evicted keys so nothing orphans. - Response classification (mirroring
_handle_response): 200 with a JSON dict is evaluated (success: falseor non-emptyerrors[]means partial failure -> whole batch requeued); 200 with an unparseable body is retried; 200 non-dict and 201 are accepted; 429 raisesRateLimitedExceptionwith Retry-After (default 60s, honored up to 300s); 401/403 are generic retried errors; 400/404/422 arePermanentClientException(batch dropped, counted, never retried); 413 isPayloadTooLargeException(split in half recursively; a singleton that still exceeds the cap is dropped); 5xx retry with backoff; any other 4xx is logged and retried. - Circuit breaker: 5 consecutive non-permanent failures open it for 60s, then HALF_OPEN probes. 400/404/413/422 are exempt (batch-level rejections, not health signals); 429 and curl errors count.
- Persistence (a documented, maintainer-approved deviation from the Python agent, which persists from a background task spawned on add: PHP persists at flush, tick or shutdown, never on add, so a request never waits on Redis): persisted by
persistPending()(end offlushBuffer(), orflushIfNeeded()/tick()between flushes, or the shutdown function, never on add) under a globally-unique key{prefix}:agent_events:event_<epoch nanos>_<8hex>(the stamp is wall-clock epoch nanoseconds like Python'stime.time_ns(), microsecond resolution) (oragent_metrics), TTL 3600s. Startup reload walks the keys in the order RedisKEYSreturns them, exactly like the Python agent (no sort; the stamp is wall-clock so a later sort would be chronological); corrupt or missing records are warned and skipped (the TTL reclaims them). Every Redis failure is fail-open: logged, counted inredisPersistFailures(durabilityDegraded), and after 3 consecutive write failures writes pause for 30s. A shutdown function the agent registers once when Redis persistence is attached (initializeRedis(), including the onestart()builds fromconfig.redis) runspersistAtShutdown(), which callspersistPending(), so items buffered by a request are written to Redis when the process ends by normal end,exit(), an uncaught exception, a fatal error, out of memory ormax_execution_time(proved bybin/test_shutdown.php). Events are lost only when PHP runs no code at all: SIGKILL (for example the OOM killer orkill -9), and SIGTERM unless the host installs its own handler (plain PHP skips shutdown functions on SIGTERM; with ext-pcntl a host handler that callsexit()makes it durable). The agent installs no signal handler because it would override the host's. It does not callfastcgi_finish_request()either: that would cut off output and shutdown functions the host registers later, so a host that wants the response out first calls it itself. - Rules refresh:
tick()refreshes dynamic rules only whenprojectIdis set, mirroring the reference'sif self.config.project_idrules loop;getDynamicRules()still works without one. - Stats:
getStats()carries exactly the referenceget_stats()key set (bufferStats,transportStatsandloopFailuresnested), camelCased (events_sentiseventsSent,buffer_statsisbufferStats,auto_flush_runningisautoFlushRunning). The array is host-facing only (the PHP adapters merge it intoagentStats); it is not serialized into any status push, health endpoint or SaaS payload, so the camelCase idiom is kept.autoFlushRunningis alwaysfalsebecause PHP has no background auto-flush. - Degraded status: circuit OPEN, or buffer >= 90 percent occupancy, or lifetime failure rate > 10 percent.
healthCheck()additionally fails at >= 95 percent occupancy or > 50 percent failure rate, and when not running.
| Command | What it runs |
|---|---|
composer test |
php bin/test_agent.php |
php bin/test_shutdown.php |
child-process proof of persistence at process end (needs Redis on 6379; REDIS_HOST=0 skips) |
composer lint |
for f in $(find src bin -name '*.php'); do php -l "$f" > /dev/null || exit 1; done && echo LINT_OK (example files are linted with php -l directly) |
composer validate --strict |
composer.json hygiene (no version field, valid schema) |
pip install mkdocs-material && mkdocs build --strict |
Build the documentation site (CI deploys it on main) |
Docker equivalents are in Quick Start. There is no Makefile (the sibling PHP repos do not use one either).
- The suite is
bin/test_agent.php, a T-harness in the guard-core-php sibling style (plainok - / FAIL -lines, exit code 0 only when everything passed). No PHPUnit, no test framework dependency. REDIS_HOSTcontrols the persistence leg:REDIS_HOST=0skips the real-Redis integration (unit-only), any hostname runs it against port 6379. The fake-Redis handshake tests always run.- The mock-server integration smoke spawns
php -Swithtests/mock_server.php, which mirrors the ingestion contract: size-based 413 (decompressed body > 262144 bytes), signature verification over the uncompressed body with an optionalrequireSignedmode, scripted per-path responses from a control file (status, body, Retry-After), and a JSON state log the tests assert against. - Pinned HMAC vector:
Signer::signPayload('{"hello":"world"}', 'test-secret')must equalv1=84cc33df716ed0b0598f07437c94069ace3730358778a592bd6bbd1423d111f3. - Coverage expectations when editing: config validation (all constraint branches), buffer overflow policies and requeue eviction, the handshake order (drain -> send -> confirm/requeue/gate), retry classification (200 partial, 429, 400, 401, 413 split and singleton drop, 5xx, dead endpoint), breaker open/exempt/half-open, persistence (deferred persistPending, TTL, reload, confirm deletes, fail-open cooldown), and the smoke contract assertions (headers, gzip, signature, endpoints).
vendor/is never committed;composer.lockis (zero-dependency lock, generated with thecomposer:2image).
- Never widen the public throwing surface: the host-facing methods must keep never throwing. New failure modes get logged and counted.
- Keep the wire format byte-faithful to the Python agent (
model_dump()snake_case) and the server contract; when Python, TS, and Go disagree, Python is normative for agent semantics and the guard-core-api source is normative for the wire. - Any change to signature or compression behavior must update the pinned HMAC test and the mock server together.
- Edit the async-of-nothing source directly: there is no unasync mirror here (unlike guard-core); the whole package is synchronous by design.
- Keep
declare(strict_types=1)on every file and PHP 8.2 compatibility (no 8.3+ syntax;readonlyclasses and enums are fine). - No em-dashes or en-dashes anywhere in this repository.
- Run the three PHP-version legs plus
composer validate --strictbefore pushing; the release gate does not re-run anything at the tag, it only requires the push run ofci.ymlon the tagged commit to have succeeded. - Never merge into
mainand never create tags without an explicit instruction; the working branch pattern isfeat/...with a draft PR.
- guard-core (engine): https://github.com/Guard-Core/guard-core
- guard-agent (Python, semantic reference): https://github.com/Guard-Core/guard-agent
- guard-agent-go (Go port): https://github.com/Guard-Core/guard-agent-go
- guardagent (TypeScript port): https://github.com/Guard-Core/guard-agent-ts
- guard-core-php (PHP engine port): https://github.com/Guard-Core/guard-core-php
- guard-core-app (SaaS ingestion API): https://github.com/Guard-Core/guard-core-app