Skip to content

Add the Activity Log package - #155

Merged
binaryfire merged 10 commits into
0.4from
feature/activity-log
Dec 1, 2026
Merged

binaryfire merged 10 commits into
0.4from
feature/activity-log

Conversation

@binaryfire

@binaryfire binaryfire commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

This adds hypervel/activity-log, an optional package for recording application activity in a database. An entry can describe an action, the model it affected, who performed it, and any properties the application wants to keep.

activity('billing')
    ->performedOn($invoice)
    ->causedBy($user)
    ->event('paid')
    ->log('Invoice paid');

Models can also use LogsActivity to record Eloquent events. The model chooses which attributes to log and whether to keep only changes. By default, the logger reads the model as it was at the event. Applications that need database-generated values can opt into a refresh inside the writing transaction.

Persistence

Activities are saved immediately by default. Applications can opt into buffering to insert rows in batches. Each coroutine owns its buffer and its current causer. For an activity recorded on a connection with an open transaction, a rollback discards the buffered entry. After commit, a later batch writes it. Applications that need the activity and the domain change to commit together can use immediate writes on the same connection.

Installation and use

Composer discovers the service provider. The application publishes the migration before running it, so it can choose the appropriate morph keys and indexes. The package includes a cleanup command with configurable retention and optional scheduling. The guide covers installation, querying, model events, transaction behavior, and differences from Spatie’s Laravel Activity Log.

Verification

The package tests cover model changes, causer resolution, coroutine isolation, buffer flushing, and rollback. The migration and row-locking tests ran against MySQL, MariaDB, and PostgreSQL. A clean application installed the split package, published and ran the migration, and recorded an activity through the helper.


Summary by cubic

Adds hypervel/activity-log, an optional package for recording application activity in a database. Activities log an action, the affected model, who performed it, and arbitrary properties through a helper or automatic model event logging.

Persistence

  • Activities save immediately by default; applications can opt into coroutine-scoped buffering that flushes rows in bounded batches at lifecycle boundaries.
  • Buffered inserts bind to the activity's connection, preserve call order across savepoints, and prepare timestamps on the activity snapshot so custom insert hooks choose the final columns; a rollback on an open transaction discards buffered entries.
  • Automatic model logging reads the model's in-memory snapshot; refreshBeforeLogging() opts into a refresh inside the writing transaction, and restores are logged separately from updates.
  • Selected JSON columns and parent paths survive child selectors, and selected values are read on the owning model through its cast serializer so enum collections audit by case name and unrelated updates stay out of the log.

Safety and installation

  • Partially selected models can no longer resolve an unresolved morph relation against the source table, and unknown morph targets stay out of the change audit.
  • Composer discovers the service provider and conflicts with spatie/laravel-activitylog; applications publish the migration to choose morph keys and indexes, and the package ships a cleanup command with configurable retention.
  • Tests cover model changes, causer resolution, coroutine isolation, buffer flushing, and rollback; migration and row-locking tests ran on MySQL, MariaDB, and PostgreSQL.

Written for commit 68ab5cf. Summary will update on new commits.

View guided diff Turn on auto-fix

Note

Add the Hypervel Activity Log package with model, logger, buffering, and cleanup

Introduces a new hypervel/activity-log package that records model events and manual activity to an activity_log table. It is modeled after spatie/laravel-activitylog and conflicts with that package in Composer.

  • Adds the Activity Eloquent model with subject/causer morph relations and query scopes (inLog, causedBy, forSubject, forEvent), plus the LogsActivity, CausesActivity, and HasActivity model concerns and the activity() helper and facade.
  • Adds LogActivityAction (description placeholders, subject hooks, before-logging callbacks) and CleanActivityLogAction (batched deletion older than a retention cutoff) with an activity-log:clean console command and scheduled cleanup.
  • Adds coroutine-scoped ActivityBuffer for transaction-aware activity buffering, flushed at application termination and after non-sync job attempts.
  • Includes a publishable migration, configuration file, and full documentation in activity-log.md.
  • Also changes core Eloquent: MorphTo relations built before the morph type is known now return as eager-loading placeholders (no query, default value returned) in MorphTo.php, and SoftDeletes exposes an is-restoring flag in SoftDeletes.php.
  • Risk: the package declares a Composer conflict with spatie/laravel-activitylog, so projects using that package cannot install both. The MorphTo placeholder change alters morphTo behavior when the morph type attribute is missing — see HasRelationships.php.

Macroscope summarized 68ab5cf.

@coderabbitai

coderabbitai Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Add Activity Log package (hypervel/activity-log)

✨ Enhancement 🧪 Tests 📝 Documentation ⚙️ Configuration changes 🕐 40+ Minutes

Grey Divider

AI Description

• Adds optional hypervel/activity-log package: fluent activity() helper and Eloquent model event
 logging via LogsActivity.
• Persists activities immediately by default; opt-in coroutine-scoped buffer batches inserts and
 discards rolled-back entries.
• Adds publishable migration, activity-log:clean command with optional scheduling, package tests,
 MySQL/MariaDB/PostgreSQL integration tests, and docs.
Merge Risk 🟡 Medium

Blast radius 🔴 High 💥 3 capabilities

  • 3 affected capabilities span independent functional scopes: activity_log_integration, eloquent_relationships.
  • The helper, logger, model trait, activity model, storage migration, and service provider form one bounded end-to-end integration that records and queries audit activities.
  • The propagation path stays within this integration; database writes are implementation hops rather than independent capabilities.
  • Retention cleanup operates on the same bounded activity-log integration and its persisted audit rows, but is a distinct useful operation from recording because it intentionally removes historical records.
  • This is a generic Eloquent relation behavior used by any model with MorphTo relationships, independent of the activity-log integration.
  • The changed path alters placeholder construction and result access for all such consumers.
Behavioral complexity 🟡 Medium 🧩 Interacting branches, Data transformation

  • Before, activity logging was absent from this repository.
  • After, explicit calls and model lifecycle events select log names, causers, subjects, descriptions, changed attributes, callbacks, casts, and persistence paths.
  • New correctness conditions include preserving event-specific filtering, callback ordering, scoped state, placeholder resolution, and consistent serialized values across direct and automatic logging.
  • The transformation pipeline is mostly established model infrastructure, but the new combination of event hooks, configurable state, and persistence introduces interacting branches.
Potential damage 🔴 High 🩹 Data loss

  • A cleanup regression can delete records outside the intended age or log-name predicate, or fail to retain records needed by the integration.
  • Deleted audit rows are persistent data and are not restored by code rollback; the repository provides no backup or automatic recovery path.
  • Stopping or reverting the cleanup code prevents further deletion, but already deleted activity rows require an external database backup or independent audit source.
  • No automatic repair path is shown.
Assessed commit 68ab5cf
Diagram

graph TD
    H["activity() helper"] --> L["ActivityLogger"]
    M["LogsActivity model events"] --> L
    L --> X["LogActivityAction"]
    X -->|buffer enabled| B["ActivityBuffer"] --> D[("activity_log table")]
    X -->|immediate| D
    F["Terminating / JobAttempted"] -.-> B
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Queue-dispatched writes
  • ➕ Moves database cost off the request path
  • ➕ Batching can happen in the worker
  • ➖ Activities can commit before or after the domain change they describe
  • ➖ Adds a queue dependency for an audit feature
  • ➖ Requires serialising model snapshots for the job
2. Immediate writes only, no buffer
  • ➕ Simpler lifecycle with no flush hooks
  • ➕ Each activity gets its ID immediately
  • ➕ Fewer code paths to test
  • ➖ One INSERT per activity on high-volume requests
  • ➖ Loses the batching benefit the package advertises

Recommendation: Keep the current design: immediate writes by default, with an opt-in per-coroutine buffer keyed to transactions. The buffer is the only option that batches inserts while keeping rollback semantics, and the defaults keep the simple path. Two alternatives were considered and rejected: dispatching activity writes to a queue job, which breaks commit-time ordering with the domain change, and dropping the buffer, which costs one INSERT per activity under high volume.

Files changed (53) +12308 / -0

Enhancement (23) +3225 / -0
2026_08_04_000000_create_activity_log_table.phpAdd publishable activity_log table migration +44/-0

Add publishable activity_log table migration

• Creates the table with nullable morphs for subject and causer using named indexes, JSON changes and properties columns, and created_at/id indexes for querying and cleanup.

src/activity-log/database/publish/2026_08_04_000000_create_activity_log_table.php

ActivityLogServiceProvider.phpWire bindings, scheduling, publishing, and flush hooks +99/-0

Wire bindings, scheduling, publishing, and flush hooks

• Registers scoped resolvers and buffer, the clean command, optional cleanup schedule, and config and migration publishing. Flushes the buffer on terminating and on JobAttempted, except for sync jobs.

src/activity-log/src/ActivityLogServiceProvider.php

ActivityLogManager.phpAdd activity() manager and per-call builder +132/-0

Add activity() manager and per-call builder

• Creates a fresh builder for each activity() call so state is not shared across coroutines.

src/activity-log/src/ActivityLogManager.php

helpers.phpAdd activity() global helper +16/-0

Add activity() global helper

• Exposes the fluent activity() entry point as a global function.

src/activity-log/src/helpers.php

ActivityBuffer.phpImplement coroutine-scoped transaction-aware insert buffer +377/-0

Implement coroutine-scoped transaction-aware insert buffer

• Stages entries inside open transactions and discards them on rollback. After commit, batches inserts by size and drains on flush, with a coroutine defer as a fallback.

src/activity-log/src/Support/ActivityBuffer.php

ActivityLogger.phpAdd fluent builder for causer, subject, event, and properties +319/-0

Add fluent builder for causer, subject, event, and properties

• Provides performedOn, causedBy, event, withChanges, withProperties, and log. Resolves the default causer lazily and supports withoutLogging.

src/activity-log/src/Support/ActivityLogger.php

CauserResolver.phpResolve causer from auth or a custom resolver +165/-0

Resolve causer from auth or a custom resolver

• Resolves the causer from explicit ID or model, the auth driver, or a custom resolver closure. Validates resolver output.

src/activity-log/src/Support/CauserResolver.php

ChangeDetector.phpCompute attribute changes for model events +128/-0

Compute attribute changes for model events

• Diffs old and new attributes for update events and applies the model's logOnly and logExcept rules.

src/activity-log/src/Support/ChangeDetector.php

LogOptions.phpAdd per-model logging options value object +227/-0

Add per-model logging options value object

• Holds log name, attribute include and exclude lists, dirty-only logging, and description callbacks for each model.

src/activity-log/src/Support/LogOptions.php

ActivityLogConfiguration.phpRead package configuration and resolve action classes +242/-0

Read package configuration and resolve action classes

• Reads config values such as buffer enablement, batch size, retention, and model class, and builds the configured action instances.

src/activity-log/src/Support/ActivityLogConfiguration.php

ActivityLogStatus.phpTrack per-scope enable and disable state +39/-0

Track per-scope enable and disable state

• Holds the logging on or off flag per scope, backing enableLogging, disableLogging, and withoutLogging.

src/activity-log/src/Support/ActivityLogStatus.php

LogsActivity.phpAdd trait recording Eloquent model events +619/-0

Add trait recording Eloquent model events

• Hooks created, updated, deleted, and restored events, builds changes, and logs with the model's options. Reads the model as it was at the event by default.

src/activity-log/src/Models/Concerns/LogsActivity.php

HasActivity.phpAdd morphMany relation for subject activities +28/-0

Add morphMany relation for subject activities

• Adds a relation returning activities where the model is the subject.

src/activity-log/src/Models/Concerns/HasActivity.php

CausesActivity.phpAdd morphMany relation for caused activities +34/-0

Add morphMany relation for caused activities

• Adds a relation returning activities where the model is the causer.

src/activity-log/src/Models/Concerns/CausesActivity.php

Activity.phpAdd default Activity Eloquent model +138/-0

Add default Activity Eloquent model

• Defines the activity model with casts for JSON changes and properties, plus subject and causer morph relations.

src/activity-log/src/Models/Activity.php

Activity.phpAdd activity model contract +25/-0

Add activity model contract

• Defines the interface that custom activity models must implement.

src/activity-log/src/Contracts/Activity.php

LogActivityAction.phpAdd persistence action with beforeLogging hooks +173/-0

Add persistence action with beforeLogging hooks

• Resolves placeholders in the description, runs global beforeLogging callbacks, then saves the activity. Overridable via config.

src/activity-log/src/Actions/LogActivityAction.php

CleanActivityLogAction.phpAdd batched deletion action for old activities +114/-0

Add batched deletion action for old activities

• Deletes activities older than the retention window in configurable batches, optionally scoped to a log name.

src/activity-log/src/Actions/CleanActivityLogAction.php

CleanActivityLogCommand.phpAdd activity-log:clean console command +74/-0

Add activity-log:clean console command

• Validates the --days option, defaults to configured retention, and runs the clean action with optional log name.

src/activity-log/src/Commands/CleanActivityLogCommand.php

ActivityLog.phpAdd ActivityLog facade +62/-0

Add ActivityLog facade

• Provides static access to the activity manager.

src/activity-log/src/Facades/ActivityLog.php

ActivityEvent.phpAdd ActivityEvent enum +14/-0

Add ActivityEvent enum

• Enumerates created, updated, deleted, and restored event names.

src/activity-log/src/Enums/ActivityEvent.php

CouldNotLogActivity.phpAdd persistence and resolver exceptions +79/-0

Add persistence and resolver exceptions

• Defines failures for insert errors and invalid causer resolver results.

src/activity-log/src/Exceptions/CouldNotLogActivity.php

InvalidConfiguration.phpAdd configuration exceptions +77/-0

Add configuration exceptions

• Defines errors for missing created_at columns and buffer target changes between connection or table.

src/activity-log/src/Exceptions/InvalidConfiguration.php

Tests (23) +8088 / -0
AfterEachTestSubscriber.phpFlush Activity Log state after each test +10/-0

Flush Activity Log state after each test

• Resets the beforeLogging callback registry and ActivityLogger macros between tests. Modifies shared framework test infrastructure.

src/testing/src/PHPUnit/AfterEachTestSubscriber.php

ActivityBufferTest.phpTest buffer batching, staging, and rollback +906/-0

Test buffer batching, staging, and rollback

• Covers batch flushing, transactional staging and rollback discard, and ordering behaviour.

tests/ActivityLog/Support/ActivityBufferTest.php

ActivityLoggerTest.phpTest fluent builder behaviour +686/-0

Test fluent builder behaviour

• Exercises causer, subject, event, properties, and log-name methods on the logger.

tests/ActivityLog/Support/ActivityLoggerTest.php

ActivityLogLifecycleTest.phpTest buffer lifecycle flushing +206/-0

Test buffer lifecycle flushing

• Verifies buffer flush at lifecycle boundaries with buffering enabled.

tests/ActivityLog/Support/ActivityLogLifecycleTest.php

ActivityLogConfigurationTest.phpTest configuration resolution +309/-0

Test configuration resolution

• Verifies configuration values and action class resolution.

tests/ActivityLog/Support/ActivityLogConfigurationTest.php

CauserResolverTest.phpTest causer resolution rules +201/-0

Test causer resolution rules

• Verifies causer resolution from auth, explicit input, and custom resolvers.

tests/ActivityLog/Support/CauserResolverTest.php

LogsActivityTest.phpTest model event logging +762/-0

Test model event logging

• Verifies that model events are recorded with the configured options.

tests/ActivityLog/Traits/LogsActivityTest.php

DetectsChangesTest.phpTest change detection +1979/-0

Test change detection

• Covers attribute change computation for updates and dirty-only logging.

tests/ActivityLog/Traits/DetectsChangesTest.php

DetectsChangesRegressionTest.phpAdd change detection regression tests +1143/-0

Add change detection regression tests

• Holds regression cases for change detection edge cases.

tests/ActivityLog/Traits/DetectsChangesRegressionTest.php

ActivityLogIsolationTest.phpTest coroutine isolation of causer and buffer +100/-0

Test coroutine isolation of causer and buffer

• Checks that each coroutine keeps its own causer and buffer state.

tests/ActivityLog/Concurrency/ActivityLogIsolationTest.php

ActivityLogPooledPersistenceTest.phpTest persistence under pooled connections +131/-0

Test persistence under pooled connections

• Checks that buffered writes persist correctly when connections are pooled.

tests/ActivityLog/Concurrency/ActivityLogPooledPersistenceTest.php

ActivityLogMigrationTest.phpTest migration schema +123/-0

Test migration schema

• Verifies the published migration creates the expected columns and indexes.

tests/ActivityLog/Database/ActivityLogMigrationTest.php

CleanActivityLogCommandTest.phpTest clean command options and output +156/-0

Test clean command options and output

• Covers --days validation, default retention, and log-name scoping.

tests/ActivityLog/Commands/CleanActivityLogCommandTest.php

CleanActivityLogActionTest.phpTest batched clean action +328/-0

Test batched clean action

• Verifies deletion by retention window and batch size.

tests/ActivityLog/Actions/CleanActivityLogActionTest.php

LogActivityActionTest.phpTest persistence action +180/-0

Test persistence action

• Verifies placeholder resolution and beforeLogging callback ordering.

tests/ActivityLog/Actions/LogActivityActionTest.php

TestCase.phpAdd package test base case +194/-0

Add package test base case

• Provides the Testbench base with the package provider and database setup.

tests/ActivityLog/TestCase.php

Activity.phpAdd test activity model fixture +130/-0

Add test activity model fixture

• Test double for the default Activity model.

tests/ActivityLog/Models/Activity.php

User.phpAdd test user model fixture +97/-0

Add test user model fixture

• Test user model used for causer resolution.

tests/ActivityLog/Models/User.php

Article.phpAdd test article model fixture +37/-0

Add test article model fixture

• Test model that uses LogsActivity.

tests/ActivityLog/Models/Article.php

TestStateTest.phpTest per-test state reset +112/-0

Test per-test state reset

• Verifies that package state is reset between tests.

tests/ActivityLog/Testing/TestStateTest.php

ActivityLogRefreshLockingTest.phpAdd MySQL/MariaDB/PostgreSQL refresh-locking integration test +178/-0

Add MySQL/MariaDB/PostgreSQL refresh-locking integration test

• Checks that a refresh inside the writing transaction reads the locked statement's result while a second writer waits. Requires mysql, mariadb, or pgsql.

tests/Integration/ActivityLog/Database/ActivityLogRefreshLockingTest.php

ActivityLogMigrationDatabaseTest.phpAdd migration integration test against real databases +83/-0

Add migration integration test against real databases

• Runs the published migration against real database engines, gated by RequiresDatabase.

tests/Integration/ActivityLog/Database/ActivityLogMigrationDatabaseTest.php

InteractsWithActivityLogDatabases.phpAdd shared database fixture trait for integration tests +37/-0

Add shared database fixture trait for integration tests

• Provides engine assertions and setup helpers shared by the integration tests.

tests/Integration/ActivityLog/Fixtures/InteractsWithActivityLogDatabases.php

Documentation (4) +833 / -0
LICENSE.mdAdd MIT license crediting Spatie +25/-0

Add MIT license crediting Spatie

• Carries the upstream Spatie copyright because the package is ported from spatie/laravel-activitylog.

src/activity-log/LICENSE.md

README.mdAdd package README with Spatie differences +25/-0

Add package README with Spatie differences

• Documents the port, notes it cannot be installed alongside spatie/laravel-activitylog, and lists behavioural differences.

src/activity-log/README.md

activity-log.mdAdd Activity Log guide +782/-0

Add Activity Log guide

• Covers installation, querying, model events, buffering and transaction behaviour, cleanup, and migrating from Spatie.

src/docs/activity-log.md

documentation.mdLink Activity Log guide from docs index +1/-0

Link Activity Log guide from docs index

• Adds the Activity Log guide to the documentation index.

src/docs/documentation.md

Other (3) +162 / -0
composer.jsonRegister package autoload, replace entry, helpers, and provider +4/-0

Register package autoload, replace entry, helpers, and provider

• Adds the PSR-4 namespace, global helpers file, package replace entry, and auto-discovered service provider.

composer.json

composer.jsonDefine hypervel/activity-log package manifest +69/-0

Define hypervel/activity-log package manifest

• Declares the package's dependencies, autoload, and extra provider metadata for split publishing.

src/activity-log/composer.json

activity-log.phpAdd activity-log configuration file +89/-0

Add activity-log configuration file

• Adds retention, cleanup schedule, default log name, excluded attributes, model and action overrides, and buffer enable and batch size options.

src/activity-log/config/activity-log.php

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Rolled-back changes leave audit entries ✓ Resolved Bug Correctness
Description
ActivityBuffer::add() registers commit and rollback callbacks using the connection’s base name,
while transactions on a read/write alias are registered under its role-qualified name. When the
activity model uses an alias such as mysql::write, the commit callback runs immediately and no
rollback callback is attached, so a later rollback still leaves the entry eligible for insertion.


Remediation recommended

2. Job audit writes bypass attempt handling 🐞 Bug ☼ Reliability
Description
ActivityLogServiceProvider registers the job-attempt flush only as a passive observer, but the
queue worker dispatches that event only when it has an active listener. With only this package
installed, buffered entries instead flush at coroutine exit; an insert failure is then reported by
the defer handler after the attempt has ended, rather than reaching the worker’s attempt handling.
Code

src/activity-log/src/ActivityLogServiceProvider.php[R80-82]

+        $events->observe(
+            JobAttempted::class,
+            static function (string $_event, array $payload): void {
Evidence
The worker guards attempt-event dispatch with hasListeners(), which excludes passive observers.
The buffer’s coroutine defer does eventually try to flush, but Coroutine::defer() catches and
reports exceptions rather than returning them to the worker’s attempt path.

src/activity-log/src/ActivityLogServiceProvider.php[76-94]
src/events/src/Dispatcher.php[256-264]
src/events/src/Dispatcher.php[305-311]
src/queue/src/Worker.php[1217-1248]
src/activity-log/src/Support/ActivityBuffer.php[272-287]
src/coroutine/src/Coroutine.php[56-70]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The worker skips `JobAttempted` dispatch when the activity-log flush is registered only as a passive observer, leaving coroutine exit to perform the normal job flush.
## Fix Focus Areas
- src/activity-log/src/ActivityLogServiceProvider.php[80-94]
## Recommended Fix
Register the flush through an active event listener that is counted by `hasListeners()`. Keep the synchronous-job exclusion and coroutine-exit fallback, and test that an asynchronous attempt flushes before its coroutine exits.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Default causer overrides an explicitly passed causer ✓ Resolved Bug Correctness
Description
CauserResolver::resolve() returns $causerOverride before it looks at the $subject argument,
and ActivityLogger::causedBy() sends every explicit model or ID through resolve(). Once
middleware calls ActivityLog::defaultCauser($serviceAccount, ...) or setCauser(), every
activity()->causedBy($user) in that scope records the service account instead of $user, so the
audit trail credits the wrong actor.

4. Enum or array placeholders make logging throw ✓ Resolved Bug Reliability
Description
replacePlaceholders() ends with (string) $value for whatever data_get() returns. A placeholder
such as :subject.status that points to an enum-cast attribute, or :properties.meta that points
to an array, raises an error or warning, and the activity is not recorded.


Informational

5. Invalid retention setting is reported as a bad --days ✓ Resolved Bug Observability
Description
CleanActivityLogCommand::handle() catches the InvalidArgumentException that cleanAfterDays()
throws for an invalid clean_after_days setting and sets $maxAgeInDays = false. The command then
prints 'The days option must be a positive integer.' even when no --days was passed, which sends
operators to the wrong place.

Grey Divider

Tip of the day
💡 Did you know, you can pick a display mode instead of tweaking every Display option by hand

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@greptile-apps

greptile-apps Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5 · The PR appears safe to merge, with the previous enum-collection failure addressed and no new blocking findings.RetriggerView in GreptileConfidence Score: 5/5 Tier: plus

[Medium impact] The PR appears safe to merge, with the previous enum-collection failure addressed and no new blocking findings.

Summary

Adds optional hypervel/activity-log with model-event logging, scoped causers, buffered writes, cleanup, and documentation.

  • Applications can record activities with an action, subject, causer, and extra details.
  • Models can record selected values when their chosen events happen.
  • Activity entries can wait in each coroutine and reach the database in batches.
  • Operators can remove old activity entries in bounded batches.
  • Unknown morph targets use a safe placeholder instead of a source-table query.
  • Composer can discover the package, and applications can publish its settings and guide.
  • The broadcast test gives its array shape a more precise type.

Reviews (5) · Last reviewed commit: "Use Eloquent cast serialization for sele..." · Reviewed by Greptile

Bind buffered inserts and transaction callbacks to the connection that
owns the activity. Flush eligible rows in call order across savepoints,
keep each coroutine's buffer independent, and preserve per-statement
hooks and binary bindings. Read cleanup batches from the writer.

Use the model's extraction overrides for both sides of a change. Keep
raw values intact, distinguish typed JSON values, and handle partial
models and explicitly selected relationships. Track actual restores so
ordinary updates and restore events each produce the intended history.

Preserve explicit and preassigned causers during nested lookups, restore
logging status after callbacks, and support backed-enum log names. Update
the generated facade and its type coverage, declare the Composer helper
conflict, and document connection selection and buffering behavior.

Exercise these paths in package and integration tests, including scoped
connections, real queue-worker completion, and competing database writes.
A partially selected model can have a foreign ID without its morph type.
The temporary relation used for eager loading then points at the source
table, where an unrelated row can have the same ID. Mark that relation at
construction so lazy reads and touches cannot use the source row.

Keep eager loading and custom typed relations on their existing paths.
Report an omitted type through the normal strict-mode handler at read time
without running unrelated cached cast setters. Use the same marker when
collecting activity changes so an unknown target stays out of the audit.

Cover projected reads, explicit queries, touches, strict access, and
association, including preservation of an unrelated cached JSON value.
Add a Credits section linking to Spatie's Laravel Activity Log and list
it in the table of contents, following the other ported package guides.
Keep a selected JSON column or parent path intact when another selector
names one of its children. Compare nested cast values by their contents so
unrelated updates leave them out of the log and scalar type changes remain
visible. Reject invalid relation paths before invoking base model helpers.

Use the activity model's insert attributes after preparing timestamps on
a snapshot. Custom insert hooks can choose the final columns in either
persistence mode while generated IDs stay available to the caller.

Respect application transactions inside database tests and flush eligible
rows inside the wrapping transaction. If a failed batch leaves rows in
memory, let the wrapper discard them on rollback. Cover the write order,
failed batch, and finalization against a real transaction manager.

Explain the primary key requirement when cleaning keyless activity models
and clarify the environment settings and JSON selections in the guide.
@binaryfire

Copy link
Copy Markdown
Member Author

On the job-attempt flush mentioned in the review summary, Foundation registers an active listener for JobAttempted in registerDeferHandler(). That makes the worker dispatch the event. I verified with a real queue worker that the Activity Log observer writes the buffered row before the attempt returns.

Let collections serialize their own items when comparing old and new
activity values. Reading the raw item list bypassed the collection's
Arrayable conversion, and loose object equality could hide a change from
a number to a string in a public field.

Compare object values through their JSON representation. Keep the fast
path for identical values, early exit for arrays, and interval handling.
Exercise public-field, Arrayable and JSON-serializable mapped items on
both an unrelated update and a change in scalar type.

Give both Arrayable test fixtures the return shape their contract expects.
Read the selected value on the model that owns it and honor its cast
serializer before comparing or recording changes. A non-backed enum
collection can now be audited by case name, including when it is reached
through a relation or JSON path.

Reuse each JSON root across sibling paths in a snapshot. Let collection
roots expose their mapped items in the same form they would record for a
whole-column selection.

Preserve raw selections and getter overrides. Enum cases and dates
returned by getters still use their configured audit formats, while
scalar values returned by getters are recorded as supplied.
@binaryfire
binaryfire merged commit 020aa27 into 0.4 Dec 1, 2026
52 of 54 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant