CLI FEATURE
Semitexa Dev
Semitexa Dev gives people and coding agents one project-aware loop for orientation, structural inspection, runtime evidence, durable work memory, and precise verification.
Feature Guide
A quick orientation block that answers the essential questions: what this feature does, how it works, why it matters, and the key concepts behind it.
What this does
Semitexa Dev is the project-aware operating layer for orientation, planning, structural inspection, runtime debugging, durable work memory, and verification.
How it works
The ai:* command family connects repository state, recipes, prior art, Project Graph, the runtime Observatory, epic/work/trace memory, and diff-aware checks through stable JSON contracts.
Why it matters
People and agents make safer changes when the project can explain its current shape, show what actually ran, preserve decisions across sessions, and verify the edited surface precisely.
Key concepts
- ai:orient
- Combines Git state, active work, recent traces, last verification, and the next useful command.
- ai:observe
- Reads live and recorded process lifecycles, full waterfalls, executed source, and sandbox replay results.
- ai:verify
- Selects the relevant checks from the actual changed files and reports one structured verdict.
Project-Aware Workflow
Start with facts, act on a narrow plan, and leave durable evidence
Semitexa Dev connects repository state, structural discovery, live runtime traces, persistent work items, and diff-aware verification in one inspectable loop.
Context before code. orient, task, ask, context, and plan expose the current project shape and the safest implementation path.
Runtime evidence. The Observatory records process lifecycles, spans, queries, payload snapshots, source locations, and sandbox replays.
Recoverable work. epic, work, trace, and verify preserve decisions and prove the resulting change across sessions.
| Command | Purpose | Why it matters |
|---|---|---|
bin/semitexa ai:orient --json |
Read Git state, active work, recent traces, and the last verification in one response. | Starts a cold session from shared facts instead of repository archaeology. |
bin/semitexa ai:ask route --path=/invoices --json |
Resolve one route from payload through handler, resource, template, and access posture. | Answers a structural question without broad file searches. |
bin/semitexa ai:observe show --id=p-123 --source |
Inspect one real process with timing, spans, queries, payload, and executed source. | Turns runtime debugging into evidence instead of source-only guessing. |
bin/semitexa ai:work resume --id=tk-invoice-export --json |
Restore the task, its recent trace, and the exact next step. | Lets work survive context compaction and session boundaries. |
bin/semitexa ai:verify --files=packages/semitexa-billing/src --json |
Select syntax, lint, structure, static-analysis, and test checks from the diff. | Verifies the changed surface without running unrelated checks blindly. |
Start a cold session
bin/semitexa ai:orient --json
bin/semitexa ai:task 'add tenant-aware invoice export' --json
Inspect before editing
bin/semitexa ai:ask route --path=/invoices --method=GET --json
bin/semitexa ai:review-graph:impact 'App\Billing\InvoiceExporter' --json
Observe and verify
bin/semitexa ai:observe tail --kind=http --follow --duration=15
bin/semitexa ai:verify --files=packages/semitexa-billing/src --json
Verified against Semitexa Ultimate 2026.09.19.1020
Semitexa Dev
Semitexa Dev is the project-aware operating layer for people and coding agents working on a Semitexa application.
It answers six practical questions:
- What state is this project in?
- What kind of task is this?
- Where does the relevant behavior live?
- What is running right now?
- What should be verified after the change?
- What must survive when the current context ends?
The agent remains the reasoning system. Semitexa supplies verified project facts, execution tools, durable work state, and targeted checks. Keeping those roles separate matters: a model can propose a change, while the project can prove what routes exist, what a class affects, which process failed, and whether the edited result is valid.
The operating loop
For a normal code change, the Semitexa Dev loop is:
orient → classify → inspect → plan → edit → verify → record
| Stage | Primary command | Result |
|---|---|---|
| Orient | ai:orient |
Git state, active work, recent traces, last verification, and the next useful action |
| Classify | ai:task |
A recipe, confidence score, risk hint, and suggested generator chain |
| Inspect | ai:ask, ai:context, ai:review-graph:* |
Runtime and structural facts scoped to the task |
| Plan | ai:plan |
Risk assessment for the recipe and exact file set |
| Edit | make:* or a focused manual edit |
A change that follows discovered project conventions |
| Verify | ai:verify |
The smallest relevant syntax, lint, structure, static-analysis, and test set |
| Record | ai:trace, ai:work, ai:epic |
Durable decisions and next steps for a later session |
This is a decision loop rather than a mandatory ceremony. A focused one-file fix can stay inline. Work that spans modules, contains branching decisions, or may outlive the current context belongs in an epic with small work items.
Start a session with facts
Use ai:orient before assembling project state from unrelated Git, task, and log commands:
bin/semitexa ai:orient --jsonJSON envelope with artifact `semitexa-dev.ai-orient/v1`, current Git and work state, and contextual `next_command` suggestions.The response combines repository state with active Semitexa work artifacts. Its next_command entries explain useful follow-ups based on the current state.
For a new executable request, classify the intent:
bin/semitexa ai:task "add tenant-aware invoice export" --json
The classifier returns a recipe and a confidence level. High confidence gives a reliable starting path. Low confidence is a signal to inspect the suggested alternatives or clarify the goal before running a generator.
Choose the narrowest inspection tool
Use ai:ask for project facts that Semitexa can answer directly:
bin/semitexa ai:ask project --json
bin/semitexa ai:ask module --name=Billing --json
bin/semitexa ai:ask route --path=/invoices --method=GET --json
bin/semitexa ai:ask event --name=InvoiceIssued --json
bin/semitexa ai:ask mechanisms --area=ssr --json
bin/semitexa ai:ask logs --grep=invoice --level=ERROR --lines=200 --json
These commands describe discovered routes, handlers, resources, templates, services, events, logs, and framework mechanisms. They are preferable to broad text searches when the question is about framework structure.
Use ai:context after ai:task chooses a recipe:
bin/semitexa ai:context add_html_page --module=Billing --json
It returns nearby prior art and repository conventions, so a new page follows the module that already works instead of inventing a parallel pattern.
Use Project Graph when the question is about relationships or blast radius:
bin/semitexa ai:review-graph:query \
--usages='Semitexa\Billing\Application\Service\InvoiceExporter' \
--json
bin/semitexa ai:review-graph:impact \
'Semitexa\Billing\Application\Service\InvoiceExporter' \
--json
Project Graph follows structural edges such as uses, implements, handles, and serves_route. Full-text search remains useful for literal strings; it should not substitute for a dependency query.
Plan against the real file set
Before a multi-file or uncertain edit, give ai:plan the recipe and the files you expect to touch:
bin/semitexa ai:plan add_html_page \
--module=Billing \
--files=packages/semitexa-billing/src/Application/Payload/Request/InvoicePayload.php,packages/semitexa-billing/src/Application/Handler/PayloadHandler/InvoiceHandler.php \
--json
The result explains why the change is low, medium, or high risk. If the reported risk is higher than expected, reduce the file set, split the work, or inspect the newly exposed dependency before editing.
Debug the runtime through the Observatory
ai:observe is the first stop for runtime behavior. It reports what actually ran instead of asking you to infer behavior from source alone.
bin/semitexa ai:observe ps
bin/semitexa ai:observe tail --kind=http --follow --duration=15
bin/semitexa ai:observe show --id=p-123 --source
The three views serve different questions:
| View | Use it for |
|---|---|
ps |
Live processes, recent completions, workers, and stale activity |
tail |
A bounded stream of new HTTP, queue, scheduler, or SSE lifecycles |
show |
One process with spans, queries, payload snapshot, timing, and optional source |
A request made with ?__trace=1 records a full waterfall. The same trace is available to humans at /__trace and to agents through ai:observe show.
The Observatory also shows the code's structure: its graph mode browses the project graph, and links a class to the recent traces that ran it. See Browsing the Graph.
When a recorded request needs controlled reproduction, replay it in the development sandbox:
bin/semitexa ai:observe replay --id=p-123 --mutate status='"cancelled"'
Replay rolls writes back and records the differences from the original process. This makes it useful for testing a hypothesis without leaving mutated application state behind.
For quick handler feedback without HTTP, auth, or middleware, use ai:invoke:
bin/semitexa ai:invoke \
--route=/invoices \
--payload='{"page":1}' \
--json
The response states which pipeline layers were omitted. Treat it as a handler probe, then use an HTTP or browser check when the complete request pipeline matters.
A page's live timeline
bin/semitexa ai:observe timeline # the pages seen lately
bin/semitexa ai:observe timeline --id=sse_… # one page, in order
In development, every page with a live stream (its KISS session id) keeps a timeline:
event: a component's UI event, with its effects and how long it took;frame: each frame its stream wrote, with id and size;subscribe/unsubscribe: a feed attached or detached;rerun: a feed that re-ran, why (a write or a view change), and what it sent (a keyed patch, a whole page, or nothing);replay/reset: a reconnect resumed, or could not;deferred: a deferred component rendered, and how long it took.
The same timeline is at /__observatory/timeline for a human, linked from the Observatory panel.
It is written one short line at a time under var/observatory/timeline/, stops at 1 MB a page,
and is removed after a day. Outside development nothing is recorded; a record is one null check.
Keep review evidence private
A screenshot, a recording, a request trace or a graph export made to prove a change shows whatever was on screen or in the database. Keep it in the evidence store, not in a pull request:
bin/semitexa ai:evidence add var/tmp/cart.png --kind=screenshot --data=synthetic --note="cart after the fix"
bin/semitexa ai:evidence list
bin/semitexa ai:evidence prune --dry-run --tmp
Each item lives in var/evidence/<id>/ with a passport — what it is, whether it was made from synthetic or real data, who recorded it, when it expires (14 days by default). var/evidence/ is in the project's .gitignore, and lint:var-artifacts fails ai:verify when anything else under var/ is about to be committed.
Publishing is the operator's step, in their own terminal: ai:evidence publish <id> --to="PR acme/shop#7" checks the item — a picture of real data never goes, text is scanned for tokens and workstation paths — then asks for the id to be typed. It refuses without a terminal, so an agent cannot approve its own upload by accident. The same check guards review-prep's PR description and pr-reply.sh.
The Observatory's evidence mode (V) lists the store: search, filters by kind, data, visibility and day, sortable columns, pages, and a passport with a preview for each item. It is dev-only, and files are served sandboxed.
Keep long work recoverable
Semitexa stores long-lived work in three layers:
| Artifact | Responsibility |
|---|---|
ai:epic |
The outcome shared by several work items |
ai:work |
One executable leaf task with recipe, risk, context, and next step |
ai:trace |
Decisions, observations, failed hypotheses, and verification events |
Create an epic when work spans several modules or will not fit safely in one sitting:
bin/semitexa ai:epic start \
--id=ep-invoice-export \
--title="Ship invoice export" \
--goal="Let tenant administrators export auditable invoice data." \
--json
bin/semitexa ai:work start \
--id=tk-invoice-export-http \
--epic=ep-invoice-export \
--title="Add the export endpoint" \
--recipe=add_html_page \
--risk=medium \
--context-ref=packages/semitexa-billing \
--next-step="Inspect the invoice route and generate the smallest export page." \
--json
Write notes for the next working session: record the decision that would otherwise be debated again, the hypothesis already disproved, and the exact next command that restarts the work.
Verify the change, not the whole universe
Run ai:verify after a coherent edit:
bin/semitexa ai:verify \
--files=packages/semitexa-billing/src/Application/Handler/PayloadHandler/InvoiceHandler.php,packages/semitexa-billing/src/Application/Resource/Response/InvoiceResource.php \
--json
Semitexa classifies the changed files and selects the relevant checks. Depending on the diff, that can include PHP syntax, handler and DI lint, template validation, module structure, static-analysis rules, generated reference drift, or focused tests.
Verification runs in a fresh CLI process and sees saved files immediately. Restart the server only before exercising the long-running HTTP worker through a browser, curl, or E2E test.
What a person sees
A passing test does not see the page. When a template or a stylesheet changes, bin/semitexa ai:verify also opens the pages it shows on:
- Where: in the e2e-runner on the host, against the app that is already running. Verify never starts or restarts the app.
- How: in light and in dark. A colour that fails only in dark is a real bug.
- What it checks: axe checks contrast, labels, names, the title and the language. The page check adds what axe does not see:
- a page that uses
--ui-*tokens with no skin linked; - a form field with no edge;
- text against the window;
- console errors;
- an HTTP status of 400 or more.
- a page that uses
Which pages. Only public GET routes that need no parameter, produce HTML and do not act when opened (logout, a sign-in start, submit…):
- a file in a module opens that module's pages;
- a package's file opens that package's pages;
- a file with no pages of its own, such as the theme or a layout, opens the project's pages.
For a template, the module is what chooses the page, not proof that the page renders that template. For a stylesheet, a page counts only when it loads the stylesheet in both modes. Make sure a page that shows your template is in the list.
The shortest paths come first, and at most 8 pages are opened. Pages past the cap are not checked. bin/semitexa ai:verify --files=… --list-pages prints the list. Open the rest yourself when the change reaches further.
When it is not a pass. A page counts as checked only when the change could show on it. A finding in either mode fails the page, even when the other mode could not be checked. Without a finding, these are reported as incomplete, never as a pass:
- a page that could not be reached;
- a page seen in one mode only;
- a page that redirected elsewhere, such as to a sign-in page;
- a page that does not load the stylesheet that changed.
What the browser saw stays under var/run/verify-e2e/<run>/pages/, a screenshot per page and mode included.
The page check needs a matching bin/semitexa. The launcher, not the app, opens the pages. bin/semitexa update replaces the launcher together with semitexa/dev. A launcher you edited is left alone: bin/semitexa update --write-scaffold-candidates writes the new one beside it as bin/semitexa.new to merge. Until you merge it, every page is reported as incomplete and the reason names what is missing.
Report framework defects with evidence
When a project must work around a Semitexa defect, capture the defect as part of the fix:
bin/semitexa ai:report \
--title="Route inspection omits response template" \
--summary="The route is valid, but ai:ask route does not report its discovered Twig template." \
--evidence="bin/semitexa ai:ask route --path=/invoices --json → template is absent" \
--workaround="Inspected the resource attribute directly." \
--package=semitexa-dev \
--json
ai:report searches for duplicates and can add another sighting instead of opening a parallel issue. Review the rendered report before publication, and keep consumer configuration, credentials, and private application code out of public evidence.
Machine-readable by design
The ai:* commands expose stable JSON envelopes for automation. A typical envelope contains:
- an artifact and schema version;
- the requested result;
- confidence, omissions, or risk where relevant;
next_commandsuggestions with reasons;- verification or trace outcomes when the command produces them.
This contract lets a human read the same facts an agent consumes. It also gives integrations a stable surface without scraping colored terminal output.
The local assistant is a separate entrypoint
bin/semitexa ai starts the optional local assistant backed by registered #[AsAiSkill] commands:
bin/semitexa ai --dry-run
bin/semitexa ai --yes
bin/semitexa ai:skills --json
The assistant translates natural-language intent into declared skills. The deterministic ai:* commands remain available whether or not a local language model is configured.
Command reference
Use this page to choose the right workflow. Use the generated AI commands reference for every argument and option supported by the installed release:
bin/semitexa help ai:orient
bin/semitexa help ai:observe
bin/semitexa help ai:verify
bin/semitexa ai:ask capabilities --json
The capability manifest is the authoritative inventory for the running project because it reflects the packages and commands actually installed there.
© Harold Abelson: "Programs must be written for people to read, and only incidentally for machines to execute."
1<?php23declare(strict_types=1);45namespace Semitexa\Dev\Application\Console\Command;67use Semitexa\Dev\Application\Service\Ai\Orient\OrientBrief;8use Semitexa\Dev\Application\Service\Ai\Presence\StackEvents;9use Semitexa\Dev\Application\Service\Ai\Presence\WorkspaceActivity;10use Semitexa\Dev\Application\Service\Ai\Presence\AgentSession;11use Semitexa\Dev\Application\Service\Ai\Presence\AgentDocsFreshness;12use Semitexa\Dev\Application\Service\Ai\Presence\AgentRegistry;13use Semitexa\Core\Support\ProjectRoot;14use Semitexa\Core\Attribute\AsCommand;15use Semitexa\Core\Attribute\InjectAsReadonly;16use Semitexa\Core\Console\BaseCommand;17use Semitexa\Dev\Application\Service\Quality\QualityAdvisor;18use Semitexa\Dev\Application\Service\Ai\Charter\CharterStore;19use Semitexa\Dev\Application\Service\Ai\Charter\OwnerQuestions;20use Semitexa\Dev\Application\Service\Ai\Trace\TraceEventKind;21use Semitexa\Dev\Application\Service\Ai\Trace\TraceHeader;22use Semitexa\Dev\Application\Service\Ai\Trace\TraceStore;23use Semitexa\Dev\Application\Service\Ai\Work\Epic;24use Semitexa\Dev\Application\Service\Ai\Work\EpicStore;25use Semitexa\Dev\Application\Service\Ai\Work\Task;26use Semitexa\Dev\Application\Service\Ai\Work\TaskStatus;27use Semitexa\Dev\Application\Service\Ai\Work\TaskStore;28use Symfony\Component\Console\Input\InputInterface;29use Symfony\Component\Console\Input\InputOption;30use Symfony\Component\Console\Output\OutputInterface;31use Symfony\Component\Console\Style\SymfonyStyle;3233/**34 * Single-call session dashboard for an agent that just opened the repo.35 *36 * Fuses: git (branch + last commit + dirty flag) + active epic + in-progress37 * tasks + recent traces + last verify result + a next-step suggestion.38 *39 * Designed as the **first command** a cold-start agent runs. One tool call40 * should replace 5–6 probes (ai:ask project, ai:epic list, ai:work list,41 * ai:trace list, git status, git log).42 *43 * Cheap by construction — reads file-backed stores and runs two short shell44 * commands for git. Does NOT execute linters, verification, or graph rebuild.45 */46#[AsCommand(47 name: 'ai:orient',48 description: 'Session dashboard: git + active epic + in-progress tasks + recent traces + next step. Run this first on a cold start. --json answers a brief; --json --full gives every field.',49)]50final class AiOrientCommand extends BaseCommand51{52 #[InjectAsReadonly]53 protected EpicStore $epicStore;5455 #[InjectAsReadonly]56 protected TaskStore $taskStore;5758 #[InjectAsReadonly]59 protected TraceStore $traceStore;6061 #[InjectAsReadonly]62 protected CharterStore $charterStore;6364 public function __construct()65 {66 parent::__construct('ai:orient');67 }6869 protected function configure(): void70 {71 $this72 ->addOption('json', null, InputOption::VALUE_NONE, 'Emit JSON: a brief by default (also for non-interactive callers); add --full for every field')73 ->addOption('human', null, InputOption::VALUE_NONE, 'Force human-readable output even in non-interactive mode')74 ->addOption('traces', null, InputOption::VALUE_REQUIRED, 'How many recent traces to include', '5')75 ->addOption('full', null, InputOption::VALUE_NONE, 'Every field under --json: whole next steps, context refs, every receipt and trace (the default is a brief)');76 }7778 protected function execute(InputInterface $input, OutputInterface $output): int79 {80 $traceLimit = max(1, min(50, (int) $input->getOption('traces')));8182 $git = $this->collectGit();83 $epics = $this->collectEpics();84 $inProgress = $this->collectTasksByStatus(TaskStatus::IN_PROGRESS);85 $blocked = $this->collectTasksByStatus(TaskStatus::BLOCKED);86 $activeEpicId = OrientBrief::activeEpicId($inProgress, $blocked, $epics);87 $recentTraces = $this->collectRecentTraces($traceLimit);88 $lastVerify = $this->findLastVerify($recentTraces);89 try {90 $qualityNext = (new QualityAdvisor(ProjectRoot::get()))->targets(3);91 $qualityError = null;92 } catch (\RuntimeException $e) {93 // A broken ledger is said, not shown as "nothing to improve".94 [$qualityNext, $qualityError] = [[], $e->getMessage()];95 }96 $hints = $this->suggestNext($git, $activeEpicId, $inProgress, $blocked, $epics);97 $workingNow = $this->workingNow();98 $hints['summary'] = OrientBrief::heldElsewhere($inProgress[0]->id ?? null, $inProgress !== [] ? $this->holderOf($inProgress[0]->id, $workingNow) : null, $workingNow['you']['id'] ?? null) . $hints['summary'];99 $ownerQuestions = OwnerQuestions::of($this->charterStore);100 $hints = OwnerQuestions::lead($hints, $ownerQuestions);101102 if ($workingNow['you'] === null || !($workingNow['you']['joined'] ?? true)) {103 // Joining is how the others see you; it is first because an agent104 // that skips it is the one the others have to guess about. One that105 // bin/semitexa recognised is listed already, but with no intent.106 array_unshift($hints['commands'], [107 'cmd' => 'ai:agent',108 'args' => ['join', '--name=<claude|codex|…>', '--intent="<what you are about to do>"', '--repo=<repo you will edit>', '--json'],109 'why' => 'other agents see who you are and what you touch; then export SEMITEXA_AGENT_SESSION',110 ]);111 }112113 $envelope = [114 'artifact' => 'semitexa.ai-orient/v1',115 'working_now' => $workingNow,116 'generated_at' => gmdate('c'),117 'cwd' => getcwd() ?: '',118 'git' => $git,119 'unshipped_commits' => \Semitexa\Dev\Application\Service\Ai\State\UnshippedCommits::in($this->getProjectRoot()), // never pushed: nobody ships them otherwise120 'backlog' => [121 'total_epics' => count($epics),122 'active_epic_id' => $activeEpicId,123 'active_epic' => $activeEpicId !== null ? $this->epicBrief($epics, $activeEpicId) : null,124 // held_by: the live agent working it, or null — an in_progress125 // task nobody live holds is one somebody walked away from.126 'in_progress_tasks' => array_map(fn(Task $t) => $this->taskBrief($t) + ['held_by' => $this->holderOf($t->id, $workingNow)], $inProgress),127 'in_progress_count' => count($inProgress),128 'blocked_tasks' => array_map(fn(Task $t) => $this->taskBrief($t), $blocked),129 'blocked_count' => count($blocked),130 ],131 'recent_traces' => $recentTraces,132 'last_verify' => $lastVerify,133 // Red runs of the last day nobody checked with ai:verify:receipt:134 // what a subagent saw and its parent may never have.135 'unread_failed_verify' => array_values(array_filter(136 (new \Semitexa\Dev\Application\Service\Ai\Verify\Receipt\VerifyReceipts($this->getProjectRoot()))->unread(86400),137 static fn (array $r): bool => $r['verdict'] !== 'pass',138 )),139 // The improvement loop's entry point: what the quality ledger says to140 // make better next. Read from the recorded baseline, measured nothing.141 'quality_next' => $qualityNext,142 // What Semitexa asks the owner next (ep-project-charter), and how.143 'owner_questions' => $ownerQuestions,144 'quality_error' => $qualityError,145 'suggest_next' => $hints['summary'],146 'next_command' => $hints['commands'],147 ];148149 $forceJson = (bool) $input->getOption('json');150 $forceHuman = (bool) $input->getOption('human');151 $useHuman = $forceHuman || (!$forceJson && $input->isInteractive());152153 if ($useHuman) {154 $this->renderHuman(new SymfonyStyle($input, $output), $envelope);155 } else {156 $full = (bool) $input->getOption('full'); // the default is the brief (tk-orient-cold-start-too-big)157 $output->writeln(json_encode($full ? $envelope : OrientBrief::of($envelope, $inProgress[0]->id ?? null, $workingNow['you']['id'] ?? null, time()), JSON_UNESCAPED_SLASHES | ($full ? JSON_PRETTY_PRINT : 0)) ?: '{}', OutputInterface::OUTPUT_RAW);158 }159160 return self::SUCCESS;161 }162163 // ─── collectors ────────────────────────────────────────────────164165 /**166 * @return array{is_repo: bool, branch: ?string, head: ?string, last_commit_summary: ?string, dirty: ?bool, ahead: ?int, behind: ?int}167 */168 private function collectGit(): array169 {170 $cwd = getcwd() ?: '';171 $cdPrefix = 'cd ' . escapeshellarg($cwd) . ' && ';172173 $isRepo = trim((string) shell_exec($cdPrefix . 'git rev-parse --is-inside-work-tree 2>/dev/null')) === 'true';174175 if (!$isRepo) {176 return [177 'is_repo' => false,178 'branch' => null,179 'head' => null,180 'last_commit_summary' => null,181 'dirty' => null,182 'ahead' => null,183 'behind' => null,184 ];185 }186187 $branch = trim((string) shell_exec($cdPrefix . 'git branch --show-current 2>/dev/null')) ?: null;188 $head = trim((string) shell_exec($cdPrefix . 'git rev-parse --short HEAD 2>/dev/null')) ?: null;189 $last = trim((string) shell_exec($cdPrefix . 'git log -1 --pretty=%s 2>/dev/null')) ?: null;190 $status = (string) shell_exec($cdPrefix . 'git status --porcelain 2>/dev/null');191 $dirty = trim($status) !== '';192193 $ahead = null;194 $behind = null;195 if ($branch !== null) {196 $track = trim((string) shell_exec($cdPrefix . 'git rev-list --left-right --count @{u}...HEAD 2>/dev/null'));197 if ($track !== '' && preg_match('/^(\d+)\s+(\d+)$/', $track, $m)) {198 $behind = (int) $m[1];199 $ahead = (int) $m[2];200 }201 }202203 return [204 'is_repo' => true,205 'branch' => $branch,206 'head' => $head,207 'last_commit_summary' => $last,208 'dirty' => $dirty,209 'ahead' => $ahead,210 'behind' => $behind,211 ];212 }213214 /**215 * @return list<Epic>216 */217 private function collectEpics(): array218 {219 try {220 return $this->epicStore->list();221 } catch (\Throwable) {222 return [];223 }224 }225226 /**227 * Collect tasks of a single status, most-recently-updated first.228 *229 * IN_PROGRESS and BLOCKED are kept apart on purpose: a blocked task is NOT230 * resumable work, so conflating the two made `in_progress_count` lie and231 * made suggest_next promote a blocked task as the next action.232 *233 * @return list<Task>234 */235 private function collectTasksByStatus(TaskStatus $status): array236 {237 $out = [];238 try {239 foreach ($this->taskStore->list(null, $status) as $task) {240 $out[] = $task;241 }242 } catch (\Throwable) {243 // store not initialised yet — that's fine, return what we have244 }245 usort($out, static fn(Task $a, Task $b) => strcmp($b->updatedAt, $a->updatedAt));246 return $out;247 }248249 /**250 * @return list<array{id: string, created_at: string, topic: ?string, recipe: ?string, last_event: ?array{kind: string, at: string, summary: string}}>251 */252 private function collectRecentTraces(int $limit): array253 {254 try {255 $headers = $this->traceStore->list();256 } catch (\Throwable) {257 return [];258 }259260 usort($headers, static fn(TraceHeader $a, TraceHeader $b) => strcmp($b->createdAt, $a->createdAt));261 $headers = array_slice($headers, 0, $limit);262263 $out = [];264 foreach ($headers as $h) {265 $lastEvent = null;266 try {267 $trace = $this->traceStore->read($h->traceId);268 $events = $trace->events;269 if ($events !== []) {270 $tail = end($events);271 $lastEvent = [272 'kind' => $tail->eventKind,273 'at' => $tail->at,274 'summary' => $tail->summary,275 ];276 }277 } catch (\Throwable) {278 // skip unreadable traces279 }280 $out[] = [281 'id' => $h->traceId,282 'created_at' => $h->createdAt,283 'topic' => $h->topic,284 'recipe' => $h->recipe,285 'last_event' => $lastEvent,286 ];287 }288 return $out;289 }290291 /**292 * @param list<array{id: string, created_at: string, topic: ?string, recipe: ?string, last_event: ?array{kind: string, at: string, summary: string}}> $recentTraces293 * @return array{trace_id: string, at: string, summary: string, verdict: ?string}|null294 */295 private function findLastVerify(array $recentTraces): ?array296 {297 foreach ($recentTraces as $row) {298 $last = $row['last_event'];299 if ($last !== null && $last['kind'] === TraceEventKind::VERIFY_RESULT) {300 return [301 'trace_id' => $row['id'],302 'at' => $last['at'],303 'summary' => $last['summary'],304 'verdict' => $this->parseVerdictFromSummary($last['summary']),305 ];306 }307 }308 // scan deeper — look through trace bodies309 foreach ($recentTraces as $row) {310 try {311 $trace = $this->traceStore->read($row['id']);312 foreach (array_reverse($trace->events) as $e) {313 if ($e->eventKind === TraceEventKind::VERIFY_RESULT) {314 return [315 'trace_id' => $row['id'],316 'at' => $e->at,317 'summary' => $e->summary,318 'verdict' => $this->parseVerdictFromSummary($e->summary),319 ];320 }321 }322 } catch (\Throwable) {323 continue;324 }325 }326 return null;327 }328329 private function parseVerdictFromSummary(string $summary): ?string330 {331 $lower = strtolower($summary);332 if (str_contains($lower, 'pass')) {333 return 'pass';334 }335 if (str_contains($lower, 'fail')) {336 return 'fail';337 }338 return null;339 }340341 // ─── next-step suggestion ──────────────────────────────────────342343 /**344 * @param array{is_repo: bool, dirty: ?bool, ...} $git345 * @param list<Task> $inProgress346 * @param list<Task> $blocked347 * @param list<Epic> $epics348 * @return array{summary: string, commands: list<array{cmd: string, args: list<string>, why: string}>}349 */350 /**351 * Every other live agent, and what is uncommitted in the workspace — the352 * two things an agent otherwise finds out by colliding with them.353 *354 * @return array{you: ?array<string, mixed>, agents: list<array<string, mixed>>, activity: list<array<string, mixed>>, activity_known: bool, stack: list<array<string, mixed>>, agent_docs: string, project: string, unclaimed_fresh: list<string>, unreadable: list<string>}355 */356 private function workingNow(): array357 {358 $now = time();359 $registry = new AgentRegistry(ProjectRoot::get());360 $registry->beat();361 $you = $registry->current();362 $live = $registry->all(false, $now);363 $others = array_values(array_filter($live, static fn (AgentSession $a): bool => $a->id !== $you?->id));364 $radar = new WorkspaceActivity(ProjectRoot::get());365 // Repo paths are matched as host paths: an agent that joined in another366 // project and edits this one's packages claims them too.367 $activity = $radar->dirtyRepos($live, $now, $registry->project());368369 return [370 'you' => $you?->toArray(),371 // Agents of other projects on this machine too: they edit the same packages.372 'agents' => array_map(static fn (AgentSession $a): array => $a->toArray() + ['silent_s' => $a->secondsSilent($now), 'elsewhere' => $a->project !== $registry->project()], $others),373 'activity' => $activity,374 // false: git is not available here, so "no edits" means unknown, not clean.375 'activity_known' => $radar->gitAvailable(),376 // Fresh edits nobody declared: another session that never joined,377 // or your own work you did not list. Either way, look before you commit.378 // The shared stack's last lifecycle events: a restart took the server379 // and everyone's one-off containers down, and this says whose it was.380 'stack' => (new StackEvents(ProjectRoot::get()))->recent(3, $now),381 // A stale manual is how a whole project's agents missed "Say you are382 // here": nothing updated AGENTS.md before 2026-10-17.383 'agent_docs' => (new AgentDocsFreshness(ProjectRoot::get()))->agentsMd(),384 'project' => $registry->project(),385 'unclaimed_fresh' => array_values(array_map(386 static fn (array $r): string => $r['repo'],387 array_filter($activity, static fn (array $r): bool => $r['fresh'] && $r['claimed_by'] === []),388 )),389 'unreadable' => array_values(array_map(390 static fn (array $r): string => $r['repo'],391 array_filter($activity, static fn (array $r): bool => !$r['readable']),392 )),393 ];394 }395396 /**397 * @param array{agents: list<array<string, mixed>>, you: ?array<string, mixed>, project: string} $workingNow398 */399 private function holderOf(string $taskId, array $workingNow): ?string400 {401 foreach ([...$workingNow['agents'], ...($workingNow['you'] !== null ? [$workingNow['you']] : [])] as $agent) {402 // The rule TaskClaim enforces (AgentSession::holds): the task's backlog, not where the agent joined.403 if (($agent['task'] ?? null) === $taskId && (($agent['task_project'] ?? null) ?: ($agent['project'] ?? '')) === $workingNow['project']) {404 return (string) $agent['id'];405 }406 }407408 return null;409 }410411 /** @return array{summary: string, commands: list<array{cmd: string, args: list<string>, why: string}>} */412 private function suggestNext(array $git, ?string $activeEpicId, array $inProgress, array $blocked, array $epics): array413 {414 $cmds = [];415 $parts = [];416417 if ($inProgress !== []) {418 $top = $inProgress[0];419 $parts[] = "Resume task `{$top->id}` ({$top->status->value}) under epic `{$top->epicId}`.";420 $cmds[] = [421 'cmd' => 'ai:work',422 'args' => ['resume', '--id=' . $top->id, '--json'],423 'why' => "resume the in-progress task directly",424 ];425 if ($top->nextStep !== null && $top->nextStep !== '') {426 $parts[] = 'Next step on record: ' . $top->nextStep;427 }428 } elseif ($blocked !== []) {429 // No live work — only blocked tasks. A blocked task is NOT resumable:430 // surface it for unblocking, but steer the agent to pickable work.431 $top = $blocked[0];432 $n = count($blocked);433 $parts[] = $n === 1434 ? "No in-progress work. Task `{$top->id}` is blocked under epic `{$top->epicId}` — unblock it or pick new work."435 : "No in-progress work. {$n} tasks are blocked (latest `{$top->id}`) — unblock one or pick new work.";436 $cmds[] = [437 'cmd' => 'ai:work',438 'args' => ['show', '--id=' . $top->id, '--json'],439 'why' => 'inspect why the blocked task is stuck',440 ];441 $cmds[] = [442 'cmd' => 'ai:work',443 'args' => ['list', '--status=new', '--json'],444 'why' => 'find pickable (new) work instead',445 ];446 } elseif ($activeEpicId !== null) {447 $parts[] = "Epic `{$activeEpicId}` has no in-progress tasks — pick one up.";448 $cmds[] = [449 'cmd' => 'ai:work',450 'args' => ['list', '--epic=' . $activeEpicId, '--status=new', '--json'],451 'why' => 'list new tasks in the active epic',452 ];453 } else {454 $activeCount = 0;455 foreach ($epics as $e) {456 if (!in_array($e->status->value, ['discarded', 'archived'], true)) {457 $activeCount++;458 }459 }460 if ($activeCount > 0) {461 $parts[] = 'No in-progress tasks. Check the backlog.';462 $cmds[] = [463 'cmd' => 'ai:epic',464 'args' => ['list', '--json'],465 'why' => 'show active epics',466 ];467 } else {468 $parts[] = 'No active backlog. Classify the request first.';469 $cmds[] = [470 'cmd' => 'ai:task',471 'args' => ['"<the request>"', '--json'],472 'why' => 'classify the user request into a recipe',473 ];474 }475 }476477 if (($git['dirty'] ?? false) === true) {478 $parts[] = 'Working tree is dirty — verify before committing.';479 $cmds[] = [480 'cmd' => 'ai:verify',481 'args' => ['--json'],482 'why' => 'lint/test the current diff',483 ];484 }485486 $cmds[] = [487 'cmd' => 'ai:ask',488 'args' => ['project', '--json'],489 'why' => 'structural overview if you need it (27 modules)',490 ];491492 return [493 'summary' => implode(' ', $parts),494 'commands' => $cmds,495 ];496 }497498 // ─── formatters ────────────────────────────────────────────────499500 /**501 * @param list<Epic> $epics502 * @return array{id: string, title: string, status: string, task_count: int}|null503 */504 private function epicBrief(array $epics, string $id): ?array505 {506 foreach ($epics as $e) {507 if ($e->id === $id) {508 return [509 'id' => $e->id,510 'title' => $e->title,511 'status' => $e->status->value,512 'task_count' => count($e->taskIds),513 ];514 }515 }516 return null;517 }518519 /**520 * @return array{id: string, epic_id: string, title: string, status: string, recipe: string, risk: string, next_step: ?string, context_refs: list<string>, updated_at: string}521 */522 private function taskBrief(Task $task): array523 {524 return [525 'id' => $task->id,526 'epic_id' => $task->epicId,527 'title' => $task->title,528 'status' => $task->status->value,529 'recipe' => $task->recipe,530 'risk' => $task->risk,531 'next_step' => $task->nextStep,532 'context_refs' => $task->contextRefs,533 'updated_at' => $task->updatedAt,534 ];535 }536537 /**538 * @param array<string, mixed> $envelope539 */540 private function renderHuman(SymfonyStyle $io, array $envelope): void541 {542 $io->title('Session dashboard (ai:orient)');543544 $git = $envelope['git'];545 if ($git['is_repo']) {546 $dirty = $git['dirty'] ? 'dirty' : 'clean';547 $track = '';548 if ($git['ahead'] !== null || $git['behind'] !== null) {549 $track = " (ahead {$git['ahead']} / behind {$git['behind']})";550 }551 $io->section('Git');552 $io->writeln(" branch: {$git['branch']}{$track} — {$dirty}");553 $io->writeln(" head: {$git['head']} {$git['last_commit_summary']}");554 } else {555 $io->section('Git');556 $io->writeln(' (not a git repository)');557 }558559 $backlog = $envelope['backlog'];560 $io->section('Backlog');561 $blockedCount = $backlog['blocked_count'] ?? 0;562 $io->writeln(" epics: {$backlog['total_epics']} total in-progress tasks: {$backlog['in_progress_count']} blocked: {$blockedCount}");563 if ($backlog['active_epic'] !== null) {564 $ae = $backlog['active_epic'];565 $io->writeln(" active epic: {$ae['id']} [{$ae['status']}] — {$ae['title']}");566 }567 foreach ($backlog['in_progress_tasks'] as $t) {568 $next = $t['next_step'] !== null && $t['next_step'] !== '' ? " — next: {$t['next_step']}" : '';569 $io->writeln(" • [{$t['status']}] {$t['id']} ({$t['recipe']}/{$t['risk']}) {$t['title']}{$next}");570 }571 foreach ($backlog['blocked_tasks'] ?? [] as $t) {572 $io->writeln(" ⊘ [blocked] {$t['id']} ({$t['recipe']}/{$t['risk']}) {$t['title']}");573 }574575 if ($envelope['recent_traces'] !== []) {576 $io->section('Recent traces');577 foreach ($envelope['recent_traces'] as $tr) {578 $tail = $tr['last_event'];579 $line = " • {$tr['id']} ({$tr['created_at']})";580 if ($tail !== null) {581 $line .= " — last: [{$tail['kind']}] {$tail['summary']}";582 }583 $io->writeln($line);584 }585 }586587 if ($envelope['last_verify'] !== null) {588 $lv = $envelope['last_verify'];589 $io->section('Last verify');590 $io->writeln(" trace: {$lv['trace_id']} at: {$lv['at']}");591 $io->writeln(" verdict: " . ($lv['verdict'] ?? 'unknown') . " — {$lv['summary']}");592 }593594 $unreadRuns = $envelope['unread_failed_verify'] ?? [];595 if (is_array($unreadRuns) && $unreadRuns !== []) {596 $io->section('Red verify runs nobody checked (24h)');597 foreach (array_slice($unreadRuns, 0, 3) as $run) {598 if (!is_array($run)) {599 continue;600 }601 $runBy = is_array($run['run_by'] ?? null) ? $run['run_by'] : [];602 $io->writeln(sprintf(603 ' %s %s %s by %s',604 is_string($run['id'] ?? null) ? $run['id'] : '?',605 is_string($run['verdict'] ?? null) ? $run['verdict'] : '?',606 is_string($run['generated_at'] ?? null) ? substr($run['generated_at'], 0, 16) : '?',607 is_string($runBy['agent_session'] ?? null) ? $runBy['agent_session'] : 'unknown session',608 ));609 }610 $io->writeln(' → bin/semitexa ai:verify:receipt --unread # a run reported as green needs a receipt that holds');611 }612613 $wn = $envelope['working_now'];614 $io->section('Working now');615 $io->writeln(' you: ' . match (true) {616 $wn['you'] === null => 'not joined — run ai:agent join so the others can see you',617 !($wn['you']['joined'] ?? true) => $wn['you']['id'] . ' — listed, but not joined: run ai:agent join so the others know what you are doing',618 default => $wn['you']['id'] . ' — ' . $wn['you']['intent'],619 });620 $docsWarning = match ($wn['agent_docs'] ?? AgentDocsFreshness::UNKNOWN) {621 AgentDocsFreshness::BEHIND => 'AGENTS.md is an older framework version: run bin/semitexa update — the rules you just read may be stale',622 AgentDocsFreshness::EDITED => 'AGENTS.md matches no framework version (edited here): bin/semitexa update leaves AGENTS.md.new to merge',623 AgentDocsFreshness::MISSING => 'AGENTS.md is missing: run bin/semitexa update',624 default => null,625 };626 if ($docsWarning !== null) { $io->writeln(' ⚠ ' . $docsWarning); }627 foreach ($envelope['unshipped_commits'] as $u) { $io->writeln(sprintf(' ⚠ %s (%s) has %d commit(s) nobody pushed, last: %s — push %2$s and ship it by a PR', $u['repo'], $u['branch'], $u['ahead'], $u['last'])); }628 foreach ($wn['agents'] as $a) {629 $io->writeln(sprintf(630 ' %s (%s%s, %d min ago): %s%s',631 $a['id'],632 $a['agent'],633 $a['elsewhere'] ? ', in ' . basename((string) $a['project']) : '',634 intdiv((int) $a['silent_s'], 60),635 $a['intent'],636 $a['task'] !== null ? ' [task ' . $a['task'] . ']' : '',637 ));638 }639 if ($wn['agents'] === []) {640 $io->writeln(' no other agent has joined');641 }642 if ($wn['stack'] !== []) {643 $io->writeln(' dev stack: last ' . StackEvents::describe($wn['stack'][0]));644 }645 if (!$wn['activity_known']) {646 $io->writeln(' ⚠ uncommitted edits unknown: git is not available here');647 }648 foreach ($wn['unreadable'] as $repo) {649 $io->writeln(" ⚠ {$repo}: git status failed — its uncommitted edits are unknown, not clean");650 }651 foreach ($wn['unclaimed_fresh'] as $repo) {652 $io->writeln(" ⚠ {$repo}: edited in the last 30 min, claimed by no agent — someone may be working there");653 }654655 if ($envelope['quality_error'] !== null) {656 $io->writeln(' ⚠ ' . $envelope['quality_error']);657 }658 if ($envelope['quality_next'] !== []) {659 $io->section('Improve next (ai:quality next)');660 foreach ($envelope['quality_next'] as $t) {661 $io->writeln(" {$t['metric']} — {$t['key']}: {$t['count']}");662 }663 }664665 $io->section('Next');666 $io->writeln(' ' . $envelope['suggest_next']);667 foreach ($envelope['next_command'] as $nc) {668 $io->writeln(" → bin/semitexa {$nc['cmd']} " . implode(' ', $nc['args']) . " # {$nc['why']}");669 }670 }671}672
1<?php23declare(strict_types=1);45namespace Semitexa\Dev\Application\Console\Command;67use Semitexa\Core\Attribute\AsCommand;8use Semitexa\Core\Console\BaseCommand;9use Semitexa\Dev\Application\Service\Console\CommandDelegator;10use Symfony\Component\Console\Input\InputArgument;11use Symfony\Component\Console\Input\InputInterface;12use Symfony\Component\Console\Input\InputOption;13use Symfony\Component\Console\Output\OutputInterface;1415/**16 * Agent-facing aggregator for read-only introspection. One entry point, one17 * argument (the "subject"), forwarded to the underlying command that owns18 * the implementation.19 *20 * ai:ask capabilities [--search=word] [--json]21 * ai:ask project [--json]22 * ai:ask module --name=Billing [--json]23 * ai:ask route --path=/billing/{id} [--method=GET] [--json]24 * ai:ask event [--name=InvoicePaid] [--json]25 * ai:ask api --name=Column | --search=regex [--json]26 * ai:ask components [--name=platform.grid] [--kind=component] [--json]27 * ai:ask logs [--file=app] [--lines=200] [--grep=…] [--json]28 *29 * Output contracts (envelope shapes, JSON keys, exit codes) belong to the30 * dispatched targets — `ai:ask` only routes; the dev:graph:* / logs:app31 * commands own behavior.32 */33#[AsCommand(name: 'ai:ask', description: 'Agent-facing introspection aggregator (capabilities, mechanisms, components, project, module, route, event, path, api, logs)')]34final class AiAskCommand extends BaseCommand35{36 /**37 * Subject → underlying command. Keeping the list short is the point: if38 * a new read-only surface is needed, add it here rather than spawning39 * another top-level command.40 *41 * @var array<string, string>42 */43 private const SUBJECT_MAP = [44 'capabilities' => 'dev:graph:capabilities',45 // Distinct from `capabilities` on purpose: that one lists the CLI46 // commands available to run, this one lists what the installed47 // FRAMEWORK can do (deferred regions, components, live transport).48 // Both answer "what can I do here"; merging them buries the handful of49 // mechanisms under a wall of command help.50 'mechanisms' => 'dev:graph:mechanisms',51 'project' => 'dev:graph:project',52 'module' => 'dev:graph:module',53 'route' => 'dev:graph:route',54 'event' => 'dev:graph:event',55 'api' => 'dev:graph:api',56 // The UI catalog: what can be rendered, its props and how to call it.57 'components' => 'platform-ui:catalog',58 'logs' => 'logs:app',59 // `path` explains a file/directory path using global module-structure60 // rules + any package-local extension. Auto-selected when --path is61 // passed without an explicit subject (see execute()).62 'path' => 'dev:graph:path',63 ];6465 public function __construct()66 {67 parent::__construct('ai:ask');68 }6970 protected function configure(): void71 {72 $this73 // Subject is now OPTIONAL: when omitted, the command auto-selects74 // `path` if --path is provided (lets `ai:ask --path=…` work75 // without naming a subject). Existing subjects keep their full76 // routing behavior.77 ->addArgument('subject', InputArgument::OPTIONAL, 'One of: ' . implode(', ', array_keys(self::SUBJECT_MAP)) . ' (omit if --path is provided to auto-select `path`)')78 // Union of options accepted by the delegated targets. Only the79 // ones the target actually declares are forwarded (see80 // CommandDelegator). Anything else is silently dropped.81 ->addOption('name', null, InputOption::VALUE_REQUIRED, 'Module/event name, a framework class, or a UI entry (for subject=module|event|api|components)')82 ->addOption('search', null, InputOption::VALUE_REQUIRED, 'Find framework classes and members by name or doc summary (for subject=api), or mechanisms and commands by a word (for subject=mechanisms|capabilities)')83 ->addOption('path', null, InputOption::VALUE_REQUIRED, 'Path: route path (subject=route) | file/directory path (subject=path, default when --path used)')84 ->addOption('method', null, InputOption::VALUE_REQUIRED, 'HTTP method (for subject=route)')85 ->addOption('file', null, InputOption::VALUE_REQUIRED, 'Log file alias (for subject=logs)')86 ->addOption('lines', null, InputOption::VALUE_REQUIRED, 'Line count (for subject=logs)')87 ->addOption('grep', null, InputOption::VALUE_REQUIRED, 'Filter (for subject=logs)')88 ->addOption('level', null, InputOption::VALUE_REQUIRED, 'Log level filter (for subject=logs)')89 ->addOption('since', null, InputOption::VALUE_REQUIRED, 'Time window (for subject=logs)')90 ->addOption('around', null, InputOption::VALUE_REQUIRED, 'Context timestamp (for subject=logs)')91 ->addOption('context', null, InputOption::VALUE_REQUIRED, 'Context radius (for subject=logs)')92 ->addOption('list', null, InputOption::VALUE_NONE, 'List available logs (for subject=logs)')93 ->addOption('kind', null, InputOption::VALUE_REQUIRED, 'primitive, component or behavior (for subject=components)')94 ->addOption('id', null, InputOption::VALUE_REQUIRED, 'Capability id (for subject=mechanisms)')95 ->addOption('area', null, InputOption::VALUE_REQUIRED, 'Capability area prefix, e.g. ssr|ui (for subject=mechanisms)')96 ->addOption('state', null, InputOption::VALUE_REQUIRED, 'installed or available (for subject=mechanisms)')97 ->addOption('limit', null, InputOption::VALUE_REQUIRED, 'How many search hits to show (for subject=api)')98 ->addOption('with-demo', null, InputOption::VALUE_NONE, 'Also search the demo and showcase packages (for subject=api)')99 ->addOption('json', null, InputOption::VALUE_NONE, 'Emit JSON envelope (target-dependent shape)');100 }101102 protected function execute(InputInterface $input, OutputInterface $output): int103 {104 $subject = (string) ($input->getArgument('subject') ?? '');105 // When subject is omitted but --path is provided, default to106 // `path`. Keeps `ai:ask --path=foo` ergonomic for AI agents while107 // preserving the explicit-subject flow for everyone else.108 if ($subject === '' && (string) ($input->getOption('path') ?? '') !== '') {109 $subject = 'path';110 }111 if ($subject === '') {112 $output->writeln(json_encode([113 'kind' => 'error',114 'error' => 'missing subject (and no --path provided to auto-select)',115 'subjects' => array_keys(self::SUBJECT_MAP),116 ], JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);117 return self::FAILURE;118 }119 $target = self::SUBJECT_MAP[$subject] ?? null;120 if ($target === null) {121 $output->writeln(json_encode([122 'kind' => 'error',123 'error' => "unknown subject '{$subject}'",124 'subjects' => array_keys(self::SUBJECT_MAP),125 ], JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);126 return self::FAILURE;127 }128129 $app = $this->getApplication();130 if ($app === null) {131 $output->writeln(json_encode([132 'kind' => 'error',133 'error' => 'Application not available — cannot dispatch subject',134 ], JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);135 return self::FAILURE;136 }137138 return CommandDelegator::run($app, $target, $input, $output);139 }140}141
1<?php23declare(strict_types=1);45namespace Semitexa\Dev\Application\Console\Command;67use Semitexa\Core\Attribute\AsCommand;8use Semitexa\Core\Attribute\InjectAsReadonly;9use Semitexa\Core\Console\BaseCommand;10use Semitexa\Dev\Application\Service\Trace\ObservatoryMode;11use Semitexa\Dev\Application\Service\Trace\PageTimelineReader;12use Semitexa\Dev\Application\Service\Trace\ObservatoryReader;13use Semitexa\Dev\Application\Service\Trace\ReplayRunner;14use Semitexa\Dev\Application\Service\Trace\EntryMethodCatalog;15use Semitexa\Dev\Application\Service\Trace\SourceSliceReader;16use Semitexa\Dev\Application\Service\Trace\SpanTarget;17use Semitexa\Dev\Application\Service\Trace\TraceReader;18use Symfony\Component\Console\Input\InputArgument;19use Symfony\Component\Console\Input\InputInterface;20use Symfony\Component\Console\Input\InputOption;21use Symfony\Component\Console\Output\OutputInterface;2223/**24 * The AI agent's window into the Observatory — the same journal and traces the25 * human panel reads, rendered for a context budget instead of a screen.26 *27 * Design rules (ep-observatory, decision 4):28 * - the agent consumes the DATA, never the human HTML;29 * - summaries first, bytes on demand: `ps` is a snapshot, `show` is one30 * process, `tail` is raw NDJSON rows — nothing dumps everything;31 * - `tail --follow` streams new journal rows as they land and exits after32 * --duration seconds, because an agent cannot Ctrl-C.33 *34 * Everything here is read-only over files; no server round-trip, so it works35 * with the app down (the journal is still there — often exactly when a crash36 * is being investigated).37 */38#[AsCommand(39 name: 'ai:observe',40 description: 'Observatory for agents: ps (live snapshot) | tail (journal rows, --follow streams) | show --id (one process + its trace) | timeline [--id] (a page: its UI events, stream frames, re-runs)',41)]42final class AiObserveCommand extends BaseCommand43{44 #[InjectAsReadonly]45 protected ObservatoryReader $reader;4647 #[InjectAsReadonly]48 protected TraceReader $traces;4950 #[InjectAsReadonly]51 protected ReplayRunner $replayRunner;5253 #[InjectAsReadonly]54 protected SourceSliceReader $source;5556 #[InjectAsReadonly]57 protected PageTimelineReader $timelines;5859 public function __construct()60 {61 parent::__construct('ai:observe');62 }6364 protected function configure(): void65 {66 $this67 ->addArgument('action', InputArgument::REQUIRED, 'ps | tail | show | replay | sandbox | timeline')68 ->addOption('id', null, InputOption::VALUE_REQUIRED, 'Process id (show, replay); a page\'s KISS session id (timeline)')69 ->addOption('mutate', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Override an input field, k=v; v parsed as JSON when it parses (replay, repeatable)')70 ->addOption('method', null, InputOption::VALUE_REQUIRED, 'HTTP method of the route to run (sandbox)', 'GET')71 ->addOption('path', null, InputOption::VALUE_REQUIRED, 'Concrete request path, e.g. /items/7 (sandbox)')72 ->addOption('input', null, InputOption::VALUE_REQUIRED, 'Payload input as a JSON object, path params included (sandbox)', '{}')73 ->addOption('kind', null, InputOption::VALUE_REQUIRED, 'Filter: process kind (tail)')74 ->addOption('name', null, InputOption::VALUE_REQUIRED, 'Filter: name substring (tail)')75 ->addOption('lines', null, InputOption::VALUE_REQUIRED, 'How many rows (tail, default 50, max 500)')76 ->addOption('follow', null, InputOption::VALUE_NONE, 'Stream new rows as they land (tail)')77 ->addOption('duration', null, InputOption::VALUE_REQUIRED, 'Seconds to follow before exiting (default 15, max 300)')78 ->addOption('source', null, InputOption::VALUE_NONE, 'Inline the source of the method/class each traced span ran (show; dev-only)')79 ->addOption('json', null, InputOption::VALUE_NONE, 'Accepted for ai:* symmetry; output is always JSON');80 }8182 protected function execute(InputInterface $input, OutputInterface $output): int83 {84 if (!$this->reader->isEnabled()) {85 $output->writeln((string) json_encode([86 'artifact' => 'semitexa-dev.ai-observe.error/v1',87 'error' => 'observatory-disabled',88 'hint' => 'The journal is off here: APP_ENV must be dev, or SEMITEXA_OBSERVATORY_MODE=monitor for journal-only production observability.',89 ]), OutputInterface::OUTPUT_RAW);9091 return self::FAILURE;92 }9394 return match ($input->getArgument('action')) {95 'ps' => $this->ps($output),96 'tail' => $this->tail($input, $output),97 'show' => $this->show($input, $output),98 'replay' => $this->replay($input, $output),99 'sandbox' => $this->sandbox($input, $output),100 'timeline' => $this->timeline($input, $output),101 default => $this->unknown($output),102 };103 }104105 /**106 * Sandbox replay of one recorded process: same route, the recorded payload107 * snapshot (with --mutate overrides) through the real handler — writes108 * rolled back, queue handoffs captured — then a trace-vs-trace diff.109 */110 private function replay(InputInterface $input, OutputInterface $output): int111 {112 // Monitor mode reads the journal; it never re-executes anything.113 // ReplayRunner refuses too — this early exit just says why, first.114 if (!ObservatoryMode::full()) {115 return $this->fail(116 $output,117 'replay-requires-dev',118 'Replay executes recorded requests and is dev-only; monitor mode is journal-only by design.',119 );120 }121122 $id = $this->strOption($input, 'id');123 if ($id === null) {124 return $this->fail($output, 'missing-id', 'ai:observe replay --id=<process-id> [--mutate k=v]');125 }126127 $found = $this->reader->find($id);128 $traceFile = $found['end']['trace'] ?? null;129 if (!is_string($traceFile) || $traceFile === '') {130 return $this->fail(131 $output,132 'not-traced',133 'Replay needs the recorded envelope; this process has no trace. Re-run the request with ?__trace=1 first.',134 );135 }136137 $mutations = [];138 foreach ((array) $input->getOption('mutate') as $pair) {139 if (!is_string($pair) || !str_contains($pair, '=')) {140 return $this->fail($output, 'bad-mutation', "each --mutate must be k=v, got: " . (string) $pair);141 }142 [$k, $v] = explode('=', $pair, 2);143 $decoded = json_decode($v, true);144 $mutations[$k] = json_last_error() === JSON_ERROR_NONE ? $decoded : $v;145 }146147 $result = $this->replayRunner->replay($traceFile, $mutations);148 if (isset($result['error'])) {149 $output->writeln((string) json_encode(['artifact' => 'semitexa-dev.ai-observe.error/v1'] + $result), OutputInterface::OUTPUT_RAW);150151 return self::FAILURE;152 }153154 $envelope = ['artifact' => 'semitexa-dev.ai-observe.replay/v1', 'id' => $id] + $result;155 if (is_string($result['replay_trace'] ?? null)) {156 $envelope['diff'] = $this->diffTraces($traceFile, $result['replay_trace']);157 }158159 $output->writeln((string) json_encode($envelope, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), OutputInterface::OUTPUT_RAW);160161 return $result['verdict'] === 'handler_threw' ? self::FAILURE : self::SUCCESS;162 }163164 /**165 * One request through the replay sandbox with no recording behind it —166 * what the API Explorer runs in a process of its own, because the sandbox167 * arms process-global registries a serving worker must never see.168 */169 private function sandbox(InputInterface $input, OutputInterface $output): int170 {171 if (!ObservatoryMode::full()) {172 return $this->fail($output, 'sandbox-requires-dev', 'The sandbox executes handlers and is dev-only.');173 }174175 $path = $this->strOption($input, 'path');176 if ($path === null || !str_starts_with($path, '/')) {177 return $this->fail($output, 'missing-path', 'ai:observe sandbox --method=POST --path=/items/7 --input=\'{"name":"x"}\'');178 }179 $data = json_decode((string) $input->getOption('input'), true);180 if (!is_array($data) || ($data !== [] && array_is_list($data))) {181 return $this->fail($output, 'bad-input', '--input must be a JSON object');182 }183184 $result = $this->replayRunner->sandbox((string) ($this->strOption($input, 'method') ?? 'GET'), $path, $data);185 if (isset($result['error'])) {186 $output->writeln((string) json_encode(['artifact' => 'semitexa-dev.ai-observe.error/v1'] + $result), OutputInterface::OUTPUT_RAW);187188 return self::FAILURE;189 }190191 $output->writeln((string) json_encode(192 ['artifact' => 'semitexa-dev.ai-observe.sandbox/v1'] + $result,193 JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,194 ), OutputInterface::OUTPUT_RAW);195196 return $result['verdict'] === 'handler_threw' ? self::FAILURE : self::SUCCESS;197 }198199 /**200 * Span-level comparison of the two recordings. Timing deltas on shared201 * spans are labeled expected drift — a replay runs on a different clock202 * with different caches; STRUCTURE changes (spans or queries appearing or203 * vanishing) are what a behaviour difference actually looks like.204 *205 * @return array<string, mixed>206 */207 private function diffTraces(string $originalFile, string $replayFile): array208 {209 $profile = function (string $file): ?array {210 $trace = $this->traces->read($file);211 if ($trace === null) {212 return null;213 }214 $spans = [];215 foreach ($trace['spans'] as $span) {216 $name = (string) $span['name'];217 $spans[$name] = ($spans[$name] ?? 0) + 1;218 }219220 return ['spans' => $spans, 'queries' => count($trace['queries']), 'totalMs' => $trace['meta']['totalMs']];221 };222223 $orig = $profile($originalFile);224 $replay = $profile($replayFile);225 if ($orig === null || $replay === null) {226 return ['error' => 'diff-unavailable'];227 }228229 $added = array_diff_key($replay['spans'], $orig['spans']);230 $missing = array_diff_key($orig['spans'], $replay['spans']);231 $countChanged = [];232 foreach (array_intersect_key($orig['spans'], $replay['spans']) as $name => $n) {233 if ($replay['spans'][$name] !== $n) {234 $countChanged[$name] = ['original' => $n, 'replay' => $replay['spans'][$name]];235 }236 }237238 return [239 'spans_added' => $added,240 'spans_missing' => $missing,241 'span_count_changed' => $countChanged,242 'queries' => ['original' => $orig['queries'], 'replay' => $replay['queries']],243 'total_ms' => [244 'original' => $orig['totalMs'],245 'replay' => $replay['totalMs'],246 'note' => 'timing drift is expected; structure changes are the signal',247 ],248 'structurally_identical' => $added === [] && $missing === [] && $countChanged === []249 && $orig['queries'] === $replay['queries'],250 ];251 }252253 private function fail(OutputInterface $output, string $error, string $hint): int254 {255 $output->writeln((string) json_encode([256 'artifact' => 'semitexa-dev.ai-observe.error/v1',257 'error' => $error,258 'hint' => $hint,259 ]), OutputInterface::OUTPUT_RAW);260261 return self::FAILURE;262 }263264 private function ps(OutputInterface $output): int265 {266 $snapshot = $this->reader->snapshot();267268 $next = [269 ['cmd' => 'ai:observe', 'args' => ['show', '--id=<process-id>'], 'why' => 'inspect one process, including its trace when it was recorded'],270 ['cmd' => 'ai:observe', 'args' => ['tail', '--follow', '--duration=15'], 'why' => 'watch new journal rows arrive live'],271 ];272 // The newest failure first: it is what someone running ps is looking for.273 foreach ($snapshot['recent'] as $row) {274 if (($row['failed'] ?? false) === true) {275 array_unshift($next, [276 'cmd' => 'ai:observe',277 'args' => ['show', '--id=' . $row['id']],278 'why' => sprintf('the newest failure: %s ended %s', $row['name'], $row['exception'] ?? ('with ' . ($row['httpStatus'] ?? 'failed'))),279 ]);280 break;281 }282 }283284 $envelope = [285 'artifact' => 'semitexa-dev.ai-observe.ps/v1',286 ] + $snapshot + [287 'next_command' => $next,288 ];289290 $output->writeln((string) json_encode($envelope, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), OutputInterface::OUTPUT_RAW);291292 return self::SUCCESS;293 }294295 private function tail(InputInterface $input, OutputInterface $output): int296 {297 $kind = $this->strOption($input, 'kind');298 $name = $this->strOption($input, 'name');299 $lines = max(1, min(500, (int) ($input->getOption('lines') ?: 50)));300301 foreach ($this->reader->tailRecords($lines, $kind, $name) as $row) {302 $output->writeln((string) json_encode($row, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), OutputInterface::OUTPUT_RAW);303 }304305 if (!$input->getOption('follow')) {306 return self::SUCCESS;307 }308309 // Follow by file growth: remember the offset, poll for appended bytes,310 // emit whole lines. Exits on its own — an agent cannot Ctrl-C, so an311 // unbounded follow would hang the tool call that issued it.312 $duration = max(1, min(300, (int) ($input->getOption('duration') ?: 15)));313 $deadline = microtime(true) + $duration;314 $path = $this->reader->todayJournalPath();315 $offset = is_file($path) ? (int) filesize($path) : 0;316 $carry = '';317318 while (microtime(true) < $deadline) {319 usleep(200_000);320 // Re-resolve EVERY iteration: at midnight the journal rolls to a321 // new dated file while the old one still exists and stops growing322 // — a follower pinned to the old path would go silent for the323 // rest of the duration.324 $current = $this->reader->todayJournalPath();325 if ($current !== $path) {326 $path = $current;327 $offset = 0;328 $carry = '';329 }330 clearstatcache(true, $path);331 if (!is_file($path)) {332 // First write of the day still pending.333 $offset = 0;334 continue;335 }336 $size = (int) filesize($path);337 if ($size < $offset) {338 // Truncated (manual cleanup): restart from the top rather339 // than waiting forever for the size to catch up.340 $offset = 0;341 $carry = '';342 }343 if ($size <= $offset) {344 continue;345 }346 $chunk = (string) file_get_contents($path, false, null, $offset, $size - $offset);347 $offset = $size;348 $carry .= $chunk;349350 while (($nl = strpos($carry, "\n")) !== false) {351 $line = substr($carry, 0, $nl);352 $carry = substr($carry, $nl + 1);353 $row = json_decode($line, true);354 if (!is_array($row)) {355 continue;356 }357 if ($kind !== null && ($row['kind'] ?? '') !== $kind) {358 continue;359 }360 if ($name !== null && !str_contains((string) ($row['name'] ?? ''), $name)) {361 continue;362 }363 $output->writeln((string) json_encode($row, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), OutputInterface::OUTPUT_RAW);364 }365 }366367 return self::SUCCESS;368 }369370 private function show(InputInterface $input, OutputInterface $output): int371 {372 $id = $this->strOption($input, 'id');373 if ($id === null) {374 $output->writeln((string) json_encode([375 'artifact' => 'semitexa-dev.ai-observe.error/v1',376 'error' => 'missing-id',377 'hint' => 'ai:observe show --id=<process-id>; ids come from ps or tail.',378 ]), OutputInterface::OUTPUT_RAW);379380 return self::FAILURE;381 }382383 $found = $this->reader->find($id);384 if ($found['begin'] === null && $found['end'] === null) {385 $output->writeln((string) json_encode([386 'artifact' => 'semitexa-dev.ai-observe.error/v1',387 'error' => 'unknown-process',388 'id' => $id,389 'hint' => 'Not in the journal tail window. ai:observe ps lists what is visible.',390 ]), OutputInterface::OUTPUT_RAW);391392 return self::FAILURE;393 }394395 $envelope = [396 'artifact' => 'semitexa-dev.ai-observe.show/v1',397 'id' => $id,398 'begin' => $found['begin'],399 'end' => $found['end'],400 // lost: it never ended, but the process that ran it restarted, stopped or crashed.401 'status' => $found['end'] !== null ? 'done' : ($found['lost'] !== null ? 'lost' : 'live'),402 'lost' => $found['lost'],403 ];404405 // Bytes on demand: the full span/query resolution only when this406 // process was traced, and only for the process that was asked about.407 $traceFile = $found['end']['trace'] ?? null;408 if (is_string($traceFile) && $traceFile !== '') {409 $trace = $this->traces->read($traceFile);410 if ($trace !== null) {411 if ((bool) $input->getOption('source')) {412 if (!ObservatoryMode::full()) {413 return $this->fail(414 $output,415 'source-requires-dev',416 'Inlining source reads files from the working copy and is dev-only; monitor mode is journal-only by design.',417 );418 }419 $trace = $this->withSource($trace);420 // An object even when empty: the field is a map keyed421 // Class::method, and a consumer indexing it must not meet422 // a JSON array on the one trace that named no class.423 $envelope['source'] = (object) $trace['source'];424 unset($trace['source']);425 }426 $envelope['trace'] = $trace;427 } else {428 // The journal says a trace was written, but the file is gone429 // (rotated, or written by another instance sharing the430 // journal). Saying so beats silently looking untraced.431 $envelope['trace_missing'] = $traceFile;432 }433 } else {434 $envelope['next_command'] = [[435 'cmd' => 'browser',436 'args' => ['?__trace=1'],437 'why' => 'no trace was recorded for this process; re-run the request with the marker for full spans',438 ]];439 }440441 $output->writeln((string) json_encode($envelope, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), OutputInterface::OUTPUT_RAW);442443 return self::SUCCESS;444 }445446 /**447 * Attach the source behind every span that named a class.448 *449 * Each distinct Class::method is read once and keyed under `source`; the450 * span carries only the key (`source_ref`), so a handler that ran ten451 * times costs one slice, not ten. The same resolution the HTML node page452 * uses: the recorded method when the span has one, the conventional entry453 * method otherwise, the class when neither exists.454 *455 * The key is the RESOLVED identity, not the requested one: a span that456 * named only the class and resolved to handle() shares its entry with a457 * span that named Class::handle outright. Only an unreadable source keeps458 * the requested key, so the consumer still learns where the span pointed.459 *460 * @param array<string, mixed> $trace461 * @return array<string, mixed> the trace with `source_ref` on spans and a top-level `source` map462 */463 private function withSource(array $trace): array464 {465 $catalog = new EntryMethodCatalog();466 $sources = [];467 /** @var array<string, string> $canonical requested key → resolved key, so each target resolves once */468 $canonical = [];469470 /** @var list<array<string, mixed>> $spans */471 $spans = is_array($trace['spans'] ?? null) ? $trace['spans'] : [];472 foreach ($spans as $i => $span) {473 $target = SpanTarget::of(is_array($span['context'] ?? null) ? $span['context'] : []);474 if ($target === null) {475 continue;476 }477478 $requested = $target->key();479 if (!isset($canonical[$requested])) {480 $slice = $target->method !== null481 ? $this->source->slice($target->class, $target->method)482 : $this->source->sliceAny($target->class, $catalog->candidates($target->class, null));483 $key = match (true) {484 $slice === null => $requested,485 $slice->method === null => $slice->fqcn,486 default => $slice->fqcn . '::' . $slice->method,487 };488 $canonical[$requested] = $key;489 // null stays in the map: the span still says it pointed490 // somewhere, and the consumer learns the source was unreadable491 // instead of wondering why a key is missing.492 if (!array_key_exists($key, $sources)) {493 $sources[$key] = $slice?->toArray();494 }495 }496497 $spans[$i]['source_ref'] = $canonical[$requested];498 }499500 $trace['spans'] = $spans;501 $trace['source'] = $sources;502503 return $trace;504 }505506 /**507 * A page's live timeline: without --id the pages seen lately, with it one508 * page's events in order (dev only — the timeline is not kept in monitor509 * mode).510 */511 private function timeline(InputInterface $input, OutputInterface $output): int512 {513 if (!ObservatoryMode::full()) {514 return $this->fail($output, 'timeline-requires-dev', 'The page timeline is recorded in development only.');515 }516 $id = $this->strOption($input, 'id');517 $lines = max(1, min(2000, (int) ($input->getOption('lines') ?: 200)));518 $output->writeln((string) json_encode($id === null519 ? ['artifact' => 'semitexa-dev.ai-observe.pages/v1', 'pages' => $this->timelines->pages()]520 : ['artifact' => 'semitexa-dev.ai-observe.timeline/v1', 'session' => $id, 'events' => $this->timelines->events($id, $lines)],521 JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), OutputInterface::OUTPUT_RAW);522523 return self::SUCCESS;524 }525526 private function unknown(OutputInterface $output): int527 {528 $output->writeln((string) json_encode([529 'artifact' => 'semitexa-dev.ai-observe.error/v1',530 'error' => 'unknown-action',531 'hint' => 'Actions: ps | tail [--kind= --name= --lines= --follow --duration=] | show --id= [--source] | replay --id= [--mutate k=v]',532 ]), OutputInterface::OUTPUT_RAW);533534 return self::FAILURE;535 }536537 private function strOption(InputInterface $input, string $name): ?string538 {539 $value = $input->getOption($name);540541 return is_string($value) && $value !== '' ? $value : null;542 }543}544
1<?php23declare(strict_types=1);45namespace Semitexa\Dev\Application\Console\Command;67use Semitexa\Core\Attribute\AsCommand;8use Semitexa\Core\Attribute\InjectAsReadonly;9use Semitexa\Core\Console\BaseCommand;10use Semitexa\Core\Support\ProjectRoot;11use Semitexa\Dev\Application\Service\Ai\Presence\AgentRegistry;12use Semitexa\Dev\Application\Service\Ai\Presence\BacklogActivity;13use Semitexa\Dev\Application\Service\Ai\Presence\TaskClaim;14use Semitexa\Dev\Application\Service\Ai\Trace\TraceEvent;15use Semitexa\Dev\Application\Service\Ai\Trace\TraceEventKind;16use Semitexa\Dev\Application\Service\Ai\Trace\TraceStore;17use Semitexa\Dev\Application\Service\Ai\Work\BacklogHygiene;18use Semitexa\Dev\Application\Service\Ai\Work\BacklogScope;19use Semitexa\Dev\Application\Service\Ai\Work\EpicStore;20use Semitexa\Dev\Application\Service\Ai\Work\ResumeService;21use Semitexa\Dev\Application\Service\Ai\Work\ResumeSnapshot;22use Semitexa\Dev\Application\Service\Ai\Work\Task;23use Semitexa\Dev\Application\Service\Ai\Work\TaskFiling;24use Semitexa\Dev\Application\Service\Ai\Work\TaskNextCommands;25use Semitexa\Dev\Application\Service\Ai\Work\TaskProofs;26use Semitexa\Dev\Application\Service\Ai\Work\TaskStatus;27use Semitexa\Dev\Application\Service\Ai\Work\TaskStore;28use Semitexa\Dev\Application\Service\Ai\Work\WorkId;29use Symfony\Component\Console\Input\InputArgument;30use Symfony\Component\Console\Input\InputInterface;31use Symfony\Component\Console\Input\InputOption;32use Symfony\Component\Console\Output\OutputInterface;3334/**35 * Work item (task) CLI — the main surface for agent decomposition and resume.36 *37 * bin/semitexa ai:work start --id=tk-fix-wm --epic=ep-wm --title="..." [--recipe=...] [--risk=...] [--phase=work|right|fast] [--trace=...] [--context-ref=...]* [--next-step=...]38 * bin/semitexa ai:work list [--epic=...] [--status=new|in_progress|blocked|done[,...]] [--json]39 * bin/semitexa ai:work show --id=tk-fix-wm [--json]40 * bin/semitexa ai:work update --id=tk-fix-wm [--status=...] [--title=...] [--recipe=...] [--risk=...] [--phase=...] [--next-step=...] [--context-ref=...]* [--epic=...]41 * bin/semitexa ai:work note --id=tk-fix-wm --note="..." [--next-step=...]42 * bin/semitexa ai:work resume --id=tk-fix-wm [--tail=5]43 *44 * `start` always links the task to a trace: if `--trace` isn't supplied the45 * task id is used as the trace id, and the trace is openOrCreate'd on the46 * fly. That way every task has a durable log, and the slugs stay aligned.47 */48#[AsCommand(name: 'ai:work', description: 'Manage work tasks: start/list/show/update/resume/note (agent-facing, NDJSON)')]49final class AiWorkCommand extends BaseCommand50{51 private const ACTION_START = 'start';52 private const ACTION_LIST = 'list';53 private const ACTION_SHOW = 'show';54 private const ACTION_UPDATE = 'update';55 private const ACTION_NOTE = 'note';56 private const ACTION_RESUME = 'resume';5758 private const ALLOWED_RISK = ['low', 'medium', 'high'];5960 #[InjectAsReadonly]61 protected TaskStore $taskStore;6263 #[InjectAsReadonly]64 protected EpicStore $epicStore;6566 #[InjectAsReadonly]67 protected TraceStore $traceStore;6869 #[InjectAsReadonly]70 protected ResumeService $resumeService;7172 #[InjectAsReadonly]73 protected BacklogHygiene $hygiene;7475 public function __construct()76 {77 parent::__construct('ai:work');78 }7980 protected function configure(): void81 {82 $this83 ->addArgument('action', InputArgument::REQUIRED, 'start | list | show | update | note | resume')84 ->addOption('id', null, InputOption::VALUE_REQUIRED, 'Task id (a-z, 0-9, -, _)')85 ->addOption('epic', null, InputOption::VALUE_REQUIRED, 'Epic id (required on start; on update, re-parents the task)')86 ->addOption('title', null, InputOption::VALUE_REQUIRED, 'Task title')87 ->addOption('recipe', null, InputOption::VALUE_REQUIRED, 'Recipe id (see ai:task)')88 ->addOption('risk', null, InputOption::VALUE_REQUIRED, 'Risk: ' . implode('|', self::ALLOWED_RISK))89 ->addOption('phase', null, InputOption::VALUE_REQUIRED, 'work | right | fast. Filed under right or fast, or under a bug recipe, it counts at once; other new work is an idea until ai:work:approve')90 ->addOption('status', null, InputOption::VALUE_REQUIRED, 'Status: ' . implode('|', TaskStatus::all()) . ' (list accepts a comma list)')91 ->addOption('scope', null, InputOption::VALUE_REQUIRED, 'List filter: ' . implode('|', BacklogScope::all()) . ' (default: active)')92 ->addOption('take-over', null, InputOption::VALUE_NONE, 'Take an in_progress task another live agent holds (update)')93 ->addOption('context-ref', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Path or symbol the task is anchored to (repeatable)')94 ->addOption('next-step', null, InputOption::VALUE_REQUIRED, 'One-line next step for the resuming agent')95 ->addOption('note', null, InputOption::VALUE_REQUIRED, 'Free-form note (appended to the linked trace)')96 ->addOption('tail', null, InputOption::VALUE_REQUIRED, 'How many trailing trace events to surface on resume (default 5)')97 ->addOption('trace', null, InputOption::VALUE_REQUIRED, 'Trace id for this task (defaults to the task id on start)')98 ->addOption('json', null, InputOption::VALUE_NONE, 'Emit a single JSON envelope instead of NDJSON');99 }100101 protected function execute(InputInterface $input, OutputInterface $output): int102 {103 $action = (string) $input->getArgument('action');104 $json = (bool) $input->getOption('json');105 BacklogActivity::announce($output, new AgentRegistry(ProjectRoot::get()), ProjectRoot::get());106107 return match ($action) {108 self::ACTION_START => $this->start($input, $output, $json),109 self::ACTION_LIST => $this->list($input, $output, $json),110 self::ACTION_SHOW => $this->show($input, $output, $json),111 self::ACTION_UPDATE => $this->update($input, $output, $json),112 self::ACTION_NOTE => $this->note($input, $output, $json),113 self::ACTION_RESUME => $this->resume($input, $output, $json),114 default => $this->error($output, "unknown action: '{$action}' (expected start | list | show | update | note | resume)", $json),115 };116 }117118 private function start(InputInterface $input, OutputInterface $output, bool $jsonMode): int119 {120 $id = $this->requireId($input, $output, $jsonMode);121 if ($id === null) {122 return self::FAILURE;123 }124 if ($this->taskStore->exists($id)) {125 return $this->error($output, "task '{$id}' already exists", $jsonMode);126 }127128 $epicId = (string) ($input->getOption('epic') ?? '');129 if ($epicId === '') {130 return $this->error($output, '--epic is required for start', $jsonMode);131 }132 try {133 WorkId::assertValid($epicId, 'epic id');134 } catch (\InvalidArgumentException $e) {135 return $this->error($output, $e->getMessage(), $jsonMode);136 }137 if (!$this->epicStore->exists($epicId)) {138 return $this->error($output, "epic '{$epicId}' does not exist — run ai:epic start first", $jsonMode);139 }140141 $title = (string) ($input->getOption('title') ?? '');142 if ($title === '') {143 return $this->error($output, '--title is required for start', $jsonMode);144 }145146 $recipe = (string) ($input->getOption('recipe') ?? '');147 $risk = $this->normaliseRisk((string) ($input->getOption('risk') ?? 'medium'), $output, $jsonMode);148 if ($risk === null) {149 return self::FAILURE;150 }151152 $traceId = (string) ($input->getOption('trace') ?? $id);153 try {154 WorkId::assertValid($traceId, 'trace id');155 $phase = TaskFiling::phaseOf(TaskFiling::parsePhase($this->optionalString($input, 'phase')), $recipe);156 } catch (\InvalidArgumentException $e) {157 return $this->error($output, $e->getMessage(), $jsonMode);158 }159 $this->traceStore->openOrCreate($traceId, topic: $title, recipe: $recipe !== '' ? $recipe : null);160161 $now = date('c');162 $refs = $this->contextRefs($input);163 $task = new Task(164 id: $id,165 epicId: $epicId,166 title: $title,167 status: TaskStatus::NEW,168 recipe: $recipe,169 risk: $risk,170 contextRefs: $refs,171 nextStep: $this->optionalString($input, 'next-step'),172 traceId: $traceId,173 createdAt: $now,174 updatedAt: $now,175 approval: TaskFiling::approvalOnFiling($phase, $recipe, $now),176 phase: $phase,177 );178 $this->taskStore->save($task);179180 $this->traceStore->append($traceId, TraceEventKind::TASK_RESULT, "task '{$id}' started — {$title}", [181 'artifact' => 'semitexa.ai-work.task-start/v1',182 'task_id' => $id,183 'epic_id' => $epicId,184 'recipe' => $recipe,185 'risk' => $risk,186 'phase' => $phase?->value,187 'context_refs' => $refs,188 'next_step' => $task->nextStep,189 ]);190191 return $this->emitTask($output, $task, 'task_started', $jsonMode);192 }193194 private function list(InputInterface $input, OutputInterface $output, bool $jsonMode): int195 {196 $epicId = $input->getOption('epic') !== null ? (string) $input->getOption('epic') : null;197 try {198 $statuses = TaskStatus::parseList((string) ($input->getOption('status') ?? ''));199 } catch (\InvalidArgumentException $e) {200 return $this->error($output, $e->getMessage(), $jsonMode);201 }202 $statusLabel = $statuses === [] ? null : implode(',', array_map(static fn(TaskStatus $s): string => $s->value, $statuses));203 if ($epicId !== null) {204 try {205 WorkId::assertValid($epicId, 'epic id');206 } catch (\InvalidArgumentException $e) {207 return $this->error($output, $e->getMessage(), $jsonMode);208 }209 }210211 $scopeRaw = (string) ($input->getOption('scope') ?? BacklogScope::ACTIVE->value);212 try {213 $scope = BacklogScope::parse($scopeRaw);214 } catch (\InvalidArgumentException $e) {215 return $this->error($output, $e->getMessage(), $jsonMode);216 }217218 $all = array_values(array_filter(219 $this->taskStore->list($epicId),220 static fn(Task $task): bool => $statuses === [] || in_array($task->status, $statuses, true),221 ));222 $rows = [];223 $hiddenByScope = 0;224 foreach ($all as $task) {225 $assessment = $this->hygiene->assessTask($task);226 if (!$this->hygiene->taskInScope($task, $assessment, $scope)) {227 $hiddenByScope++;228 continue;229 }230 $rows[] = $task->toArray() + [231 'quality' => $assessment->quality->value,232 'issues' => $assessment->issues,233 'suggested_status' => $assessment->suggestedStatus,234 'suggested_action' => $assessment->suggestedAction,235 ];236 }237238 if ($jsonMode) {239 $output->writeln(json_encode([240 'artifact' => 'semitexa.ai-work.task-list/v1',241 'epic' => $epicId,242 'status' => $statusLabel,243 'scope' => $scope->value,244 'tasks' => $rows,245 'task_count' => count($rows),246 'hidden_by_scope' => $hiddenByScope,247 'total_in_store' => count($all),248 ], JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);249 return self::SUCCESS;250 }251252 $output->writeln(json_encode([253 'kind' => 'summary',254 'epic' => $epicId,255 'status' => $statusLabel,256 'scope' => $scope->value,257 'task_count' => count($rows),258 'hidden_by_scope' => $hiddenByScope,259 'total_in_store' => count($all),260 ], JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);261 foreach ($rows as $row) {262 $output->writeln(json_encode(['kind' => 'task'] + $row, JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);263 }264 return self::SUCCESS;265 }266267 private function show(InputInterface $input, OutputInterface $output, bool $jsonMode): int268 {269 $id = $this->requireId($input, $output, $jsonMode);270 if ($id === null) {271 return self::FAILURE;272 }273 try {274 $task = $this->taskStore->get($id);275 } catch (\RuntimeException $e) {276 return $this->error($output, $e->getMessage(), $jsonMode);277 }278 return $this->emitTask($output, $task, 'task', $jsonMode);279 }280281 private function update(InputInterface $input, OutputInterface $output, bool $jsonMode): int282 {283 $id = $this->requireId($input, $output, $jsonMode);284 if ($id === null) {285 return self::FAILURE;286 }287 try {288 $task = $this->taskStore->get($id);289 } catch (\RuntimeException $e) {290 return $this->error($output, $e->getMessage(), $jsonMode);291 }292293 $statusRaw = $input->getOption('status');294 $status = null;295 if ($statusRaw !== null && $statusRaw !== '') {296 try {297 $status = TaskStatus::parse((string) $statusRaw);298 } catch (\InvalidArgumentException $e) {299 return $this->error($output, $e->getMessage(), $jsonMode);300 }301 }302303 $title = $this->optionalString($input, 'title');304 $recipe = $this->optionalString($input, 'recipe');305 $riskRaw = $this->optionalString($input, 'risk');306 $risk = null;307 if ($riskRaw !== null) {308 $risk = $this->normaliseRisk($riskRaw, $output, $jsonMode);309 if ($risk === null) {310 return self::FAILURE;311 }312 }313 try {314 $phase = TaskFiling::parsePhase($this->optionalString($input, 'phase'));315 } catch (\InvalidArgumentException $e) {316 return $this->error($output, $e->getMessage(), $jsonMode);317 }318 $nextStep = $this->optionalString($input, 'next-step');319 $refs = $this->contextRefs($input);320 $refsOpt = $refs === [] ? null : $refs;321322 // Re-parenting. Epic membership is derived from the task, so a move is323 // one field — and without this it was one field edited in the JSON by324 // hand, which leaves no trace event and no record of why. Validated325 // against the store because an unknown epic id is the orphan case326 // BacklogHygiene already reports, and creating one here is worse than327 // refusing: the task disappears from every listing that starts at an328 // epic.329 $epicId = $this->optionalString($input, 'epic');330 if ($epicId !== null) {331 try {332 WorkId::assertValid($epicId, 'epic id');333 } catch (\InvalidArgumentException $e) {334 return $this->error($output, $e->getMessage(), $jsonMode);335 }336 if (!$this->epicStore->exists($epicId)) {337 return $this->error($output, "epic '{$epicId}' does not exist — run ai:epic start first", $jsonMode);338 }339 if ($epicId === $task->epicId) {340 $epicId = null; // already there; not a change to report341 }342 }343 $movedFrom = $epicId === null ? null : $task->epicId;344345 // Read here, not only in the note action. --note is declared on the346 // command and its description promises the trace; update() ignored it,347 // so closing a task WITH its reasoning changed the status, printed the348 // task as updated, exited 0 and threw the reasoning away. Eighteen349 // closures in one session were recorded that way and kept none of it.350 $note = $this->optionalString($input, 'note');351352 if ($title === null && $recipe === null && $risk === null && $status === null353 && $nextStep === null && $refsOpt === null && $note === null && $epicId === null && $phase === null) {354 return $this->error($output, 'update requires at least one of --title, --recipe, --risk, --status, --phase, --next-step, --context-ref, --note, --epic', $jsonMode);355 }356357 if (($refused = TaskClaim::claim(ProjectRoot::get(), $id, $status, (bool) $input->getOption('take-over'))) !== null) {358 return $this->error($output, $refused, $jsonMode);359 }360 $updated = $this->taskStore->change($id, static fn (Task $current): Task => (new TaskProofs(ProjectRoot::get()))->settle(TaskFiling::afterEdit($current->with(361 title: $title,362 status: $status,363 recipe: $recipe,364 risk: $risk,365 contextRefs: $refsOpt,366 nextStep: $nextStep,367 updatedAt: date('c'),368 epicId: $epicId,369 phase: $phase,370 ), date('c')), $status));371372 $kind = $status !== null ? TraceEventKind::NEXT_STEP : TraceEventKind::NOTE;373 $summary = match (true) {374 $status !== null => "task '{$id}' status → {$status->value}",375 // The move is named in the summary rather than left in the payload:376 // a reader scanning a trace for where a task went reads summaries.377 $epicId !== null => "task '{$id}' moved {$movedFrom} → {$epicId}",378 default => "task '{$id}' updated",379 };380 $changes = array_filter([381 'title' => $title,382 'recipe' => $recipe,383 'risk' => $risk,384 'status' => $status?->value,385 'phase' => $phase?->value,386 'next_step' => $nextStep,387 'context_refs' => $refsOpt,388 'epic_id' => $epicId,389 'moved_from' => $movedFrom,390 ], static fn($v) => $v !== null);391392 if ($changes !== []) {393 $this->safeAppend($updated->traceId, $kind, $summary, [394 'artifact' => 'semitexa.ai-work.task-update/v1',395 'task_id' => $id,396 'changes' => $changes,397 ]);398 }399400 // Its own event, and the same shape the note action writes: a reader of401 // the trace should not have to know which command spelling produced a402 // note, and the two must not drift into two shapes.403 if ($note !== null) {404 try {405 $this->appendNote($updated->traceId, $id, $note);406 } catch (\InvalidArgumentException|\RuntimeException $e) {407 return $this->noteError($output, $updated, true, $e->getMessage(), $jsonMode);408 }409 }410411 return $this->emitTask($output, $updated, 'task_updated', $jsonMode);412 }413414 private function note(InputInterface $input, OutputInterface $output, bool $jsonMode): int415 {416 $id = $this->requireId($input, $output, $jsonMode);417 if ($id === null) {418 return self::FAILURE;419 }420 try {421 $task = $this->taskStore->get($id);422 } catch (\RuntimeException $e) {423 return $this->error($output, $e->getMessage(), $jsonMode);424 }425426 $note = $this->optionalString($input, 'note');427 $nextStep = $this->optionalString($input, 'next-step');428 if ($note === null && $nextStep === null) {429 return $this->error($output, 'note requires --note and/or --next-step', $jsonMode);430 }431432 if ($nextStep !== null) {433 $task = $this->taskStore->change($id, static fn (Task $current): Task => $current->with(nextStep: $nextStep, updatedAt: date('c')));434 }435436 if ($note !== null) {437 try {438 $this->appendNote($task->traceId, $id, $note, $nextStep);439 } catch (\InvalidArgumentException|\RuntimeException $e) {440 return $this->noteError($output, $task, $nextStep !== null, $e->getMessage(), $jsonMode);441 }442 } else {443 $this->safeAppend($task->traceId, TraceEventKind::NOTE, "task '{$id}' next step updated", array_filter([444 'artifact' => 'semitexa.ai-work.task-note/v1',445 'task_id' => $id,446 'next_step' => $nextStep,447 ], static fn($v) => $v !== null));448 }449450 return $this->emitTask($output, $task, 'task_noted', $jsonMode);451 }452453 /**454 * One place that writes a note to a trace, so `ai:work note` and455 * `ai:work update --note` cannot end up writing two different shapes of the456 * same thing.457 */458 private function appendNote(string $traceId, string $id, string $note, ?string $nextStep = null): void459 {460 // An explicitly requested note is the primary action, not best-effort461 // trace hygiene. Missing traces and failed writes must reach the caller.462 $this->traceStore->append(463 $traceId,464 TraceEventKind::NOTE,465 "note on task '{$id}': " . $this->truncate($note, 80),466 array_filter([467 'artifact' => 'semitexa.ai-work.task-note/v1',468 'task_id' => $id,469 'note' => $note,470 'next_step' => $nextStep,471 ], static fn($v) => $v !== null),472 );473 }474475 private function resume(InputInterface $input, OutputInterface $output, bool $jsonMode): int476 {477 $id = $this->requireId($input, $output, $jsonMode);478 if ($id === null) {479 return self::FAILURE;480 }481 $tail = (int) ($input->getOption('tail') ?? 5);482483 try {484 $snapshot = $this->resumeService->resume($id, $tail);485 } catch (\RuntimeException $e) {486 return $this->error($output, $e->getMessage(), $jsonMode);487 }488489 $this->safeAppend(490 $snapshot->task->traceId,491 TraceEventKind::NEXT_STEP,492 "resuming task '{$id}' (status={$snapshot->task->status->value})",493 [494 'artifact' => 'semitexa.ai-work.task-resume/v1',495 'task_id' => $id,496 'status' => $snapshot->task->status->value,497 'next_step' => $snapshot->task->nextStep,498 ],499 );500501 return $this->emitResume($output, $snapshot, $jsonMode);502 }503504 private function emitResume(OutputInterface $output, ResumeSnapshot $snapshot, bool $jsonMode): int505 {506 $envelope = [507 'artifact' => 'semitexa.ai-work.task-resume/v1',508 'task' => $snapshot->task->toArray(),509 'trace_header' => $snapshot->traceHeader?->toArray(),510 'tail_events' => array_map(static fn(TraceEvent $e) => $e->toArray(), $snapshot->tailEvents),511 'trace_warning' => $snapshot->traceWarning,512 ];513514 if ($jsonMode) {515 $output->writeln(json_encode($envelope, JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);516 return self::SUCCESS;517 }518519 $output->writeln(json_encode([520 'kind' => 'summary',521 'task_id' => $snapshot->task->id,522 'status' => $snapshot->task->status->value,523 'epic_id' => $snapshot->task->epicId,524 'trace_id' => $snapshot->task->traceId,525 'tail_events' => count($snapshot->tailEvents),526 'next_step' => $snapshot->task->nextStep,527 ], JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);528 $output->writeln(json_encode(['kind' => 'task'] + $snapshot->task->toArray(), JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);529 if ($snapshot->traceHeader !== null) {530 $output->writeln(json_encode(['kind' => 'trace_header'] + $snapshot->traceHeader->toArray(), JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);531 }532 foreach ($snapshot->tailEvents as $event) {533 $output->writeln(json_encode(['kind' => 'trace_event'] + $event->toArray(), JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);534 }535 if ($snapshot->traceWarning !== null) {536 $output->writeln(json_encode([537 'kind' => 'warning',538 'warning' => $snapshot->traceWarning,539 ], JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);540 }541 $output->writeln(json_encode([542 'kind' => 'next',543 'action' => 'proceed',544 'hint' => $snapshot->task->nextStep ?? 'no next_step recorded — inspect trace with ai:trace show --id=' . $snapshot->task->traceId,545 ], JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);546 return self::SUCCESS;547 }548549 private function emitTask(OutputInterface $output, Task $task, string $kind, bool $jsonMode): int550 {551 if ($jsonMode) {552 $output->writeln(json_encode([553 'artifact' => 'semitexa.ai-work.task/v1',554 'task' => $task->toArray(),555 'next_command' => TaskNextCommands::for($task),556 ], JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);557 return self::SUCCESS;558 }559 $output->writeln(json_encode(['kind' => $kind] + $task->toArray(), JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);560 return self::SUCCESS;561 }562563 /**564 * @param array<string, mixed> $payload565 */566 private function safeAppend(string $traceId, string $kind, string $summary, array $payload): void567 {568 if ($traceId === '') {569 return;570 }571 if (!$this->traceStore->exists($traceId)) {572 return;573 }574 try {575 $this->traceStore->append($traceId, $kind, $summary, $payload);576 } catch (\RuntimeException) {577 // Trace hygiene is best-effort; never let it break the primary action.578 }579 }580581 private function requireId(InputInterface $input, OutputInterface $output, bool $jsonMode): ?string582 {583 $id = (string) ($input->getOption('id') ?? '');584 if ($id === '') {585 $this->error($output, '--id is required', $jsonMode);586 return null;587 }588 try {589 WorkId::assertValid($id, 'task id');590 } catch (\InvalidArgumentException $e) {591 $this->error($output, $e->getMessage(), $jsonMode);592 return null;593 }594 return $id;595 }596597 private function normaliseRisk(string $value, OutputInterface $output, bool $jsonMode): ?string598 {599 $lower = strtolower(trim($value));600 if (!in_array($lower, self::ALLOWED_RISK, true)) {601 $this->error(602 $output,603 "invalid risk '{$value}': expected one of " . implode(', ', self::ALLOWED_RISK),604 $jsonMode,605 );606 return null;607 }608 return $lower;609 }610611 /**612 * @return list<string>613 */614 private function contextRefs(InputInterface $input): array615 {616 $raw = $input->getOption('context-ref');617 if (!is_array($raw)) {618 return [];619 }620 $out = [];621 foreach ($raw as $ref) {622 $trimmed = trim((string) $ref);623 if ($trimmed !== '') {624 $out[] = $trimmed;625 }626 }627 return $out;628 }629630 private function optionalString(InputInterface $input, string $name): ?string631 {632 if (!$input->hasOption($name)) {633 return null;634 }635 $value = $input->getOption($name);636 if ($value === null) {637 return null;638 }639 $value = (string) $value;640 return $value === '' ? null : $value;641 }642643 private function truncate(string $value, int $max): string644 {645 // The limit is in Unicode characters; the full note stays in payload.646 return mb_strlen($value, 'UTF-8') > $max ? mb_substr($value, 0, $max - 1, 'UTF-8') . '…' : $value;647 }648649 private function noteError(OutputInterface $output, Task $task, bool $taskSaved, string $reason, bool $jsonMode): int650 {651 $prefix = $taskSaved ? 'Task changes were saved, but the note' : 'The note';652653 return $this->error($output, $prefix . ' could not be saved: ' . $reason, $jsonMode, [654 'task_saved' => $taskSaved,655 'note_saved' => false,656 'task' => $task->toArray(),657 ]);658 }659660 /** @param array<string, mixed> $details */661 private function error(OutputInterface $output, string $message, bool $jsonMode, array $details = []): int662 {663 $record = $jsonMode664 ? ['artifact' => 'semitexa.ai-work.task/v1', 'status' => 'error']665 : ['kind' => 'error'];666 $output->writeln(json_encode($record + ['error' => $message] + $details, JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);667 return self::FAILURE;668 }669}670
1<?php23declare(strict_types=1);45namespace Semitexa\Dev\Application\Console\Command;67use Semitexa\Core\Attribute\AsCommand;8use Semitexa\Core\Attribute\InjectAsReadonly;9use Semitexa\Core\Console\BaseCommand;10use Semitexa\Dev\Application\Service\Ai\Trace\TraceAutoAppender;11use Semitexa\Dev\Application\Service\Ai\Trace\TraceEventKind;12use Semitexa\Dev\Application\Service\Ai\Verify\ChangedFile;13use Semitexa\Dev\Application\Service\Ai\Verify\CoverageGap;14use Semitexa\Dev\Application\Service\Ai\Verify\UnselectedChanges;15use Semitexa\Dev\Application\Service\Ai\Verify\DirtyWorkspaceScanner;16use Semitexa\Dev\Application\Service\Ai\Verify\ChangedFileClassifier;17use Semitexa\Dev\Application\Service\Ai\Verify\VerificationExecutor;18use Semitexa\Dev\Application\Service\Ai\Verify\VerificationPlan;19use Semitexa\Dev\Application\Service\Ai\Verify\VerificationPlanner;20use Semitexa\Dev\Application\Service\Ai\Verify\VerificationResult;21use Semitexa\Dev\Application\Service\Ai\Verify\VerificationTarget;22use Semitexa\Dev\Application\Service\Ai\Verify\VerifyReportSerializer;23use Semitexa\Dev\Application\Service\Ai\Verify\TaskCommitFiles;24use Semitexa\Dev\Application\Service\Ai\Verify\Impact\ImpactProbe;25use Semitexa\Dev\Application\Service\Ai\Verify\Impact\ImpactReport;26use Semitexa\Orm\Application\Service\Connection\ConnectionRegistry;27use Symfony\Component\Console\Input\InputInterface;28use Symfony\Component\Console\Input\InputOption;29use Symfony\Component\Console\Output\OutputInterface;30use Symfony\Component\Console\Output\BufferedOutput;3132/**33 * Agent-facing verifier: takes a diff or file list, plans the precise lint /34 * syntax / phpunit / module-structure subset to run, executes it, and emits35 * an NDJSON envelope.36 *37 * bin/semitexa ai:verify --files=src/modules/Foo/src/Application/Handler/PayloadHandler/Bar.php38 * bin/semitexa ai:verify --git-ref=HEAD~1 --scope=standard39 * git diff --name-only HEAD~1 | bin/semitexa ai:verify --diff-stdin40 *41 * Output (NDJSON, one JSON object per line):42 * {"kind":"summary", recipe-style header}43 * {"kind":"expansion", note-of-why-scope-bumped} (zero or more)44 * {"kind":"target", pre-execution per-target metadata}45 * {"kind":"result", post-execution per-target outcome}46 * {"kind":"violation", per-target structured diagnostic} (zero or more)47 * {"kind":"verdict", pass/fail rollup}48 *49 * `--json` mode flips the output into a single envelope (artifact:50 * `semitexa-dev.verify-report/v1`) for callers that prefer one blob over a51 * stream — both modes carry exactly the same data, including the52 * `violations` aggregate from the `module_structure` check (rules and53 * remediation guidance live in54 * `packages/semitexa-docs/docs/MODULE_STRUCTURE.md`).55 */56#[AsCommand(name: 'ai:verify', description: 'Run the precise lint+test+module-structure subset for a diff/file list (NDJSON, agent-facing)')]57final class AiVerifyCommand extends BaseCommand58{59 #[InjectAsReadonly]60 protected TraceAutoAppender $traceAppender;6162 // Optional (nullable) so ai:verify still runs where no DB is bound63 // (e.g. the command's own test harness); only --impact needs it.64 #[InjectAsReadonly]65 protected ?ConnectionRegistry $connections = null;6667 // Optional too: only the page check needs the routes, and a harness may have none.68 #[InjectAsReadonly]69 protected ?\Semitexa\Core\Discovery\AttributeDiscovery $attributeDiscovery = null;7071 #[InjectAsReadonly]72 protected ?\Semitexa\Core\ModuleRegistry $moduleRegistry = null;7374 public function __construct()75 {76 parent::__construct('ai:verify');77 }7879 protected function configure(): void80 {81 $this82 ->addOption('files', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Repo-relative path(s) to verify. Repeat the flag and/or comma-separate; both forms combine.')83 ->addOption('git-ref', null, InputOption::VALUE_REQUIRED, 'Compare working tree against this git ref (e.g. HEAD~1, origin/main)')84 ->addOption('diff-stdin', null, InputOption::VALUE_NONE, 'Read newline-separated paths from stdin (output of `git diff --name-only`)')85 ->addOption('dirty', null, InputOption::VALUE_NONE, 'Every uncommitted change this workspace can see: each packages/semitexa-* repository, plus the project root when it is one. Says which roots it could not ask. The default when no scope is given.')86 ->addOption('all', null, InputOption::VALUE_NONE, 'Scan every Semitexa package under packages/semitexa-* and every local module under src/modules/* (deterministic repo-wide module-structure check)')87 ->addOption('scope', null, InputOption::VALUE_REQUIRED, 'Verification scope: minimal, standard, broad', VerificationPlan::SCOPE_STANDARD)88 ->addOption('trace', null, InputOption::VALUE_REQUIRED, 'Append a verify_result event to this ai:trace id (falls back to $SEMITEXA_AI_TRACE_ID)')89 ->addOption('json', null, InputOption::VALUE_NONE, 'Emit a single JSON envelope instead of NDJSON')90 ->addOption('impact', null, InputOption::VALUE_NONE, 'Annotate each changed file with a project-graph blast-radius band (low|medium|high). Read-only: does not change which checks run.')91 ->addOption('list-e2e', null, InputOption::VALUE_NONE, 'Print the changed Playwright specs this plan would check, one per line, and run nothing (bin/semitexa runs them on the host first).')92 ->addOption('list-pages', null, InputOption::VALUE_NONE, 'Print the pages this plan would open in light and dark, one path per line, and run nothing (bin/semitexa opens them on the host first).');93 }9495 protected function execute(InputInterface $input, OutputInterface $output): int96 {97 $jsonMode = (bool) $input->getOption('json');98 $scope = (string) $input->getOption('scope');99100 // No scope named: the working tree, as --dirty (bench-verify-bare-errors: a bare run was an error).101 if ((array) $input->getOption('files') === [] && !$input->getOption('git-ref') && !(bool) $input->getOption('diff-stdin') && !(bool) $input->getOption('all')) {102 $input->setOption('dirty', true);103 }104 try {105 $paths = $this->collectPaths($input);106 if ($paths === [] && (bool) $input->getOption('dirty') && ($trace = $this->traceAppender->resolveTraceId($input)) !== null) {107 $paths = (new TaskCommitFiles($this->getProjectRoot()))->entries($trace);108 }109 } catch (\RuntimeException $e) {110 $this->emitError($output, $e->getMessage(), $jsonMode);111 return self::FAILURE;112 }113114 if ($paths === [] && !(bool) $input->getOption('list-e2e') && !(bool) $input->getOption('list-pages')) {115 // `--dirty` finding nothing is an ANSWER (the tree is clean): a verdict of its own. A named task checks its commits.116 if ((bool) $input->getOption('dirty')) {117 $scan = (new DirtyWorkspaceScanner($this->getProjectRoot()))->report();118119 // In the SAME shape the mode promises. Default mode is NDJSON120 // whose records are dispatched by `kind`, so an envelope121 // without one is a record such a consumer cannot place — and122 // every ordinary run ends with a `verdict` record.123 // An empty plan, so this answer reaches `--trace` the way every124 // other one does. Returning before maybeAppendToTrace() left a125 // traced workflow with no `verify_result` and no trace status126 // for the run at all — a gap in an audit trail reads as a step127 // that was never taken. Raised in review of dev#84.128 //129 // AND the report keeps its CONTRACT. This branch used to write130 // its own envelope, so a clean run was the one answer missing131 // `completed`, `counts` and `restart` — a consumer reading the132 // stable v1 schema had to special-case it, or fail on the133 // absent keys. The fields come off VerifyReportSerializer, the134 // same source the other two paths use, so there is one135 // definition of what an empty result looks like. Raised in136 // review of dev#84 by both reviewers.137 $emptyPlan = new VerificationPlan($scope, $scope, [], []);138 $report = new VerifyReportSerializer();139 // A receipt for the clean run too: "the latest receipt" must be this run (review of dev#130).140 $envelope = (new \Semitexa\Dev\Application\Service\Ai\Verify\Receipt\VerifyReceipts($this->getProjectRoot()))->attach([141 'artifact' => 'semitexa-dev.verify-report/v1',142 'generated_at' => date('c'),143 'verdict' => 'nothing_to_verify',144 'completed' => $report->completed([]),145 'counts' => $report->countByStatus([]),146 'changed_files' => [],147 'dirty_scan' => $scan,148 'restart' => $report->restartAdvice([]),149 ], []);150151 if ($jsonMode) {152 $traceOutput = new BufferedOutput();153 $this->maybeAppendToTrace($input, $traceOutput, $emptyPlan, [], 'nothing_to_verify', $envelope);154 $envelope['trace'] = array_map(155 static fn(string $line): mixed => json_decode($line, true, 512, JSON_THROW_ON_ERROR),156 array_values(array_filter(explode("\n", trim($traceOutput->fetch())))),157 );158 $output->writeln(json_encode($envelope, JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);159160 return self::SUCCESS;161 }162163 // The same two records a run WITH changes emits, so a consumer164 // reads the scan out of one place regardless of the answer.165 $output->writeln(json_encode(['kind' => 'dirty_scan'] + $scan, JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);166 $output->writeln((string) json_encode(167 ['kind' => 'restart'] + $report->restartAdvice([]),168 JSON_UNESCAPED_SLASHES,169 ), OutputInterface::OUTPUT_RAW);170 $output->writeln(json_encode([171 'kind' => 'verdict',172 'verdict' => 'nothing_to_verify',173 // FALSE, and deliberately so. Nothing ran, and `completed`174 // is what a consumer reads to decide whether the required175 // checks happened — saying true here offered an empty run176 // as verification evidence, and contradicted177 // VerifyReportSerializer::completed([]) besides. Raised in178 // review of dev#84.179 'completed' => $report->completed([]),180 'counts' => $report->countByStatus([]),181 'dirty_scan' => $scan,182 ], JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);183184 $this->maybeAppendToTrace($input, $output, $emptyPlan, [], 'nothing_to_verify', $envelope);185186 return self::SUCCESS;187 }188189 $this->emitError($output, 'no changed files supplied — pass --files, --git-ref, --diff-stdin or --dirty', $jsonMode);190 return self::FAILURE;191 }192193 $projectRoot = $this->getProjectRoot();194 $classifier = new ChangedFileClassifier();195 $changed = array_map(196 static fn(array $entry): ChangedFile => $classifier->classify(197 $entry['path'],198 $entry['status'],199 ($entry['originalPath'] ?? '') !== '' ? $entry['originalPath'] : null,200 ),201 $paths,202 );203 /** @var list<ChangedFile> $changed */204205 $planner = new VerificationPlanner($projectRoot, $classifier, pageRoutes: \Semitexa\Dev\Application\Service\Ai\Verify\PageRoutes::of($this->attributeDiscovery, $this->moduleRegistry));206 $plan = $planner->plan($changed, $scope, (bool) $input->getOption('all'), $baseRef = is_string($input->getOption('git-ref')) && $input->getOption('git-ref') !== '' ? $input->getOption('git-ref') : null);207 if ((bool) $input->getOption('list-pages')) {208 $output->writeln(implode("\n", array_map(static fn (VerificationTarget $t): string => (string) ($t->commandInput['path'] ?? ''), array_values(array_filter($plan->targets, static fn (VerificationTarget $t): bool => $t->type === VerificationTarget::TYPE_PAGE)))), OutputInterface::OUTPUT_RAW);209 return self::SUCCESS;210 }211 if ((bool) $input->getOption('list-e2e')) {212 $output->writeln(implode("\n", array_map(static fn (VerificationTarget $t): string => (string) $t->filePath, array_values(array_filter($plan->targets, static fn (VerificationTarget $t): bool => $t->type === VerificationTarget::TYPE_E2E)))), OutputInterface::OUTPUT_RAW);213 return self::SUCCESS;214 }215216 $app = $this->getApplication();217 if ($app === null) {218 $this->emitError($output, 'Application not available — cannot dispatch lint commands', $jsonMode);219 return self::FAILURE;220 }221 $executor = new VerificationExecutor($app, $projectRoot, $recorder = new \Semitexa\Dev\Application\Service\Ai\Verify\Receipt\RecordingProcessRunner(new \Semitexa\Dev\Application\Service\Ai\Verify\ShellProcessRunner()), baseRef: $baseRef);222 // What the targets are about to check: a file edited before the receipt is written must not ride on this verdict.223 $treeBefore = (new \Semitexa\Dev\Application\Service\Ai\Verify\Receipt\VerifyReceipts($projectRoot))->fingerprintOf(array_map(static fn (ChangedFile $f): string => $f->path, $plan->changedFiles));224 $results = $executor->execute($plan);225226 $verdict = CoverageGap::of($plan, $results, $this->getProjectRoot())->adjust($this->verdict($results));227 $exit = in_array($verdict, [VerificationResult::STATUS_PASS, VerificationResult::STATUS_SKIPPED], true) ? self::SUCCESS : self::FAILURE;228229 $impact = null;230 if ((bool) $input->getOption('impact')) {231 $impact = $this->probeImpact($plan);232 }233234 $unselected = UnselectedChanges::ofRun($input, $projectRoot, $plan);235 $envelope = (new \Semitexa\Dev\Application\Service\Ai\Verify\Receipt\VerifyReceipts($projectRoot))->attach($this->buildEnvelope($plan, $results, $verdict, $impact, $unselected), $recorder->calls(), $treeBefore, is_string($input->getOption('trace')) ? $input->getOption('trace') : null); // ai:verify:receipt checks it236 $dirtyScan = null;237 if ((bool) $input->getOption('dirty')) {238 // The reach of the answer, beside the answer. A scan that could not239 // ask half the tree must not read as "half the tree is clean".240 $dirtyScan = (new DirtyWorkspaceScanner($this->getProjectRoot()))->report();241 $envelope['dirty_scan'] = $dirtyScan;242 }243 if ($jsonMode) {244 $traceOutput = new BufferedOutput();245 $this->maybeAppendToTrace($input, $traceOutput, $plan, $results, $verdict, $envelope);246 $envelope['trace'] = array_map(247 static fn(string $line): mixed => json_decode($line, true, 512, JSON_THROW_ON_ERROR),248 array_values(array_filter(explode("\n", trim($traceOutput->fetch())))),249 );250 $output->writeln(json_encode($envelope, JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);251 } else {252 $this->emitNdjson($output, $plan, $results, $verdict, $impact, $dirtyScan, $unselected);253 $this->maybeAppendToTrace($input, $output, $plan, $results, $verdict, $envelope);254 }255256 return $exit;257 }258259 /**260 * @param list<VerificationResult> $results261 * @param array<string, mixed> $envelope262 */263 private function maybeAppendToTrace(264 InputInterface $input,265 OutputInterface $output,266 VerificationPlan $plan,267 array $results,268 string $verdict,269 array $envelope,270 ): void {271 $counts = (new VerifyReportSerializer())->countByStatus($results);272 (new \Semitexa\Dev\Application\Service\Ai\Verify\RuleStats\RuleFireLedger($this->getProjectRoot()))->record($envelope); // every run, traced or not: ai:verify:rules273 $summary = sprintf(274 'verify %s — scope=%s targets=%d pass=%d fail=%d skipped=%d incomplete=%d',275 $verdict,276 $plan->effectiveScope,277 count($plan->targets),278 $counts['pass'] ?? 0,279 $counts['fail'] ?? 0,280 $counts['skipped'] ?? 0,281 $counts['incomplete'] ?? 0,282 );283 $this->traceAppender->appendIfActive($input, $output, TraceEventKind::VERIFY_RESULT, $summary, $envelope);284 }285286 /**287 * @return list<array{path: string, status: string, originalPath?: string}>288 */289 private function collectPaths(InputInterface $input): array290 {291 $sources = [];292 // --files is VALUE_IS_ARRAY: repeated flags arrive as a list, and each293 // element may itself be a comma-separated batch. Both forms combine, so294 // no path is ever silently dropped (the repeated-flag form previously295 // kept only the last value and returned a false-green partial verify).296 foreach ((array) $input->getOption('files') as $files) {297 foreach (explode(',', (string) $files) as $p) {298 $p = trim($p);299 if ($p !== '') {300 $sources[] = (new \Semitexa\Dev\Application\Service\Ai\Verify\ExplicitFiles($this->getProjectRoot()))->resolve($p); // on disk, a deletion git knows, or refused301 }302 }303 }304 if (($ref = $input->getOption('git-ref')) !== null && $ref !== '') {305 foreach ($this->gitDiffNameStatus((string) $ref) as $entry) {306 $sources[] = $entry;307 }308 }309 if ((bool) $input->getOption('diff-stdin')) {310 foreach ($this->readStdinPaths() as $entry) {311 $sources[] = $entry;312 }313 }314 if ((bool) $input->getOption('dirty')) {315 foreach ((new DirtyWorkspaceScanner($this->getProjectRoot()))->changedFiles() as $entry) {316 $sources[] = $entry;317 }318 }319 if ((bool) $input->getOption('all')) {320 foreach ($this->repoWidePaths() as $entry) {321 $sources[] = $entry;322 }323 }324 return $this->dedupe($sources);325 }326327 /**328 * Repo-wide module / package roots: every `packages/semitexa-X` whose329 * package root contains `composer.json`, plus every `src/modules/X`.330 * Used by `--all` for deterministic AI-facing repo-wide structure331 * verification. Output is sorted lexicographically so NDJSON is stable.332 *333 * @return list<array{path: string, status: string}>334 */335 private function repoWidePaths(): array336 {337 $root = rtrim($this->getProjectRoot(), '/');338 $paths = [];339340 $packagesDir = $root . '/packages';341 if (is_dir($packagesDir)) {342 foreach (glob($packagesDir . '/semitexa-*', GLOB_ONLYDIR) ?: [] as $abs) {343 if (!is_file($abs . '/composer.json')) {344 continue;345 }346 $rel = ltrim(substr($abs, strlen($root)), '/');347 $paths[] = $rel;348 }349 }350351 $modulesDir = $root . '/src/modules';352 if (is_dir($modulesDir)) {353 foreach (glob($modulesDir . '/*', GLOB_ONLYDIR) ?: [] as $abs) {354 $rel = ltrim(substr($abs, strlen($root)), '/');355 $paths[] = $rel;356 }357 }358359 sort($paths);360 return array_map(361 static fn(string $p) => ['path' => $p, 'status' => ChangedFile::STATUS_MODIFIED],362 $paths,363 );364 }365366 /**367 * @return list<array{path: string, status: string, originalPath?: string}>368 */369 private function gitDiffNameStatus(string $ref): array370 {371 // Every repository of the project: the workspace root is none of them.372 return (new \Semitexa\Dev\Application\Service\Ai\Verify\GitRefChanges($this->getProjectRoot()))->changes($ref);373 }374375 /**376 * @return list<array{path: string, status: string, originalPath?: string}>377 */378 private function readStdinPaths(): array379 {380 $raw = (string) stream_get_contents(STDIN);381 $lines = preg_split('/\R/', trim($raw)) ?: [];382 return $this->parseNameStatus($lines);383 }384385 /**386 * @param list<string> $lines git --name-status output OR plain `git diff --name-only` lines387 * @return list<array{path: string, status: string, originalPath?: string}>388 */389 private function parseNameStatus(array $lines): array390 {391 $out = [];392 foreach ($lines as $line) {393 $line = trim($line);394 if ($line === '') {395 continue;396 }397 $parts = preg_split('/\s+/', $line, 3) ?: [];398 if (count($parts) >= 2 && preg_match('/^[AMDR][0-9]*$/', $parts[0])) {399 $status = match ($parts[0][0]) {400 'A' => ChangedFile::STATUS_ADDED,401 'M' => ChangedFile::STATUS_MODIFIED,402 'D' => ChangedFile::STATUS_DELETED,403 'R' => ChangedFile::STATUS_RENAMED,404 default => ChangedFile::STATUS_MODIFIED,405 };406 // For R entries, `git diff --name-status` emits OLD<TAB>NEW; take the407 // new path AND carry the old path so the broken-FQCN guard can query408 // the renamed symbol's previous FQCN too.409 $path = $parts[count($parts) - 1];410 $entry = ['path' => $path, 'status' => $status];411 if ($status === ChangedFile::STATUS_RENAMED && count($parts) >= 3) {412 $entry['originalPath'] = $parts[1];413 }414 $out[] = $entry;415 continue;416 }417 $out[] = ['path' => $line, 'status' => ChangedFile::STATUS_MODIFIED];418 }419 return $out;420 }421422 /**423 * @param list<array{path: string, status: string, originalPath?: string}> $entries424 * @return list<array{path: string, status: string, originalPath?: string}>425 */426 private function dedupe(array $entries): array427 {428 $seen = [];429 $out = [];430 foreach ($entries as $entry) {431 $key = $entry['path'];432 if (isset($seen[$key])) {433 // First-wins, EXCEPT where the first entry knows less. Two434 // ways that happens, and both produced a false green.435 //436 // A RENAME arriving second: `--files=<renamed destination>437 // --dirty` supplies the path by hand as a plain modification438 // and the scanner then finds the same path as a rename.439 // Dropping the second entry discarded `originalPath`, so440 // ContractMoveResolver never expanded consumers of the old441 // contract.442 //443 // A RECREATED file arriving second: staged for deletion and444 // then written again at the same path, git reports `D path`445 // followed by `?? path`. Keeping only the deletion made the446 // planner skip a file that is sitting right there, so a syntax447 // error in its new contents verified clean. If ANY source says448 // the path exists, it exists — a deletion never wins over a449 // record of a live file. Both raised in review of dev#84.450 $at = $seen[$key];451 $original = $entry['originalPath'] ?? '';452 $existingOriginal = $out[$at]['originalPath'] ?? '';453 $learnsOrigin = $original !== '' && $existingOriginal === '';454 $wasDeleted = $out[$at]['status'] === ChangedFile::STATUS_DELETED;455 $isAlive = $entry['status'] !== ChangedFile::STATUS_DELETED;456457 if ($learnsOrigin || ($wasDeleted && $isAlive)) {458 $merged = ['path' => $key, 'status' => $entry['status']];459 $keptOriginal = $original !== '' ? $original : $existingOriginal;460 if ($keptOriginal !== '') {461 $merged['originalPath'] = $keptOriginal;462 }463 $out[$at] = $merged;464 }465 continue;466 }467 $seen[$key] = count($out);468 $out[] = $entry;469 }470 return $out;471 }472473 /**474 * @param list<VerificationResult> $results475 */476 private function verdict(array $results): string477 {478 $report = new VerifyReportSerializer();479 if ($results === []) {480 return VerificationResult::STATUS_INCOMPLETE;481 }482 $hasFail = false;483 $allSkipped = true;484 foreach ($results as $r) {485 if ($r->status === VerificationResult::STATUS_FAIL) {486 $hasFail = true;487 }488 if ($r->status !== VerificationResult::STATUS_SKIPPED) {489 $allSkipped = false;490 }491 }492 if ($hasFail) {493 return VerificationResult::STATUS_FAIL;494 }495 if (!$report->completed($results)) {496 return VerificationResult::STATUS_INCOMPLETE;497 }498 return $allSkipped ? VerificationResult::STATUS_SKIPPED : VerificationResult::STATUS_PASS;499 }500501 /**502 * Read-only blast-radius probe. Never throws into the verify flow — a503 * graph problem must degrade to an "unknown" band, not fail verification.504 */505 private function probeImpact(VerificationPlan $plan): ImpactReport506 {507 $paths = [];508 foreach ($plan->changedFiles as $file) {509 if (str_ends_with($file->path, '.php')) {510 $paths[] = $file->path;511 }512 }513 if ($paths === []) {514 return ImpactReport::empty();515 }516517 if ($this->connections === null) {518 return ImpactReport::stale($paths, 'impact unavailable: no database connection bound in this context');519 }520521 try {522 return (new ImpactProbe($this->connections))->probe(array_values($paths));523 } catch (\Throwable $e) {524 return ImpactReport::stale($paths, 'impact probe failed: ' . $e->getMessage());525 }526 }527528 /**529 * @return array<string, string> path → band, for merging into changed_files530 */531 private function bandsByPath(?ImpactReport $impact): array532 {533 if ($impact === null) {534 return [];535 }536 $bands = [];537 foreach ($impact->files as $file) {538 $bands[$file->path] = $file->band;539 }540 return $bands;541 }542543 /**544 * @param list<VerificationResult> $results545 * @param list<array{path: string, status: string}> $unselected546 */547 private function buildEnvelope(VerificationPlan $plan, array $results, string $verdict, ?ImpactReport $impact = null, array $unselected = []): array548 {549 $report = new VerifyReportSerializer();550 $violations = $this->collectViolations($results);551 $bands = $this->bandsByPath($impact);552 return [553 'artifact' => 'semitexa-dev.verify-report/v1',554 'generated_at' => date('c'),555 'requested_scope' => $plan->scope,556 'effective_scope' => $plan->effectiveScope,557 'expansions' => $plan->expansions,558 'changed_files' => array_map(559 static function (ChangedFile $f) use ($bands): array {560 $entry = ['path' => $f->path, 'kind' => $f->kind, 'status' => $f->status];561 if (isset($bands[$f->path])) {562 $entry['impact'] = $bands[$f->path];563 }564 return $entry;565 },566 $plan->changedFiles,567 ),568 'targets' => array_map(fn($t) => $report->serializeTarget($t), $plan->targets),569 'results' => array_map(fn($r) => $report->serializeResult($r), $results),570 'violations' => $violations,571 'verdict' => $verdict,572 'completed' => $report->completed($results),573 'counts' => $report->countByStatus($results),574 'impact' => $impact?->toSummary(),575 'next_command' => $this->buildNextCommands($verdict, $results),576 'restart' => $report->restartAdvice($plan->changedFiles, $plan->opensPages()),577 ] + UnselectedChanges::annotate(CoverageGap::of($plan, $results, $this->getProjectRoot())->toArray(), $unselected);578 }579580 /**581 * @param list<VerificationResult> $results582 * @return list<array<string, mixed>>583 */584 private function collectViolations(array $results): array585 {586 $out = [];587 foreach ($results as $r) {588 foreach ($r->diagnostics as $diag) {589 $out[] = $diag;590 }591 }592 return $out;593 }594595 /**596 * @param list<VerificationResult> $results597 * @return list<array{cmd: string, args: list<string>, why: string}>598 */599 private function buildNextCommands(string $verdict, array $results): array600 {601 if ($verdict === VerificationResult::STATUS_PASS) {602 return [603 ['cmd' => 'ai:work', 'args' => ['update', '--id=<task-id>', '--status=done', '--json'], 'why' => 'close the active task — verify passed'],604 ['cmd' => 'ai:orient', 'args' => ['--json'], 'why' => 'pick up the next task'],605 ];606 }607 if (in_array($verdict, [VerificationResult::STATUS_FAIL, VerificationResult::STATUS_INCOMPLETE], true)) {608 $failingFile = null;609 $hasStructureFailure = false;610 $hasDiFailure = false;611 foreach ($results as $r) {612 if (in_array($r->status, [VerificationResult::STATUS_FAIL, VerificationResult::STATUS_INCOMPLETE], true)) {613 if ($r->target->type === VerificationTarget::TYPE_MODULE_STRUCTURE) {614 $hasStructureFailure = true;615 }616 if ($r->target->type === VerificationTarget::TYPE_PHPSTAN_DI) {617 $hasDiFailure = true;618 }619 if ($failingFile === null && $r->target->filePath !== null) {620 $failingFile = $r->target->filePath;621 }622 }623 }624 $out = [625 ['cmd' => 'ai:work', 'args' => ['update', '--id=<task-id>', '--status=blocked', '--note="verify failed"'], 'why' => 'record the block before iterating (§9.3)'],626 ];627 if ($hasStructureFailure) {628 $out[] = [629 'cmd' => 'cat',630 'args' => ['packages/semitexa-docs/docs/MODULE_STRUCTURE.md'],631 'why' => 'module structure violations — re-read the rule table before moving files',632 ];633 }634 if ($hasDiFailure) {635 $out[] = [636 'cmd' => 'cat',637 'args' => ['packages/semitexa-docs/docs/AI_BEST_PRACTICES.md'],638 'why' => 'DI violations — Semitexa is attribute-only DI; re-read before reshaping a class',639 ];640 }641 if ($failingFile !== null) {642 $out[] = ['cmd' => 'ai:ask', 'args' => ['path', '--path=' . $failingFile, '--json'], 'why' => 'inspect the failing file before querying symbol impact'];643 }644 $out[] = ['cmd' => 'logs:app', 'args' => ['--grep=error', '--lines=200', '--level=ERROR', '--json'], 'why' => 'runtime errors that might explain the failure'];645 return $out;646 }647 return [648 ['cmd' => 'ai:verify', 'args' => ['--files=<paths>', '--scope=standard', '--json'], 'why' => 'no actionable verification ran — select files and try standard scope'],649 ];650 }651652 /**653 * @param list<VerificationResult> $results654 * @param array{scanned: list<string>, unscannable: list<string>}|null $dirtyScan655 * @param list<array{path: string, status: string}> $unselected656 */657 private function emitNdjson(658 OutputInterface $output,659 VerificationPlan $plan,660 array $results,661 string $verdict,662 ?ImpactReport $impact = null,663 ?array $dirtyScan = null,664 array $unselected = [],665 ): void {666 $report = new VerifyReportSerializer();667 // NDJSON is the DEFAULT mode, and the reach of a `--dirty` scan existed668 // only in the `--json` envelope -- so a run that could not ask half the669 // tree said so exclusively to the readers who had not asked for this670 // mode. A record of its own, dispatchable by `kind` like every other.671 // Raised in review of dev#84.672 if ($dirtyScan !== null) {673 $output->writeln(json_encode(674 ['kind' => 'dirty_scan'] + $dirtyScan,675 JSON_UNESCAPED_SLASHES,676 ), OutputInterface::OUTPUT_RAW);677 }678679 $output->writeln(json_encode([680 'kind' => 'summary',681 'requested_scope' => $plan->scope,682 'effective_scope' => $plan->effectiveScope,683 'changed_files' => count($plan->changedFiles),684 'targets' => count($plan->targets),685 ], JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);686687 if ($impact !== null) {688 $output->writeln(json_encode([689 'kind' => 'impact',690 'impact' => $impact->toSummary(),691 'files' => array_map(static fn ($f) => $f->toArray(), $impact->files),692 ], JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);693 }694695 foreach ($plan->expansions as $note) {696 $output->writeln(json_encode([697 'kind' => 'expansion',698 'note' => $note,699 ], JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);700 }701702 foreach ($plan->targets as $target) {703 $output->writeln(json_encode([704 'kind' => 'target',705 'target' => $report->serializeTarget($target),706 ], JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);707 }708709 foreach ($results as $result) {710 $output->writeln(json_encode([711 'kind' => 'result',712 'result' => $report->serializeResult($result),713 ], JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);714 foreach ($result->diagnostics as $diagnostic) {715 $output->writeln(json_encode([716 'kind' => 'violation',717 'target_id' => $result->target->id,718 ...$diagnostic,719 ], JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);720 }721 }722723 // Before the verdict, so it is read rather than scrolled past.724 //725 // The advice existed only in the `--json` envelope, and NDJSON is the726 // default — so the habit this was written to correct (wrapping every727 // verify in a 16s server:restart) never met the sentence that corrects728 // it. An unstated assumption is not fixed by being wrong somewhere the729 // reader does not look.730 $output->writeln((string) json_encode(731 ['kind' => 'restart'] + $report->restartAdvice($plan->changedFiles, $plan->opensPages()),732 JSON_UNESCAPED_SLASHES,733 ), OutputInterface::OUTPUT_RAW);734735 $verdictLine = [736 'kind' => 'verdict',737 'verdict' => $verdict,738 'completed' => $report->completed($results),739 'counts' => $report->countByStatus($results),740 ] + UnselectedChanges::annotate(CoverageGap::of($plan, $results, $this->getProjectRoot())->toArray(), $unselected);741 if ($impact !== null) {742 $verdictLine['impact'] = $impact->toSummary();743 }744 $output->writeln(json_encode($verdictLine, JSON_UNESCAPED_SLASHES), OutputInterface::OUTPUT_RAW);745 }746747 private function emitError(OutputInterface $output, string $message, bool $jsonMode): void748 {749 if ($jsonMode) {750 $output->writeln((string) json_encode([751 'artifact' => 'semitexa-dev.verify-report/v1',752 'generated_at' => date('c'), 'verdict' => 'fail',753 'error' => $message, // may carry a git ref or path that is not UTF-8754 ], JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE), OutputInterface::OUTPUT_RAW);755 return;756 }757 $output->writeln((string) json_encode(['kind' => 'error', 'error' => $message], JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE), OutputInterface::OUTPUT_RAW);758 }759}760
Operating Rules
What makes the workflow trustworthy
The tools stay useful when each one answers a narrow question and reports its limits in a machine-readable form.
Use ai:ask and Project Graph before broad source searches when the question is structural.
Use ai:observe before forming a runtime hypothesis; the process journal records what actually ran.
Keep long work in epic, work, and trace artifacts with a concrete next step for the next session.
Run ai:verify after a coherent edit, then restart workers only when exercising the live server.
How it works
The ai:* command family connects repository state, recipes, prior art, Project Graph, the runtime Observatory, epic/work/trace memory, and diff-aware checks through stable JSON contracts.
Why it matters
People and agents make safer changes when the project can explain its current shape, show what actually ran, preserve decisions across sessions, and verify the edited surface precisely.
Key concepts
- ai:orient
- Combines Git state, active work, recent traces, last verification, and the next useful command.
- ai:observe
- Reads live and recorded process lifecycles, full waterfalls, executed source, and sandbox replay results.
- ai:verify
- Selects the relevant checks from the actual changed files and reports one structured verdict.