Download the PHP package milpa/devtools without Composer
On this page you can find all versions of the php package milpa/devtools. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Table of contents
Download milpa/devtools
More information about milpa/devtools
Files in milpa/devtools
Download milpa/devtools
More information about milpa/devtools
Files in milpa/devtools
Vendor milpa
Package devtools
Short Description The coa generate-verify-inspect developer loop for the Milpa PHP framework: deterministic controller/entity scaffolding (Make engine), framework health + plugin-manifest + capability-graph validators, and BaseController/Doctrine-entity convention verifiers.
License Apache-2.0
Package devtools
Short Description The coa generate-verify-inspect developer loop for the Milpa PHP framework: deterministic controller/entity scaffolding (Make engine), framework health + plugin-manifest + capability-graph validators, and BaseController/Doctrine-entity convention verifiers.
License Apache-2.0
Please rate this library. Is it a good library?
Informations about the package devtools
# Milpa DevTools
> The **generate-verify-inspect** developer loop for the Milpa PHP framework: deterministic plugin/controller/entity/CRUD/service/tool scaffolding (the Make engine), boot-time doctors, and architectural validators — capability graphs, plugin manifests, boundary rules — that run **in-process**, with Composer-safe root resolution.
[](https://github.com/getmilpa/devtools/actions/workflows/ci.yml)
[](https://packagist.org/packages/milpa/devtools)
[](https://www.php.net/)
[](LICENSE)
[](https://getmilpa.github.io/devtools/)
`milpa/devtools` is what `coa` calls when you type `coa:make`, `coa:doctor`, `coa:validate`, or
`coa:inspect` — the engine behind that whole CLI surface, extracted so it runs the same in-process
whether it's driven by a real host app's console or by your own tests. **Generate** deterministic,
convention-following scaffolding; **verify** it against the exact runtime rules the framework
enforces; **inspect** a plugin ecosystem's capability graph and manifests for problems before they
become a boot-time failure. No `exec()` to a script at a hardcoded path, no assumption about
install depth — just classes you can `new` and call.
## Install
## Quick example: generate, then read what you got
`EntityGenerator`/`ControllerGenerator` both target **two conventions** — a Doctrine `Milpa\app`
legacy host, or a plain `milpa/data`/PSR-7 `milpa/runtime` host — auto-detected per app root by
`ConventionDetector` (override with `GenerationContext`'s `flavor` option, e.g. `--flavor=runtime`).
The full split, exact CLI syntax for each host, and the `--fields` DSL live in
[`docs/DEVTOOLS-MAKE.md`](../../docs/DEVTOOLS-MAKE.md) of the host monorepo; this README's example
below shows the **legacy** flavor. Either way it's a string, in memory, with zero disk I/O of its
own (that's `WriteGuard`'s job, so a caller can inspect, diff, or dry-run a generation before
anything touches the filesystem):
produces (verbatim, this is a real run — see [What's inside](#whats-inside) for the full field DSL):
`$result->verifyKind` is `'entity'` and `$result->verifyTarget` is the class's FQCN — the exact two
values `VerifyRunner::run()` needs to close the loop (see below) once the file is actually written.
## The five atoms a host adopts: `DevToolsOperations`
The engine below is callable on its own, but a Milpa host normally adopts it as **declared
operations** — one `Operation` each for `validate`, `make`, `implement`, `edit` and `test`, enlisted
once and materialised by every surface the host projects to (terminal, HTTP, TUI, MCP). A host adds
`DevToolsOperations` to its operation providers and gets `coa make …` *and* a `make` tool its agent
can call, from the same declaration.
The five are a loop: scaffold it, **write its body**, check it follows the convention, then **run
it** to find out whether it also does what it was supposed to. Without the last the loop closes on
form and never on behaviour — an entity can satisfy `EntityInterface` perfectly and still return the
wrong field from `toArray()`.
### Catalogue relationships for local source
`artifact:list` declares its output schema, including each artifact's `plugin` directory. Call it
without a filter to discover local code, including code whose plugin is not registered yet.
The plugin inputs of `make`, `implement`, `edit`, `artifact:contract`, `artifact:list`, `test:list`
and `test:show`, plus `validate.target`, point to that producer through `x-milpa-source`.
These references teach where to find existing directories. They do not restrict inputs to an
enum: scaffolding a new plugin still accepts a new name, and validation also accepts a manifest
path. A directory's existence does not promise that it contains the requested class or test.
Use the plugin management catalogue for registry names; they can differ from source directories.
### `implement` and `edit`: writing code through a gate, not around it
`make` scaffolds; these two fill. Both target **a class `make` already scaffolded** — the target is
a name the request can carry (the intent contract applies), and the path is derived by searching
only inside `src/Plugins//`, so escaping the tree is impossible by construction. Landing is
a **postcondition**: syntax on a staged copy, `strict_types`, the class it claims, the namespace its
location dictates — and, when the app ships PHPStan, **static conformance analysed in place**
(unknown collaborators and interface mismatches were the two measured ways a clean-parsing body
still failed to load). Bodies rejected after installation are restored byte for byte; a failed restoration is explicitly
reported and cannot emit a static diagnostic receipt.
A native `TOKEN_PARSE` failure on the normalized staged proposal carries phase `syntax` of
`milpa.authoring-diagnostic/v1`. Its submitted/judged/preserved SHA-256 digests distinguish the
proposal from the destination: `candidate_installed:false`, `destination_preserved:true` and
`stable_subject:true` describe preservation, with no rollback claim. The result retains the
parser, exact message and line. Its fingerprint excludes the line, including PHP's embedded
opening-delimiter location in a delimiter mismatch; other numbers in a message stay significant.
Parsing does not execute the proposal. Bodies without a ParseError still pass the existing
`php -l` compilation gate; process failures and other compiler errors do not receive syntax receipts.
A completed PHPStan rule rejection can carry `milpa.authoring-diagnostic/v1` with phase
`static-analysis`. It binds the relative subject, submitted/normalized/restored body hashes,
subject stability and completed rollback to the complete JSON report's findings. It accepts only
exit 1, consistent positive counts, one matching file, identified rule findings and no global errors.
Incomplete reports, foreign files, internal errors, timeouts and changed subjects earn no receipt.
The default analyzer separates JSON stdout from stderr notes; older injected raw analyzers still
reject and restore, but cannot supply this structured witness.
The static result retains messages, identifiers and lines. Its fingerprint uses the sorted unique
message/identifier pairs, ignoring lines and duplicate occurrences; local app-root prefixes are
removed from messages. Thus a comment that only shifts line numbers does not create new information.
The body hash attributes the judgment; it is not the static novelty key. This is equality of observed
findings, not semantic equivalence of programs. The installed analyzer remains a trusted producer.
When the class's own PHPUnit test rejects a complete body, the result also carries
`diagnostic` with schema `milpa.authoring-diagnostic/v1` and phase `behavior`: the relative subject and test
selector, submitted/judged/restored SHA-256 digests, subject stability, rollback status,
and the existing judge's exit code and counts. Namespace resolution can make the submitted
and judged digests differ. Inline calls and `mode=finish` use this same gate. Missing counts
remain `null`; a timeout or an unexecuted suite is not an executed diagnostic. This receipt
never grants permission, publishes a rejected body, or claims positive verification.
`implement` accepts at most **8192 bytes (8 KiB)** of decoded `content` per call.
Larger files use `mode=start`, then `mode=append` with sections of at most 8192 bytes,
and `mode=finish` without content. Sections stay in a staging sibling until `finish`
passes the same syntax, linkage and behavioral checks as a complete-file call.
For current-file `edit`, the same 8192-byte ceiling counts all `find` and `replace`
strings together. The existing file may be larger: its patched result passes the
same syntax, linkage and behavioral gate without re-entering the inline-input path.
This does not consume or alter an existing multipart staging file. Malformed pairs,
missing or ambiguous matches and oversized patch input refuse without changing the
current file. The inline, start and append limits remain unchanged.
To repair an assembled staging file, call `implement` with `mode=amend`, the same
`plugin` and `class`, its current `expected_sha256`, and an `edits` list of exact
`{find, replace}` pairs, anchored `{before, after, replace}` replacements, or
`{start_line, end_line, replace}` ranges. Each find or anchor must occur exactly
once, in order. Line ranges are 1-based and inclusive in the content produced by
preceding edits; replacement bytes are verbatim. All transmitted edit values
together are limited to 8192 bytes; `content` is forbidden in this mode. Start,
append and amend return the staging path and SHA-256. A stale hash,
missing or ambiguous match, or linked staging path refuses without changing it.
Amend replaces only the unverified staging sibling, never the live PHP class.
Through a governed trial, promote that staging change before calling `finish`;
only the usual finish judges and final promotion can deliver working code. A green
amendment therefore says nothing about PHP validity or behavior. Edits and expected
hash are refused in other implement modes. Serialize staging writers: the amendment
lock and inode recheck coordinate amendments, not arbitrary external writes or other
modes. Recorded `edit.source` retains its separate complete-inline-proposal contract.
An anchored amendment uses `{before, after, replace}`. Both anchors must each occur
exactly once and in that order; they remain in staging while only the bytes between
them are replaced. This keeps a large current block out of the tool call while still
binding the mutation to its staging hash, two unambiguous boundaries and the same
8192-byte transmitted-input ceiling. A line-range amendment avoids quoting either
the old block or its boundaries while the staging hash still binds the complete
input. Exact, anchored and line-range edits may be ordered together.
To discard a damaged assembly without retransmitting a large working class, call
`implement` with `mode=reset`, the same `plugin` and `class`, and no content. It
atomically replaces the staging sibling with an exact byte copy of the current live
PHP while leaving that live file untouched. Reset returns the new staging SHA-256 and
makes no verification claim. Through a governed trial, promote the reset before using
bounded `mode=amend` edits, then use `mode=finish` for the normal judges and publication.
`implement` takes the complete file; `edit` takes find→replace pairs that must match **exactly
once** — measured on real sessions: re-generating a whole file is where a model's priors sneak back
in, and a pair that matches nothing returns the CURRENT file verbatim, so the next pair is built
against ground truth instead of memory.
`EditPairs::apply()` exposes that same exact byte transformation without filesystem writes
or judgment, so a host runtime can compose repairs of retained proposals with the existing
`implement` gate. The standalone editor refuses a `source` argument: a compatible runtime
must first resolve and authorize the recorded proposal. It never silently treats a source
reference as permission to edit the current host file.
`make service` creates a plain class by default, suitable as a presentation helper or as the
starting point for a renderer. Its optional boolean `--interface` generates a new local
`Interface` companion. To implement an existing SDK contract such as
`ComponentRendererInterface`, omit that flag and add the contract when implementing the class.
The `interface` tool input takes a boolean, not an interface name.
And landing conformant is not behaving: when the class has its own test
(`tests/Plugins//Test.php`), the gate **runs it** — the behavioural judge. A judge
is never asked to judge itself, so a TDD red is landable: `coa make test` scaffolds the judge
*failing on purpose* (a vacuous judge must not green-light an empty class), `implement` lands the
subject only when its judge passes. Measured with a real model in the loop: the judge converts
«shipped broken» into «correct or nothing».
`make` takes `what` from **six** kinds — `plugin`, `controller`, `entity`, `crud`, `service`,
`tool` — plus the target plugin and the class name. With `what=plugin` the target *is* the artifact,
so both names are the same value. Everything else is optional and per-kind: `--fields`, `--route`,
`--methods`, `--table`, `--provides`, `--requires`, `--interface`, `--needs`, `--tool-name`,
`--description`, `--flavor`.
The result is a value, not a log line:
Four actions, and each says something different: `would-create` (a `dry_run` plan, nothing touched),
`created`, `merged` (grafted into an existing file at its marker — not an overwrite), and
`rolled-back` (written, then undone because the verify failed). `guidance` is the generator's own
next step — *"register it in config/plugins.php"*, *"no `// {coa:routes}` marker, add the 5 REST
routes by hand"* — and it is `null` when the write was rolled back, because pointing someone at
files that no longer exist is worse than saying nothing.
`make` declares `mutating: true` and does **not** require a signature: its blast radius is already
bounded by `WriteGuard` (never clobbers without `--force`) and by the rollback. `--force` overwrites
the artifact; it deliberately does *not* reach `MarkerInserter`, so forcing a regeneration can never
duplicate a service registration.
### `test` — run the host's suite
The verdict is PHPUnit's **exit code**, not its text — the same thing a CI reads about the same run.
`ran` separates "the suite failed" from "the suite could not run" (no phpunit installed, a `path`
that escapes the project root): two different pieces of news, and confusing them means fixing the
wrong thing. Counts that cannot be read come back `null`, never `0` — zero tests and could-not-count
are different answers.
Unlike the other two, `test` declares `surfaces: ['cli', 'tui', 'mcp']`. A web request that fires the
app's own test suite is a surface nobody asked for: redundant in development, and a way to knock over
a deployed process from outside. It is also the one place in this package that spawns a subprocess —
a suite needs its own: inherited autoload state would make the result meaningless, and a fatal in one
test would take the caller down with it.
## Composer-safe root resolution: `RootResolver`
Every `coa:*` devtools command needs one thing before it can do anything else: the Milpa **host
application's** filesystem root — the directory holding its `composer.json`, `plugins/`,
`scripts/`. Computing that as `dirname(__DIR__, N)` from a command's own file only works while the
command lives at a fixed depth relative to the host; the moment this package is Composer-vendored
(`vendor/milpa/devtools/...`, any install depth, a global install), that walk lands under `vendor/`
instead — silently, since `plugins/` or `scripts/` just aren't found under the wrong root (or worse,
a same-named directory is found there instead).
`RootResolver::resolve()` tries three strategies, in order, and throws
`RootNotFoundException` — never a plausible-looking wrong path — if none of them lands:
1. **An explicit root passed to the constructor.** Host wiring always wins — e.g. a container
binding the app root once from a known-good source, or a test fixture.
2. **`Composer\InstalledVersions::getRootPackage()['install_path']`.** The Composer-canonical answer
to "where is the application that required me" — correct regardless of install depth, path-repo
dev install vs. a real registry install, valid the instant Composer's generated autoloader is on
the include path, which it always is for any Composer-managed PHP process (`composer-runtime-api`
is a real dependency of this package, not an optional one — see [Requirements](#requirements)).
3. **Walk up from `getcwd()`** looking for the nearest ancestor `composer.json` — a last-resort
fallback for the pathological case where Composer's own runtime API is unavailable.
## The loop: generate → verify → inspect
| Layer | Namespace | What it does |
|-------|-----------|---------------|
| **Generate** | `Make` | Six `GeneratorInterface` implementations — `PluginGenerator`, `ControllerGenerator`, `EntityGenerator`, `CrudGenerator`, `ServiceGenerator`, `ToolGenerator` — render a `.php.stub` template into a `PlannedFile` (path + contents, no I/O yet). The four composite ones also *graft* their wiring into an existing plugin at its `// {coa:*}` markers (`MarkerInserter`, idempotent: re-running does not duplicate the insertion), planning that file with `PlannedFile::$merge` so `WriteGuard` grafts instead of refusing. `FieldParser` reads the `--fields` DSL; `WriteGuard` refuses to clobber an existing file unless `--force`; `VerifyRunner` closes the loop by running the matching verifier against the freshly written class, in-process. |
| **Verify** | `Verify` | `ControllerVerifier` / `EntityVerifier` reflect an *already-autoloaded* class and check it against the framework's real runtime conventions — extends `BaseController`, calls `parent::__construct()`, correct `#[ORM\Column]` nullability, no debug output, no duplicate routes, and more. A `VerificationResult` never throws for a violation; it collects `errors` (fail the run) and `warnings` (advisory only). |
| **Inspect** | `Validators` | `PluginManifestValidator` checks one `milpa.json` against the plugin manifest shape. `CapabilityGraphValidator` checks an entire plugin ecosystem: every hard `requires` must be satisfied by some plugin's `provides`, and the dependency graph must be acyclic (unmet `suggests` degrade, they never fail). `ProviderImplementsValidator` autoloads every declared provider and asserts it really implements what it claims. `BoundaryValidator` runs host-supplied `BoundaryRule`s (which directories may not reference which namespaces) — the engine is generic, the rules are yours. |
A validator example, real output — a manifest with a non-semver `version` fails with a precise,
addressable message instead of a generic "invalid manifest":
**The generated code targets your host app's conventions, not this package's.** `ControllerGenerator`
and `ControllerVerifier` both know the exact FQCNs `Milpa\app\Providers\BaseController` /
`HttpResponse` and the `#[Route]` attribute — that convention belongs to a real Milpa host
application, not to `milpa/devtools` itself, which ships **zero** `use` imports of those classes
(the `.stub` templates reference them as generated-code *text*, not real dependencies). `coa:make
controller` scaffolds a class that targets those FQCNs; `ControllerVerifier` closes the loop by
checking generated output against that same convention.
## What's inside
| Namespace | What it provides |
|-----------|-------------------|
| `Milpa\DevTools\Make` | `GeneratorInterface`, `GenerationContext`/`GenerationResult`/`PlannedFile`, the six generators — `PluginGenerator`, `ControllerGenerator`, `EntityGenerator`, `CrudGenerator`, `ServiceGenerator`, `ToolGenerator` (each targets `Flavor::Runtime` or `Flavor::Legacy`, picked by `ConventionDetector`; `plugin` is runtime-only), `MarkerInserter`/`Markers` (the `// {coa:services}`, `// {coa:routes}`, `// {coa:tools}` anchors composites graft into), `FieldParser`/`FieldSpec` (the `--fields` DSL: `name:type[:mods]`, `?` prefix for nullable, `enum:`; `:belongsTo:` creates a Doctrine relation only for a legacy entity, while a runtime resource accepts it solely as a named scalar-id degradation and runtime entity/CRUD callers must pass that scalar directly), `StubRenderer`, `WriteGuard`, `VerifyRunner` |
| `Milpa\DevTools\Verify` | `VerifierInterface`, `VerificationResult`, `ControllerVerifier`, `EntityVerifier` |
| `Milpa\DevTools\Validators` | `PluginManifestValidator`, `CapabilityGraphValidator`, `ProviderImplementsValidator`, `BoundaryValidator` (+ `BoundaryRule`/`BoundaryRuleResult`/`BoundaryReport`) and each validator's typed result |
| `Milpa\DevTools\Support` | `RootResolver`/`RootNotFoundException`, `ClassNameExtractor` (file path → FQCN, no autoloading — lets a CLI accept either), `ProcessRunner` (the one subprocess this package spawns: output *and* exit code, with a deadline) |
Every public symbol carries a DocBlock; the full field DSL, every generator/verifier check, and
every validator's exact error messages are documented at the source and in the
[API reference](https://getmilpa.github.io/devtools/).
## Requirements
- PHP **≥ 8.3**
- [`milpa/data`](https://packagist.org/packages/milpa/data) — a genuine runtime `require`: the
runtime entity path (`Milpa\Data\EntityInterface`/`RepositoryFactory` — the scaffold picks its backend from `storage.driver`: file, sqlite, mysql or memory) is always loadable once
`milpa/devtools` itself is composer-installed. `milpa/core` still appears only in `require-dev`
(docs tooling).
- [`doctrine/orm`](https://packagist.org/packages/doctrine/orm) **^3** — **optional** (`suggest`,
not `require`): only the **legacy** entity path needs it — `EntityGenerator::generateLegacy()` and
`EntityVerifier`'s legacy branch reflect real `#[ORM\Column]`/`#[ORM\JoinColumn]` attributes, they
don't just pattern-match their names. Generating/verifying a legacy entity without it installed
fails fast with one clear message instead of a crash deep in attribute reflection. The controller
path (either flavor) and the runtime entity path never touch Doctrine.
- `composer-runtime-api` **^2.2** — the documented way to depend on `Composer\InstalledVersions`,
which `RootResolver` uses as its second resolution tier
## Documentation
**Full API reference: [getmilpa.github.io/devtools](https://getmilpa.github.io/devtools/)** — generated
straight from the source DocBlocks and dressed with the Milpa design system.
## Contributing
Contributions are welcome — see [CONTRIBUTING.md](CONTRIBUTING.md). Please report security
issues via [SECURITY.md](SECURITY.md), and note that this project follows a
[Code of Conduct](CODE_OF_CONDUCT.md).
## License
[Apache-2.0](LICENSE) © Rodrigo Vicente - TeamX Agency.
---
Milpa is designed, built, and maintained by **[Rodrigo Vicente - TeamX Agency](https://teamx.agency/?utm_source=github&utm_medium=readme&utm_campaign=milpa&utm_content=devtools)**.
## Contract discovery
`contract:search --q=ResearchDesk` finds type names in the app's runtime `autoload.psr-4`
directories, including multiple directories per prefix. Components can live outside `src/Plugins`.
Conventional plugin folders remain searchable for compatibility. App candidates must resolve
inside the project and outside `vendor`; development-only autoload roots do not enlarge the
search. Installed vendor code retains its package provenance and optional `--package=vendor/name`
filter. Search tokenizes declarations without executing candidate PHP files. Discovery of a name
does not establish that its class can be loaded or that the caller may execute it.
Each match includes `path`, the project-relative canonical file that was scanned.
Pass that value unchanged to `source_page` in the model loop (`source:page` on
the CLI) to read its installed documentation. `discover` preserves this path on
contract rows. Paths obey the
reader's project boundary, including symlinks; an external declaration is excluded.
Duplicate FQCNs retain the first scanned declaration in sorted file order, so the
path is evidence of that declaration, not a claim about Composer's runtime choice.
Search still returns at most 25 matches and declares truncation.
## Complete source pages
`source:page` is additive: `source:read` keeps its line-based response and defaults. A page preserves UTF-8 source bytes, including line endings, and returns `ok`, `path`, `sha256`, `offset`, `next_offset`, `total_bytes`, `content`, and `next_cursor`. Offsets count **bytes**; a result budget counts **characters of the whole JSON result**, including metadata and escapes.
MCP exposes `source_page` with the same inputs. Pass `next_cursor` unchanged; `null` means complete. Inside the model loop, the transport supplies the budget. Outside it, specify `max_chars` (integer, at least 256). An explicit value can only tighten a transport budget. Very small budgets may fail because metadata and one character cannot fit. The bound covers the handler's JSON result, not outer CLI/MCP envelopes.
The cursor identifies canonical relative path, whole-file SHA-256 and a UTF-8 byte boundary. Changed files and cross-file cursors fail; restart without a cursor after a content change. Paths resolve through the same realpath boundary as `source:read`, including symlinks. A cursor carries no permission and is not an authenticated token. Each page rereads the whole file: this API does not provide streaming memory bounds or a snapshot across concurrent file writes. Native progress policy can still stop long diagnostic sequences.
All versions of devtools with dependencies
PHP Build Version
Package Version
Requires
php Version
>=8.3
composer-runtime-api Version ^2.2
milpa/command Version >=0.24 <1.0
milpa/data Version >=0.2 <1.0
milpa/plugin Version >=0.19 <1.0
milpa/core Version >=0.6.2 <1.0
milpa/tool-runtime Version >=0.18 <1.0
composer-runtime-api Version ^2.2
milpa/command Version >=0.24 <1.0
milpa/data Version >=0.2 <1.0
milpa/plugin Version >=0.19 <1.0
milpa/core Version >=0.6.2 <1.0
milpa/tool-runtime Version >=0.18 <1.0
The package milpa/devtools contains the following files
Loading the files please wait ...