From d19e1ebc28e967cd790a11bb0ba65d261d68d2df Mon Sep 17 00:00:00 2001 From: Serhan Asad Date: Tue, 17 Nov 2026 13:04:59 -0800 Subject: [PATCH 1/4] feat(cli): group root pdd --help and add pdd autopilot logs --follow (#3496, #3475) --- docs/cli.md | 22 +- prompts/cli/autopilot-logs.prompt.md | 142 +++ prompts/cli/autopilot.prompt.md | 5 +- prompts/cli/command-catalog.prompt.md | 86 +- prompts/cli/pdd-cli.prompt.md | 9 +- src/autopilot-logs.mjs | 1213 +++++++++++++++++++++++++ src/autopilot.mjs | 10 +- src/command-catalog.mjs | 341 ++++--- src/pdd-cli.mjs | 54 +- test/approval-help.test.mjs | 53 +- test/autopilot-logs.test.mjs | 450 +++++++++ test/cli.test.mjs | 2 +- test/grouped-help.test.mjs | 107 +++ test/help-teaches-pdd.test.mjs | 27 +- test/runtime-seam.test.mjs | 3 +- 15 files changed, 2264 insertions(+), 260 deletions(-) create mode 100644 prompts/cli/autopilot-logs.prompt.md create mode 100644 src/autopilot-logs.mjs create mode 100644 test/autopilot-logs.test.mjs create mode 100644 test/grouped-help.test.mjs diff --git a/docs/cli.md b/docs/cli.md index 87fd4772c2..2ef93da81c 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -1,6 +1,6 @@ # CLI reference -This page lists every command of pdd 0.1.35, as `pdd --help` shows it. A test (`test/docs-commands.test.mjs`) checks that each command form of the help is on this page. +This page lists every command of pdd 0.1.35, as `pdd --help` and `pdd --help` show it. A test (`test/docs-commands.test.mjs`) checks that each command form of the help catalog is on this page. You need the pdd command only for runs with PRs, for `pdd test`, `pdd lint`, `pdd simulate` and `pdd approve`. Install the skills with `npx skills add promptdriven/pdd` (add `-g` for all your projects), and set up a repo with the `pdd-setup` skill in your agent. For simulations that your agent drives, use the Try tools in `pdd mcp`. Then use a PDD skill: `pdd-feature`, `pdd-bug`, `pdd-small-change`, `pdd-product` or `pdd-prompting`. Call a skill with `$pdd-feature` in Codex or `/pdd-feature` in Claude Code (or ask for it by name). See [Install](USAGE.md#2-install). @@ -188,6 +188,8 @@ Autopilot opens no chat and needs no Herdr. | `pdd autopilot audit RUN PR` | Audit a confirmed automatic merge once with a fresh configured agent. Save OK, CONCERN or BAD and the separate revert recommendation with the run. Post the evidence once on the issue. BAD opens a revert PR only when recommended; otherwise it keeps the merge and reopens the issue with the missing parts. One decision alert states the recommendation and choices. Unknown external outcomes require inspection before any retry. | | `pdd autopilot check-base RUN PR` | Check the saved automatic base, PR target, current default branch and newest release before a merge or after it. This command reads only. | | `pdd autopilot status [--all] [--json]` | Show this machine's Autopilot for this repo: enabled or disabled, the timer, the next tick, the jobs, an [alert](#alerts) that was not delivered and the last tick. `--all` lists every repository with Autopilot on this machine, from any folder. `--json` prints the [local cost report](#local-issue-costs) | +| `pdd autopilot logs [ISSUE] [--follow\|-f] [--lines N] [--json]` | List current headless Autopilot workers for this repository with stage, owned process state, suite queue position, blockers, last activity and saved log or evidence paths, or inspect and follow one worker live (`--follow` / `-f` detaches on Ctrl-C without stopping the worker or changing `observe` mode). Read-only; no GitHub call or approval effect | +| `pdd autopilot logs --issue N [--follow\|-f] [--lines N] [--json]` | Select one worker explicitly with `--issue N` (issue number, `#N`, `owner/repo#N`, or GitHub issue URL) to inspect saved progress or stream live updates | | `pdd autopilot add N...` | Create the `pdd:autopilot` label when it is missing and add it to each named issue of this repository. Use it to choose the issues that Autopilot may take | | `pdd autopilot release ISSUE` | Release this machine's claim and remove `pdd:working` and `pdd:stuck`; keep the run folder, branch and PRs | | `pdd autopilot regressions [--json] [--file PATH]` | Read core merge history and GitHub CI, parent checks, revert, reopen and issue-link evidence. Classify each merge as ok, suspect or proven; count distinct proven PRs per UTC evidence day. Issue-body attribution uses issue creation time even if added in a later edit; these buckets require a consumer confirmation policy before use as daily scorecard counts. At most 100 GitHub requests per scan; rate exhaustion or Retry-After stops further reads, preserving collected evidence and marking missing evidence incomplete. --json prints structured results; --file exclusively creates a local report without overwriting existing files. No GitHub writes or reverts. Incomplete reads exit 1; complete scans exit 0 even when they detect regressions | @@ -200,7 +202,7 @@ Autopilot opens no chat and needs no Herdr. | `pdd autopilot alerts clear [--destination autopilot\|infrastructure]` | Remove the alert destination from this machine | | `pdd autopilot alert --issue N --kind usage-limit\|resource\|interpreter\|interpreter-access\|access\|decision\|stuck\|test-suite\|long-running\|recovered --input - [--update]` | Record one alert and send it to this machine's destination. See [Alerts](#alerts) | -Outside a Git repository, `start`, `stop`, `status`, `add`, `off`, `observe`, +Outside a Git repository, `start`, `stop`, `status`, `logs`, `add`, `off`, `observe`, `auto`, `trust` and `untrust` stop with exit code 1 and say: `This folder is not a Git repository. cd into the repo you want Autopilot to work on, then run the command again.` `status --all` works from any folder. @@ -273,6 +275,20 @@ unreadable`. One bad line changes no other line. Without saved state it prints `No Autopilot on this machine.` The local cost lines come last. It makes no GitHub call. +`pdd autopilot logs` inspects headless Autopilot workers from local state files +without knowing internal state folders or touching running jobs. With no issue +argument, it prints the effective mode (`observe`, `auto` or `off`), active +workers sorted by issue number (stage, owned process state, suite queue position, +blockers, last activity, and saved log and evidence paths), recent finished +workers, and the follow command. With `ISSUE` or `--issue N`, it prints the +worker header and the last `--lines N` (default 40, maximum 5000) human-readable +progress lines formatted from Codex, Claude, Gemini/agy or test-suite logs, with +secrets redacted. It distinguishes waiting in the shared test-suite queue from a +running full suite, a repair pass, and a stale suite receipt. Add `--follow` or +`-f` to stream live worker and test-suite progress and stage changes; pressing +Ctrl-C detaches the viewer without stopping the worker or changing `observe` +mode. Add `--json` for structured snapshot output (`pdd.autopilot-logs.v1`). + A machine state that ran the full engine moves to the core engine at its next tick. A start runs a tick, so a start moves it too. No new work starts before the move is complete. While old work is busy (a live run with a merged PR, or a working @@ -817,7 +833,7 @@ The agent runs these from the run's worktree. pdd finds the run from that folder | Command | What it does | |---|---| -| `pdd`, `pdd --help`, `pdd -h`, `pdd help` | Show the commands and the full paths of the installed Prompting guide and RUNBOOK | +| `pdd`, `pdd --help`, `pdd -h`, `pdd help` | Show the grouped command overview, quick-start examples, focused-help hint (`pdd --help`), and the full paths of the installed Prompting guide and RUNBOOK | | `pdd help prompting` | Show how to write a prompt, a Story and its test, which commands check them, and the full paths of the Prompting guide and RUNBOOK | | `pdd --version` | Print the version, `0.1.35`. When the PDD skills that your agent finds are older, also print the update command on stderr | | `pdd -V` | Same version and local diagnostics as `pdd --version` | diff --git a/prompts/cli/autopilot-logs.prompt.md b/prompts/cli/autopilot-logs.prompt.md new file mode 100644 index 0000000000..2c9a9ed579 --- /dev/null +++ b/prompts/cli/autopilot-logs.prompt.md @@ -0,0 +1,142 @@ +# Autopilot worker logs + +Own `src/autopilot-logs.mjs`. Export `runAutopilotLogs(input, ports)`, +`inspectAutopilotWorkers(input, ports)` and `formatWorkerLogLine(line)`. +Give a person a supported read-only way to list headless Autopilot workers, +inspect a worker's stage, process state, queue position, blockers and saved +evidence, and follow live worker output from the terminal without knowing +internal state folders or touching running jobs. + +## Safety and observe mode + +Every operation in this module is strictly read-only: + +- Never write, create, rename or delete files in the repository, Autopilot + state folders, validation folders, or user configuration. +- Never approve gates, merge pull requests, claim or release issues, wake + scheduler ticks, or call GitHub (`gh`). Viewing preserves `observe`, `auto` + and `off` modes unchanged. +- Check process liveness read-only (`kill(pid, 0)` and `ps` command match on + the job's `.spec.json` token when present). Never send `SIGTERM`, `SIGKILL`, + `SIGINT` or any stopping signal to a worker or test-suite process. +- Redact credentials and tokens in every displayed log line, error note and + path summary with `redactSecrets`. Strip terminal escape sequences so output + is safe in both interactive terminals and redirected files. + +## CLI contract + +`runAutopilotLogs({cwd, env, issue, follow, lines, json}, ports)` accepts: + +- `issue`: optional issue selector from the positional `[ISSUE]` operand or + `--issue N` (`17`, `#17`, `owner/repo#17`, or a GitHub issue URL). Passing + two different selectors, a blank/invalid selector, or `--follow` together + with `--json` returns exit code `2` with one clear usage message before state + inspection. +- `follow`: Boolean from `--follow` or `-f`. Requires a selected issue; calling + `--follow` with no issue returns exit code `2` explaining how to pass an + issue (`pdd autopilot logs ISSUE --follow`). +- `lines`: positive integer tail count from `--lines N` (default `40`, range + `1` to `5000`). +- `json`: Boolean from `--json` for structured machine-readable inspection. + +Injectable `ports` provide `fs`, `git(args, {cwd, env})`, `now()`, `stateRoot`, +`coreRoot`, `isProcessAlive(pid, token)`, `readSuite({cwd, env})`, `stdout`, +`signal`, `pollMs` (default `250`) and `sleep(ms)`. Resolve the repository root +with `git rev-parse --show-toplevel` under `LC_ALL=C` and `LANG=C`. Outside a +Git repository, return `{exitCode: 1, message: "This folder is not a Git repository. cd into the repo you want Autopilot to work on, then run pdd autopilot logs again."}`. +Derive the state key from `sha256(gitToplevel).slice(0, 20)` under `stateRoot` +(default `/.local/state/pdd/autopilot`), reading `.json`, +`-core/core.json`, `-core/jobs/*.json`, +`-core/intake/jobs/*.json`, `-core/logs/*` and +`-core/history.jsonl` plus the checkout's `pdd.json` mode. + +## Worker inspection and stage distinction + +`inspectAutopilotWorkers` classifies each active job in `-core/jobs` (and +any active read-only intake card job in `-core/intake/jobs`) and recent +completed history rows so a person can immediately tell live progress from +waiting or stale state: + +1. **Stage**: + - `build` for initial headless implementation; + - `repair` (with repair count and PR number when present) so repair passes + stand out clearly from initial builds and checks; + - `conflict` for base-branch conflict resolution; + - `pr-check` on `phase === "pr"`, detailing `review`, `suite`, `vectors`, + `runtime` check wait, or `merge-lane` state; + - `ending` or `release-pending` when finishing cleanup; + - `intake` for read-only intake card workers; + - `finished` when selected by issue from `history.jsonl` after `jobs/N.json` + has already completed. +2. **Owned process state**: + - Inspect each sub-process handle (`job.agent`, `job.review?.agent`, + `job.suite?.agent`, `job.vectors?.agent`, `job.runtimeWait?.agent`) and + its `.exit.json` receipt. + - Report `running (pid N)` when `isProcessAlive(pid, token)` is true; + - Report `exited (code C)` when `.exit.json` is recorded while the job waits + for the next scheduler tick; + - Report `stale (pid N not running, no exit receipt)` when the recorded PID + is gone without `.exit.json`. +3. **Suite queue waiting versus live test execution versus stale receipts**: + - Query `readSuiteProgress({cwd: suiteCwd, env})` for PR suite checks. + - Report `queued (position P in shared test-suite queue)` when `state` is + `waiting`; + - Report `running full test suite` (with live validation `logPath`, child + PID and pass/fail counts when available) when `state` is `running`; + - Report `stale suite receipt` when a saved suite record has a dead runner + reason (`recorder_not_running` / ended before reporting) or belongs to an + older commit than `job.head`. +4. **Blockers and last activity**: + - Surface blockers plainly: shared test-suite queue wait, merge-lane wait + (naming the holder PR when present), PDD interpreter maintenance wait, AI + quota or login-pool cooldown, machine pause, GitHub Actions outage, safety + circuit-breaker downgrade, hung commands recorded in `.hangs.json`, and + `job.lastError`. + - Compute `lastActivityAt` from the newest `mtimeMs` across active worker + and suite validation logs (falling back to `watch.at` or `started`) and + show both relative age and UTC timestamp. + - Collect saved log paths and `-evidence-.json` files for the + issue so evidence is directly linked. + +## Output modes and live following + +- **No issue selected (`pdd autopilot logs`)**: + Print repository and effective Autopilot mode (noting read-only viewer safety + when in `observe` mode), active machine-wide blockers if any, a clear list of + current workers sorted by issue number (showing issue, stage, process/queue + status, last activity, blockers and log path), recent finished workers when + present, and the exact command `pdd autopilot logs --follow` to + attach read-only to a worker. When no workers or history exist yet, exit `0` + with a plain empty-state message. +- **Selected issue snapshot (`pdd autopilot logs [--lines N]`)**: + Print the worker summary header (issue, mode, stage, owned process state, + suite/queue state, blockers, last activity, saved log and evidence paths), + followed by the last `N` human-readable lines formatted by + `formatWorkerLogLine` from the active log stream(s). If the issue has no + active worker and no saved history or log in this repository, return exit + code `1` with a hint to run `pdd autopilot logs`. +- **Readable progress lines (`formatWorkerLogLine`)**: + Convert Codex `--json` JSONL, Claude `stream-json`, and Gemini/Agy + `stream-json` records into concise human-readable progress lines (`[session]`, + `[run]`, `[cmd]`, `[tool]`, `[edit]`, `[agent]`, `[turn]`, `[result]`, + `[error]`), skipping noisy token-accounting heartbeats while keeping plain + test/command text lines intact and redacted. +- **Live follow (`--follow` / `-f`)**: + Stream the worker header, initial tail lines, and newly appended complete log + lines to `stdout` as the worker runs, emitting `[stage]` notices whenever the + worker transitions across stages or opens a new log (including live suite + validation logs). Stop cleanly with exit code `0` when the job finishes (or + has no live process while the Autopilot timer is off) or when `signal` / + `SIGINT` / `SIGTERM` detaches the viewer. Detaching prints a confirmation + that the background worker continues untouched. + +## Dependencies + +- [Autopilot core](autopilot-core.prompt.md): required context for `jobs/N.json`, + `core.json`, `logs/` and `history.jsonl` state shapes. +- [Shared full-suite queue](test-suite-queue.prompt.md): required context for + read-only `readSuiteProgress` queue and validation-log inspection. +- [Repository Autopilot settings](autopilot.prompt.md): required context for + `pdd.json` mode display and CLI subcommand routing. +- [Secret redaction](secret-redaction.prompt.md): required for redacting + displayed log lines and diagnostics. diff --git a/prompts/cli/autopilot.prompt.md b/prompts/cli/autopilot.prompt.md index 66047c3c32..2fa997c642 100644 --- a/prompts/cli/autopilot.prompt.md +++ b/prompts/cli/autopilot.prompt.md @@ -29,6 +29,9 @@ unknown Autopilot keys. ## Dependencies - [GitHub calls](github-calls.prompt.md#budget): required generation and verification context for reading `autopilot.github` with `githubBudgetSettings`. +- [Autopilot worker logs](autopilot-logs.prompt.md): required native generation and verification context for routing the read-only `logs` CLI subcommand (`runAutopilotSubcommand("logs", input, ports)`) to `runAutopilotLogs` without modifying `pdd.json` or `runAutopilot`. + +`src/autopilot.mjs` also exports `runAutopilotSubcommand(subcommand, input, ports)` as the CLI subcommand router for `pdd autopilot logs`, dynamically delegating `subcommand === "logs"` to `runAutopilotLogs(input, ports)` in `src/autopilot-logs.mjs` and returning `{exitCode: 2, message: "Unsupported Autopilot subcommand. Use pdd autopilot --help."}` for unknown subcommands. `runAutopilot` keeps its existing inputs, outputs and Runtime interface unchanged. Actions outside the stated set, invalid mode operands and missing or blank names return exit code 2 with a clear message and no save. Trust takes one or more nonblank names; untrust takes exactly one; isTrusted takes one nonblank author. Omitted interactive and inRepo default false. Successful actions return exit code 0, effective mode, explicit names, trusted false except for isTrusted, and a human-readable message (empty for outside-repository setup). Preserve unrelated top-level and Autopilot keys when saving; absent mode and trust read as off and empty. Failed writes return nonzero with a clear error and leave the file unchanged. @@ -335,7 +338,7 @@ Actions outside the stated set, invalid mode operands and missing or blank names "max_model_calls": 6 }, "conventions": [], - "prose_sha256":"ff8929dbe22ab5e36cfbadfaaa4cc7d970a6eaf0fefdb69979443fa9d644178a" + "prose_sha256":"551a26c7f6f78a1aefe2e131baa14e422a8f865144d3c6c5413d6ea0f2b83fa9" } ``` diff --git a/prompts/cli/command-catalog.prompt.md b/prompts/cli/command-catalog.prompt.md index f6be6f4b00..387ee973b6 100644 --- a/prompts/cli/command-catalog.prompt.md +++ b/prompts/cli/command-catalog.prompt.md @@ -52,9 +52,10 @@ Help forms and completion name only the `NAMES` words. Catalog four local routes before the product routes: `autopilot.start` (`autopilot start`, local `autopilot-start`, no operands, optional text `--runs`, `--checks`, `--label`, `--share`, `--agent` with completion choices `codex`, `claude`, `gemini` and `agy`, hidden text `--pool`, plus value options `--engine`, `--mode`, `--report`, `--decisions`, `--intake` and `--auto-update`); `autopilot.stop` (matching prefix/disposition, no operands/options); `autopilot.status` (matching prefix/disposition, no operands, optional flag --all); `autopilot.add` (`autopilot add`, local `autopilot-add`, required repeated issue operands). Forms and descriptions: -- `pdd autopilot start [--runs N] [--checks N] [--label NAME] [--mode auto|observe|off] [--report file|draft|off] [--decisions ask|decide] [--intake off|shadow|active] [--share PERCENT] [--agent codex|claude|gemini|agy] [--auto-update release|main|off]`: Start this repo with headless agent jobs (the core engine): check now and every 10 minutes, with no AI call on empty ticks. Autopilot works on issues with an opt-in label (--label NAME or autopilot.label in pdd.json) or on vetted ready cards when --intake active is enabled; without --intake active, a start with no label starts nothing. --runs and --checks override machine-sized run and heavy-check limits; --label (text), --mode (choice auto, observe or off) and --report (choice file, draft or off) save this machine's opt-in label, mode and report mode for this repo, over pdd.json (--mode observe runs every check but never merges; --report draft, the default, keeps problem reports on this machine); --decisions (choice ask or decide) saves this machine's decision mode (ask asks a person only for a big decision; decide, the default, never asks); --intake (choice off, shadow or active) saves this machine's intake mode (shadow writes local intake cards that never change what starts; active selects ready cards, refines improve cards via read-only repo inspection and groups related small work; off is the default). --share (text) saves the percent of this machine's CPU and memory that Autopilot may use (1-100, default 50; it sets the automatic slots, the room check and the timer's memory limit). --agent saves or replaces this machine's agent and sign-in profile. --auto-update (choice release, main or off; default release) saves this machine's between-tick self-update mode for a user-owned global pdd install and its skills when no job is publishing or merging (#2710). A machine that ran the removed full engine moves to the core engine at its next tick. The route also accepts `--engine` (choice core or full) and hidden `--pool` (text) and shows neither in public help or completion. +- `pdd autopilot start [--runs N] [--checks N] [--label NAME] [--mode auto|observe|off] [--report file|draft|off] [--decisions ask|decide] [--intake off|shadow|active] [--share PERCENT] [--agent codex|claude|gemini|agy] [--auto-update release|main|off]`: Start this repo with headless agent jobs (the core engine): check now and every 10 minutes, with no AI call on empty ticks. Autopilot works on issues with an opt-in label (--label NAME or autopilot.label in pdd.json) or on vetted ready cards when --intake active is enabled; without --intake active, a start with no label starts nothing. --runs and --checks override machine-sized run and heavy-check limits; --label (text), --mode (choice auto, observe or off) and --report (choice file, draft or off) save this machine's opt-in label, mode and report mode for this repo, over pdd.json (--mode observe runs every check but never merges; --report draft, the default, keeps problem reports on this machine); --decisions (choice ask or decide) saves this machine's decision mode (ask asks a person only for a big decision; decide, the default, never asks); --intake (choice off, shadow or active) saves this machine's intake mode (shadow writes local intake cards that never change what starts; active selects ready cards, refines improve cards via read-only repo inspection and groups related small work; off is the default). --share (text) saves the percent of this machine's CPU and memory that Autopilot may use (1-100, default 50; it sets the automatic slots, the room check and the timer's memory limit). --agent saves or replaces this machine's agent and sign-in profile. --auto-update (choice release, main or off; default release) saves this machine's between-tick self-update mode for a user-owned global pdd install and its skills when no job is publishing or merging (#2710). The route also accepts `--engine` (choice core or full) and hidden `--pool` (text) and shows neither in public help or completion. - `pdd autopilot stop`: Stop this machine's timer; let the current agent step finish. - `pdd autopilot status [--all] [--json]`: Show this machine's repo, folder, agent and next tick; --all lists every repository with Autopilot on this machine, from any folder. +- `pdd autopilot logs [ISSUE] [--follow|-f] [--lines N] [--json]` and `pdd autopilot logs --issue N [--follow|-f] [--lines N] [--json]` (route `autopilot.logs`, prefix `autopilot logs`, local `autopilot-logs`, optional issue operand `issue`, text option `--issue`, Boolean flags `--follow`, `-f` and `--json`, integer `--lines` from 1 to 5000): List current headless Autopilot workers for this repository with stage, owned process state, suite queue position, blockers and saved log/evidence paths, or inspect and follow one issue worker's live readable progress (`--follow` / `-f` streams live updates and detaches cleanly on Ctrl-C without stopping the worker or changing `observe` mode). Read-only; no GitHub write or approval effect. - `pdd autopilot add N...`: Mark named old issues with pdd:autopilot so Autopilot may take them. - `pdd autopilot release ISSUE`: End this machine's idle run, release its claim, and remove pdd:working and pdd:stuck; keep the run folder, branch and PRs. A live worker, check, or another machine's claim prevents release. @@ -212,92 +213,15 @@ Catalog local disposition `accounts` ([Cloud accounts CLI](accounts-cli.prompt.m ## Help forms -`PUBLIC_COMMAND_MANIFEST` owns the forms, descriptions and order below. Each route owns entries whose form starts with its prefix. A help entry may include multiline example text. After each approval entry, include the shared policy's quoted-heredoc example with that route's command (`pdd approve PATH` or `pdd workflow approve N`). The example preserves person text without shell interpolation. Tell the caller to choose a delimiter absent from the text. Both approval descriptions state that --said - reads all UTF-8 stdin, including trailing newlines; simple literal --said text remains supported. A person terminal uses y/N; workflow y/N covers the ready gate and all selected drafts in one call. - -The ordered help-form list consists of the lines below in their displayed order, inserting the canonical form and description for catalog route `workflow.request-uptake` immediately after the ask line. That inserted entry uses that route's prefix followed by `REQUEST_ID --summary TEXT` and its catalog-owned agent uptake description; resolve it by stable id rather than a copied public verb. Each line is two spaces, the form, two spaces and its description. The [catalog](command-catalog.prompt.md) routes own them; the first words after `pdd` are the route prefix. This complete list, including the catalog-derived inserted entry, defines the manifest and root help. - - -```text - pdd product status [--json] Count Stories by part and slice from the product plan; no interpreter calls. - pdd product next Show ready planned runs and their start commands; no interpreter calls. - pdd product start RUN [--no-run] [--agent codex|claude|gemini|agy|ENTRY] Create or reuse the run issue and start a normal feature run; --no-run only prepares the issue; ENTRY is a name from ~/.config/pdd/agents.json. No interpreter calls. - pdd workflow run NAME ISSUE [--agent codex|claude|gemini|agy|ENTRY] [--base BRANCH] [--draft] Start the first area chat for a GitHub issue in Herdr and exit; ENTRY is a name from ~/.config/pdd/agents.json; --base selects an existing origin branch (default: repository default); --adopt-corpus FILE adopts exact unchanged approved content for a fresh replay-evidence-enabled workflow; pdd later pushes the issue branch and opens a real PR; --draft keeps this run's publications draft. - pdd workflow prove ISSUE --test COMMAND --expect TEXT [--timeout MIN] Run the supplied command on the fetched base branch merge-base and committed head, including when no eligible tests changed, with a limit per phase (default 10 minutes; --timeout sets 1 to 120); save a non-gating report that pull requests show as pdd's own result. - pdd workflow done STEP [--summary TEXT] [--skipped REASON] For the agent in a run worktree: record a step with pdd's own latest pdd test, pdd lint and prove results (the summary is an agent note) and print what to do next; --skipped records that the step was skipped, and why. - pdd workflow evidence ISSUE --summary FILE Record source-verified saved check JSON without rerunning steps, gates or publication. - pdd workflow evidence-associate ISSUE --workspace PATH --stage current|pr1|before [--commit SHA] --test PATH... Register this run's evidence workspace, stage and selected tests; before needs the commit of an earlier checked source; no checks or workflow progress. - pdd workflow ask QUESTION For the agent in a run worktree: show the person that the chat waits for their answer. - pdd workflow approve [ISSUE] [--said WORDS] [--draft] Use --said - with the shared quoted-heredoc template to record chat words for the gate and all its drafts, or use terminal y/N; --draft requests draft publication at the current unpublished gate; strict mode requires a person terminal. - pdd workflow changes ISSUE TEXT Send a change request to the same area chat; the gate stays open. - pdd workflow cancel ISSUE Cancel the run and close its Herdr tabs; keep the worktree and branch. - pdd workflow status [ISSUE] [--all] [--cancelled] [--json] Show this repo's runs, or one run with its area, gate, chat and PRs. --all (or outside a repo): every run on this machine, people-waiting first. - pdd workflow view ISSUE Read-only review of gates, approvals, files, PRs and Simulator links; never start or resume a chat. - pdd workflow open ISSUE [AREA] [--new] Focus or resume a saved area chat; --new replaces the current session while keeping the run and approvals. - pdd Show local commands. - pdd --help Show local commands. - pdd -h Show local commands. - pdd help Show local commands. - pdd help prompting Show how to write prompts, Stories and tests, and where the guide is. - pdd --version Show this package version. - pdd -V Show this package version. - pdd -VV Show this package version, interpreter build and supported formats; unavailable metadata is unknown. - pdd completion bash|zsh Print local shell completion. - pdd workflow list [--json] List the bundled workflows with their areas and gates. - pdd test [PATH|STORY...] [--lf] [--cache-clear] [--json] [--details] [--timeout MIN] [--max-calls N] Check stories on the PDD interpreter with your gh login: reuses unchanged passing Stories from .pdd/cache/test/; --lf selects previous failures in scope or uses the normal selection when none match, --cache-clear clears the cache and sends the selected Stories again (the interpreter may reuse saved answers); sends selected PATH or STORY dependencies (every Story when you name none), waits for every check (no default limit in any shell; --timeout MIN sets the limit) with a progress line every 30 s, then prints one table with report links. Defaults to 12 calls per step, at least 18 and at most 1000; --max-calls accepts 1 to 1000. - pdd test [PATH|STORY...] [--max-total-calls N] [--no-restart-replacement] [--max-calls N] [--timeout MIN] [--json] Cap logical interpreter calls across all selected Stories and any permitted service-restarted replacement (--max-total-calls 1..999999), or decline automatic service-restarted replacement (--no-restart-replacement; saved across --read and --retry). Also accepted with --affected and --journeys. - pdd test --read [BATCH|CALL_ID] [--json] [--timeout MIN] Read saved results; a normal Check held for lint may continue its original checks. Other reads send no work. - pdd test --retry BATCH [--json] [--details] [--timeout MIN] Retry only confirmed unstarted checks from a saved batch, with the same source and call caps; preserve completed and uncertain runs. - pdd test --files [STORY...] [--app-map PATH] List the exact selected upload files and byte sizes; no network. --app-map selects the Simulator's app map. - pdd test --screen URL --drawing PATH [--look] [--json] Compare a real page with its drawing at the drawing viewport in installed headless Chrome/Chromium (--look also checks main colors, painted boxes and spacing within tolerance); no AI or interpreter calls. - pdd lint [STORY...] [--json] [--timeout MIN] [--max-calls N] Print local SVG layout warnings, then the PDD interpreter lint (0 AI calls) on selected Stories and their dependencies; sends no checks. - pdd lint --local [STORY...] [--json] Check linked SVG layout parts locally with warning diagnostics and 0 AI/network calls. - pdd files [--json] List prompts, Stories, tests and refusal reasons; no network calls. - pdd owner PATH... [--json] Show which prompt owns each file, from pdd-bindings.json, Generated from headers and prompt opening sentences; reads local files only. - pdd approve PROMPT [--said WORDS] Approve one prompt with the person's chat words in easy mode, or show its text changes and ask terminal y/N; strict mode requires a person terminal. - pdd simulate [STORY] [--max-calls N] [--tab call|screen|terminal|world] [--app-map PATH] [--new] [--no-open] [--no-wait] [--agent NAME] Open the Story in the PDD Simulator: make a link on the PDD interpreter with your gh login and open it in your browser; it ends in 24 hours. Short form: pdd sim. A new simulation defaults to 400 calls; --max-calls accepts 1 to 1000. With terminal stdout or explicit --agent, it stays running to connect your own agent; otherwise it reads saved cases once and returns. --agent selects a configured name or a default Codex, Claude or Gemini; --no-wait skips the bridge. In a terminal it adds each test saved in the Simulator to the story's test file. - pdd simulate [STORY] --cli [--shell] [--max-calls N] [--new] Run your program in your terminal through a Simulator session; prints a PATH line, or opens a shell with --shell. - pdd simulate [STORY] --serve [PORT] [--max-calls N] [--new] Serve real HTTP requests through your Simulator session on localhost (default port 8080). - pdd simulate --save-last Save the last terminal command and its output in the original Story test file. - pdd simulate --stop [STORY] Stop the open Simulator link of a story. - pdd jobs List active and waiting interpreter jobs on this machine without contacting the interpreter. - pdd contracts List shared records, their users and Stories stale since their last check; local working files only. - pdd contracts sync [--write] Show proposed changes for moving schema copies to references; apply only with --write. No interpreter calls. - pdd mcp Serve the current repository’s Try tools over stdio MCP. - pdd autopilot off Set the repository Autopilot mode to off. - pdd autopilot observe Set the repository Autopilot mode to observe. - pdd autopilot auto Set the repository Autopilot mode to auto. - pdd autopilot trust NAME... Add explicitly trusted GitHub names. - pdd autopilot untrust NAME Remove an explicitly trusted GitHub name. - pdd accounts [--json] List enrolled and shared Cloud accounts, active selection, 5-hour and weekly usage windows, refresh status, and pending invites. - pdd accounts list [--json] List enrolled and shared Cloud accounts, active selection, 5-hour and weekly usage windows, refresh status, and pending invites. - pdd accounts status [--json] Show Cloud account enrollment, isolated Codex home, shell auto-switch status, active leases, and token refresh/expiry health. - pdd accounts add [--provider codex|claude] [--label NAME] [--loop] [--device-auth] [--with USER|ORG/TEAM[,...]] Sign in inside an isolated folder, upload the encrypted bundle to PDD Cloud, materialize in PDD's isolated Codex home or Claude settings, and optionally enroll in a loop or share immediately. - pdd accounts import [--provider codex|claude] [--from PATH] [--label NAME] [--with USER|ORG/TEAM[,...]] Import a local or external Codex auth.json or Claude token into PDD Cloud, materialize in PDD's isolated Codex home or Claude settings, and optionally share immediately. - pdd accounts use LABEL Pin and materialize LABEL in PDD's isolated Codex home or ~/.claude/settings.json. - pdd accounts next [--provider codex|claude] Skip the active login and switch to the next ready account sorted by soonest weekly reset. - pdd accounts sync [--provider codex|claude] [--quiet] [--timeout-ms MS] Refresh the PDD-managed login from PDD Cloud when near expiry or at 100% usage; no-op when cached and healthy; fail-open when offline. - pdd accounts auto on|off|status Manage the opt-in fail-open shell wrapper in ~/.zshrc, ~/.bashrc, and ~/.config/fish/config.fish for plain terminal codex and claude launches (off by default). - pdd accounts pause LABEL Pause automatic leasing for LABEL. - pdd accounts unpause LABEL Resume automatic leasing for LABEL. - pdd accounts share LABEL --with USER|ORG/TEAM[,...] Share LABEL with GitHub users, organization teams, or @ORG targets without exposing raw credentials. - pdd accounts share --all [--provider codex|claude] --with USER|ORG/TEAM[,...] Share all owned Cloud accounts (optionally filtered by provider) with GitHub users, organization teams, or @ORG targets. - pdd accounts accept INVITE Accept a pending Cloud account share invite. - pdd accounts unshare LABEL --user USER Revoke shared access to LABEL for USER. - pdd accounts unshare [LABEL] [--all] [--provider codex|claude] [--user USER] [--with USER|ORG/TEAM[,...]] Revoke shared access for users, organization teams, or @ORG targets across LABEL or all owned accounts. - pdd accounts leave LABEL Leave a shared Cloud account. - pdd accounts remove LABEL Delete LABEL from PDD Cloud and revoke active leases. - pdd accounts log LABEL [--json] Show the lease and sharing audit log for LABEL. - pdd setup [--yes] Install the PDD skills for Codex and Claude if they are missing, and add the short PDD block to CLAUDE.md, else AGENTS.md. Offer detected Codex, Claude Code and Gemini MCP registrations after showing exact config changes and one y/N question. Offer Autopilot settings in a Git repository with a terminal; keep an existing mode on repeat setup. Without a terminal or with --yes, use safe defaults without questions. - pdd upgrade [--main] Upgrade a user-owned global pdd installation from the latest GitHub release (or pinned main commit with --main) and refresh installed user PDD skills. -``` - +`PUBLIC_COMMAND_MANIFEST` owns every supported command form and its detailed command-specific description. Each route owns entries whose form starts with its prefix, ordered by human-first command groups: Core PDD workflow (`setup`, `check`, `lint`, `try`, `approve`, `files`, `owner`, `contracts`, `contracts.sync`, `jobs`, `mcp`, `upgrade`), Cloud accounts (`accounts` and its subcommands), Workflows & product (`product.*`, `workflow.list`, `workflow.run`, `workflow.status`, `workflow.view`, `workflow.card`, `workflow.approve`, `workflow.changes`, `workflow.open`, `workflow.prove`, `workflow.suite`, `workflow.done`, `workflow.publish`, `workflow.ask`, `workflow.request-uptake`, `workflow.resend`, `workflow.park`, `workflow.yield`, `workflow.tidy`, `workflow.cancel`, `workflow.cost`, `workflow.evidence`, `workflow.evidence-associate`, `graph`, `dependencies.*`), Autopilot (`autopilot.doctor`, `autopilot.start`, `autopilot.status`, `autopilot.logs`, `autopilot.stop`, `autopilot.observe`, `autopilot.auto`, `autopilot.off`, `autopilot.trust`, `autopilot.untrust`, `autopilot.add`, `autopilot.release`, `autopilot.intake`, `autopilot.report`, `autopilot.regressions`, `autopilot.alerts`, `autopilot.alert`, `autopilot.audit`, `autopilot.check-base`), and Metrics, shell & help (`metrics.*`, `completion`, `help`, `version`, `version.detailed`). After each approval entry in `PUBLIC_COMMAND_MANIFEST` (`pdd approve` and `pdd workflow approve`), include the shared policy's quoted-heredoc example with that route's command (`pdd approve PATH` or `pdd workflow approve N`) so command-specific help (`pdd approve --help`, `pdd workflow --help`, `pdd workflow approve --help`) shows the complete approval rules and heredoc template without duplicating them on the root `--help` page. The example preserves person text without shell interpolation. Tell the caller to choose a delimiter absent from the text. Both approval descriptions state that `--said -` reads all UTF-8 stdin, including trailing newlines; simple literal `--said` text remains supported. A person terminal uses y/N; workflow y/N covers the ready gate and all selected drafts in one call. +Root help (`pdd`, `pdd --help`, `pdd -h`, `pdd -help`, `pdd help`) uses concise grouped summaries (`PUBLIC_HELP_TEXT.groups`) preceded by `PUBLIC_HELP_TEXT.usageLine` (`Usage: pdd [options]`) and `PUBLIC_HELP_TEXT.quickStartLines` (practical starting examples using `pdd setup`, `pdd `, `pdd ` and `pdd help prompting`) and followed by `PUBLIC_HELP_TEXT.focusedHelpLines` (`Focused help: run pdd --help ...`), `learnLines` and `closingLines`. Keep every line in `usageLine`, `quickStartLines`, `groups` and `focusedHelpLines` within 80 columns, derive every `test`, `lint`, `simulate`, `run` and `requestUptake` command word from `NAMES`, and place `workflow.request-uptake` (`pdd workflow REQUEST_ID --summary TEXT`) immediately after `pdd workflow ask` (which follows `pdd workflow done` and `pdd workflow publish`). Command-specific and family-scoped help (`pdd --help`, such as `pdd test --help`, `pdd workflow --help`, `pdd autopilot --help`, `pdd accounts --help`) renders the complete `PUBLIC_COMMAND_MANIFEST` entries matching that prefix. The `help` route owns the forms `pdd`, `pdd --help`, `pdd -h`, `pdd help` and `pdd help prompting`, and lists one help topic: `prompting`. A topic is no route prefix, so `prompting` alone is no command. The [Learn PDD](#learn-pdd) section owns the topic's text; the [parser](argument-parser.prompt.md#help-topics) owns its syntax. ## Help text -Export the frozen `PUBLIC_HELP_TEXT` object with `heading`, `closingLines`, `learnLines` and `promptingLines`. The heading is exactly `PDD: prompt-driven development for your coding agent.` The three line arrays contain the exact ordered lines in the closing block below, the Learn PDD block and the prompting topic block respectively. Keep `PACKAGE_ROOT` as a template marker in `learnLines`; the CLI substitutes its absolute package root. The topic uses the last two learn lines after its prompting lines. This catalog owns every help text template; the dispatcher owns composition and path substitution. +Export the frozen `PUBLIC_HELP_TEXT` object with `heading`, `usageLine`, `quickStartLines`, `groups`, `focusedHelpLines`, `closingLines`, `learnLines` and `promptingLines`. The heading is exactly `PDD: prompt-driven development for your coding agent.` `groups` is a frozen array of `{title, lines}` objects for the five command groups (`Core PDD workflow`, `Cloud accounts (pdd accounts --help)`, `Workflows & product (pdd workflow --help, pdd product --help)`, `Autopilot (pdd autopilot --help)`, and `Metrics, shell & help (pdd metrics --help)`), where each line begins with two spaces and `pdd ` and stays within 80 columns. Keep `PACKAGE_ROOT` as a template marker in `learnLines`; the CLI substitutes its absolute package root. The topic uses the last two learn lines after its prompting lines. This catalog owns every help text template; the dispatcher owns composition and path substitution. The closing lines are exactly: diff --git a/prompts/cli/pdd-cli.prompt.md b/prompts/cli/pdd-cli.prompt.md index 05cf0fc048..dc51aae9df 100644 --- a/prompts/cli/pdd-cli.prompt.md +++ b/prompts/cli/pdd-cli.prompt.md @@ -156,7 +156,8 @@ finite safe failure and exits 1. Do not load the launcher or remote settings. - [Autopilot launcher](autopilot-launcher.prompt.md): required native generation/verification context for launch, tick, stop, status and backlog selection. These native effects are not bound by the existing syntax transport. Launcher ports are separate from the settings module's `autopilotPorts`. -- [Autopilot settings](autopilot.prompt.md): required authoring, generation, runtime, verification and testing context for setup and Autopilot dispatch. +- [Autopilot settings](autopilot.prompt.md): required authoring, generation, runtime, verification and testing context for setup, Autopilot settings and `autopilot logs` subcommand dispatch. +- [Autopilot worker logs](autopilot-logs.prompt.md): required native generation, verification and testing context for read-only worker listing and live log following (`pdd autopilot logs`). - [Autopilot settings on GitHub](autopilot-github.prompt.md): required generation, verification and testing context for the GitHub copy of the settings after the mode, trust, untrust, start and status commands. - [Autopilot alerts](autopilot-alerts.prompt.md): required native generation, verification and testing context for alert and destination dispatch. @@ -185,6 +186,8 @@ operands in issues. Use the same reply and stream rules; no remote settings warn For catalog dispositions `autopilot-start`, `autopilot-stop`, `autopilot-status`, `autopilot-add`, `autopilot-release` and `autopilot-check-base`, dynamically import [Autopilot launcher](autopilot-launcher.prompt.md). Call its module function `runAutopilotLauncher({command, issues, runs, checks, share, all, cwd, packageRoot, env}, ports)`: command is the disposition suffix, issues are the operands unchanged, runs is the --runs text when present, checks is the --checks text when present, share is the --share text when present (#3231), and all is true only for `autopilot status --all`. Tests may inject `dependencies.autopilotLauncher` and `autopilotLauncherPorts`. Print its {exitCode,message} once, stdout on zero and stderr otherwise, and return that code. After `autopilot-start` or `autopilot-status` without `--all` with exit 0, call [Autopilot settings on GitHub](autopilot-github.prompt.md) `checkAutopilotSettings({cwd}, autopilotGithubPorts)` and print its nonempty warning as one stderr line; a throw prints nothing. This check never writes, never changes the exit code, and start never writes `pdd.json` to GitHub. Invalid replies or exceptions produce one finite diagnostic and exit 1 without retry. Help and parsing do not load the launcher or check sign-ins. Existing admission applies only to setup and workflow-run; the launcher owns its own startup checks. +For catalog disposition `autopilot-logs`, skip post-upgrade skill sync and GitHub settings checks on this read-only local viewer. Resolve the optional issue selector from `operands[0]` or `--issue` (rejecting conflicting selectors or `--follow`/`-f` combined with `--json` with exit 2 and one finite stderr line before importing execution). Dynamically delegate to `dependencies.autopilotLogs.runAutopilotLogs` when injected, else [Autopilot settings](autopilot.prompt.md) `runAutopilotSubcommand("logs", {cwd, env, issue, follow, lines, json}, {stdout, stderr, ...autopilotLogsPorts})`. When `streamed` is true, output has already been streamed to `stdout`; otherwise print nonempty `message` once to `stdout` on exit 0 and `stderr` otherwise, and return `exitCode`. An unexpected exception prints one finite safe failure and returns 1. + For catalog dispositions `autopilot-alert` and `autopilot-alerts`, dynamically import [Autopilot alerts](autopilot-alerts.prompt.md) and call its module function `runAutopilotAlerts({action, cwd, env, text, issue, kind, update}, ports)`. The action is `alert` for `autopilot-alert`, else the `set`, `test` or `clear` operand. For `alert`, `--input` must be `-`; otherwise return 2 with one line before importing the module. Read all stdin as UTF-8 `text` for `alert` and `set` only, and not for `set` with `--token-command`; when `set` reads a terminal, first print one hint line to stderr. Pass `--issue`, `--kind` and the `--update` flag unchanged, pass `--destination` as `destination` only when given, and pass `--discord-channel` as `discordChannel` and `--token-command` as `tokenCommand` only when given. Either of these two options with `test` or `clear` returns 2 with one line. Tests may inject `dependencies.autopilotAlerts` and `autopilotAlertsPorts`. Print the reply once, stdout on zero and stderr otherwise. An invalid reply or exception prints one fixed line without the error text, so a webhook URL can never reach the output, and returns 1. ## Workflow dispatch @@ -217,7 +220,7 @@ authentication or runtime-client import belongs to these routes. ## Help contract -The required [catalog help text](command-catalog.prompt.md#help-text) owns the heading and closing lines. Root help (`pdd`, `pdd --help`, `pdd -h`, `pdd help`) prints the heading, one empty line, every complete [catalog help entry](command-catalog.prompt.md#help-forms) in order, one empty line, the learn line and the two path lines of [Learn PDD](command-catalog.prompt.md#learn-pdd), one empty line, then the closing lines. `pdd WORDS --help` prints the heading, one empty line, only the complete catalog help entries whose form starts with `pdd WORDS`, one empty line and the closing lines, with no learn or path lines. A [quiet name](argument-parser.prompt.md#quiet-names) gets the lines of its route: `pdd sim --help` gives the `pdd simulate` lines and `pdd workflow start --help` the `pdd workflow run` line. A removed name gets no help, also with a help flag or after `help`. Print each help entry exactly as the catalog lists it, including quoted heredocs, never a made-up `Usage:` line. +The required [catalog help text](command-catalog.prompt.md#help-text) owns the heading, usage line, quick-start lines, grouped summaries, focused-help note, Learn PDD lines and closing lines. Root help (`pdd`, `pdd --help`, `pdd -h`, `pdd -help`, `pdd help`) prints the heading, one empty line, `usageLine`, one empty line, `Quick start:` followed by `quickStartLines`, one empty line, each `{title, lines}` group from `PUBLIC_HELP_TEXT.groups` separated by one empty line, one empty line, `focusedHelpLines`, `learnLines` (with `PACKAGE_ROOT` substituted), one empty line, and `closingLines`. `pdd WORDS --help` prints the heading, one empty line, only the complete `PUBLIC_COMMAND_MANIFEST` entries whose form starts with `pdd WORDS` (`
`), one empty line and `closingLines`, with no learn or path lines. A [quiet name](argument-parser.prompt.md#quiet-names) gets the lines of its route: `pdd sim --help` gives the `pdd simulate` lines and `pdd workflow start --help` the `pdd workflow run` line. A removed name gets no help, also with a help flag or after `help`. Print each scoped help entry exactly as the catalog manifest lists it, including quoted heredocs. Render `pdd help prompting` from the catalog's heading, one empty line, prompting lines, one empty line and the two path lines. Substitute `PACKAGE_ROOT` with the absolute `packageRoot` of `runPdd`, defaulting to the parent folder of `src/`, never cwd or the person's repo. Read no file to print the paths. Help is exit 0, writes nothing to stderr and is local, with no runner, network or auth effects. @@ -308,7 +311,7 @@ reply. { "kind": "partial", "status": "approved", - "prose_sha256": "474428b1732eac654830e259d5ef79f7e6926c1d00d6d7cbc4c86db7c5bbb21d", + "prose_sha256": "587b53290ec9051188fbcb75b536a6640f6c8a6a8b8a9805b0529d311cc47fd5", "entries": [ { "operation": "runPdd", diff --git a/src/autopilot-logs.mjs b/src/autopilot-logs.mjs new file mode 100644 index 0000000000..f7dcac93f8 --- /dev/null +++ b/src/autopilot-logs.mjs @@ -0,0 +1,1213 @@ +// Generated from prompts/cli/autopilot-logs.prompt.md (sha256: 8b345c3f03e51f5c556ed65221ba2fe82d41490371f48304181f244a439d7588). +import * as nativeFs from 'node:fs'; +import { homedir } from 'node:os'; +import { basename, join, resolve } from 'node:path'; +import { createHash } from 'node:crypto'; +import { execFile, spawnSync } from 'node:child_process'; +import { promisify } from 'node:util'; +import { readSuiteProgress } from './test-suite-queue.mjs'; +import { redactSecrets } from './secret-redaction.mjs'; + +const execute = promisify(execFile); +const ANSI_RE = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07]*(?:\x07|\x1b\\)/g; +const CTRL_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g; +const DEFAULT_LINES = 40; +const MAX_LINES = 5000; +const DEFAULT_POLL_MS = 250; +const MAX_CMD_PREVIEW_LINES = 6; +const READ_CHUNK_LIMIT = 512 * 1024; + +const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value); +const named = value => typeof value === 'string' && value.trim().length > 0; + +function cleanText(value, maxLen = 400) { + const sanitized = redactSecrets(String(value ?? '').replace(ANSI_RE, '').replace(/\r\n/g, '\n').replace(/\r/g, '\n').replace(CTRL_RE, '')); + return sanitized.length > maxLen ? `${sanitized.slice(0, maxLen - 3)}...` : sanitized; +} + +function oneLine(value, maxLen = 200) { + return cleanText(value, maxLen * 2).replace(/\s+/g, ' ').trim().slice(0, maxLen); +} + +function shortSha(sha) { + return typeof sha === 'string' && sha.trim() ? sha.trim().slice(0, 8) : 'unknown'; +} + +function formatAge(nowMs, atMs) { + if (!Number.isFinite(atMs) || atMs <= 0) return 'unknown'; + const diffSec = Math.max(0, Math.round((nowMs - atMs) / 1000)); + if (diffSec < 60) return `${diffSec}s ago`; + const diffMin = Math.floor(diffSec / 60); + if (diffMin < 60) return `${diffMin}m ago`; + const hours = Math.floor(diffMin / 60); + const mins = diffMin % 60; + return mins > 0 ? `${hours}h ${mins}m ago` : `${hours}h ago`; +} + +function formatStamp(nowMs, atMs) { + if (!Number.isFinite(atMs) || atMs <= 0) return 'unknown'; + return `${formatAge(nowMs, atMs)} (${new Date(atMs).toISOString()})`; +} + +function readJson(fs, filePath, fallback = null) { + if (typeof filePath !== 'string' || !filePath) return fallback; + try { + const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')); + return parsed ?? fallback; + } catch { + return fallback; + } +} + +function statInfo(fs, filePath) { + if (typeof filePath !== 'string' || !filePath) return null; + try { + const st = fs.statSync(filePath); + return st.isFile() ? { size: st.size, mtimeMs: st.mtimeMs } : null; + } catch { + return null; + } +} + +function listDir(fs, dirPath) { + try { return fs.readdirSync(dirPath); } catch { return []; } +} + +function defaultIsProcessAlive(pid, token) { + if (!Number.isSafeInteger(pid) || pid <= 0) return false; + try { process.kill(pid, 0); } catch (error) { if (error?.code !== 'EPERM') return false; } + if (!named(token)) return true; + const row = spawnSync('ps', ['-ww', '-o', 'command=', '-p', String(pid)], { + encoding: 'utf8', + timeout: 3000, + maxBuffer: 4 * 1024 * 1024, + env: { ...process.env, LC_ALL: 'C', LANG: 'C' }, + }); + return row.status === 0 && String(row.stdout ?? '').includes(token); +} + +async function defaultGit(args, { cwd, env }) { + try { + const out = await execute('git', args, { + cwd, + encoding: 'utf8', + env: { ...env, LC_ALL: 'C', LANG: 'C' }, + }); + return { code: 0, stdout: String(out.stdout ?? ''), stderr: String(out.stderr ?? '') }; + } catch (error) { + return { + code: Number.isInteger(error?.code) ? error.code : 1, + stdout: String(error?.stdout ?? ''), + stderr: String(error?.stderr ?? error?.message ?? ''), + }; + } +} + +export function parseIssueSelector(raw) { + if (raw === undefined || raw === null) return { ok: true, issue: null, repo: null }; + const text = String(raw).trim().replace(/\/$/, ''); + if (!text) return { ok: false, issue: null, repo: null }; + const plain = /^#?([1-9][0-9]*)$/.exec(text); + if (plain) return { ok: true, issue: Number(plain[1]), repo: null }; + const qualified = /^([A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9_.-]+)#([1-9][0-9]*)$/.exec(text); + if (qualified) return { ok: true, issue: Number(qualified[2]), repo: qualified[1] }; + const url = /^https:\/\/github\.com\/([A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9_.-]+)\/issues\/([1-9][0-9]*)$/.exec(text); + if (url) return { ok: true, issue: Number(url[2]), repo: url[1] }; + return { ok: false, issue: null, repo: null }; +} + +function previewCommandOutput(output) { + if (!named(output)) return []; + const rawLines = cleanText(output, 4000) + .split('\n') + .map(line => line.trimEnd()) + .filter(line => line.trim().length > 0); + if (!rawLines.length) return []; + const tail = rawLines.slice(-MAX_CMD_PREVIEW_LINES); + const omitted = rawLines.length - tail.length; + return [ + ...(omitted > 0 ? [` | ... (${omitted} earlier line${omitted === 1 ? '' : 's'})`] : []), + ...tail.map(line => ` | ${line.length > 180 ? `${line.slice(0, 177)}...` : line}`), + ]; +} + +export function formatWorkerLogLine(rawLine) { + if (typeof rawLine !== 'string') return ''; + const stripped = rawLine.replace(ANSI_RE, '').replace(/\r/g, ''); + const trimmed = stripped.trim(); + if (!trimmed) return ''; + if (!trimmed.startsWith('{') || !trimmed.endsWith('}')) { + return cleanText(stripped, 500); + } + let event; + try { event = JSON.parse(trimmed); } catch { return cleanText(stripped, 500); } + if (!isObject(event)) return cleanText(stripped, 500); + + // Skip noisy token-count and delta heartbeats. + if (event.type === 'token_count' || (event.type === 'event_msg' && event.payload?.type === 'token_count')) return ''; + if (event.type === 'content_block_delta' || event.type === 'message_delta' || event.type === 'message_stop' || event.type === 'ping') return ''; + + // Codex thread/turn lifecycle + if (event.type === 'thread.started' || event.type === 'session_meta') { + const model = event.model ?? event.payload?.model; + return `[session] started${named(model) ? ` (${oneLine(model, 80)})` : ''}`; + } + if (event.type === 'turn.started' || event.type === 'message_start') return ''; + if (event.type === 'turn.completed') { + const u = isObject(event.usage) ? event.usage : null; + return u && (Number.isFinite(u.input_tokens) || Number.isFinite(u.output_tokens)) + ? `[turn] completed (in ${u.input_tokens ?? 0}, out ${u.output_tokens ?? 0} tokens)` + : '[turn] completed'; + } + if (event.type === 'turn.failed' || event.type === 'error') { + const msg = event.error?.message ?? event.message ?? JSON.stringify(event); + return `[error] ${oneLine(msg, 240)}`; + } + + // Codex item.started / item.completed + if ((event.type === 'item.started' || event.type === 'item.completed') && isObject(event.item)) { + const item = event.item; + const itemType = String(item.type ?? item.item_type ?? ''); + const cmd = item.command ?? item.arguments?.command; + if (event.type === 'item.started') { + if (itemType === 'command_execution' && named(cmd)) return `[run] $ ${oneLine(cmd, 180)}`; + if (named(item.tool ?? item.name)) return `[tool] ${oneLine(item.tool ?? item.name, 80)} started`; + return ''; + } + if (itemType === 'agent_message' && named(item.text)) { + return cleanText(item.text, 800) + .split('\n') + .filter(line => line.trim()) + .map(line => `[agent] ${line}`) + .join('\n'); + } + if (itemType === 'reasoning') { + return named(item.text) ? `[think] ${oneLine(item.text, 160)}` : ''; + } + if (itemType === 'command_execution') { + const code = Number.isInteger(item.exit_code) ? item.exit_code : 0; + const head = `[cmd exit=${code}] $ ${oneLine(cmd ?? '(command)', 170)}`; + return [head, ...previewCommandOutput(item.aggregated_output ?? item.output)].join('\n'); + } + if (itemType === 'file_change' || itemType === 'patch') { + const paths = Array.isArray(item.changes) + ? item.changes.map(c => c?.path).filter(named).join(', ') + : (item.path ?? ''); + return `[edit] ${oneLine(paths || 'updated files', 180)}`; + } + const toolName = item.tool ?? item.name ?? (itemType || 'item'); + return `[tool] ${oneLine(toolName, 120)}`; + } + + // Claude stream-json events + if (event.type === 'system' && event.subtype === 'init') { + return `[session] started${named(event.model) ? ` (${oneLine(event.model, 80)})` : ''}`; + } + if (event.type === 'assistant' && isObject(event.message)) { + const parts = Array.isArray(event.message.content) ? event.message.content : []; + const out = []; + for (const part of parts) { + if (part?.type === 'text' && named(part.text)) { + for (const l of cleanText(part.text, 800).split('\n').filter(s => s.trim())) out.push(`[agent] ${l}`); + } else if (part?.type === 'tool_use' && named(part.name)) { + const detail = part.input?.command ?? part.input?.file_path ?? part.input?.path ?? part.input?.pattern ?? ''; + out.push(`[tool] ${oneLine(part.name, 60)}${named(detail) ? `: ${oneLine(detail, 150)}` : ''}`); + } + } + return out.join('\n'); + } + if (event.type === 'user' && isObject(event.message)) { + const parts = Array.isArray(event.message.content) ? event.message.content : []; + const out = []; + for (const part of parts) { + if (part?.type === 'tool_result') { + const raw = typeof part.content === 'string' + ? part.content + : Array.isArray(part.content) + ? part.content.map(c => c?.text ?? '').join('\n') + : ''; + if (part.is_error) out.push(`[tool error] ${oneLine(raw || 'command failed', 200)}`); + else out.push(...previewCommandOutput(raw)); + } + } + return out.join('\n'); + } + if (event.type === 'result') { + const status = event.subtype ?? (event.is_error ? 'error' : 'done'); + return `[result] ${oneLine(status, 40)}${named(event.result) ? `: ${oneLine(event.result, 180)}` : ''}`; + } + + // Gemini / Agy stream-json events + if (event.event === 'step_update' && isObject(event.step_update)) { + const step = event.step_update; + if (step.step_type === 'tool' && named(step.tool_name)) { + const cmd = step.tool_info?.parameters?.command ?? step.tool_info?.parameters?.CommandLine ?? ''; + const head = `[tool] ${oneLine(step.tool_name, 60)}${named(cmd) ? `: ${oneLine(cmd, 150)}` : ''} (${oneLine(step.state ?? 'update', 20)})`; + return step.state === 'DONE' ? [head, ...previewCommandOutput(step.tool_info?.output)].join('\n') : head; + } + return ''; + } + if (event.type === 'tool_use' && named(event.tool_name)) { + const cmd = event.parameters?.command ?? event.parameters?.cmd ?? event.parameters?.path ?? event.parameters?.file_path ?? ''; + return `[tool] ${oneLine(event.tool_name, 60)}${named(cmd) ? `: ${oneLine(cmd, 150)}` : ''}`; + } + if (event.type === 'tool_result') { + const raw = typeof event.output === 'string' ? event.output : JSON.stringify(event.output ?? ''); + return previewCommandOutput(raw).join('\n'); + } + if (event.type === 'message' && named(event.content)) { + const prefix = event.role === 'assistant' ? '[agent]' : `[${oneLine(event.role ?? 'msg', 20)}]`; + return cleanText(event.content, 800).split('\n').filter(s => s.trim()).map(l => `${prefix} ${l}`).join('\n'); + } + + if (named(event.type)) return `[event] ${oneLine(event.type, 80)}`; + return ''; +} + +function formatLogTail(fs, filePath, maxLines) { + if (!filePath) return []; + let raw; + try { + const st = fs.statSync(filePath); + if (!st.isFile() || st.size <= 0) return []; + const readSize = Math.min(st.size, Math.max(64 * 1024, maxLines * 2048)); + const start = Math.max(0, st.size - readSize); + const fd = fs.openSync(filePath, 'r'); + try { + const buf = Buffer.alloc(readSize); + const bytes = fs.readSync(fd, buf, 0, readSize, start); + raw = buf.subarray(0, bytes).toString('utf8'); + if (start > 0) { + const nl = raw.indexOf('\n'); + if (nl >= 0) raw = raw.slice(nl + 1); + } + } finally { + try { fs.closeSync(fd); } catch {} + } + } catch { + return []; + } + const formatted = []; + for (const rawLine of raw.split('\n')) { + const rendered = formatWorkerLogLine(rawLine); + if (!rendered) continue; + for (const line of rendered.split('\n')) { + if (line.trim()) formatted.push(line); + } + } + return formatted.slice(-maxLines); +} + +function validExitRecord(value) { + return isObject(value) + && (Number.isSafeInteger(value.code) || value.code === null) + && (value.signal === null || typeof value.signal === 'string') + && Number.isFinite(value.at); +} + +function inspectPart(part, role, { fs, isProcessAlive }) { + if (!isObject(part)) return null; + const exitRecord = typeof part.exit === 'string' ? readJson(fs, part.exit, null) : null; + const hasExit = validExitRecord(exitRecord); + const pid = Number.isSafeInteger(part.pid) && part.pid > 0 ? part.pid : null; + const alive = pid !== null ? Boolean(isProcessAlive(pid, part.token)) : false; + const logStat = typeof part.log === 'string' ? statInfo(fs, part.log) : null; + const hangsRaw = typeof part.hangs === 'string' ? readJson(fs, part.hangs, null) : null; + const hangs = Array.isArray(hangsRaw) ? hangsRaw.filter(isObject) : []; + + let state = 'idle'; + let summary = `${role}: idle`; + if (alive) { + state = 'running'; + summary = `${role}: running (pid ${pid}${named(part.agentKind) ? `, ${part.agentKind}` : ''})`; + } else if (hasExit) { + state = 'exited'; + const why = exitRecord.signal ? `signal ${exitRecord.signal}` : `code ${exitRecord.code ?? 'null'}`; + summary = `${role}: exited (${why})`; + } else if (pid !== null) { + state = 'stale'; + summary = `${role}: stale (pid ${pid} not running, no exit receipt)`; + } + + const activityCandidates = [ + logStat?.mtimeMs, + hasExit ? exitRecord.at : null, + Number.isFinite(part.watch?.at) ? part.watch.at : null, + Number.isFinite(part.started) ? part.started : null, + ].filter(n => Number.isFinite(n) && n > 0); + + return { + role, + pid, + agentKind: named(part.agentKind) ? part.agentKind : null, + state, + summary, + logPath: typeof part.log === 'string' ? part.log : null, + logSize: logStat?.size ?? 0, + exit: hasExit ? exitRecord : null, + hangCount: hangs.length, + lastHang: hangs.at(-1) ?? null, + startedAt: Number.isFinite(part.started) ? part.started : null, + lastActivityAt: activityCandidates.length ? Math.max(...activityCandidates) : null, + }; +} + +function classifySuite(job, coreRoot, { fs, env, readSuite }) { + const hasSuiteField = isObject(job?.suite) || job?.phase === 'pr'; + if (!hasSuiteField) return null; + const suiteCwd = named(job?.suite?.cwd) + ? job.suite.cwd + : (coreRoot && Number.isSafeInteger(job?.issue) ? join(coreRoot, 'worktrees', `${job.issue}-suite`) : null); + if (!suiteCwd) return null; + const canQuery = Boolean(isObject(job?.suite)) || Boolean(statInfo(fs, join(suiteCwd, 'package.json'))); + if (!canQuery && typeof readSuite !== 'function') return null; + + let progress = null; + try { + progress = readSuite({ cwd: suiteCwd, env }); + } catch { + progress = null; + } + if (!isObject(progress)) return null; + + const logStat = typeof progress.logPath === 'string' ? statInfo(fs, progress.logPath) : null; + const recordedCommit = progress.source?.commit ?? job.suite?.head ?? null; + const headMismatch = named(job.head) && named(recordedCommit) + && !String(job.head).startsWith(String(recordedCommit)) + && !String(recordedCommit).startsWith(String(job.head)); + const deadRunner = typeof progress.reason === 'string' && /runner ended|recorder_not_running/i.test(progress.reason); + + if (progress.state === 'unavailable') { + return { + kind: 'unavailable', + detail: `full test suite queue unavailable (${oneLine(progress.reason || 'unreadable queue', 140)})`, + position: null, + childPid: null, + logPath: null, + receiptPath: null, + lastActivityAt: null, + }; + } + if (deadRunner || (progress.state === 'finished' && headMismatch)) { + const why = deadRunner + ? oneLine(progress.reason, 140) + : `receipt commit ${shortSha(recordedCommit)} differs from current PR head ${shortSha(job.head)}`; + return { + kind: 'stale-receipt', + detail: `stale suite receipt (${why})`, + position: null, + childPid: null, + logPath: typeof progress.logPath === 'string' ? progress.logPath : null, + receiptPath: typeof progress.receiptPath === 'string' ? progress.receiptPath : null, + lastActivityAt: logStat?.mtimeMs ?? progress.finishedAt ?? progress.queuedAt ?? null, + }; + } + if (progress.state === 'waiting') { + const pos = Number.isSafeInteger(progress.position) ? progress.position : 1; + return { + kind: 'queued', + detail: `queued in shared test-suite queue (position ${pos})`, + position: pos, + childPid: null, + logPath: typeof progress.logPath === 'string' ? progress.logPath : null, + receiptPath: typeof progress.receiptPath === 'string' ? progress.receiptPath : null, + lastActivityAt: progress.queuedAt ?? logStat?.mtimeMs ?? null, + }; + } + if (progress.state === 'running') { + const counts = isObject(progress.counts) + && Number.isFinite(progress.counts.pass) + && Number.isFinite(progress.counts.fail) + ? ` [pass ${progress.counts.pass}, fail ${progress.counts.fail}]` + : ''; + const pidPart = Number.isSafeInteger(progress.childPid) && progress.childPid > 0 + ? ` (pid ${progress.childPid})` + : ''; + return { + kind: 'running', + detail: `running full test suite${pidPart}${counts}`, + position: null, + childPid: Number.isSafeInteger(progress.childPid) ? progress.childPid : null, + logPath: typeof progress.logPath === 'string' ? progress.logPath : null, + receiptPath: typeof progress.receiptPath === 'string' ? progress.receiptPath : null, + lastActivityAt: logStat?.mtimeMs ?? progress.startedAt ?? null, + }; + } + return { + kind: 'finished', + detail: `full test suite finished (${oneLine(progress.outcome ?? `exit ${progress.exitCode ?? 'unknown'}`, 60)})`, + position: null, + childPid: null, + logPath: typeof progress.logPath === 'string' ? progress.logPath : null, + receiptPath: typeof progress.receiptPath === 'string' ? progress.receiptPath : null, + lastActivityAt: progress.finishedAt ?? logStat?.mtimeMs ?? null, + }; +} + +function collectIssueArtifacts(fs, logsDir, issue) { + const prefix = `${issue}-`; + const logs = []; + const evidence = []; + for (const name of listDir(fs, logsDir)) { + if (!name.startsWith(prefix)) continue; + const full = join(logsDir, name); + if (name.endsWith('.log')) { + const st = statInfo(fs, full); + if (st) logs.push({ path: full, mtimeMs: st.mtimeMs, size: st.size }); + } else if (/^\d+-evidence-.*\.json$/.test(name)) { + const st = statInfo(fs, full); + if (st) evidence.push({ path: full, mtimeMs: st.mtimeMs }); + } + } + logs.sort((a, b) => b.mtimeMs - a.mtimeMs || b.path.localeCompare(a.path)); + evidence.sort((a, b) => b.mtimeMs - a.mtimeMs || b.path.localeCompare(a.path)); + return { + logPaths: logs.map(item => item.path), + latestLogMtimeMs: logs[0]?.mtimeMs ?? null, + evidencePaths: evidence.map(item => item.path), + }; +} + +function readMachineBlockers(machine, state, nowMs) { + const blockers = []; + if (Number.isFinite(machine?.pausedUntil) && machine.pausedUntil > nowMs) { + blockers.push(`New jobs paused until ${new Date(machine.pausedUntil).toISOString()} (${machine.streak ?? 0} no-result runs in a row)`); + } + if (isObject(machine?.poolOut)) { + const until = named(machine.poolOut.wakeAt) + ? machine.poolOut.wakeAt + : (Number.isFinite(machine.poolOut.resetAt) ? new Date(machine.poolOut.resetAt).toISOString() : null); + blockers.push(`AI login pool exhausted${until ? ` until ${until}` : ''}`); + } + if (isObject(machine?.ciDown) && ['queued', 'billing'].includes(machine.ciDown.reason)) { + blockers.push(`GitHub Actions hold (${machine.ciDown.reason}) since ${new Date(machine.ciDown.since).toISOString()}`); + } + const breaker = (isObject(state?.circuitBreaker) && state.circuitBreaker.active !== false ? state.circuitBreaker : null) + ?? (isObject(machine?.circuitBreaker) && machine.circuitBreaker.active !== false ? machine.circuitBreaker : null); + if (breaker && Number.isSafeInteger(breaker.pr)) { + blockers.push(`Safety circuit breaker tripped on PR #${breaker.pr}: mode downgraded to observe (${oneLine(breaker.reason ?? breaker.code ?? 'post-merge regression', 120)})`); + } + return blockers; +} + +function buildWorkerView(job, ctx) { + const { fs, coreRoot, logsDir, isProcessAlive, env, readSuite, machineBlockers } = ctx; + const issue = job.issue; + const isIntake = job.__intake === true; + const artifacts = collectIssueArtifacts(fs, logsDir, issue); + + const mainRole = isIntake ? 'intake' : (named(job.role) ? job.role : 'build'); + const mainPart = inspectPart(job.agent ?? (isIntake ? job : null), mainRole, { fs, isProcessAlive }); + const reviewPart = inspectPart(job.review?.agent, 'review', { fs, isProcessAlive }); + const suiteAgentPart = inspectPart(job.suite?.agent, 'suite-runner', { fs, isProcessAlive }); + const vectorsPart = inspectPart(job.vectors?.agent, 'vectors', { fs, isProcessAlive }); + const runtimePart = inspectPart(job.runtimeWait?.agent, 'interpreter-check', { fs, isProcessAlive }); + const suiteView = isIntake ? null : classifySuite(job, coreRoot, { fs, env, readSuite }); + + const parts = [mainPart, reviewPart, suiteAgentPart, vectorsPart, runtimePart].filter(Boolean); + const liveParts = parts.filter(part => part.state === 'running'); + const staleParts = parts.filter(part => part.state === 'stale'); + + let stage = mainRole; + let stageDetail = mainRole; + if (isIntake) { + stage = 'intake'; + stageDetail = 'read-only intake card worker'; + } else if (job.phase === 'ending') { + stage = 'ending'; + stageDetail = `ending (${oneLine(job.end?.cause?.text ?? 'finishing cleanup', 140)})`; + } else if (job.phase === 'released') { + stage = 'release-pending'; + stageDetail = `release pending (retry pdd autopilot release ${issue})`; + } else if (job.phase === 'pr') { + const prLabel = Number.isSafeInteger(job.pr) ? `PR #${job.pr} (${shortSha(job.head)})` : 'PR check'; + if (suiteView?.kind === 'queued') { + stage = 'suite-queued'; + stageDetail = `${prLabel}: ${suiteView.detail}`; + } else if (suiteView?.kind === 'running') { + stage = 'suite-running'; + stageDetail = `${prLabel}: ${suiteView.detail}`; + } else if (suiteView?.kind === 'stale-receipt') { + stage = 'suite-stale'; + stageDetail = `${prLabel}: ${suiteView.detail}`; + } else if (reviewPart?.state === 'running') { + stage = 'review'; + stageDetail = `${prLabel}: independent review running`; + } else if (vectorsPart?.state === 'running') { + stage = 'vectors'; + stageDetail = `${prLabel}: vector checks running`; + } else if (runtimePart?.state === 'running') { + stage = 'interpreter-check'; + stageDetail = `${prLabel}: PDD interpreter check running`; + } else if (job.lane?.state === 'waiting') { + stage = 'merge-lane'; + stageDetail = `${prLabel}: waiting in merge lane${job.lane.holder ? ` behind PR #${job.lane.holder}` : ''}`; + } else if (job.lane?.state === 'final') { + stage = 'merge-lane'; + stageDetail = `${prLabel}: final merge check`; + } else { + stage = 'pr-check'; + const reviewNote = named(job.review?.verdict) ? `review ${job.review.verdict}` : 'review pending'; + const suiteNote = suiteView?.detail ?? (job.suite ? 'suite started' : 'suite pending'); + stageDetail = `${prLabel}: ${reviewNote}, ${suiteNote}`; + } + } else if (mainRole === 'repair') { + stage = 'repair'; + const attempt = Number.isSafeInteger(job.repairs) && job.repairs > 0 ? ` #${job.repairs}` : ''; + const prNote = Number.isSafeInteger(job.pr) ? ` on PR #${job.pr}` : ''; + stageDetail = `repair${attempt}${prNote}`; + } else if (mainRole === 'conflict') { + stage = 'conflict'; + stageDetail = `conflict resolution${Number.isSafeInteger(job.pr) ? ` on PR #${job.pr}` : ''}`; + } else { + stage = 'build'; + stageDetail = 'headless build'; + } + + // Owned process summary + let processState = 'idle'; + let processSummary = 'no active worker process'; + if (suiteView?.kind === 'running' && (suiteView.childPid || suiteAgentPart?.state === 'running')) { + processState = 'running'; + const pieces = []; + if (suiteView.childPid) pieces.push(`suite pid ${suiteView.childPid}`); + else if (suiteAgentPart?.pid) pieces.push(`suite wrapper pid ${suiteAgentPart.pid}`); + if (reviewPart?.state === 'running') pieces.push(`review pid ${reviewPart.pid}`); + processSummary = `running (${pieces.join(', ')})`; + } else if (suiteView?.kind === 'queued' && suiteAgentPart?.state === 'running') { + processState = 'waiting'; + processSummary = `waiting in suite queue (queue client pid ${suiteAgentPart.pid}${reviewPart?.state === 'running' ? `, review pid ${reviewPart.pid} running` : ''})`; + } else if (liveParts.length > 0) { + processState = 'running'; + processSummary = liveParts.map(part => part.summary).join('; '); + } else if (staleParts.length > 0 || suiteView?.kind === 'stale-receipt') { + processState = 'stale'; + const reasons = [ + ...staleParts.map(part => part.summary), + ...(suiteView?.kind === 'stale-receipt' ? [suiteView.detail] : []), + ]; + processSummary = reasons.join('; '); + } else { + const exitedParts = parts.filter(part => part.state === 'exited'); + if (exitedParts.length > 0) { + processState = 'exited'; + processSummary = `${exitedParts.map(part => part.summary).join('; ')}; awaiting next Autopilot tick`; + } + } + + // Plain blockers + const blockers = []; + if (suiteView?.kind === 'queued') { + blockers.push(`Queued in shared test-suite queue at position ${suiteView.position}`); + } + if (suiteView?.kind === 'stale-receipt') { + blockers.push(`Stale test receipt: ${suiteView.detail}`); + } + if (staleParts.length > 0) { + blockers.push(`Recorded worker process exited without a receipt (${staleParts.map(p => `${p.role} pid ${p.pid}`).join(', ')})`); + } + if (job.lane?.state === 'waiting') { + blockers.push(`Waiting in merge lane${job.lane.holder ? ` for PR #${job.lane.holder}` : ''}${Number.isFinite(job.lane.since) ? ` since ${new Date(job.lane.since).toISOString()}` : ''}`); + } + if (job.runtimeWait?.state === 'waiting') { + blockers.push(`Waiting on PDD interpreter maintenance${job.runtimeWait.until ? ` until ${new Date(job.runtimeWait.until).toISOString()}` : ''}`); + } + if (job.stepStop?.poolExhausted) { + const wake = named(job.stepStop.wakeAt) + ? job.stepStop.wakeAt + : (Number.isFinite(job.stepStop.until) ? new Date(job.stepStop.until).toISOString() : null); + blockers.push(`Waiting on AI quota / login pool${wake ? ` until ${wake}` : ''}`); + } + for (const part of parts) { + if (part.hangCount > 0) { + const cmd = oneLine(part.lastHang?.command ?? 'hung child command', 100); + blockers.push(`Watchdog stopped ${part.hangCount} hung command${part.hangCount === 1 ? '' : 's'} (${cmd})`); + } + } + if (named(job.lastError)) { + blockers.push(`Last error: ${oneLine(job.lastError, 180)}`); + } + for (const mb of machineBlockers) { + if (!blockers.includes(mb)) blockers.push(mb); + } + + // Active streams to tail (prefer live suite validation log when running, plus active worker logs) + const streams = []; + const addStream = (label, filePath) => { + if (!named(filePath)) return; + if (streams.some(s => s.path === filePath)) return; + if (statInfo(fs, filePath)) streams.push({ label, path: filePath }); + }; + if (job.phase === 'pr') { + if (suiteView?.kind === 'running' && suiteView.logPath) addStream('suite', suiteView.logPath); + if (reviewPart?.state === 'running') addStream('review', reviewPart.logPath); + if (suiteAgentPart?.state === 'running' && suiteView?.kind !== 'running') addStream('suite-queue', suiteAgentPart.logPath); + if (vectorsPart?.state === 'running') addStream('vectors', vectorsPart.logPath); + if (runtimePart?.state === 'running') addStream('interpreter', runtimePart.logPath); + // Fallback to latest finished PR sub-logs when nothing is currently live + if (!streams.length) { + if (suiteView?.logPath) addStream('suite', suiteView.logPath); + addStream('suite-queue', suiteAgentPart?.logPath); + addStream('review', reviewPart?.logPath); + addStream(mainRole, mainPart?.logPath); + } + } else { + addStream(mainRole, mainPart?.logPath); + } + if (!streams.length && artifacts.logPaths.length) { + addStream('worker', artifacts.logPaths[0]); + } + + const evidencePaths = [ + ...artifacts.evidencePaths, + ...(named(suiteView?.receiptPath) && statInfo(fs, suiteView.receiptPath) ? [suiteView.receiptPath] : []), + ]; + const allLogPaths = [ + ...new Set([ + ...streams.map(s => s.path), + ...(named(suiteView?.logPath) && statInfo(fs, suiteView.logPath) ? [suiteView.logPath] : []), + ...artifacts.logPaths, + ]), + ]; + + const activityTimes = [ + ...parts.map(p => p.lastActivityAt), + suiteView?.lastActivityAt, + artifacts.latestLogMtimeMs, + job.__fileMtimeMs, + Number.isFinite(job.started) ? job.started : null, + ].filter(n => Number.isFinite(n) && n > 0); + const lastActivityAt = activityTimes.length ? Math.max(...activityTimes) : null; + + return { + issue, + issues: Array.isArray(job.issues) && job.issues.length ? job.issues : [issue], + title: named(job.title) ? oneLine(job.title, 140) : null, + pr: Number.isSafeInteger(job.pr) ? job.pr : null, + head: named(job.head) ? job.head : null, + active: true, + liveProcess: processState === 'running' || processState === 'waiting', + stage, + stageDetail, + processState, + processSummary, + suite: suiteView, + blockers, + lastActivityAt, + startedAt: Number.isFinite(job.started) ? job.started : (mainPart?.startedAt ?? null), + streams, + logPaths: allLogPaths, + evidencePaths, + }; +} + +function readJobsFromDir(fs, dirPath, intake = false) { + const rows = []; + for (const name of listDir(fs, dirPath)) { + if (!/^\d+\.json$/.test(name)) continue; + const full = join(dirPath, name); + const parsed = readJson(fs, full, null); + if (!isObject(parsed)) continue; + const issue = Number.isSafeInteger(parsed.issue) ? parsed.issue : Number(name.replace(/\.json$/, '')); + if (!Number.isSafeInteger(issue) || issue <= 0) continue; + const st = statInfo(fs, full); + rows.push({ + ...parsed, + issue, + __intake: intake, + __fileMtimeMs: st?.mtimeMs ?? null, + }); + } + return rows.sort((a, b) => a.issue - b.issue); +} + +function readRecentHistory(fs, coreRoot, logsDir) { + const historyPath = join(coreRoot, 'history.jsonl'); + let raw = ''; + try { raw = fs.readFileSync(historyPath, 'utf8'); } catch { return []; } + const parsed = []; + for (const line of raw.split('\n')) { + const trimmed = line.trim(); + if (!trimmed) continue; + try { + const row = JSON.parse(trimmed); + if (isObject(row) && typeof row.outcome === 'string' && Number.isSafeInteger(row.issue) && row.issue > 0) { + parsed.push(row); + } + } catch { /* Ignore partial/corrupt line. */ } + } + parsed.reverse(); + const seen = new Set(); + const unique = []; + for (const row of parsed) { + if (seen.has(row.issue)) continue; + seen.add(row.issue); + const artifacts = collectIssueArtifacts(fs, logsDir, row.issue); + unique.push({ + issue: row.issue, + outcome: oneLine(row.outcome, 40), + at: Number.isFinite(row.at) ? row.at : null, + pr: Number.isSafeInteger(row.pr) ? row.pr : null, + text: named(row.text) ? oneLine(row.text, 180) : '', + logPaths: artifacts.logPaths, + evidencePaths: artifacts.evidencePaths, + }); + } + return unique; +} + +function resolveEffectiveMode(fs, gitRoot, launcherState, machineState) { + const repoConfig = readJson(fs, join(gitRoot, 'pdd.json'), null); + const configMode = ['off', 'observe', 'auto'].includes(repoConfig?.autopilot?.mode) + ? repoConfig.autopilot.mode + : null; + const breaker = (isObject(launcherState?.circuitBreaker) && launcherState.circuitBreaker.active !== false) + || (isObject(machineState?.circuitBreaker) && machineState.circuitBreaker.active !== false); + if (breaker) return { mode: 'observe', modeSource: 'circuit-breaker' }; + if (['off', 'observe', 'auto'].includes(launcherState?.mode)) { + return { mode: launcherState.mode, modeSource: 'machine' }; + } + if (configMode) return { mode: configMode, modeSource: 'pdd.json' }; + return { mode: 'off', modeSource: 'default' }; +} + +export async function inspectAutopilotWorkers(input = {}, ports = {}) { + const fs = ports.fs ?? nativeFs; + const env = input.env ?? process.env; + const cwd = input.cwd ?? process.cwd(); + const now = ports.now ?? Date.now; + const nowMs = now(); + const git = ports.git ?? defaultGit; + const isProcessAlive = ports.isProcessAlive ?? defaultIsProcessAlive; + const readSuite = ports.readSuite ?? ((suiteInput) => readSuiteProgress(suiteInput)); + + let gitRoot = ports.gitRoot ?? null; + if (!gitRoot) { + const reply = await git(['rev-parse', '--show-toplevel'], { cwd, env }); + if (reply.code !== 0 || !named(reply.stdout)) { + const notRepo = /not a git repository/i.test(String(reply.stderr ?? '')); + return { + ok: false, + exitCode: 1, + message: notRepo + ? 'This folder is not a Git repository. cd into the repo you want Autopilot to work on, then run pdd autopilot logs again.' + : 'Autopilot logs could not read the Git repository; retry.', + }; + } + gitRoot = reply.stdout.trim(); + } + + const stateRoot = ports.stateRoot ?? join(env.HOME || homedir(), '.local', 'state', 'pdd', 'autopilot'); + const stateId = createHash('sha256').update(gitRoot).digest('hex').slice(0, 20); + const stateFile = join(stateRoot, `${stateId}.json`); + const coreRoot = ports.coreRoot ?? join(stateRoot, `${stateId}-core`); + const logsDir = join(coreRoot, 'logs'); + + const launcherState = readJson(fs, stateFile, null); + const machineState = readJson(fs, join(coreRoot, 'core.json'), null); + const { mode, modeSource } = resolveEffectiveMode(fs, gitRoot, launcherState, machineState); + const machineBlockers = readMachineBlockers(machineState, launcherState, nowMs); + + const coreJobs = readJobsFromDir(fs, join(coreRoot, 'jobs'), false); + const activeIssueIds = new Set(coreJobs.map(j => j.issue)); + const intakeJobs = readJobsFromDir(fs, join(coreRoot, 'intake', 'jobs'), true) + .filter(j => !activeIssueIds.has(j.issue)); + + const ctx = { + fs, + coreRoot, + logsDir, + isProcessAlive, + env, + readSuite, + machineBlockers, + }; + const workers = [...coreJobs, ...intakeJobs] + .map(job => buildWorkerView(job, ctx)) + .sort((a, b) => a.issue - b.issue); + const recent = readRecentHistory(fs, coreRoot, logsDir) + .filter(row => !workers.some(w => w.issue === row.issue)); + + return { + ok: true, + nowMs, + repo: named(launcherState?.repo) ? launcherState.repo : null, + gitRoot, + stateId, + stateFile, + coreRoot, + mode, + modeSource, + timerEnabled: Boolean(launcherState?.enabled), + machineBlockers, + workers, + recent, + }; +} + +function buildHistoricalWorkerView(issue, snapshot, fs) { + const logsDir = join(snapshot.coreRoot, 'logs'); + const historyRow = snapshot.recent.find(row => row.issue === issue) ?? null; + const artifacts = collectIssueArtifacts(fs, logsDir, issue); + if (!historyRow && !artifacts.logPaths.length && !artifacts.evidencePaths.length) return null; + + const outcome = historyRow ? `${historyRow.outcome}${historyRow.text ? ` — ${historyRow.text}` : ''}` : 'saved log on disk'; + return { + issue, + issues: [issue], + title: null, + pr: historyRow?.pr ?? null, + head: null, + active: false, + liveProcess: false, + stage: 'finished', + stageDetail: `finished (${outcome})`, + processState: 'finished', + processSummary: 'not running (completed)', + suite: null, + blockers: [], + lastActivityAt: historyRow?.at ?? artifacts.latestLogMtimeMs ?? null, + startedAt: null, + streams: artifacts.logPaths.length ? [{ label: 'worker', path: artifacts.logPaths[0] }] : [], + logPaths: artifacts.logPaths, + evidencePaths: artifacts.evidencePaths, + }; +} + +function modeBanner(snapshot) { + const repoLabel = snapshot.repo ?? snapshot.gitRoot; + const observeNote = snapshot.mode === 'observe' ? ' (read-only viewer; observe mode never approves or merges)' : ' (read-only viewer)'; + return `Autopilot logs: ${repoLabel} · mode ${snapshot.mode}${observeNote}`; +} + +function renderWorkerList(snapshot) { + const lines = [modeBanner(snapshot)]; + for (const blocker of snapshot.machineBlockers) { + lines.push(`Blocker: ${blocker}`); + } + if (!snapshot.workers.length && !snapshot.recent.length) { + lines.push('No active or recent Autopilot workers found for this repository.'); + lines.push('Start Autopilot with pdd autopilot start, or check configuration with pdd autopilot status.'); + return lines.join('\n'); + } + if (snapshot.workers.length) { + lines.push('', `Current workers (${snapshot.workers.length}):`); + for (const worker of snapshot.workers) { + const titlePart = worker.title ? ` "${worker.title}"` : ''; + lines.push(` #${worker.issue}${titlePart}`); + lines.push(` Stage: ${worker.stageDetail}`); + lines.push(` Process: ${worker.processSummary}`); + lines.push(` Last activity: ${formatStamp(snapshot.nowMs, worker.lastActivityAt)}`); + lines.push(` Blockers: ${worker.blockers.length ? worker.blockers.join('; ') : 'none'}`); + if (worker.logPaths[0]) lines.push(` Log: ${worker.logPaths[0]}`); + if (worker.evidencePaths[0]) lines.push(` Evidence: ${worker.evidencePaths[0]}`); + } + const exampleIssue = snapshot.workers[0].issue; + lines.push('', `Follow a worker live: pdd autopilot logs ${exampleIssue} --follow`); + } else { + lines.push('', 'Current workers: none active right now.'); + } + if (snapshot.recent.length) { + const shown = snapshot.recent.slice(0, 5); + lines.push('', `Recent finished workers (${shown.length}):`); + for (const row of shown) { + const prText = row.pr ? ` (PR #${row.pr})` : ''; + const logHint = row.logPaths[0] ? ` · log: ${basename(row.logPaths[0])}` : ''; + lines.push(` #${row.issue}${prText}: ${row.outcome} ${formatAge(snapshot.nowMs, row.at)}${row.text ? ` — ${row.text}` : ''}${logHint}`); + } + if (!snapshot.workers.length) { + lines.push('', `Inspect a finished worker's saved log: pdd autopilot logs ${shown[0].issue}`); + } + } + return lines.join('\n'); +} + +function renderWorkerHeader(snapshot, worker) { + const lines = [ + modeBanner(snapshot), + `Issue: #${worker.issue}${worker.title ? ` — ${worker.title}` : ''}${worker.pr ? ` (PR #${worker.pr})` : ''}`, + `Stage: ${worker.stageDetail}`, + `Process: ${worker.processSummary}`, + ]; + if (worker.suite) { + lines.push(`Suite queue: ${worker.suite.detail}`); + } + lines.push(`Last activity: ${formatStamp(snapshot.nowMs, worker.lastActivityAt)}`); + lines.push(`Blockers: ${worker.blockers.length ? worker.blockers.join('; ') : 'none'}`); + if (worker.logPaths.length) { + lines.push(`Log: ${worker.logPaths[0]}`); + for (const extra of worker.logPaths.slice(1, 3)) lines.push(`Saved log: ${extra}`); + } else { + lines.push('Log: (no log file written yet)'); + } + for (const ev of worker.evidencePaths.slice(0, 3)) { + lines.push(`Evidence: ${ev}`); + } + return lines; +} + +function readAppendedCompleteLines(fs, filePath, offset) { + let fd; + try { + fd = fs.openSync(filePath, 'r'); + const size = fs.fstatSync(fd).size; + if (size < offset) offset = 0; // Handle log truncation cleanly. + const length = Math.min(READ_CHUNK_LIMIT, size - offset); + if (length <= 0) return { nextOffset: offset, lines: [] }; + const buffer = Buffer.alloc(length); + const bytesRead = fs.readSync(fd, buffer, 0, length, offset); + if (bytesRead <= 0) return { nextOffset: offset, lines: [] }; + const text = buffer.subarray(0, bytesRead).toString('utf8'); + const lastNewline = text.lastIndexOf('\n'); + if (lastNewline < 0) { + if (bytesRead >= READ_CHUNK_LIMIT) { + return { nextOffset: offset + bytesRead, lines: [text] }; + } + return { nextOffset: offset, lines: [] }; + } + const completeChunk = text.slice(0, lastNewline + 1); + const usedBytes = Buffer.byteLength(completeChunk, 'utf8'); + return { + nextOffset: offset + usedBytes, + lines: completeChunk.slice(0, -1).split('\n'), + }; + } catch { + return { nextOffset: offset, lines: [] }; + } finally { + if (fd !== undefined) { + try { fs.closeSync(fd); } catch {} + } + } +} + +export async function runAutopilotLogs(input = {}, ports = {}) { + const fs = ports.fs ?? nativeFs; + const follow = Boolean(input.follow); + const json = Boolean(input.json); + const tailLines = input.lines === undefined ? DEFAULT_LINES : Number(input.lines); + + if (!Number.isInteger(tailLines) || tailLines < 1 || tailLines > MAX_LINES) { + return { exitCode: 2, message: `Use --lines N with an integer from 1 to ${MAX_LINES}.` }; + } + if (follow && json) { + return { exitCode: 2, message: '--json prints one snapshot and cannot be combined with --follow.' }; + } + if (input.positionalIssue !== undefined && input.optionIssue !== undefined && input.positionalIssue !== input.optionIssue) { + return { exitCode: 2, message: 'Pass the issue once: pdd autopilot logs ISSUE or pdd autopilot logs --issue ISSUE.' }; + } + const rawIssue = input.issue ?? input.positionalIssue ?? input.optionIssue; + const parsedIssue = parseIssueSelector(rawIssue); + if (!parsedIssue.ok) { + return { exitCode: 2, message: `"${oneLine(rawIssue, 80)}" is not a valid issue number, owner/repo#N or GitHub issue URL.` }; + } + if (follow && parsedIssue.issue === null) { + return { exitCode: 2, message: 'Select an issue to follow: pdd autopilot logs ISSUE --follow.' }; + } + + const snapshot = await inspectAutopilotWorkers(input, ports); + if (!snapshot.ok) return { exitCode: snapshot.exitCode, message: snapshot.message }; + + if (parsedIssue.repo && snapshot.repo && parsedIssue.repo.toLowerCase() !== snapshot.repo.toLowerCase()) { + return { exitCode: 1, message: `Issue ${parsedIssue.repo}#${parsedIssue.issue} does not belong to ${snapshot.repo}.` }; + } + + if (parsedIssue.issue === null) { + if (json) { + const payload = { + schema: 'pdd.autopilot-logs.v1', + repo: snapshot.repo, + gitRoot: snapshot.gitRoot, + mode: snapshot.mode, + modeSource: snapshot.modeSource, + timerEnabled: snapshot.timerEnabled, + machineBlockers: snapshot.machineBlockers, + workers: snapshot.workers, + recent: snapshot.recent.slice(0, 10), + }; + return { exitCode: 0, message: JSON.stringify(payload, null, 2), data: payload }; + } + return { exitCode: 0, message: renderWorkerList(snapshot) }; + } + + const issue = parsedIssue.issue; + const findTarget = snap => snap.workers.find(w => w.issue === issue || w.issues.includes(issue)) + ?? buildHistoricalWorkerView(issue, snap, fs); + + const initialWorker = findTarget(snapshot); + if (!initialWorker) { + return { + exitCode: 1, + message: `No active or saved Autopilot worker found for issue #${issue} in this repository. Run pdd autopilot logs to list workers.`, + }; + } + + if (json) { + const tail = initialWorker.streams[0] + ? formatLogTail(fs, initialWorker.streams[0].path, tailLines) + : []; + const payload = { + schema: 'pdd.autopilot-logs.v1', + repo: snapshot.repo, + gitRoot: snapshot.gitRoot, + mode: snapshot.mode, + modeSource: snapshot.modeSource, + timerEnabled: snapshot.timerEnabled, + worker: initialWorker, + lines: tail, + }; + return { exitCode: 0, message: JSON.stringify(payload, null, 2), data: payload }; + } + + if (!follow) { + const out = renderWorkerHeader(snapshot, initialWorker); + const multi = initialWorker.streams.length > 1; + let printedAny = false; + for (const stream of initialWorker.streams) { + const tail = formatLogTail(fs, stream.path, tailLines); + if (!tail.length) continue; + printedAny = true; + out.push('', `--- Recent progress${multi ? ` (${stream.label})` : ''} ---`); + for (const line of tail) out.push(multi ? `[${stream.label}] ${line}` : line); + } + if (!printedAny) { + out.push('', '--- Recent progress ---', '(no readable log output recorded yet)'); + } + if (initialWorker.active) { + out.push('', `Follow live output: pdd autopilot logs ${initialWorker.issue} --follow`); + } + return { exitCode: 0, message: out.join('\n') }; + } + + // Live --follow streaming mode (strictly read-only; detaches without signaling worker) + const stdout = ports.stdout ?? process.stdout; + const writeLine = text => stdout.write(`${text}\n`); + for (const headerLine of renderWorkerHeader(snapshot, initialWorker)) writeLine(headerLine); + + if (!initialWorker.active) { + const tail = initialWorker.streams[0] ? formatLogTail(fs, initialWorker.streams[0].path, tailLines) : []; + if (tail.length) { + writeLine(''); + writeLine('--- Saved progress ---'); + for (const l of tail) writeLine(l); + } + writeLine(''); + writeLine(`Worker #${initialWorker.issue} has already finished; nothing live to follow.`); + return { exitCode: 0, message: '', streamed: true }; + } + + writeLine('Following live output (press Ctrl-C to detach without stopping the worker)...'); + writeLine(''); + + const offsets = new Map(); + const multiInitial = initialWorker.streams.length > 1; + for (const stream of initialWorker.streams) { + const st = statInfo(fs, stream.path); + const tail = formatLogTail(fs, stream.path, tailLines); + for (const l of tail) writeLine(multiInitial ? `[${stream.label}] ${l}` : l); + offsets.set(stream.path, st?.size ?? 0); + } + + let lastStageSig = `${initialWorker.stageDetail}|${initialWorker.processSummary}`; + let lastBlockersSig = initialWorker.blockers.join('; '); + const pollMs = Math.max(10, Number.isFinite(ports.pollMs) ? ports.pollMs : DEFAULT_POLL_MS); + + let detached = false; + let wakeSleep = null; + const triggerDetach = () => { + if (detached) return; + detached = true; + wakeSleep?.(); + }; + + const signal = ports.signal ?? null; + const onSigint = () => triggerDetach(); + const onSigterm = () => triggerDetach(); + if (signal) { + if (signal.aborted) detached = true; + else signal.addEventListener('abort', triggerDetach, { once: true }); + } else { + process.once('SIGINT', onSigint); + process.once('SIGTERM', onSigterm); + } + + const waitNext = ports.sleep + ? async ms => { + if (detached) return; + await ports.sleep(ms); + } + : ms => new Promise(resolveWait => { + if (detached) { resolveWait(); return; } + const timer = setTimeout(() => { wakeSleep = null; resolveWait(); }, ms); + wakeSleep = () => { clearTimeout(timer); wakeSleep = null; resolveWait(); }; + }); + + const maxPolls = Number.isInteger(ports.maxPolls) && ports.maxPolls > 0 ? ports.maxPolls : Infinity; + let polls = 0; + + try { + while (!detached && polls < maxPolls) { + await waitNext(pollMs); + if (detached) break; + polls++; + + const currentSnap = await inspectAutopilotWorkers(input, ports); + if (!currentSnap.ok) break; + const currentWorker = findTarget(currentSnap); + if (!currentWorker) { + writeLine(`[stage] Worker #${issue} finished.`); + return { exitCode: 0, message: '', streamed: true }; + } + + const stageSig = `${currentWorker.stageDetail}|${currentWorker.processSummary}`; + if (stageSig !== lastStageSig) { + lastStageSig = stageSig; + writeLine(`[stage] ${currentWorker.stageDetail} · ${currentWorker.processSummary}`); + } + const blockersSig = currentWorker.blockers.join('; '); + if (blockersSig !== lastBlockersSig) { + lastBlockersSig = blockersSig; + if (currentWorker.blockers.length) writeLine(`[blocker] ${blockersSig}`); + } + + const multiNow = currentWorker.streams.length > 1; + for (const stream of currentWorker.streams) { + const isNewStream = !offsets.has(stream.path); + if (isNewStream) { + offsets.set(stream.path, 0); + writeLine(`[stage] Streaming ${stream.label} log: ${stream.path}`); + } + const prevOffset = offsets.get(stream.path) ?? 0; + const { nextOffset, lines } = readAppendedCompleteLines(fs, stream.path, prevOffset); + offsets.set(stream.path, nextOffset); + for (const raw of lines) { + const rendered = formatWorkerLogLine(raw); + if (!rendered) continue; + for (const line of rendered.split('\n')) { + if (line.trim()) writeLine(multiNow ? `[${stream.label}] ${line}` : line); + } + } + } + + if (!currentWorker.active) { + writeLine(`[stage] ${currentWorker.stageDetail}`); + return { exitCode: 0, message: '', streamed: true }; + } + if (!currentWorker.liveProcess && !currentSnap.timerEnabled) { + writeLine(`[stage] Worker #${currentWorker.issue} has no live process and the Autopilot timer is stopped.`); + return { exitCode: 0, message: '', streamed: true }; + } + } + } finally { + if (signal) { + try { signal.removeEventListener('abort', triggerDetach); } catch {} + } else { + process.removeListener('SIGINT', onSigint); + process.removeListener('SIGTERM', onSigterm); + } + } + + if (detached) { + writeLine(`Detached from issue #${initialWorker.issue} (background worker continues untouched).`); + } + return { exitCode: 0, message: '', streamed: true }; +} diff --git a/src/autopilot.mjs b/src/autopilot.mjs index 2fd8a0eea0..1ad5fb86df 100644 --- a/src/autopilot.mjs +++ b/src/autopilot.mjs @@ -1,4 +1,4 @@ -// Generated from prompts/cli/autopilot.prompt.md (sha256: edebaa98faf38f5cd25b91cce6d7522cbfe107dbaa03147a4b9492ef2453b3fb). +// Generated from prompts/cli/autopilot.prompt.md (sha256: 305ab5f08edbc298f9ab0ca816fbb91dd70f3f7f8d7113543ab2093b793850c5). import * as nativeFs from 'node:fs'; import { join } from 'node:path'; import { randomUUID } from 'node:crypto'; @@ -181,3 +181,11 @@ export async function runAutopilot(input, ports = {}) { return result(1, `Autopilot settings failed: ${error.message}`); } } + +export async function runAutopilotSubcommand(subcommand, input = {}, ports = {}) { + if (subcommand === 'logs') { + const { runAutopilotLogs } = await import('./autopilot-logs.mjs'); + return runAutopilotLogs(input, ports); + } + return { exitCode: 2, message: 'Unsupported Autopilot subcommand. Use pdd autopilot --help.' }; +} diff --git a/src/command-catalog.mjs b/src/command-catalog.mjs index 0c5fee028c..4f8148fb35 100644 --- a/src/command-catalog.mjs +++ b/src/command-catalog.mjs @@ -1,14 +1,82 @@ -// Generated from prompts/cli/command-catalog.prompt.md (sha256: 0462bc1987c0a817bb5fb26daf0425cbb4634d0490dee1e484ba557f21446e45). +// Generated from prompts/cli/command-catalog.prompt.md (sha256: f0b12e421937140fc52987e2607420da7388ce5d35b780dec830c98efc1aaec8). const form = (form, description) => Object.freeze({ form, description }); // The one place for the words of five commands; a later rename changes only NAMES. export const NAMES = Object.freeze({ test: 'test', lint: 'lint', simulate: 'simulate', run: 'run', requestUptake: 'ack' }); -const { test, lint, simulate, run, requestUptake } = NAMES; +const { test, lint, simulate, run, requestUptake = 'ack' } = NAMES; export const BUNDLED_WORKFLOW_NAMES = Object.freeze(['feature', 'bug', 'small-change', 'product']); +const group = (title, lines) => Object.freeze({ title, lines: Object.freeze(lines) }); export const PUBLIC_HELP_TEXT = Object.freeze({ heading: "PDD: prompt-driven development for your coding agent.", + usageLine: "Usage: pdd [options]", + quickStartLines: Object.freeze([ + " pdd setup Install PDD skills and project setup.", + ` pdd ${test} [STORY...] Check Stories on the PDD interpreter.`, + ` pdd ${simulate} [STORY] Open the PDD Simulator for a Story or repo.`, + " pdd help prompting Learn how prompts, Stories and tests work.", + ]), + groups: Object.freeze([ + group("Core PDD workflow", [ + " pdd setup [--yes] Set up skills, AGENTS.md, MCP and Autopilot.", + ` pdd ${test} [PATH|STORY...] Check Stories on the PDD interpreter.`, + ` pdd ${lint} [STORY...] Run local SVG checks and interpreter lint.`, + ` pdd ${simulate} [STORY] Run Stories interactively in PDD Simulator.`, + " pdd approve PROMPT Review prompt changes and record approval.", + " pdd files [--json] List prompts, Stories, tests and refusals.", + " pdd owner PATH... [--json] Show which prompt owns each file.", + " pdd contracts [sync] Inspect or sync shared record schemas.", + " pdd jobs List active local interpreter jobs.", + " pdd mcp Serve repository simulator tools over MCP.", + " pdd upgrade [--main] Upgrade global pdd and installed skills.", + ]), + group("Cloud accounts (pdd accounts --help)", [ + " pdd accounts [list|status] Show Cloud accounts, usage and lease health.", + " pdd accounts add|import Enroll or import Codex and Claude logins.", + " pdd accounts use|next|sync Pin, rotate or refresh managed logins.", + " pdd accounts share|auto|... Share accounts or manage shell auto-switch.", + ]), + group("Workflows & product (pdd workflow --help, pdd product --help)", [ + " pdd product status|next|start Inspect or launch planned product runs.", + " pdd workflow list [--json] List bundled workflows, areas and gates.", + ` pdd workflow ${run} NAME ISSUE Start an issue workflow chat in Herdr.`, + " pdd workflow status [ISSUE] Show active runs, waiting gates and PRs.", + " pdd workflow view|card [ISSUE] Review run gates, files or Story card.", + " pdd workflow approve [ISSUE] Approve a ready gate and draft prompts.", + " pdd workflow changes|open ... Send a change request or reopen a chat.", + " pdd workflow prove|suite ... Run base/head proof or queued test suite.", + " pdd workflow done STEP Record step completion in a run worktree.", + " pdd workflow publish ISSUE Publish a completed code PR area.", + " pdd workflow ask QUESTION Mark a run chat waiting on a person.", + ` pdd workflow ${requestUptake} REQUEST_ID --summary TEXT Acknowledge a change request.`, + " pdd graph [--open] [--issue N] Inspect or open issue dependency graph.", + " pdd dependencies prepare|... Prepare or record dependency reviews.", + ]), + group("Autopilot (pdd autopilot --help)", [ + " pdd autopilot doctor Run read-only first-start checks.", + " pdd autopilot start|stop Start or stop headless Autopilot timer.", + " pdd autopilot status [--all] Show repo Autopilot state and next tick.", + " pdd autopilot logs [ISSUE] [-f] List workers or follow live worker logs.", + " pdd autopilot observe|auto|off Set repository Autopilot mode.", + " pdd autopilot trust|untrust Manage trusted GitHub collaborators.", + " pdd autopilot add|release ... Opt in issues or release an idle claim.", + " pdd autopilot intake|report Inspect local intake cards or reports.", + " pdd autopilot alerts|regressions Configure alerts or scan regressions.", + ]), + group("Metrics, shell & help (pdd metrics --help)", [ + " pdd metrics [export|import|record] Show, share or record repo metrics.", + " pdd completion bash|zsh Print shell tab-completion script.", + " pdd --help | pdd --help Show this overview or full command help.", + " pdd help prompting Show the 5-step PDD authoring summary.", + " pdd --version | -V | -VV Show CLI version (and interpreter build).", + ]), + ]), + focusedHelpLines: Object.freeze([ + `Focused help: run pdd --help (for example, pdd ${test} --help,`, + "pdd approve --help, pdd workflow --help, or pdd autopilot --help) for", + "all options, defaults, approval heredocs, and execution details.", + ]), closingLines: Object.freeze(["Open Codex or Claude as usual and call a PDD skill: $pdd-feature in Codex, /pdd-feature in Claude Code (also pdd-bug, pdd-small-change, pdd-prompting).", `workflow ${run} opens the first area chat in Herdr session pdd and exits. Manual workflows follow RUNBOOK §2 and its person gates; pdd opens a real PR.`, "The CLI has no merge command. In auto mode, Autopilot merges its own pull request after CI, a fresh review and the full test suite pass; required human approvals still apply."]), learnLines: Object.freeze(["Learn PDD: run pdd help prompting, or read the Prompting guide and the RUNBOOK.", "Prompting guide: PACKAGE_ROOT/docs/prompting-guide.md", "RUNBOOK: PACKAGE_ROOT/RUNBOOK.md"]), - promptingLines: Object.freeze(["In PDD, prompts are the source. Code follows the prompts.", "1. Prompt: prompts/NAME.prompt.md. Write what the program does in plain English, then ## Dependencies.", "2. Story: user_stories/STORY.md. Write one thing that a person can do, then a numbered ## Acceptance criteria list.", "3. Test: tests/STORY.json. When the repo keeps its own tests in tests/ or test/, use tests/runtime/ or test/runtime/. Write steps with an exact check for each criterion.", `4. Check: run pdd ${test} --files STORY && pdd ${test} STORY in one shell call. Test includes interpreter lint (0 AI calls); use pdd lint for lint-only diagnosis.`, "5. Approve: a person reads each prompt and runs pdd approve PROMPT. New behavior needs a person."]) + promptingLines: Object.freeze(["In PDD, prompts are the source. Code follows the prompts.", "1. Prompt: prompts/NAME.prompt.md. Write what the program does in plain English, then ## Dependencies.", "2. Story: user_stories/STORY.md. Write one thing that a person can do, then a numbered ## Acceptance criteria list.", "3. Test: tests/STORY.json. When the repo keeps its own tests in tests/ or test/, use tests/runtime/ or test/runtime/. Write steps with an exact check for each criterion.", `4. Check: run pdd ${test} --files STORY && pdd ${test} STORY in one shell call. Test includes interpreter lint (0 AI calls); use pdd ${lint} for lint-only diagnosis.`, "5. Approve: a person reads each prompt and runs pdd approve PROMPT. New behavior needs a person."]) }); const approvalHelp = command => `Use the person's words after showing the gate or prompt. Ask the person in any chat, then relay their nonblank words without grading. Ask the person, then relay their words with --said. Without --said, use a separate person terminal. Chat alone never approves. Use this quoted heredoc by default: ${command} --said - <<'PDD_SAID' @@ -16,117 +84,9 @@ ${command} --said - <<'PDD_SAID' PDD_SAID Choose a delimiter absent as a whole line from the words. Keep the delimiter quoted. --said - reads all UTF-8 stdin, including trailing newlines. Simple words may use --said WORDS. Without --said, a person can use terminal y/N. Root pdd.json strict_approvals true requires a person terminal.`; const routes = [ - { id: 'metrics', prefix: ['metrics'], local: 'metrics', operands: [], options: [{name:'--json',kind:'flag'},{name:'--date',kind:'text'},{name:'--week',kind:'optional-text'},{name:'--snapshot',kind:'text'},{name:'--timezone',kind:'text'},{name:'--at',kind:'text'},{name:'--expected-source',kind:'text-list'}], - forms: [form('pdd metrics [--json] [--date YYYY-MM-DD | --week [YYYY-MM-DD] | --snapshot ID] [--timezone IANA] [--at UTC] [--expected-source ID...]', 'Show metrics for this repository.')] }, - { id: 'metrics.export', prefix: ['metrics', 'export'], local: 'metrics', operands: [{name:'file',type:'text'}], options: [{name:'--timezone',kind:'text'}], forms: [form('pdd metrics export FILE [--timezone IANA]', 'Export metrics for sharing.')] }, - { id: 'metrics.import', prefix: ['metrics', 'import'], local: 'metrics', operands: [{name:'file',type:'text'}], options: [], forms: [form('pdd metrics import FILE', 'Import a metrics bundle.')] }, - { id: 'metrics.record', prefix: ['metrics', 'record'], local: 'metrics', operands: [{name:'file',type:'text'}], options: [], forms: [form('pdd metrics record FILE', 'Record explicit metrics observations.')] }, - { id: 'autopilot.regressions', prefix: ['autopilot', 'regressions'], local: 'autopilot-regressions', operands: [], options: [{name:'--json',kind:'flag'},{name:'--file',kind:'text'}], - forms: [form('pdd autopilot regressions [--json] [--file PATH]', 'Read core merge history and GitHub regression evidence; optionally save a local report, without GitHub writes or reverts.')] }, - { id: 'autopilot.doctor', prefix: ['autopilot', 'doctor'], local: 'autopilot-doctor', operands: [], options: [], forms: [form('pdd autopilot doctor', 'Read-only first-start checks and fix commands; no AI call or GitHub write.')] }, - { id: 'autopilot.start', prefix: ['autopilot', 'start'], local: 'autopilot-start', operands: [], options: [{name:'--runs',kind:'text'},{name:'--checks',kind:'text'},{name:'--engine',kind:'value',choices:['core','full']},{name:'--label',kind:'text'},{name:'--mode',kind:'value',choices:['auto','observe','off']},{name:'--report',kind:'value',choices:['file','draft','off']},{name:'--decisions',kind:'value',choices:['ask','decide']},{name:'--intake',kind:'value',choices:['off','shadow','active']},{name:'--share',kind:'text'},{name:'--agent',kind:'text',choices:['codex','claude','gemini','agy']},{name:'--pool',kind:'text',hidden:true},{name:'--auto-update',kind:'value',choices:['release','main','off']}], - forms: [form('pdd autopilot start [--runs N] [--checks N] [--label NAME] [--mode auto|observe|off] [--report file|draft|off] [--decisions ask|decide] [--intake off|shadow|active] [--share PERCENT] [--agent codex|claude|gemini|agy] [--auto-update release|main|off]', 'Start this repo with headless agent jobs (the core engine): check now and every 10 minutes, with no AI call on empty ticks. Autopilot works on issues with an opt-in label (--label NAME or autopilot.label in pdd.json) or on vetted ready cards when --intake active is enabled; without --intake active, a start with no label starts nothing. --runs and --checks override machine-sized run and heavy-check limits; --label, --mode and --report save this machine\'s opt-in label, mode and report mode for this repo, over pdd.json (--mode observe runs every check but never merges; --report draft, the default, keeps problem reports on this machine); --decisions saves this machine\'s decision mode (ask asks a person only for a big decision; decide, the default, never asks); --intake saves this machine\'s intake mode (shadow writes local intake cards that never change what starts; active selects ready cards, refines improve cards via read-only repo inspection and groups related small work; off is the default). --share saves the percent of this machine\'s CPU and memory that Autopilot may use (1-100, default 50; it sets the automatic slots, the room check and the timer\'s memory limit). --agent saves or replaces this machine\'s agent and sign-in profile. --auto-update saves this machine\'s between-tick self-update mode for a user-owned global pdd install and its skills when no job is publishing or merging (release is the default; main tracks promptdriven/pdd main; off disables self-update). A machine that ran the removed full engine moves to the core engine at its next tick.')] }, - { id: 'autopilot.audit', prefix: ['autopilot', 'audit'], local: 'autopilot-audit', operands: [{name:'run',type:'text'},{name:'pr',type:'text'}], options: [], - forms: [form('pdd autopilot audit RUN PR', 'Audit an automatic merge once with a fresh agent and save its verdict.')] }, - { id: 'autopilot.check-base', prefix: ['autopilot', 'check-base'], local: 'autopilot-check-base', operands: [{name:'run',type:'text'},{name:'pr',type:'text'}], options: [], - forms: [form('pdd autopilot check-base RUN PR', 'Check the saved automatic base, PR target, current default branch and newest release before a merge or after it. This command reads only.')] }, - { id: 'autopilot.stop', prefix: ['autopilot', 'stop'], local: 'autopilot-stop', operands: [], options: [], - forms: [form('pdd autopilot stop', "Stop this machine's timer; let the current agent step finish.")] }, - { id: 'autopilot.status', prefix: ['autopilot', 'status'], local: 'autopilot-status', operands: [], options: [{name:'--all',kind:'flag'},{name:'--json',kind:'flag'}], - forms: [form('pdd autopilot status [--all] [--json]', "Show this machine's repo, folder, agent and next tick; --all lists every repository with Autopilot on this machine, from any folder.")] }, - { id: 'autopilot.report', prefix: ['autopilot', 'report'], local: 'autopilot-report', operands: [{name:'action',type:'choice:send',optional:true},{name:'fingerprint',type:'text',optional:true}], options: [], - forms: [form('pdd autopilot report', 'List the local Autopilot report drafts of this machine; no GitHub call.'), form('pdd autopilot report send FINGERPRINT', 'File one local report draft to promptdriven/pdd, or count it on the matching open report.')] }, - { id: 'autopilot.intake', prefix: ['autopilot', 'intake'], local: 'autopilot-intake', operands: [], options: [{name:'--json',kind:'flag'}], forms: [form('pdd autopilot intake [--json]', 'Print this machine\'s local intake cards for this repo (shadow mode), the would-pick list and today\'s changes; no AI call or GitHub write.')] }, - { id: 'autopilot.add', prefix: ['autopilot', 'add'], local: 'autopilot-add', operands: [{name:'issue',type:'issue',repeat:true}], options: [], - forms: [form('pdd autopilot add N...', 'Mark named old issues with pdd:autopilot so Autopilot may take them.')] }, - { id: 'autopilot.release', prefix: ['autopilot', 'release'], local: 'autopilot-release', operands: [{name:'issue',type:'issue'}], options: [], - forms: [form('pdd autopilot release ISSUE', "Release this machine's claim and remove pdd:working and pdd:stuck; keep the run folder, branch and PRs.")] }, - { id: 'autopilot.alert', prefix: ['autopilot', 'alert'], local: 'autopilot-alert', operands: [], - options: [{name:'--issue',kind:'text'},{name:'--kind',kind:'value',choices:['usage-limit','resource','interpreter','interpreter-access','access','decision','stuck','test-suite','long-running','recovered']},{name:'--input',kind:'text'},{name:'--update',kind:'flag'}], - forms: [form('pdd autopilot alert --issue N --kind usage-limit|resource|interpreter|interpreter-access|access|decision|stuck|test-suite|long-running|recovered --input - [--update]', 'Record one alert for a real human need or incident and send it to this machine\'s destination. Reads {"cause","tried","need"} JSON from stdin. usage-limit, resource, interpreter and interpreter-access are one alert per repository and machine for all blocked issues; access, decision, stuck, test-suite and long-running are one alert per issue. A repeat sends nothing unless the last send failed; --update sends a changed cause, decision or issue list, never attempt notes alone; one digest of open work per repository and machine is sent at most every 6 hours; recovered sends one recovery and closes the matching alerts.')] }, - { id: 'autopilot.alerts', prefix: ['autopilot', 'alerts'], local: 'autopilot-alerts', operands: [{name:'action',type:'choice:set,test,clear'}], options: [{name:'--discord-channel',kind:'text'},{name:'--token-command',kind:'text'},{name:'--destination',kind:'value',choices:['autopilot','infrastructure']}], - forms: [form('pdd autopilot alerts set [--destination autopilot|infrastructure]', 'Read a Discord or Slack incoming webhook URL from stdin and save it for this machine outside every repository, readable only by you; the URL is never printed. Post changed causes, decisions and recoveries; an unchanged stuck review sends nothing. Send one digest of open work per repository and machine at most every 6 hours. Use --destination infrastructure to separate machine incidents.'), - form('pdd autopilot alerts set --discord-channel ID [--token-command CMD] [--destination autopilot|infrastructure]', 'Use a Discord bot instead: read its token from stdin and save it readable only by you, or save CMD and run it at each send so the token is never written to disk. The token and the command output are never printed.'), - form('pdd autopilot alerts test [--destination autopilot|infrastructure]', 'Send one test message and confirm the posted message; for a bot, first show the bot name and channel name.'), - form('pdd autopilot alerts clear [--destination autopilot|infrastructure]', 'Remove the alert destination from this machine.')] }, - { id: 'graph', prefix: ['graph'], local: 'issue-dependency-graph', operands: [], options: [{name:'--open',kind:'flag'},{name:'--issue',kind:'text'},{name:'--repo',kind:'text'}], - forms: [form('pdd graph', 'Read native dependencies and saved reviews without AI.'), form('pdd graph --open', 'Open the local viewer.'), form('pdd graph --issue N', 'Select a root issue.'), form('pdd graph --open --issue N --repo OWNER/REPO', 'Open a selected issue in an explicit repository, including outside a checkout.')] }, - { id: 'dependencies.prepare', prefix: ['dependencies','prepare'], local: 'dependencies-prepare', operands: [], options: [{name:'--issue',kind:'text'}], forms: [form('pdd dependencies prepare [--issue N]', 'Read a scoped native coordinator packet without AI or GitHub writes.')] }, - { id: 'dependencies.complete', prefix: ['dependencies','complete'], local: 'dependencies-complete', operands: [], options: [{name:'--input',kind:'text'}], forms: [form('pdd dependencies complete --input -', 'Read a structured completion from stdin, save the review and reconcile its intended effects.')] }, - { id: 'workflow.suite', prefix: ['workflow', 'suite'], local: 'workflow-suite', operands: [], options: [{name:'--command',kind:'text'},{name:'--timeout',kind:'integer',min:0,max:120}], forms: [form('pdd workflow suite --command COMMAND [--timeout MIN]', 'Run a full suite through the shared machine queue (machine-sized check slots, 30-minute execution timeout; --timeout 0 runs it with no time limit, for a caller that watches it).')] }, - { id: 'workflow.park', prefix: ['workflow','park'], local: 'workflow-park', operands: [], options: [{name:'--reason',kind:'text'},{name:'--step',kind:'text'},{name:'--interpreter',kind:'flag'},{name:'--blocker',kind:'text'},{name:'--until',kind:'text'},{name:'--route',kind:'text'}], forms: [form('pdd workflow park --route KIND --reason TEXT [--until FIX] [--step STEP]', 'Record and park a missing supported PDD route.'), form('pdd workflow park --reason TEXT --blocker KIND [--until VALUE]', 'Wait for a named external blocker.'), form('pdd workflow park --reason TEXT --step STEP', 'Record an environment failure of a named validation step.'), form('pdd workflow park --reason TEXT', 'Record an automatic stop from its run worktree.'), form('pdd workflow park --interpreter --reason TEXT', 'Wait for the interpreter after an AI-service, busy or network result of its interpreter check: no question to a person, the worker slot can be yielded, and Autopilot wakes the run when the interpreter is back.')] }, - { id: 'workflow.yield', prefix: ['workflow','yield'], local: 'workflow-yield', operands: [{name:'ref',type:'text'}], options: [], forms: [form('pdd workflow yield N', 'Hand off automatic capacity after the worker has stopped.')] }, - { id: 'product.status', prefix: ['product', 'status'], local: 'product-status', operands: [], options: [{name:'--json',kind:'flag'}], - forms: [form('pdd product status [--json]', 'Count Stories by part and slice from the product plan; no interpreter calls.')] }, - { id: 'product.next', prefix: ['product', 'next'], local: 'product-next', operands: [], options: [], - forms: [form('pdd product next', 'Show ready planned runs and their start commands; no interpreter calls.')] }, - { id: 'product.start', prefix: ['product', 'start'], local: 'product-start', operands: [{name:'run',type:'text'}], options: [{name:'--no-run',kind:'flag'},{name:'--agent',kind:'text',choices:['codex','claude','gemini','agy']}], - forms: [form('pdd product start RUN [--no-run] [--agent codex|claude|gemini|agy|ENTRY]', 'Create or reuse the run issue and start a normal feature run; --no-run only prepares the issue; ENTRY is a name from ~/.config/pdd/agents.json. No interpreter calls.')] }, - // `workflow start` is a quiet word for now; a later change moves it to `removed`: one data edit. - { id: 'workflow.run', prefix: ['workflow', run], local: 'workflow-run', quiet: ['workflow', 'start'], - operands: [{name:'name',type:'workflow-name'},{name:'issue',type:'issue'}], - options:[{name:'--model',kind:'text'},{name:'--herdr-agent-name',kind:'text'},{name:'--codex-threads',kind:'text'},{name:'--agent',kind:'text',choices:['codex','claude','gemini','agy']},{name:'--base',kind:'text'},{name:'--adopt-corpus',kind:'text'},{name:'--draft',kind:'flag'},{name:'--through',kind:'value',choices:['prompt-pr','code']},{name:'--origin',kind:'value',choices:['manual','autopilot','unknown']},{name:'--decision-id',kind:'text'},{name:'--outcome',kind:'value',choices:['code','prompt-only']}], - forms:[form(`pdd workflow ${run} NAME ISSUE [--agent codex|claude|gemini|agy|ENTRY] [--base BRANCH] [--draft] [--model MODEL] [--herdr-agent-name NAME] [--codex-threads N]`, 'Start the first area chat for a GitHub issue in Herdr and exit; ENTRY is a name from ~/.config/pdd/agents.json; --base selects an existing origin branch (default: repository default); --draft requests draft PRs for this run; --adopt-corpus FILE adopts exact unchanged approved content for a fresh replay-evidence-enabled workflow; --origin, --decision-id and --outcome record optional metrics metadata; --through prompt-pr|code saves where a normal run goes after PR 1 (stop, or go on to the code PR); pdd later pushes the issue branch and opens a real PR.')] }, - { id: 'workflow.prove', prefix: ['workflow', 'prove'], local: 'workflow-prove', - operands: [{name:'issue',type:'issue'}], options: [{name:'--test',kind:'text'},{name:'--expect',kind:'text'},{name:'--timeout',kind:'integer',min:1,max:120}], - forms: [form('pdd workflow prove ISSUE --test COMMAND --expect TEXT [--timeout MIN]', 'Run committed changed tests on the fetched base branch merge-base and committed head with a limit per phase (default 10 minutes; --timeout sets 1 to 120); save a non-gating report that pull requests show as pdd\'s own result.')] }, - { id: 'workflow.done', prefix: ['workflow', 'done'], local: 'workflow-done', - operands: [{name:'step',type:'workflow-name'}], options: [{name:'--summary',kind:'text'},{name:'--skipped',kind:'text'},{name:'--no-publish',kind:'flag'}], - forms: [form('pdd workflow done STEP [--summary TEXT] [--skipped REASON] [--no-publish]', `For the agent in a run worktree: record a step with pdd's own latest pdd ${test}, pdd ${lint} and prove results (the summary is an agent note) and print what to do next; --skipped records that the step was skipped, and why; --no-publish records code-area completion locally before publishing.`)] }, - { id: 'workflow.publish', prefix: ['workflow', 'publish'], local: 'workflow-publish', operands: [{name:'issue',type:'issue'}], options: [], - forms: [form('pdd workflow publish ISSUE', 'Publish a finished code PR area without recording its steps again.')] }, - { id: 'workflow.cost', prefix: ['workflow', 'cost'], local: 'workflow-cost', operands: [{name:'issue',type:'issue'}], options: [{name:'--input',kind:'text'}], - forms: [form('pdd workflow cost ISSUE [--input -]', 'Read local issue costs or record measured suite/person minutes and outcome from JSON stdin.')] }, - { id: 'workflow.evidence', prefix: ['workflow', 'evidence'], local: 'workflow-evidence', - operands: [{name:'issue',type:'issue'}], options: [{name:'--summary',kind:'text'}], - forms: [form('pdd workflow evidence ISSUE --summary FILE', 'Record source-verified saved check JSON without rerunning steps, gates or publication.')] }, - { id: 'workflow.evidence-associate', prefix: ['workflow', 'evidence-associate'], local: 'workflow-evidence-associate', - operands: [{name:'issue',type:'issue'}], options: [{name:'--workspace',kind:'text'},{name:'--stage',kind:'value',choices:['current','pr1','before']},{name:'--commit',kind:'text'},{name:'--test',kind:'text-list'}], - forms: [form('pdd workflow evidence-associate ISSUE --workspace PATH --stage current|pr1|before [--commit SHA] --test PATH...', "Register this run's evidence workspace, stage and selected tests; before needs the commit of an earlier checked source; no checks or workflow progress.")] }, - { id: 'workflow.ask', prefix: ['workflow', 'ask'], local: 'workflow-ask', - operands: [{name:'question',type:'text',repeat:true}], options: [], - forms: [form('pdd workflow ask QUESTION', 'For the agent in a run worktree: show the person that the chat waits for their answer.')] }, - { id: 'workflow.request-uptake', prefix: ['workflow', requestUptake], local: 'workflow-request-uptake', - operands: [{name:'request-id',type:'text'}], options: [{name:'--summary',kind:'text'}], - forms: [form(`pdd workflow ${requestUptake} REQUEST_ID --summary TEXT`, 'For the agent in a run worktree: acknowledge a delivered change request with a short note.')] }, - { id: 'workflow.approve', prefix: ['workflow', 'approve'], local: 'workflow-approve', - operands: [{name:'issue',type:'issue',optional:true}], options: [{name:'--said',kind:'text'},{name:'--draft',kind:'flag'},{name:'--through',kind:'value',choices:['prompt-pr','code']}], - forms: [form('pdd workflow approve [ISSUE] [--said WORDS] [--draft]', 'Approve the gate and all its selected draft prompts in one step; --draft requests draft PRs at the current unpublished gate; --through prompt-pr|code records the person\'s code-or-stop choice from the Story card of a normal run. ' + approvalHelp('pdd workflow approve N'))] }, - { id: 'workflow.resend', prefix: ['workflow','resend'], local: 'workflow-resend', - operands: [{name:'issue',type:'issue',repeat:true}], options: [{name:'--said',kind:'text'}], - forms: [form('pdd workflow resend ISSUE... [--said WORDS]', 'Record one person decision and resend each lost check once; --said - reads exact words from stdin; strict mode requires a person terminal.')] }, - { id: 'workflow.card', prefix: ['workflow', 'card'], local: 'workflow-card', - operands: [{name:'issue',type:'issue',optional:true}], options: [], - forms: [form('pdd workflow card [ISSUE]', "Print the run's Story card from its real files: the request, the Story, the test cases, the prompts that change and the next step. Read-only; no GitHub, Herdr or interpreter call.")] }, - { id: 'workflow.changes', prefix: ['workflow', 'changes'], local: 'workflow-changes', - operands: [{name:'issue',type:'issue'},{name:'request',type:'text',repeat:true}], options: [], - forms: [form('pdd workflow changes ISSUE TEXT', 'Send a change request to the same area chat; the gate stays open.')] }, - { id: 'workflow.tidy', prefix: ['workflow','tidy'], local: 'workflow-tidy', operands: [], options: [{name:'--dry-run',kind:'flag'}], forms: [form('pdd workflow tidy [--dry-run]', 'Close safely finished chat tabs on this machine; dry-run reports without changes.')] }, - { id: 'workflow.cancel', prefix: ['workflow', 'cancel'], local: 'workflow-cancel', - operands: [{name:'issue',type:'issue'}], options: [], - forms: [form('pdd workflow cancel ISSUE', 'Cancel the run and close its Herdr tabs; keep the worktree and branch.')] }, - { id: 'workflow.status', prefix: ['workflow', 'status'], local: 'workflow-status', - operands: [{name:'issue',type:'issue',optional:true}], options: [{name:'--all',kind:'flag'},{name:'--cancelled',kind:'flag'},{name:'--json',kind:'flag'}], - forms: [form('pdd workflow status [ISSUE] [--all] [--cancelled] [--json]', 'Show this repo\'s runs, or one run with its area, gate, chat and PRs. --all (or outside a repo): every run on this machine, people-waiting first.')] }, - { id: 'workflow.view', prefix: ['workflow', 'view'], local: 'workflow-view', - operands: [{name:'issue',type:'issue'}], options: [], - forms: [form('pdd workflow view ISSUE', 'Read-only review of gates, approvals, files, PRs and Simulator links; never start or resume a chat.')] }, - { id: 'workflow.open', prefix: ['workflow', 'open'], local: 'workflow-open', - operands: [{name:'issue',type:'issue'}, {name:'area',type:'workflow-name',optional:true}], options: [{name:'--new',kind:'flag'},{name:'--model',kind:'text'},{name:'--herdr-agent-name',kind:'text'},{name:'--codex-threads',kind:'text'}], - forms: [form('pdd workflow open ISSUE [AREA] [--new] [--model MODEL] [--herdr-agent-name NAME] [--codex-threads N]', 'Focus or resume a saved area chat; --new replaces the current session while keeping the run and approvals.')] }, - // A help topic is a word after `help` only; it is no route prefix, so `pdd prompting` stays unknown. - { id: 'help', prefix: ['help'], local: 'help', operands: [], options: [], topics: ['prompting'], forms: [ - form('pdd', 'Show local commands.'), form('pdd --help', 'Show local commands.'), - form('pdd -h', 'Show local commands.'), form('pdd help', 'Show local commands.'), - form('pdd help prompting', 'Show how to write prompts, Stories and tests, and where the guide is.') ] }, - { id: 'version', prefix: ['--version'], quiet: ['-V'], local: 'version', operands: [], options: [], - forms: [form('pdd --version', 'Show this package version.'), form('pdd -V', 'Show this package version.')] }, - { id: 'version.detailed', prefix: ['-VV'], local: 'version-detailed', operands: [], options: [], - forms: [form('pdd -VV', 'Show this package version and the interpreter build and supported formats; unknown when unavailable. Uses existing gh sign-in, with no AI call.')] }, - { id: 'completion', prefix: ['completion'], local: 'completion', operands: [{ name: 'shell', type: 'choice:bash,zsh' }], options: [], - forms: [form('pdd completion bash|zsh', 'Print local shell completion.')] }, - { id: 'workflow.list', prefix: ['workflow', 'list'], local: 'workflow-list', operands: [], options: [{ name: '--json', kind: 'flag' }], - forms: [form('pdd workflow list [--json]', 'List the bundled workflows with their areas and gates.')] }, + // Core PDD workflow + { id: 'setup', prefix: ['setup'], local: 'setup', operands: [], options: [{ name: '--yes', kind: 'flag' }], + forms: [form('pdd setup [--yes]', 'Install the PDD skills for Codex and Claude if they are missing, and add the short PDD block to CLAUDE.md, else AGENTS.md. Offer detected Codex, Claude Code and Gemini MCP registrations after showing exact config changes and one y/N question. Offer Autopilot settings in a Git repository with a terminal; keep an existing mode on repeat setup. Without a terminal or with --yes, use safe defaults without questions.')] }, // A removed word runs nothing: the parser refuses it with one line that names the route's prefix. { id: 'check', prefix: [test], local: 'runtime-check', removed: ['check'], operands: [{ name: 'story', type: 'text', optional: true, repeat: true }], options: [{ name: '--target', kind: 'value', choices: ['code'] }, {name:'--affected',kind:'flag'}, {name:'--journeys',kind:'flag'}, { name: '--lf', kind: 'flag' }, { name: '--cache-clear', kind: 'flag' }, { name: '--json', kind: 'flag' }, { name: '--details', kind: 'flag' }, { name: '--timeout', kind: 'integer', min: 1, max: 120 }, @@ -144,12 +104,6 @@ const routes = [ options: [{ name: '--json', kind: 'flag' }, { name: '--timeout', kind: 'integer', min: 1, max: 120 }, { name: '--max-calls', kind: 'integer', min: 1, max: 1000 }, { name: '--local', kind: 'flag' }], forms: [form(`pdd ${lint} [STORY...] [--json] [--timeout MIN] [--max-calls N]`, 'Print local SVG layout warnings, then the PDD interpreter lint (0 AI calls) on selected Stories and their dependencies; sends no checks. --max-calls selects 1 to 1000 calls for structural preflight; warnings do not change the cap or guarantee completion.'), form(`pdd ${lint} --local [STORY...] [--json]`, 'Check linked SVG layout parts locally with warning diagnostics and 0 AI/network calls.')] }, - { id: 'files', prefix: ['files'], local: 'project-files', operands: [], options: [{ name: '--json', kind: 'flag' }], - forms: [form('pdd files [--json]', 'List prompts, Stories, tests and refusal reasons; no network calls.')] }, - { id: 'owner', prefix: ['owner'], local: 'file-owner', operands: [{ name: 'path', type: 'text', repeat: true }], options: [{ name: '--json', kind: 'flag' }], - forms: [form('pdd owner PATH... [--json]', 'Show which prompt owns each file, from pdd-bindings.json, Generated from headers and prompt opening sentences; reads local files only.')] }, - { id: 'approve', prefix: ['approve'], local: 'prompt-approve', operands: [{ name: 'prompt', type: 'text' }], options: [{name:'--said',kind:'text'}], - forms: [form('pdd approve PROMPT [--said WORDS]', "Show one prompt's text changes since its last approval (plus any embedded runtime interface or native-only declaration). Approve only that prompt. Easy mode accepts the person's nonblank words without grading them. " + approvalHelp('pdd approve PATH'))] }, // A quiet word (`sim`) parses like the prefix, with nothing added; help names `sim` once, completion never. { id: 'try', prefix: [simulate], local: 'runtime-try', quiet: ['sim'], removed: ['try'], operands: [{ name: 'story', type: 'text', optional: true }], options: [{name:'--product',kind:'flag'},{name:'--parts',kind:'text'},{name:'--journey',kind:'text'}, { name: '--agent', kind: 'text' }, { name: '--tab', kind: 'value', choices: ['call', 'screen', 'terminal', 'world'] }, { name: '--new', kind: 'flag' }, @@ -162,19 +116,23 @@ const routes = [ form(`pdd ${simulate} [STORY] --serve [PORT] [--max-calls N] [--new]`, 'Serve real HTTP requests through your Simulator session on localhost (default port 8080).'), form(`pdd ${simulate} --save-last`, 'Save the last terminal command and its output in the original Story test file.'), form(`pdd ${simulate} --stop [STORY]`, 'Stop the open Simulator link of a story.')] }, - { id: 'jobs', prefix: ['jobs'], local: 'runtime-jobs', operands: [], options: [], - forms: [form('pdd jobs', 'List active and waiting interpreter jobs on this machine without contacting the interpreter.')] }, + { id: 'approve', prefix: ['approve'], local: 'prompt-approve', operands: [{ name: 'prompt', type: 'text' }], options: [{name:'--said',kind:'text'}], + forms: [form('pdd approve PROMPT [--said WORDS]', "Show one prompt's text changes since its last approval (plus any embedded runtime interface or native-only declaration). Approve only that prompt. Easy mode accepts the person's nonblank words without grading them. " + approvalHelp('pdd approve PATH'))] }, + { id: 'files', prefix: ['files'], local: 'project-files', operands: [], options: [{ name: '--json', kind: 'flag' }], + forms: [form('pdd files [--json]', 'List prompts, Stories, tests and refusal reasons; no network calls.')] }, + { id: 'owner', prefix: ['owner'], local: 'file-owner', operands: [{ name: 'path', type: 'text', repeat: true }], options: [{ name: '--json', kind: 'flag' }], + forms: [form('pdd owner PATH... [--json]', 'Show which prompt owns each file, from pdd-bindings.json, Generated from headers and prompt opening sentences; reads local files only.')] }, { id: 'contracts', prefix: ['contracts'], local: 'contracts', operands: [], options: [], forms: [form('pdd contracts', 'List shared records, their users and Stories stale since their last check; local working files only.')] }, { id: 'contracts.sync', prefix: ['contracts', 'sync'], local: 'contracts-sync', operands: [], options: [{name:'--write',kind:'flag'}], forms: [form('pdd contracts sync [--write]', 'Show proposed changes for moving schema copies to references; apply only with --write. No interpreter calls.')] }, + { id: 'jobs', prefix: ['jobs'], local: 'runtime-jobs', operands: [], options: [], + forms: [form('pdd jobs', 'List active and waiting interpreter jobs on this machine without contacting the interpreter.')] }, { id: 'mcp', prefix: ['mcp'], local: 'mcp', operands: [], options: [], forms: [form('pdd mcp', 'Serve the current repository’s Try tools over stdio MCP.')] }, - { id: 'autopilot.off', prefix: ['autopilot', 'off'], local: 'autopilot.off', operands: [], options: [], forms: [form('pdd autopilot off', 'Set the repository Autopilot mode to off.')] }, - { id: 'autopilot.observe', prefix: ['autopilot', 'observe'], local: 'autopilot.observe', operands: [], options: [], forms: [form('pdd autopilot observe', 'Set the repository Autopilot mode to observe.')] }, - { id: 'autopilot.auto', prefix: ['autopilot', 'auto'], local: 'autopilot.auto', operands: [], options: [], forms: [form('pdd autopilot auto', 'Set the repository Autopilot mode to auto.')] }, - { id: 'autopilot.trust', prefix: ['autopilot', 'trust'], local: 'autopilot-trust', operands: [{name:'name',type:'text',repeat:true}], options: [], forms: [form('pdd autopilot trust NAME...', 'Add explicitly trusted GitHub names.')] }, - { id: 'autopilot.untrust', prefix: ['autopilot', 'untrust'], local: 'autopilot-untrust', operands: [{name:'name',type:'text'}], options: [], forms: [form('pdd autopilot untrust NAME', 'Remove an explicitly trusted GitHub name.')] }, + { id: 'upgrade', prefix: ['upgrade'], local: 'upgrade', operands: [], options: [{ name: '--main', kind: 'flag' }], + forms: [form('pdd upgrade [--main]', 'Upgrade a user-owned global pdd installation from the latest GitHub release (or pinned main commit with --main) and refresh installed user PDD skills.')] }, + // Cloud accounts { id: 'accounts', prefix: ['accounts'], local: 'accounts', operands: [], options: [{ name: '--json', kind: 'flag' }], forms: [form('pdd accounts [--json]', 'List enrolled and shared Cloud accounts, active selection, 5-hour and weekly usage windows, refresh status, and pending invites.')] }, { id: 'accounts.list', prefix: ['accounts', 'list'], local: 'accounts', operands: [], options: [{ name: '--json', kind: 'flag' }], @@ -215,10 +173,131 @@ const routes = [ forms: [form('pdd accounts remove LABEL', 'Delete LABEL from PDD Cloud and revoke active leases.')] }, { id: 'accounts.log', prefix: ['accounts', 'log'], local: 'accounts', operands: [{ name: 'label', type: 'text' }], options: [{ name: '--json', kind: 'flag' }], forms: [form('pdd accounts log LABEL [--json]', 'Show the lease and sharing audit log for LABEL.')] }, - { id: 'setup', prefix: ['setup'], local: 'setup', operands: [], options: [{ name: '--yes', kind: 'flag' }], - forms: [form('pdd setup [--yes]', 'Install the PDD skills for Codex and Claude if they are missing, and add the short PDD block to CLAUDE.md, else AGENTS.md. Offer detected Codex, Claude Code and Gemini MCP registrations after showing exact config changes and one y/N question. Offer Autopilot settings in a Git repository with a terminal; keep an existing mode on repeat setup. Without a terminal or with --yes, use safe defaults without questions.')] }, - { id: 'upgrade', prefix: ['upgrade'], local: 'upgrade', operands: [], options: [{ name: '--main', kind: 'flag' }], - forms: [form('pdd upgrade [--main]', 'Upgrade a user-owned global pdd installation from the latest GitHub release (or pinned main commit with --main) and refresh installed user PDD skills.')] }, + // Workflows & product + { id: 'product.status', prefix: ['product', 'status'], local: 'product-status', operands: [], options: [{name:'--json',kind:'flag'}], + forms: [form('pdd product status [--json]', 'Count Stories by part and slice from the product plan; no interpreter calls.')] }, + { id: 'product.next', prefix: ['product', 'next'], local: 'product-next', operands: [], options: [], + forms: [form('pdd product next', 'Show ready planned runs and their start commands; no interpreter calls.')] }, + { id: 'product.start', prefix: ['product', 'start'], local: 'product-start', operands: [{name:'run',type:'text'}], options: [{name:'--no-run',kind:'flag'},{name:'--agent',kind:'text',choices:['codex','claude','gemini','agy']}], + forms: [form('pdd product start RUN [--no-run] [--agent codex|claude|gemini|agy|ENTRY]', 'Create or reuse the run issue and start a normal feature run; --no-run only prepares the issue; ENTRY is a name from ~/.config/pdd/agents.json. No interpreter calls.')] }, + { id: 'workflow.list', prefix: ['workflow', 'list'], local: 'workflow-list', operands: [], options: [{ name: '--json', kind: 'flag' }], + forms: [form('pdd workflow list [--json]', 'List the bundled workflows with their areas and gates.')] }, + // `workflow start` is a quiet word for now; a later change moves it to `removed`: one data edit. + { id: 'workflow.run', prefix: ['workflow', run], local: 'workflow-run', quiet: ['workflow', 'start'], + operands: [{name:'name',type:'workflow-name'},{name:'issue',type:'issue'}], + options:[{name:'--model',kind:'text'},{name:'--herdr-agent-name',kind:'text'},{name:'--codex-threads',kind:'text'},{name:'--agent',kind:'text',choices:['codex','claude','gemini','agy']},{name:'--base',kind:'text'},{name:'--adopt-corpus',kind:'text'},{name:'--draft',kind:'flag'},{name:'--through',kind:'value',choices:['prompt-pr','code']},{name:'--origin',kind:'value',choices:['manual','autopilot','unknown']},{name:'--decision-id',kind:'text'},{name:'--outcome',kind:'value',choices:['code','prompt-only']}], + forms:[form(`pdd workflow ${run} NAME ISSUE [--agent codex|claude|gemini|agy|ENTRY] [--base BRANCH] [--draft] [--model MODEL] [--herdr-agent-name NAME] [--codex-threads N]`, 'Start the first area chat for a GitHub issue in Herdr and exit; ENTRY is a name from ~/.config/pdd/agents.json; --base selects an existing origin branch (default: repository default); --draft requests draft PRs for this run; --adopt-corpus FILE adopts exact unchanged approved content for a fresh replay-evidence-enabled workflow; --origin, --decision-id and --outcome record optional metrics metadata; --through prompt-pr|code saves where a normal run goes after PR 1 (stop, or go on to the code PR); pdd later pushes the issue branch and opens a real PR.')] }, + { id: 'workflow.status', prefix: ['workflow', 'status'], local: 'workflow-status', + operands: [{name:'issue',type:'issue',optional:true}], options: [{name:'--all',kind:'flag'},{name:'--cancelled',kind:'flag'},{name:'--json',kind:'flag'}], + forms: [form('pdd workflow status [ISSUE] [--all] [--cancelled] [--json]', 'Show this repo\'s runs, or one run with its area, gate, chat and PRs. --all (or outside a repo): every run on this machine, people-waiting first.')] }, + { id: 'workflow.view', prefix: ['workflow', 'view'], local: 'workflow-view', + operands: [{name:'issue',type:'issue'}], options: [], + forms: [form('pdd workflow view ISSUE', 'Read-only review of gates, approvals, files, PRs and Simulator links; never start or resume a chat.')] }, + { id: 'workflow.card', prefix: ['workflow', 'card'], local: 'workflow-card', + operands: [{name:'issue',type:'issue',optional:true}], options: [], + forms: [form('pdd workflow card [ISSUE]', "Print the run's Story card from its real files: the request, the Story, the test cases, the prompts that change and the next step. Read-only; no GitHub, Herdr or interpreter call.")] }, + { id: 'workflow.approve', prefix: ['workflow', 'approve'], local: 'workflow-approve', + operands: [{name:'issue',type:'issue',optional:true}], options: [{name:'--said',kind:'text'},{name:'--draft',kind:'flag'},{name:'--through',kind:'value',choices:['prompt-pr','code']}], + forms: [form('pdd workflow approve [ISSUE] [--said WORDS] [--draft]', 'Approve the gate and all its selected draft prompts in one step; --draft requests draft PRs at the current unpublished gate; --through prompt-pr|code records the person\'s code-or-stop choice from the Story card of a normal run. ' + approvalHelp('pdd workflow approve N'))] }, + { id: 'workflow.changes', prefix: ['workflow', 'changes'], local: 'workflow-changes', + operands: [{name:'issue',type:'issue'},{name:'request',type:'text',repeat:true}], options: [], + forms: [form('pdd workflow changes ISSUE TEXT', 'Send a change request to the same area chat; the gate stays open.')] }, + { id: 'workflow.open', prefix: ['workflow', 'open'], local: 'workflow-open', + operands: [{name:'issue',type:'issue'}, {name:'area',type:'workflow-name',optional:true}], options: [{name:'--new',kind:'flag'},{name:'--model',kind:'text'},{name:'--herdr-agent-name',kind:'text'},{name:'--codex-threads',kind:'text'}], + forms: [form('pdd workflow open ISSUE [AREA] [--new] [--model MODEL] [--herdr-agent-name NAME] [--codex-threads N]', 'Focus or resume a saved area chat; --new replaces the current session while keeping the run and approvals.')] }, + { id: 'workflow.prove', prefix: ['workflow', 'prove'], local: 'workflow-prove', + operands: [{name:'issue',type:'issue'}], options: [{name:'--test',kind:'text'},{name:'--expect',kind:'text'},{name:'--timeout',kind:'integer',min:1,max:120}], + forms: [form('pdd workflow prove ISSUE --test COMMAND --expect TEXT [--timeout MIN]', 'Run committed changed tests on the fetched base branch merge-base and committed head with a limit per phase (default 10 minutes; --timeout sets 1 to 120); save a non-gating report that pull requests show as pdd\'s own result.')] }, + { id: 'workflow.suite', prefix: ['workflow', 'suite'], local: 'workflow-suite', operands: [], options: [{name:'--command',kind:'text'},{name:'--timeout',kind:'integer',min:0,max:120}], forms: [form('pdd workflow suite --command COMMAND [--timeout MIN]', 'Run a full suite through the shared machine queue (machine-sized check slots, 30-minute execution timeout; --timeout 0 runs it with no time limit, for a caller that watches it).')] }, + { id: 'workflow.done', prefix: ['workflow', 'done'], local: 'workflow-done', + operands: [{name:'step',type:'workflow-name'}], options: [{name:'--summary',kind:'text'},{name:'--skipped',kind:'text'},{name:'--no-publish',kind:'flag'}], + forms: [form('pdd workflow done STEP [--summary TEXT] [--skipped REASON] [--no-publish]', `For the agent in a run worktree: record a step with pdd's own latest pdd ${test}, pdd ${lint} and prove results (the summary is an agent note) and print what to do next; --skipped records that the step was skipped, and why; --no-publish records code-area completion locally before publishing.`)] }, + { id: 'workflow.publish', prefix: ['workflow', 'publish'], local: 'workflow-publish', operands: [{name:'issue',type:'issue'}], options: [], + forms: [form('pdd workflow publish ISSUE', 'Publish a finished code PR area without recording its steps again.')] }, + { id: 'workflow.ask', prefix: ['workflow', 'ask'], local: 'workflow-ask', + operands: [{name:'question',type:'text',repeat:true}], options: [], + forms: [form('pdd workflow ask QUESTION', 'For the agent in a run worktree: show the person that the chat waits for their answer.')] }, + { id: 'workflow.request-uptake', prefix: ['workflow', requestUptake], local: 'workflow-request-uptake', + operands: [{name:'request-id',type:'text'}], options: [{name:'--summary',kind:'text'}], + forms: [form(`pdd workflow ${requestUptake} REQUEST_ID --summary TEXT`, 'For the agent in a run worktree: acknowledge a delivered change request with a short note.')] }, + { id: 'workflow.resend', prefix: ['workflow','resend'], local: 'workflow-resend', + operands: [{name:'issue',type:'issue',repeat:true}], options: [{name:'--said',kind:'text'}], + forms: [form('pdd workflow resend ISSUE... [--said WORDS]', 'Record one person decision and resend each lost check once; --said - reads exact words from stdin; strict mode requires a person terminal.')] }, + { id: 'workflow.park', prefix: ['workflow','park'], local: 'workflow-park', operands: [], options: [{name:'--reason',kind:'text'},{name:'--step',kind:'text'},{name:'--interpreter',kind:'flag'},{name:'--blocker',kind:'text'},{name:'--until',kind:'text'},{name:'--route',kind:'text'}], forms: [form('pdd workflow park --route KIND --reason TEXT [--until FIX] [--step STEP]', 'Record and park a missing supported PDD route.'), form('pdd workflow park --reason TEXT --blocker KIND [--until VALUE]', 'Wait for a named external blocker.'), form('pdd workflow park --reason TEXT --step STEP', 'Record an environment failure of a named validation step.'), form('pdd workflow park --reason TEXT', 'Record an automatic stop from its run worktree.'), form('pdd workflow park --interpreter --reason TEXT', 'Wait for the interpreter after an AI-service, busy or network result of its interpreter check: no question to a person, the worker slot can be yielded, and Autopilot wakes the run when the interpreter is back.')] }, + { id: 'workflow.yield', prefix: ['workflow','yield'], local: 'workflow-yield', operands: [{name:'ref',type:'text'}], options: [], forms: [form('pdd workflow yield N', 'Hand off automatic capacity after the worker has stopped.')] }, + { id: 'workflow.tidy', prefix: ['workflow','tidy'], local: 'workflow-tidy', operands: [], options: [{name:'--dry-run',kind:'flag'}], forms: [form('pdd workflow tidy [--dry-run]', 'Close safely finished chat tabs on this machine; dry-run reports without changes.')] }, + { id: 'workflow.cancel', prefix: ['workflow', 'cancel'], local: 'workflow-cancel', + operands: [{name:'issue',type:'issue'}], options: [], + forms: [form('pdd workflow cancel ISSUE', 'Cancel the run and close its Herdr tabs; keep the worktree and branch.')] }, + { id: 'workflow.cost', prefix: ['workflow', 'cost'], local: 'workflow-cost', operands: [{name:'issue',type:'issue'}], options: [{name:'--input',kind:'text'}], + forms: [form('pdd workflow cost ISSUE [--input -]', 'Read local issue costs or record measured suite/person minutes and outcome from JSON stdin.')] }, + { id: 'workflow.evidence', prefix: ['workflow', 'evidence'], local: 'workflow-evidence', + operands: [{name:'issue',type:'issue'}], options: [{name:'--summary',kind:'text'}], + forms: [form('pdd workflow evidence ISSUE --summary FILE', 'Record source-verified saved check JSON without rerunning steps, gates or publication.')] }, + { id: 'workflow.evidence-associate', prefix: ['workflow', 'evidence-associate'], local: 'workflow-evidence-associate', + operands: [{name:'issue',type:'issue'}], options: [{name:'--workspace',kind:'text'},{name:'--stage',kind:'value',choices:['current','pr1','before']},{name:'--commit',kind:'text'},{name:'--test',kind:'text-list'}], + forms: [form('pdd workflow evidence-associate ISSUE --workspace PATH --stage current|pr1|before [--commit SHA] --test PATH...', "Register this run's evidence workspace, stage and selected tests; before needs the commit of an earlier checked source; no checks or workflow progress.")] }, + { id: 'graph', prefix: ['graph'], local: 'issue-dependency-graph', operands: [], options: [{name:'--open',kind:'flag'},{name:'--issue',kind:'text'},{name:'--repo',kind:'text'}], + forms: [form('pdd graph', 'Read native dependencies and saved reviews without AI.'), form('pdd graph --open', 'Open the local viewer.'), form('pdd graph --issue N', 'Select a root issue.'), form('pdd graph --open --issue N --repo OWNER/REPO', 'Open a selected issue in an explicit repository, including outside a checkout.')] }, + { id: 'dependencies.prepare', prefix: ['dependencies','prepare'], local: 'dependencies-prepare', operands: [], options: [{name:'--issue',kind:'text'}], forms: [form('pdd dependencies prepare [--issue N]', 'Read a scoped native coordinator packet without AI or GitHub writes.')] }, + { id: 'dependencies.complete', prefix: ['dependencies','complete'], local: 'dependencies-complete', operands: [], options: [{name:'--input',kind:'text'}], forms: [form('pdd dependencies complete --input -', 'Read a structured completion from stdin, save the review and reconcile its intended effects.')] }, + // Autopilot + { id: 'autopilot.doctor', prefix: ['autopilot', 'doctor'], local: 'autopilot-doctor', operands: [], options: [], forms: [form('pdd autopilot doctor', 'Read-only first-start checks and fix commands; no AI call or GitHub write.')] }, + { id: 'autopilot.start', prefix: ['autopilot', 'start'], local: 'autopilot-start', operands: [], options: [{name:'--runs',kind:'text'},{name:'--checks',kind:'text'},{name:'--engine',kind:'value',choices:['core','full']},{name:'--label',kind:'text'},{name:'--mode',kind:'value',choices:['auto','observe','off']},{name:'--report',kind:'value',choices:['file','draft','off']},{name:'--decisions',kind:'value',choices:['ask','decide']},{name:'--intake',kind:'value',choices:['off','shadow','active']},{name:'--share',kind:'text'},{name:'--agent',kind:'text',choices:['codex','claude','gemini','agy']},{name:'--pool',kind:'text',hidden:true},{name:'--auto-update',kind:'value',choices:['release','main','off']}], + forms: [form('pdd autopilot start [--runs N] [--checks N] [--label NAME] [--mode auto|observe|off] [--report file|draft|off] [--decisions ask|decide] [--intake off|shadow|active] [--share PERCENT] [--agent codex|claude|gemini|agy] [--auto-update release|main|off]', 'Start this repo with headless agent jobs (the core engine): check now and every 10 minutes, with no AI call on empty ticks. Autopilot works on issues with an opt-in label (--label NAME or autopilot.label in pdd.json) or on vetted ready cards when --intake active is enabled; without --intake active, a start with no label starts nothing. --runs and --checks override machine-sized run and heavy-check limits; --label, --mode and --report save this machine\'s opt-in label, mode and report mode for this repo, over pdd.json (--mode observe runs every check but never merges; --report draft, the default, keeps problem reports on this machine); --decisions saves this machine\'s decision mode (ask asks a person only for a big decision; decide, the default, never asks); --intake saves this machine\'s intake mode (shadow writes local intake cards that never change what starts; active selects ready cards, refines improve cards via read-only repo inspection and groups related small work; off is the default). --share saves the percent of this machine\'s CPU and memory that Autopilot may use (1-100, default 50; it sets the automatic slots, the room check and the timer\'s memory limit). --agent saves or replaces this machine\'s agent and sign-in profile. --auto-update saves this machine\'s between-tick self-update mode for a user-owned global pdd install and its skills when no job is publishing or merging (release is the default; main tracks promptdriven/pdd main; off disables self-update).')] }, + { id: 'autopilot.status', prefix: ['autopilot', 'status'], local: 'autopilot-status', operands: [], options: [{name:'--all',kind:'flag'},{name:'--json',kind:'flag'}], + forms: [form('pdd autopilot status [--all] [--json]', "Show this machine's repo, folder, agent and next tick; --all lists every repository with Autopilot on this machine, from any folder.")] }, + { id: 'autopilot.logs', prefix: ['autopilot', 'logs'], local: 'autopilot-logs', operands: [{ name: 'issue', type: 'issue', optional: true }], + options: [{ name: '--issue', kind: 'text' }, { name: '--follow', kind: 'flag' }, { name: '-f', kind: 'flag' }, { name: '--lines', kind: 'integer', min: 1, max: 5000 }, { name: '--json', kind: 'flag' }], + forms: [ + form('pdd autopilot logs [ISSUE] [--follow|-f] [--lines N] [--json]', 'List current headless Autopilot workers with stage, owned process state, suite queue position, blockers and saved log or evidence paths, or inspect and follow one issue worker live (--follow / -f detaches cleanly on Ctrl-C without stopping the worker or changing observe mode). Read-only; no GitHub write or approval effect.'), + form('pdd autopilot logs --issue N [--follow|-f] [--lines N] [--json]', 'Select one worker explicitly with --issue N (number, #N, owner/repo#N or issue URL) to inspect saved progress or stream live updates.'), + ] }, + { id: 'autopilot.stop', prefix: ['autopilot', 'stop'], local: 'autopilot-stop', operands: [], options: [], + forms: [form('pdd autopilot stop', "Stop this machine's timer; let the current agent step finish.")] }, + { id: 'autopilot.observe', prefix: ['autopilot', 'observe'], local: 'autopilot.observe', operands: [], options: [], forms: [form('pdd autopilot observe', 'Set the repository Autopilot mode to observe.')] }, + { id: 'autopilot.auto', prefix: ['autopilot', 'auto'], local: 'autopilot.auto', operands: [], options: [], forms: [form('pdd autopilot auto', 'Set the repository Autopilot mode to auto.')] }, + { id: 'autopilot.off', prefix: ['autopilot', 'off'], local: 'autopilot.off', operands: [], options: [], forms: [form('pdd autopilot off', 'Set the repository Autopilot mode to off.')] }, + { id: 'autopilot.trust', prefix: ['autopilot', 'trust'], local: 'autopilot-trust', operands: [{name:'name',type:'text',repeat:true}], options: [], forms: [form('pdd autopilot trust NAME...', 'Add explicitly trusted GitHub names.')] }, + { id: 'autopilot.untrust', prefix: ['autopilot', 'untrust'], local: 'autopilot-untrust', operands: [{name:'name',type:'text'}], options: [], forms: [form('pdd autopilot untrust NAME', 'Remove an explicitly trusted GitHub name.')] }, + { id: 'autopilot.add', prefix: ['autopilot', 'add'], local: 'autopilot-add', operands: [{name:'issue',type:'issue',repeat:true}], options: [], + forms: [form('pdd autopilot add N...', 'Mark named old issues with pdd:autopilot so Autopilot may take them.')] }, + { id: 'autopilot.release', prefix: ['autopilot', 'release'], local: 'autopilot-release', operands: [{name:'issue',type:'issue'}], options: [], + forms: [form('pdd autopilot release ISSUE', "Release this machine's claim and remove pdd:working and pdd:stuck; keep the run folder, branch and PRs.")] }, + { id: 'autopilot.intake', prefix: ['autopilot', 'intake'], local: 'autopilot-intake', operands: [], options: [{name:'--json',kind:'flag'}], forms: [form('pdd autopilot intake [--json]', 'Print this machine\'s local intake cards for this repo (shadow mode), the would-pick list and today\'s changes; no AI call or GitHub write.')] }, + { id: 'autopilot.report', prefix: ['autopilot', 'report'], local: 'autopilot-report', operands: [{name:'action',type:'choice:send',optional:true},{name:'fingerprint',type:'text',optional:true}], options: [], + forms: [form('pdd autopilot report', 'List the local Autopilot report drafts of this machine; no GitHub call.'), form('pdd autopilot report send FINGERPRINT', 'File one local report draft to promptdriven/pdd, or count it on the matching open report.')] }, + { id: 'autopilot.regressions', prefix: ['autopilot', 'regressions'], local: 'autopilot-regressions', operands: [], options: [{name:'--json',kind:'flag'},{name:'--file',kind:'text'}], + forms: [form('pdd autopilot regressions [--json] [--file PATH]', 'Read core merge history and GitHub regression evidence; optionally save a local report, without GitHub writes or reverts.')] }, + { id: 'autopilot.alerts', prefix: ['autopilot', 'alerts'], local: 'autopilot-alerts', operands: [{name:'action',type:'choice:set,test,clear'}], options: [{name:'--discord-channel',kind:'text'},{name:'--token-command',kind:'text'},{name:'--destination',kind:'value',choices:['autopilot','infrastructure']}], + forms: [form('pdd autopilot alerts set [--destination autopilot|infrastructure]', 'Read a Discord or Slack incoming webhook URL from stdin and save it for this machine outside every repository, readable only by you; the URL is never printed. Post changed causes, decisions and recoveries; an unchanged stuck review sends nothing. Send one digest of open work per repository and machine at most every 6 hours. Use --destination infrastructure to separate machine incidents.'), + form('pdd autopilot alerts set --discord-channel ID [--token-command CMD] [--destination autopilot|infrastructure]', 'Use a Discord bot instead: read its token from stdin and save it readable only by you, or save CMD and run it at each send so the token is never written to disk. The token and the command output are never printed.'), + form('pdd autopilot alerts test [--destination autopilot|infrastructure]', 'Send one test message and confirm the posted message; for a bot, first show the bot name and channel name.'), + form('pdd autopilot alerts clear [--destination autopilot|infrastructure]', 'Remove the alert destination from this machine.')] }, + { id: 'autopilot.alert', prefix: ['autopilot', 'alert'], local: 'autopilot-alert', operands: [], + options: [{name:'--issue',kind:'text'},{name:'--kind',kind:'value',choices:['usage-limit','resource','interpreter','interpreter-access','access','decision','stuck','test-suite','long-running','recovered']},{name:'--input',kind:'text'},{name:'--update',kind:'flag'}], + forms: [form('pdd autopilot alert --issue N --kind usage-limit|resource|interpreter|interpreter-access|access|decision|stuck|test-suite|long-running|recovered --input - [--update]', 'Record one alert for a real human need or incident and send it to this machine\'s destination. Reads {"cause","tried","need"} JSON from stdin. usage-limit, resource, interpreter and interpreter-access are one alert per repository and machine for all blocked issues; access, decision, stuck, test-suite and long-running are one alert per issue. A repeat sends nothing unless the last send failed; --update sends a changed cause, decision or issue list, never attempt notes alone; one digest of open work per repository and machine is sent at most every 6 hours; recovered sends one recovery and closes the matching alerts.')] }, + { id: 'autopilot.audit', prefix: ['autopilot', 'audit'], local: 'autopilot-audit', operands: [{name:'run',type:'text'},{name:'pr',type:'text'}], options: [], + forms: [form('pdd autopilot audit RUN PR', 'Audit an automatic merge once with a fresh agent and save its verdict.')] }, + { id: 'autopilot.check-base', prefix: ['autopilot', 'check-base'], local: 'autopilot-check-base', operands: [{name:'run',type:'text'},{name:'pr',type:'text'}], options: [], + forms: [form('pdd autopilot check-base RUN PR', 'Check the saved automatic base, PR target, current default branch and newest release before a merge or after it. This command reads only.')] }, + // Metrics, shell & help + { id: 'metrics', prefix: ['metrics'], local: 'metrics', operands: [], options: [{name:'--json',kind:'flag'},{name:'--date',kind:'text'},{name:'--week',kind:'optional-text'},{name:'--snapshot',kind:'text'},{name:'--timezone',kind:'text'},{name:'--at',kind:'text'},{name:'--expected-source',kind:'text-list'}], + forms: [form('pdd metrics [--json] [--date YYYY-MM-DD | --week [YYYY-MM-DD] | --snapshot ID] [--timezone IANA] [--at UTC] [--expected-source ID...]', 'Show metrics for this repository.')] }, + { id: 'metrics.export', prefix: ['metrics', 'export'], local: 'metrics', operands: [{name:'file',type:'text'}], options: [{name:'--timezone',kind:'text'}], forms: [form('pdd metrics export FILE [--timezone IANA]', 'Export metrics for sharing.')] }, + { id: 'metrics.import', prefix: ['metrics', 'import'], local: 'metrics', operands: [{name:'file',type:'text'}], options: [], forms: [form('pdd metrics import FILE', 'Import a metrics bundle.')] }, + { id: 'metrics.record', prefix: ['metrics', 'record'], local: 'metrics', operands: [{name:'file',type:'text'}], options: [], forms: [form('pdd metrics record FILE', 'Record explicit metrics observations.')] }, + { id: 'completion', prefix: ['completion'], local: 'completion', operands: [{ name: 'shell', type: 'choice:bash,zsh' }], options: [], + forms: [form('pdd completion bash|zsh', 'Print local shell completion.')] }, + // A help topic is a word after `help` only; it is no route prefix, so `pdd prompting` stays unknown. + { id: 'help', prefix: ['help'], local: 'help', operands: [], options: [], topics: ['prompting'], forms: [ + form('pdd', 'Show local commands.'), form('pdd --help', 'Show local commands.'), + form('pdd -h', 'Show local commands.'), form('pdd help', 'Show local commands.'), + form('pdd help prompting', 'Show how to write prompts, Stories and tests, and where the guide is.') ] }, + { id: 'version', prefix: ['--version'], quiet: ['-V'], local: 'version', operands: [], options: [], + forms: [form('pdd --version', 'Show this package version.'), form('pdd -V', 'Show this package version.')] }, + { id: 'version.detailed', prefix: ['-VV'], local: 'version-detailed', operands: [], options: [], + forms: [form('pdd -VV', 'Show this package version and the interpreter build and supported formats; unknown when unavailable. Uses existing gh sign-in, with no AI call.')] }, ]; export const PUBLIC_COMMAND_ROUTES = Object.freeze(routes.map(route => Object.freeze({ ...route, prefix: Object.freeze(route.prefix), ...(route.quiet ? { quiet: Object.freeze(route.quiet) } : {}), diff --git a/src/pdd-cli.mjs b/src/pdd-cli.mjs index 83d6af331b..fa5df08f2e 100644 --- a/src/pdd-cli.mjs +++ b/src/pdd-cli.mjs @@ -105,16 +105,27 @@ const RUNNER_ROUTES = { const packageLines = packageRoot => PUBLIC_HELP_TEXT.learnLines.map(line => line.replace('PACKAGE_ROOT', () => packageRoot)); const renderTopic = (topic, packageRoot) => [PUBLIC_HELP_TEXT.heading, '', ...PUBLIC_HELP_TEXT.promptingLines, '', ...packageLines(packageRoot).slice(1)].join('\n'); export function renderHelp(prefix = [], packageRoot = PACKAGE_ROOT) { - const rows = PUBLIC_COMMAND_MANIFEST.filter(({ form }) => !prefix.length - || prefix.every((word, index) => form.slice(4).split(/\s+/)[index] === word)); - return [PUBLIC_HELP_TEXT.heading, '', ...rows.map(({ form, description }) => ` ${form} ${description}`), '', - ...(prefix.length ? [] : [...packageLines(packageRoot), '']), ...PUBLIC_HELP_TEXT.closingLines].join('\n'); + if (prefix.length > 0) { + const rows = PUBLIC_COMMAND_MANIFEST.filter(({ form }) => + prefix.every((word, index) => form.slice(4).split(/\s+/)[index] === word)); + return [PUBLIC_HELP_TEXT.heading, '', ...rows.map(({ form, description }) => ` ${form} ${description}`), '', + ...PUBLIC_HELP_TEXT.closingLines].join('\n'); + } + return [ + PUBLIC_HELP_TEXT.heading, '', + PUBLIC_HELP_TEXT.usageLine, '', + 'Quick start:', ...PUBLIC_HELP_TEXT.quickStartLines, '', + ...PUBLIC_HELP_TEXT.groups.flatMap((group, index) => [...(index ? [''] : []), `${group.title}:`, ...group.lines]), '', + ...PUBLIC_HELP_TEXT.focusedHelpLines, + ...packageLines(packageRoot), '', + ...PUBLIC_HELP_TEXT.closingLines, + ].join('\n'); } export async function runPdd(argv, { stdout = process.stdout, stderr = process.stderr, cwd = process.cwd(), packageRoot = PACKAGE_ROOT, env = process.env, workflowRunner, workflowAreas, stdin = process.stdin, confirm, mcpServer, runtimeSlots, contracts, product, productPorts, gitContext, workflowProve, provePorts, autopilotRegressions, autopilotRegressionsPorts = {}, issueGraph, issueGraphPorts = {}, dependencyIntake, dependencyIntakePorts = {}, autopilotLauncher, autopilotLauncherPorts = {}, workflowAgents = { checkWorkflowAgents }, workflowAgentPorts = {}, setupSkills = defaultSetupSkills, - setupProject = defaultSetupProject, setupAgentMcp, autopilot, autopilotPorts = {}, autopilotAlerts, autopilotAlertsPorts = {}, autopilotGithub: autopilotGithubModule, autopilotGithubPorts = {}, pathDiagnostic = defaultPathDiagnostic, + setupProject = defaultSetupProject, setupAgentMcp, autopilot, autopilotPorts = {}, autopilotLogs, autopilotLogsPorts = {}, autopilotAlerts, autopilotAlertsPorts = {}, autopilotGithub: autopilotGithubModule, autopilotGithubPorts = {}, pathDiagnostic = defaultPathDiagnostic, readPackageVersion = defaultReadPackageVersion, findSkills = defaultFindSkills, syncOwnedUserSkills = defaultSyncOwnedUserSkills, interpreterVersion, interpreterVersionPorts = {}, releaseNotice, releaseNoticePorts = {}, accountsCli, accountsPorts = {}, cliUpgrade, cliUpgradePorts = {} } = {}) { let plan; try { plan = parseArgv(argv); } @@ -122,7 +133,7 @@ export async function runPdd(argv, { stdout = process.stdout, stderr = process.s line(stderr, error instanceof CommandInputError ? error.message : 'The command could not be parsed. Run pdd --help.'); return 2; } - if (!['help', 'version', 'version-detailed', 'completion', 'workflow-list', 'project-files', 'file-owner', 'mcp', 'setup', 'upgrade'].includes(plan.local) + if (!['help', 'version', 'version-detailed', 'completion', 'workflow-list', 'project-files', 'file-owner', 'mcp', 'setup', 'upgrade', 'autopilot-logs'].includes(plan.local) && !(plan.local === 'accounts' && plan.options['--quiet'] === true) && plan.options['--json'] !== true && !argv.includes('--json')) { @@ -175,6 +186,35 @@ export async function runPdd(argv, { stdout = process.stdout, stderr = process.s line(result.exitCode === 0 ? stdout : stderr, result.message); return result.exitCode; } catch { line(stderr, 'Regression scan failed.'); return 1; } } + case 'autopilot-logs': { + const follow = Boolean(plan.options['--follow'] || plan.options['-f']); + const json = plan.options['--json'] === true; + if (follow && json) { line(stderr, '--json prints one snapshot and cannot be combined with --follow.'); return 2; } + if (plan.operands[0] !== undefined && plan.options['--issue'] !== undefined && plan.operands[0] !== plan.options['--issue']) { + line(stderr, 'Pass the issue once: pdd autopilot logs ISSUE or pdd autopilot logs --issue ISSUE.'); return 2; + } + if (follow && plan.operands[0] === undefined && plan.options['--issue'] === undefined) { + line(stderr, 'Select an issue to follow: pdd autopilot logs ISSUE --follow.'); return 2; + } + try { + const input = { + cwd, + env, + ...(plan.operands[0] !== undefined ? { positionalIssue: plan.operands[0] } : {}), + ...(plan.options['--issue'] !== undefined ? { optionIssue: plan.options['--issue'] } : {}), + follow, + ...(plan.options['--lines'] !== undefined ? { lines: Number(plan.options['--lines']) } : {}), + json, + }; + const ports = { stdout, stderr, ...autopilotLogsPorts }; + const result = autopilotLogs + ? await autopilotLogs.runAutopilotLogs(input, ports) + : await (await (autopilot ?? import('./autopilot.mjs'))).runAutopilotSubcommand('logs', input, ports); + if (!result || !Number.isInteger(result.exitCode) || result.exitCode < 0 || result.exitCode > 255 || typeof result.message !== 'string') throw Error('Invalid Autopilot logs reply'); + if (!result.streamed && result.message) line(result.exitCode === 0 ? stdout : stderr, result.message); + return result.exitCode; + } catch (error) { line(stderr, `Autopilot logs failed.${reason(error)}`); return 1; } + } case 'autopilot-doctor': case 'autopilot-audit': case 'autopilot-check-base': case 'autopilot-start': case 'autopilot-stop': case 'autopilot-status': case 'autopilot-add': case 'autopilot-release': case 'autopilot-report': case 'autopilot-intake': { try { const module = autopilotLauncher ?? await import('./autopilot-launcher.mjs'); @@ -483,7 +523,7 @@ export async function runPdd(argv, { stdout = process.stdout, stderr = process.s } catch { line(stderr, 'The bundled workflows could not be read. Use a complete PDD package.');return 1; } default: line(stderr, 'Unsupported command in pdd. Run pdd --help.');return 2; } })(); - if (!['help', 'completion', 'version', 'version-detailed', 'mcp', 'upgrade'].includes(plan.local) && !(plan.local === 'accounts' && plan.options['--quiet'] === true) && plan.options['--json'] !== true && (stderr?.isTTY === true || Boolean(releaseNotice))) { + if (!['help', 'completion', 'version', 'version-detailed', 'mcp', 'upgrade'].includes(plan.local) && !(plan.local === 'accounts' && plan.options['--quiet'] === true) && !(plan.local === 'autopilot-logs' && (plan.options['--follow'] === true || plan.options['-f'] === true)) && plan.options['--json'] !== true && (stderr?.isTTY === true || Boolean(releaseNotice))) { try { const metadata = await readPackageVersion({ packageRoot }); if (metadata?.ok && typeof metadata.version === 'string' && metadata.version) { diff --git a/test/approval-help.test.mjs b/test/approval-help.test.mjs index 886f999a55..9181e5f5b9 100644 --- a/test/approval-help.test.mjs +++ b/test/approval-help.test.mjs @@ -7,27 +7,40 @@ import path from 'node:path'; // Portable when copied into test/; external proof selects the source root explicitly. const root = process.env.PDD_HELP_SOURCE_ROOT || fileURLToPath(new URL('../', import.meta.url)); -test('public workflow approval help requires explicit person relay or person terminal', () => { - const result = spawnSync(process.execPath, [path.join(root, 'bin/pdd.mjs'), '--help'], {encoding: 'utf8', timeout: 10000}); - assert.equal(result.error, undefined, 'CLI help must execute'); - assert.equal(result.status, 0, result.stderr); - const line = result.stdout.split('\n').find(row => /^\s+pdd workflow approve /.test(row)); - assert.ok(line, 'workflow approve must appear in public help'); +const runHelp = args => spawnSync(process.execPath, [path.join(root, 'bin/pdd.mjs'), ...args], {encoding: 'utf8', timeout: 10000}); + +test('public approval help keeps root overview concise and shows full person-relay heredocs in focused help', () => { + const rootHelp = runHelp(['--help']); + assert.equal(rootHelp.error, undefined, 'CLI root help must execute'); + assert.equal(rootHelp.status, 0, rootHelp.stderr); + assert.match(rootHelp.stdout, /^\s+pdd approve PROMPT\b/m, 'approve must appear in root help'); + assert.match(rootHelp.stdout, /^\s+pdd workflow approve \[ISSUE\]/m, 'workflow approve must appear in root help'); + assert.doesNotMatch(rootHelp.stdout, /<<'PDD_SAID'/, 'root help must not duplicate approval heredocs'); + + const workflowApprove = runHelp(['workflow', 'approve', '--help']); + assert.equal(workflowApprove.error, undefined, 'workflow approve help must execute'); + assert.equal(workflowApprove.status, 0, workflowApprove.stderr); + const line = workflowApprove.stdout.split('\n').find(row => /^\s+pdd workflow approve /.test(row)); + assert.ok(line, 'workflow approve must appear in focused help'); assert.doesNotMatch(line, /no-said keeps terminal\/native-chat approval|or use terminal\/native area-chat approval/i, 'help must not advertise independent native-chat approval'); assert.match(line, /--said/); assert.match(line, /gate.*all.*draft/i); - assert.match(result.stdout, /nonblank|non-empty|nonempty/i); - assert.match(result.stdout, /any chat/i); - assert.match(result.stdout, /without grading|does not grade|no grading/i); - assert.match(result.stdout, /ask.*person/i); - assert.match(result.stdout, /agent/i); - assert.match(result.stdout, /ask the person[.;,]? then relay their words with --said/i); - assert.match(result.stdout, /without --said, use a separate person terminal/i); - assert.doesNotMatch(result.stdout, /non-TTY|current[- ]area[- ]pane/i); - assert.match(result.stdout, /terminal y\/N/i); - assert.match(result.stdout, /strict_approvals.*terminal/i); - assert.ok(result.stdout.includes("pdd workflow approve N --said - <<'PDD_SAID'\n")); - assert.ok(result.stdout.includes("pdd approve PATH --said - <<'PDD_SAID'\n")); - assert.match(result.stdout,/trailing newlines/i); - assert.match(result.stdout,/delimiter absent/i); + for (const out of [workflowApprove.stdout, runHelp(['approve', '--help']).stdout]) { + assert.match(out, /nonblank|non-empty|nonempty/i); + assert.match(out, /any chat/i); + assert.match(out, /without grading|does not grade|no grading/i); + assert.match(out, /ask.*person/i); + assert.match(out, /agent/i); + assert.match(out, /ask the person[.;,]? then relay their words with --said/i); + assert.match(out, /without --said, use a separate person terminal/i); + assert.doesNotMatch(out, /non-TTY|current[- ]area[- ]pane/i); + assert.match(out, /terminal y\/N/i); + assert.match(out, /strict_approvals.*terminal/i); + assert.match(out, /trailing newlines/i); + assert.match(out, /delimiter absent/i); + } + assert.ok(workflowApprove.stdout.includes("pdd workflow approve N --said - <<'PDD_SAID'\n")); + const promptApprove = runHelp(['approve', '--help']); + assert.equal(promptApprove.status, 0, promptApprove.stderr); + assert.ok(promptApprove.stdout.includes("pdd approve PATH --said - <<'PDD_SAID'\n")); }); diff --git a/test/autopilot-logs.test.mjs b/test/autopilot-logs.test.mjs new file mode 100644 index 0000000000..f3342dbeab --- /dev/null +++ b/test/autopilot-logs.test.mjs @@ -0,0 +1,450 @@ +import './helpers/test-home.mjs'; +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { formatWorkerLogLine, inspectAutopilotWorkers, parseIssueSelector, runAutopilotLogs } from '../src/autopilot-logs.mjs'; +import { runAutopilotSubcommand } from '../src/autopilot.mjs'; +import { renderCompletion } from '../src/completion.mjs'; +import { renderHelp, runPdd } from '../src/pdd-cli.mjs'; + +const sink = () => ({ text: '', write(chunk) { this.text += chunk; return true; } }); + +function makeSandbox(t, { mode = 'observe', repo = 'acme/widgets' } = {}) { + const base = mkdtempSync(join(tmpdir(), 'pdd-ap-logs-')); + t.after(() => rmSync(base, { recursive: true, force: true })); + const gitRoot = join(base, 'repo'); + const stateRoot = join(base, 'state', 'pdd', 'autopilot'); + const stateId = createHash('sha256').update(gitRoot).digest('hex').slice(0, 20); + const coreRoot = join(stateRoot, `${stateId}-core`); + mkdirSync(gitRoot, { recursive: true }); + mkdirSync(join(coreRoot, 'jobs'), { recursive: true }); + mkdirSync(join(coreRoot, 'intake', 'jobs'), { recursive: true }); + mkdirSync(join(coreRoot, 'logs'), { recursive: true }); + + writeFileSync(join(gitRoot, 'pdd.json'), JSON.stringify({ autopilot: { mode, trust: ['alice'] } }, null, 2) + '\n'); + writeFileSync(join(stateRoot, `${stateId}.json`), JSON.stringify({ + repo, + root: gitRoot, + enabled: true, + mode, + }, null, 2) + '\n'); + writeFileSync(join(coreRoot, 'core.json'), JSON.stringify({ streak: 0 }, null, 2) + '\n'); + + const git = async args => { + if (args[0] === 'rev-parse' && args[1] === '--show-toplevel') return { code: 0, stdout: `${gitRoot}\n`, stderr: '' }; + return { code: 1, stdout: '', stderr: 'unexpected git call' }; + }; + + return { base, gitRoot, stateRoot, stateId, coreRoot, git }; +} + +function snapshotTree(dir) { + const entries = []; + const walk = current => { + for (const name of readdirSync(current).sort()) { + const full = join(current, name); + const st = statSync(full); + if (st.isDirectory()) { + entries.push({ path: full, kind: 'dir' }); + walk(full); + } else { + entries.push({ path: full, kind: 'file', size: st.size, sha: createHash('sha256').update(readFileSync(full)).digest('hex') }); + } + } + }; + walk(dir); + return entries; +} + +test('3475: pdd autopilot logs is discoverable in help and shell completion and validates selectors', async () => { + assert.match(renderHelp(['autopilot']), /pdd autopilot logs \[ISSUE\] \[--follow\|-f\] \[--lines N\] \[--json\]/); + assert.match(renderCompletion('bash'), /\blogs\b/); + assert.match(renderCompletion('zsh'), /\blogs\b/); + + assert.deepEqual(parseIssueSelector('42'), { ok: true, issue: 42, repo: null }); + assert.deepEqual(parseIssueSelector('#42'), { ok: true, issue: 42, repo: null }); + assert.deepEqual(parseIssueSelector('acme/widgets#42'), { ok: true, issue: 42, repo: 'acme/widgets' }); + assert.deepEqual(parseIssueSelector('https://github.com/acme/widgets/issues/42'), { ok: true, issue: 42, repo: 'acme/widgets' }); + assert.equal(parseIssueSelector('0').ok, false); + assert.equal(parseIssueSelector('not-an-issue').ok, false); + + // Invalid CLI combinations fail fast with exit 2 and no side effects + for (const argv of [ + ['autopilot', 'logs', '--follow'], + ['autopilot', 'logs', '-f'], + ['autopilot', 'logs', '12', '--follow', '--json'], + ['autopilot', 'logs', '12', '--issue', '13'], + ['autopilot', 'logs', '--lines', '0'], + ]) { + const stdout = sink(), stderr = sink(); + const code = await runPdd(argv, { stdout, stderr, cwd: '/tmp' }); + assert.equal(code, 2, argv.join(' ')); + assert.equal(stdout.text, ''); + assert.ok(stderr.text.trim().length > 0); + } + + const unknownSub = await runAutopilotSubcommand('unknown', {}); + assert.equal(unknownSub.exitCode, 2); +}); + +test('3475: outside a Git repository pdd autopilot logs exits 1 with clear guidance', async () => { + const stdout = sink(), stderr = sink(); + const code = await runPdd(['autopilot', 'logs'], { + stdout, + stderr, + cwd: '/tmp/not-a-repo', + autopilotLogsPorts: { + git: async () => ({ code: 128, stdout: '', stderr: 'fatal: not a git repository (or any of the parent directories): .git\n' }), + }, + }); + assert.equal(code, 1); + assert.equal(stdout.text, ''); + assert.match(stderr.text, /This folder is not a Git repository/); +}); + +test('3475: formatWorkerLogLine renders Codex, Claude, Gemini/agy JSONL and redacts secrets & ANSI codes', () => { + // Codex events + assert.equal( + formatWorkerLogLine(JSON.stringify({ type: 'thread.started', model: 'gpt-5-codex' })), + '[session] started (gpt-5-codex)', + ); + assert.equal( + formatWorkerLogLine(JSON.stringify({ + type: 'item.started', + item: { type: 'command_execution', command: '/bin/zsh -lc "node --test test/foo.test.mjs"' }, + })), + '[run] $ /bin/zsh -lc "node --test test/foo.test.mjs"', + ); + const completedCmd = formatWorkerLogLine(JSON.stringify({ + type: 'item.completed', + item: { + type: 'command_execution', + command: 'bash -lc "gh auth token"', + exit_code: 0, + aggregated_output: '\x1b[32mToken: ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\x1b[0m\nDone\n', + }, + })); + assert.match(completedCmd, /\[cmd exit=0\] \$ bash -lc "gh auth token"/); + assert.doesNotMatch(completedCmd, /ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890/); + assert.doesNotMatch(completedCmd, /\x1b\[/); + + assert.equal( + formatWorkerLogLine(JSON.stringify({ + type: 'item.completed', + item: { type: 'file_change', changes: [{ kind: 'update', path: 'src/foo.mjs' }] }, + })), + '[edit] src/foo.mjs', + ); + assert.equal( + formatWorkerLogLine(JSON.stringify({ + type: 'item.completed', + item: { type: 'agent_message', text: 'Updated prompt and verified tests.' }, + })), + '[agent] Updated prompt and verified tests.', + ); + // Noisy token heartbeat events return empty string + assert.equal(formatWorkerLogLine(JSON.stringify({ type: 'turn.started' })), ''); + assert.equal(formatWorkerLogLine(JSON.stringify({ type: 'token_count', total: 100 })), ''); + + // Claude stream-json events + const claudeLine = formatWorkerLogLine(JSON.stringify({ + type: 'assistant', + message: { + content: [ + { type: 'text', text: 'Checking worker logs.' }, + { type: 'tool_use', name: 'Bash', input: { command: 'git status' } }, + ], + }, + })); + assert.match(claudeLine, /\[agent\] Checking worker logs\./); + assert.match(claudeLine, /\[tool\] Bash: git status/); + + // Gemini / agy stream-json events + assert.equal( + formatWorkerLogLine(JSON.stringify({ type: 'tool_use', tool_name: 'read_file', parameters: { path: 'docs/cli.md' } })), + '[tool] read_file: docs/cli.md', + ); +}); + +test('3475: distinguishes queued suite, live running suite, repair worker, and stale suite receipt / dead process', async t => { + const sb = makeSandbox(t, { mode: 'observe' }); + const nowMs = Date.parse('2026-11-17T20:30:00Z'); + + // Worker #101: PR check queued in shared test-suite queue (position 2) + const log101 = join(sb.coreRoot, 'logs', '101-suite-1.log'); + writeFileSync(log101, 'Waiting in shared suite queue...\n'); + utimesSync(log101, (nowMs - 15_000) / 1000, (nowMs - 15_000) / 1000); + writeFileSync(join(sb.coreRoot, 'jobs', '101.json'), JSON.stringify({ + issue: 101, + title: 'Add queue status header', + phase: 'pr', + pr: 210, + head: 'aaaa1111bbbb2222', + root: join(sb.base, 'wt-101'), + suite: { + cwd: join(sb.base, 'wt-101'), + head: 'aaaa1111bbbb2222', + agent: { pid: 4101, token: 'tok-101', log: log101, startedAt: nowMs - 60_000 }, + }, + })); + + // Worker #102: PR check with LIVE running full test suite + validation log + saved evidence + const suiteLiveLog = join(sb.base, 'validation-102.log'); + writeFileSync(suiteLiveLog, 'ok 1 - first suite case\nok 2 - second suite case\n'); + utimesSync(suiteLiveLog, (nowMs - 5_000) / 1000, (nowMs - 5_000) / 1000); + const ev102 = join(sb.coreRoot, 'logs', '102-evidence-cccc3333.json'); + writeFileSync(ev102, '{"ok":true}\n'); + writeFileSync(join(sb.coreRoot, 'jobs', '102.json'), JSON.stringify({ + issue: 102, + title: 'Stream validation progress', + phase: 'pr', + pr: 211, + head: 'cccc3333dddd4444', + root: join(sb.base, 'wt-102'), + suite: { + cwd: join(sb.base, 'wt-102'), + head: 'cccc3333dddd4444', + agent: { pid: 4102, token: 'tok-102', log: join(sb.coreRoot, 'logs', '102-suite-1.log'), startedAt: nowMs - 90_000 }, + }, + })); + + // Worker #103: Active repair #2 on PR #212 + const log103 = join(sb.coreRoot, 'logs', '103-repair-2.log'); + writeFileSync(log103, JSON.stringify({ + type: 'item.completed', + item: { type: 'agent_message', text: 'Fixing failing edge case in parser.' }, + }) + '\n'); + utimesSync(log103, (nowMs - 3_000) / 1000, (nowMs - 3_000) / 1000); + writeFileSync(join(sb.coreRoot, 'jobs', '103.json'), JSON.stringify({ + issue: 103, + title: 'Handle empty input', + role: 'repair', + repairs: 2, + pr: 212, + head: 'eeee5555ffff6666', + lastError: 'Review requested null guard', + agent: { pid: 4103, token: 'tok-103', log: log103, startedAt: nowMs - 45_000 }, + })); + + // Worker #104: Stale suite receipt (runner crashed before reporting) + const log104 = join(sb.coreRoot, 'logs', '104-suite-1.log'); + writeFileSync(log104, 'Started suite wrapper\n'); + writeFileSync(join(sb.coreRoot, 'jobs', '104.json'), JSON.stringify({ + issue: 104, + title: 'Detect stale suite receipt', + phase: 'pr', + pr: 213, + head: '99990000aaaa1111', + root: join(sb.base, 'wt-104'), + suite: { + cwd: join(sb.base, 'wt-104'), + head: '99990000aaaa1111', + agent: { pid: 4104, token: 'tok-104', log: log104, startedAt: nowMs - 300_000 }, + }, + })); + + // Historical finished worker #99 in history.jsonl + const log99 = join(sb.coreRoot, 'logs', '99-build-1.log'); + writeFileSync(log99, JSON.stringify({ + type: 'item.completed', + item: { type: 'agent_message', text: 'Opened PR #199 cleanly.' }, + }) + '\n'); + writeFileSync(join(sb.coreRoot, 'history.jsonl'), JSON.stringify({ + issue: 99, + outcome: 'ready-observe', + pr: 199, + at: nowMs - 600_000, + text: 'checks passed in observe mode', + }) + '\n'); + + const alivePids = new Set([4101, 4102, 4103]); // 4104 is dead with no .exit.json! + const ports = { + git: sb.git, + stateRoot: sb.stateRoot, + now: () => nowMs, + isProcessAlive: pid => alivePids.has(pid), + readSuite: ({ cwd }) => { + if (cwd.endsWith('wt-101')) return { ok: true, state: 'waiting', position: 2, commit: 'aaaa1111bbbb2222' }; + if (cwd.endsWith('wt-102')) { + return { + ok: true, + state: 'running', + childPid: 5202, + commit: 'cccc3333dddd4444', + counts: { pass: 2, fail: 0 }, + logPath: suiteLiveLog, + }; + } + if (cwd.endsWith('wt-104')) { + return { + ok: false, + reason: 'recorder_not_running', + outcome: 'The suite runner ended before reporting.', + commit: '99990000aaaa1111', + }; + } + return { ok: false, reason: 'none' }; + }, + }; + + const beforeSnapshot = snapshotTree(sb.base); + + // 1. List view (`pdd autopilot logs`) + const listOut = sink(), listErr = sink(); + const listCode = await runPdd(['autopilot', 'logs'], { + stdout: listOut, + stderr: listErr, + cwd: sb.gitRoot, + autopilotLogsPorts: ports, + }); + assert.equal(listCode, 0, listErr.text); + assert.equal(listErr.text, ''); + assert.match(listOut.text, /mode observe \(read-only viewer; observe mode never approves or merges\)/); + assert.match(listOut.text, /#101 "Add queue status header"[\s\S]*?queued in shared test-suite queue \(position 2\)/); + assert.match(listOut.text, /#102 "Stream validation progress"[\s\S]*?running full test suite \(pid 5202\) \[pass 2, fail 0\]/); + assert.match(listOut.text, /#103 "Handle empty input"[\s\S]*?Stage: repair #2 on PR #212/); + assert.match(listOut.text, /#104 "Detect stale suite receipt"[\s\S]*?stale suite receipt/); + assert.match(listOut.text, /Recent finished workers[\s\S]*?#99 \(PR #199\): ready-observe/); + assert.match(listOut.text, /Follow a worker live: pdd autopilot logs 101 --follow/); + + // 2. Selected worker view via --issue N (`pdd autopilot logs --issue 102 --lines 5`) + const issueOut = sink(), issueErr = sink(); + const issueCode = await runPdd(['autopilot', 'logs', '--issue', '102', '--lines', '5'], { + stdout: issueOut, + stderr: issueErr, + cwd: sb.gitRoot, + autopilotLogsPorts: ports, + }); + assert.equal(issueCode, 0, issueErr.text); + assert.match(issueOut.text, /Stage: PR #211 \(cccc3333\): running full test suite \(pid 5202\) \[pass 2, fail 0\]/); + assert.match(issueOut.text, new RegExp(ev102.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))); + assert.match(issueOut.text, /ok 1 - first suite case/); + assert.match(issueOut.text, /ok 2 - second suite case/); + + // 3. JSON snapshot (`pdd autopilot logs 101 --json`) + const jsonOut = sink(), jsonErr = sink(); + const jsonCode = await runPdd(['autopilot', 'logs', '101', '--json'], { + stdout: jsonOut, + stderr: jsonErr, + cwd: sb.gitRoot, + autopilotLogsPorts: ports, + }); + assert.equal(jsonCode, 0, jsonErr.text); + const parsed = JSON.parse(jsonOut.text); + assert.equal(parsed.schema, 'pdd.autopilot-logs.v1'); + assert.equal(parsed.mode, 'observe'); + assert.equal(parsed.worker.stage, 'suite-queued'); + assert.equal(parsed.worker.suite.position, 2); + + // 4. Historical worker inspection (`pdd autopilot logs 99`) + const histRes = await runAutopilotLogs({ cwd: sb.gitRoot, issue: '99' }, ports); + assert.equal(histRes.exitCode, 0); + assert.match(histRes.message, /Stage: finished \(ready-observe/); + assert.match(histRes.message, /\[agent\] Opened PR #199 cleanly\./); + + // Strict read-only invariant: zero files created, modified or deleted anywhere in repo or state folder! + assert.deepEqual(snapshotTree(sb.base), beforeSnapshot, 'viewer must be 100% read-only and preserve observe mode'); +}); + +test('3475: --follow streams live updates across stage transitions and detaches cleanly without stopping the worker', async t => { + const sb = makeSandbox(t, { mode: 'observe' }); + let nowMs = Date.parse('2026-11-17T20:40:00Z'); + const buildLog = join(sb.coreRoot, 'logs', '77-build-1.log'); + const suiteLog = join(sb.base, 'suite-77.log'); + const jobFile = join(sb.coreRoot, 'jobs', '77.json'); + + writeFileSync(buildLog, JSON.stringify({ + type: 'item.completed', + item: { type: 'agent_message', text: 'Initial build step started.' }, + }) + '\n'); + writeFileSync(jobFile, JSON.stringify({ + issue: 77, + title: 'Follow live worker safely', + role: 'build', + agent: { pid: 7701, token: 'tok-77', log: buildLog, startedAt: nowMs - 10_000 }, + })); + + const abortController = new AbortController(); + let suiteState = { ok: false, reason: 'none' }; + let tick = 0; + const stdout = sink(), stderr = sink(); + + const exitCode = await runPdd(['autopilot', 'logs', '77', '-f'], { + stdout, + stderr, + cwd: sb.gitRoot, + autopilotLogsPorts: { + git: sb.git, + stateRoot: sb.stateRoot, + now: () => nowMs, + isProcessAlive: pid => pid === 7701 || pid === 7702, + readSuite: () => suiteState, + signal: abortController.signal, + pollMs: 10, + sleep: async () => { + tick++; + nowMs += 1000; + if (tick === 1) { + // Worker appends another JSONL progress line while building + writeFileSync(buildLog, readFileSync(buildLog, 'utf8') + JSON.stringify({ + type: 'item.completed', + item: { type: 'command_execution', command: 'npm run check', exit_code: 0, aggregated_output: '' }, + }) + '\n'); + } else if (tick === 2) { + // Worker transitions to PR suite-running and opens live suite validation log + writeFileSync(suiteLog, 'TAP version 13\nok 1 - live streamed test\n'); + suiteState = { + ok: true, + state: 'running', + childPid: 7702, + commit: '1234abcd', + counts: { pass: 1, fail: 0 }, + logPath: suiteLog, + }; + writeFileSync(jobFile, JSON.stringify({ + issue: 77, + title: 'Follow live worker safely', + phase: 'pr', + pr: 301, + head: '1234abcd', + root: sb.gitRoot, + suite: { + cwd: sb.gitRoot, + head: '1234abcd', + agent: { pid: 7701, token: 'tok-77', log: buildLog, startedAt: nowMs - 10_000 }, + }, + })); + } else if (tick === 3) { + // Operator presses Ctrl-C (aborts viewer) while worker is still running + abortController.abort(); + } + }, + }, + }); + + assert.equal(exitCode, 0, stderr.text); + assert.equal(stderr.text, ''); + assert.match(stdout.text, /Following live output \(press Ctrl-C to detach without stopping the worker\)/); + assert.match(stdout.text, /\[agent\] Initial build step started\./); + assert.match(stdout.text, /\[cmd exit=0\] \$ npm run check/); + assert.match(stdout.text, /\[stage\] PR #301 \(1234abcd\): running full test suite \(pid 7702\) \[pass 1, fail 0\]/); + assert.match(stdout.text, /\[stage\] Streaming suite log:/); + assert.match(stdout.text, /ok 1 - live streamed test/); + assert.match(stdout.text, /Detached from issue #77 \(background worker continues untouched\)\./); + + // Confirm observe mode in pdd.json and active job file remain untouched after detach + assert.equal(JSON.parse(readFileSync(join(sb.gitRoot, 'pdd.json'), 'utf8')).autopilot.mode, 'observe'); + const postSnap = await inspectAutopilotWorkers({ cwd: sb.gitRoot }, { + git: sb.git, + stateRoot: sb.stateRoot, + now: () => nowMs, + isProcessAlive: () => true, + readSuite: () => suiteState, + }); + assert.equal(postSnap.workers.length, 1); + assert.equal(postSnap.workers[0].issue, 77); + assert.equal(postSnap.workers[0].liveProcess, true); +}); diff --git a/test/cli.test.mjs b/test/cli.test.mjs index be5dfbc101..5a7e35ae32 100644 --- a/test/cli.test.mjs +++ b/test/cli.test.mjs @@ -18,7 +18,7 @@ const capture = () => ({ text: '', write(value) { this.text += value; } }); // Wrong: deleting the adapter leaves private catalog/validator routes or unknown help succeeds. test('ALPHA1: only local plans are admitted without Host disposition or forwarded arguments', () => { - assert.deepEqual(PUBLIC_COMMAND_IDS, ['metrics', 'metrics.export', 'metrics.import', 'metrics.record', 'autopilot.regressions', 'autopilot.doctor', 'autopilot.start', 'autopilot.audit', 'autopilot.check-base', 'autopilot.stop', 'autopilot.status', 'autopilot.report', 'autopilot.intake', 'autopilot.add', 'autopilot.release', 'autopilot.alert', 'autopilot.alerts', 'graph', 'dependencies.prepare', 'dependencies.complete', 'workflow.suite', 'workflow.park', 'workflow.yield', 'product.status', 'product.next', 'product.start', 'workflow.run', 'workflow.prove', 'workflow.done', 'workflow.publish', 'workflow.cost', 'workflow.evidence', 'workflow.evidence-associate', 'workflow.ask', 'workflow.request-uptake', 'workflow.approve', 'workflow.resend', 'workflow.card', 'workflow.changes', 'workflow.tidy', 'workflow.cancel', 'workflow.status', 'workflow.view', 'workflow.open', 'help', 'version', 'version.detailed', 'completion', 'workflow.list', 'check', 'lint', 'files', 'owner', 'approve', 'try', 'jobs', 'contracts', 'contracts.sync', 'mcp', 'autopilot.off', 'autopilot.observe', 'autopilot.auto', 'autopilot.trust', 'autopilot.untrust', 'accounts', 'accounts.list', 'accounts.status', 'accounts.add', 'accounts.import', 'accounts.use', 'accounts.next', 'accounts.sync', 'accounts.auto', 'accounts.pause', 'accounts.unpause', 'accounts.share', 'accounts.accept', 'accounts.unshare', 'accounts.leave', 'accounts.remove', 'accounts.log', 'setup', 'upgrade']); + assert.deepEqual(PUBLIC_COMMAND_IDS, ['setup', 'check', 'lint', 'try', 'approve', 'files', 'owner', 'contracts', 'contracts.sync', 'jobs', 'mcp', 'upgrade', 'accounts', 'accounts.list', 'accounts.status', 'accounts.add', 'accounts.import', 'accounts.use', 'accounts.next', 'accounts.sync', 'accounts.auto', 'accounts.pause', 'accounts.unpause', 'accounts.share', 'accounts.accept', 'accounts.unshare', 'accounts.leave', 'accounts.remove', 'accounts.log', 'product.status', 'product.next', 'product.start', 'workflow.list', 'workflow.run', 'workflow.status', 'workflow.view', 'workflow.card', 'workflow.approve', 'workflow.changes', 'workflow.open', 'workflow.prove', 'workflow.suite', 'workflow.done', 'workflow.publish', 'workflow.ask', 'workflow.request-uptake', 'workflow.resend', 'workflow.park', 'workflow.yield', 'workflow.tidy', 'workflow.cancel', 'workflow.cost', 'workflow.evidence', 'workflow.evidence-associate', 'graph', 'dependencies.prepare', 'dependencies.complete', 'autopilot.doctor', 'autopilot.start', 'autopilot.status', 'autopilot.logs', 'autopilot.stop', 'autopilot.observe', 'autopilot.auto', 'autopilot.off', 'autopilot.trust', 'autopilot.untrust', 'autopilot.add', 'autopilot.release', 'autopilot.intake', 'autopilot.report', 'autopilot.regressions', 'autopilot.alerts', 'autopilot.alert', 'autopilot.audit', 'autopilot.check-base', 'metrics', 'metrics.export', 'metrics.import', 'metrics.record', 'completion', 'help', 'version', 'version.detailed']); for (const argv of [[], ['--help'], ['-h'], ['help'], ['--version'], ['completion', 'bash'], ['completion', 'zsh'], ['autopilot', 'doctor'], ['jobs'], ['mcp'], ['setup'], ['workflow', 'list'], ['workflow', 'list', '--json'], ['workflow', '--help']]) { const input = [...argv], plan = parseArgv(input); diff --git a/test/grouped-help.test.mjs b/test/grouped-help.test.mjs new file mode 100644 index 0000000000..99bb12d35a --- /dev/null +++ b/test/grouped-help.test.mjs @@ -0,0 +1,107 @@ +import './helpers/test-home.mjs'; +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { PUBLIC_COMMAND_MANIFEST, PUBLIC_COMMAND_ROUTES, PUBLIC_HELP_TEXT } from '../src/command-catalog.mjs'; +import { renderHelp, runPdd } from '../src/pdd-cli.mjs'; + +const sink = () => ({ text: '', write(chunk) { this.text += chunk; return true; } }); +const ANSI_RE = /\x1b\[[0-9;]*[A-Za-z]/; + +async function runHelp(argv, packageRoot = '/opt/pdd') { + const stdout = sink(), stderr = sink(); + const exit = await runPdd(argv, { stdout, stderr, packageRoot, cwd: '/nonexistent/dir' }); + return { exit, stdout: stdout.text, stderr: stderr.text }; +} + +test('3496: root help is concise, grouped human-first, 80-column wrapped in its catalog body, and identical across aliases', async () => { + const aliases = [[], ['--help'], ['-h'], ['-help'], ['help']]; + const results = await Promise.all(aliases.map(argv => runHelp(argv))); + const baseline = results[0].stdout; + + for (let i = 0; i < aliases.length; i++) { + assert.equal(results[i].exit, 0, JSON.stringify(aliases[i])); + assert.equal(results[i].stderr, '', JSON.stringify(aliases[i])); + assert.equal(results[i].stdout, baseline, JSON.stringify(aliases[i])); + assert.doesNotMatch(results[i].stdout, ANSI_RE); + } + + // Concise scannable entry point rather than multi-page wall of option paragraphs + assert.ok(Buffer.byteLength(baseline, 'utf8') < 6500, `expected concise root help, got ${Buffer.byteLength(baseline, 'utf8')} bytes`); + const allLines = baseline.replace(/\n$/, '').split('\n'); + assert.ok(allLines.length < 90, `expected < 90 lines in root help, got ${allLines.length}`); + + // Leads with description, usage, and practical Quick start examples + assert.equal(allLines[0], 'PDD: prompt-driven development for your coding agent.'); + assert.equal(allLines[2], 'Usage: pdd [options]'); + assert.equal(allLines[4], 'Quick start:'); + assert.match(baseline, /Quick start:\n pdd setup\b[\s\S]*?\n pdd test\b[\s\S]*?\n pdd simulate\b[\s\S]*?\n pdd help prompting\b/); + + // Human-first group ordering: Core PDD workflow before Cloud accounts, Workflows, Autopilot, Metrics + const coreIdx = baseline.indexOf('Core PDD workflow:'); + const accountsIdx = baseline.indexOf('Cloud accounts (pdd accounts --help):'); + const workflowsIdx = baseline.indexOf('Workflows & product (pdd workflow --help, pdd product --help):'); + const autopilotIdx = baseline.indexOf('Autopilot (pdd autopilot --help):'); + const metricsIdx = baseline.indexOf('Metrics, shell & help (pdd metrics --help):'); + assert.ok(coreIdx > 0 && coreIdx < accountsIdx, 'Core PDD workflow comes before Cloud accounts'); + assert.ok(accountsIdx < workflowsIdx, 'Cloud accounts comes before Workflows & product'); + assert.ok(workflowsIdx < autopilotIdx, 'Workflows & product comes before Autopilot'); + assert.ok(autopilotIdx < metricsIdx, 'Autopilot comes before Metrics, shell & help'); + + // Core commands come right at the top, not buried behind metrics/internals + assert.ok(baseline.indexOf(' pdd setup [--yes]') < baseline.indexOf(' pdd metrics')); + assert.ok(baseline.indexOf(' pdd autopilot logs [ISSUE] [-f]') > autopilotIdx); + + // No duplicate approval heredoc blocks or stale removed-engine migration note on root help + assert.doesNotMatch(baseline, /<<'PDD_SAID'/); + assert.doesNotMatch(baseline, /removed full engine/i); + + // Every line in usageLine, quickStartLines, groups, and focusedHelpLines fits in 80 columns + const wrappedLines = [ + PUBLIC_HELP_TEXT.usageLine, + 'Quick start:', + ...PUBLIC_HELP_TEXT.quickStartLines, + ...PUBLIC_HELP_TEXT.groups.flatMap(g => [`${g.title}:`, ...g.lines]), + ...PUBLIC_HELP_TEXT.focusedHelpLines, + ]; + for (const line of wrappedLines) { + assert.ok(line.length <= 80, `line exceeds 80 columns (${line.length}): "${line}"`); + } + + // Preserves Focused help guidance and installed Prompting guide / RUNBOOK paths + assert.match(baseline, /Focused help: run pdd --help/); + assert.match(baseline, /Prompting guide: \/opt\/pdd\/docs\/prompting-guide\.md/); + assert.match(baseline, /RUNBOOK: \/opt\/pdd\/RUNBOOK\.md/); +}); + +test('3496: focused family and command help exposes complete options, defaults, constraints and approval heredocs', async () => { + const families = ['test', 'lint', 'simulate', 'approve', 'accounts', 'product', 'workflow', 'autopilot', 'metrics']; + for (const family of families) { + const res = await runHelp([family, '--help']); + assert.equal(res.exit, 0, `${family} --help`); + assert.equal(res.stderr, '', `${family} --help`); + const expectedForms = PUBLIC_COMMAND_MANIFEST.filter(({ form }) => form.slice(4).split(/\s+/)[0] === family); + assert.ok(expectedForms.length > 0, `manifest has forms for ${family}`); + for (const entry of expectedForms) { + assert.ok(res.stdout.includes(` ${entry.form} ${entry.description}`), `${family} --help includes ${entry.form}`); + } + } + + // Autopilot start focused help keeps complete options and removes stale full-engine migration sentence + const startHelp = renderHelp(['autopilot', 'start']); + assert.match(startHelp, /--mode auto\|observe\|off/); + assert.match(startHelp, /--share PERCENT/); + assert.doesNotMatch(startHelp, /removed full engine/i); + + // Autopilot logs focused help documents both positional ISSUE and --issue N forms + const logsHelp = renderHelp(['autopilot', 'logs']); + assert.match(logsHelp, /pdd autopilot logs \[ISSUE\] \[--follow\|-f\] \[--lines N\] \[--json\]/); + assert.match(logsHelp, /pdd autopilot logs --issue N \[--follow\|-f\] \[--lines N\] \[--json\]/); + assert.match(logsHelp, /observe mode/); + + // Every top-level command family in PUBLIC_COMMAND_ROUTES is discoverable from root --help + const rootText = renderHelp([], '/opt/pdd'); + const topWords = new Set(PUBLIC_COMMAND_ROUTES.map(r => r.prefix[0]).filter(w => w !== 'help')); + for (const word of topWords) { + assert.ok(word.startsWith('-') ? rootText.includes(word) : rootText.includes(`pdd ${word}`), `root help mentions top-level command "${word}"`); + } +}); diff --git a/test/help-teaches-pdd.test.mjs b/test/help-teaches-pdd.test.mjs index 0b71205828..db2f3218df 100644 --- a/test/help-teaches-pdd.test.mjs +++ b/test/help-teaches-pdd.test.mjs @@ -7,7 +7,7 @@ import { tmpdir } from 'node:os'; import { isAbsolute, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { CommandInputError, parseArgv } from '../src/argument-parser.mjs'; -import { PUBLIC_COMMAND_MANIFEST } from '../src/command-catalog.mjs'; +import { PUBLIC_COMMAND_MANIFEST, PUBLIC_HELP_TEXT } from '../src/command-catalog.mjs'; import { runPdd } from '../src/pdd-cli.mjs'; // Node checks of user_stories/help-teaches-pdd.md that the PDD interpreter cannot make: the two printed paths @@ -110,7 +110,7 @@ test('prompting is a help topic, not a command, and takes no other word', async } }); -test('root help keeps its first line, every form line and its closing lines; command help is unchanged', async () => { +test('root help keeps its first line, grouped commands, learn paths and closing lines; command help shows full manifest forms', async () => { const outputs = await Promise.all(ROOT_HELP.map(argv => pdd(argv))); for (const output of outputs) assert.equal(output.stdout, outputs[0].stdout); const rootHelp = lines(outputs[0].stdout), scoped = lines((await pdd(['test', '--help'])).stdout); @@ -120,19 +120,24 @@ test('root help keeps its first line, every form line and its closing lines; com const closing = scoped.slice(3 + testRows.length); assert.equal(closing.length, 3); assert.doesNotMatch(scoped.join('\n'), /help prompting|prompting-guide\.md|RUNBOOK\.md/); - // Root help: the same first line, every catalog form in order, the learn line and two path lines, the same closing lines. - const all = PUBLIC_COMMAND_MANIFEST.flatMap(row => formLine(row).split('\n')); - assert.ok(all.some(line => line.startsWith(' pdd help prompting '))); + // Root help: the same first line, usage, quick start, grouped summaries, focused help note, learn/path lines, and closing lines. + const expectedBody = [ + PUBLIC_HELP_TEXT.usageLine, '', + 'Quick start:', ...PUBLIC_HELP_TEXT.quickStartLines, '', + ...PUBLIC_HELP_TEXT.groups.flatMap((group, index) => [...(index ? [''] : []), `${group.title}:`, ...group.lines]), '', + ...PUBLIC_HELP_TEXT.focusedHelpLines, + ]; + assert.ok(expectedBody.some(line => line.startsWith(' pdd help prompting '))); assert.equal(rootHelp[0], scoped[0]); assert.ok(rootHelp[0].startsWith('PDD')); - assert.equal(rootHelp[1], ''); assert.deepEqual(rootHelp.slice(2, 2 + all.length), all); - const rest = rootHelp.slice(2 + all.length); - assert.equal(rest[0], ''); assert.equal(rest[4], ''); assert.deepEqual(rest.slice(5), closing); - assert.ok(rest[1].includes('pdd help prompting'), rest[1]); - assert.ok(rest[2].endsWith(`/${FILES.guide}`) && rest[3].endsWith(`/${FILES.runbook}`), rest.join('\n')); + assert.equal(rootHelp[1], ''); assert.deepEqual(rootHelp.slice(2, 2 + expectedBody.length), expectedBody); + const rest = rootHelp.slice(2 + expectedBody.length); + assert.equal(rest[3], ''); assert.deepEqual(rest.slice(4), closing); + assert.ok(rest[0].includes('pdd help prompting'), rest[0]); + assert.ok(rest[1].endsWith(`/${FILES.guide}`) && rest[2].endsWith(`/${FILES.runbook}`), rest.join('\n')); // The topic: the same first line, the steps, then only the two path lines; no closing lines. const topic = lines((await pdd(TOPIC)).stdout); assert.equal(topic[0], rootHelp[0]); assert.equal(topic[1], ''); assert.equal(topic.at(-3), ''); - assert.deepEqual(topic.slice(-2), rest.slice(2, 4)); + assert.deepEqual(topic.slice(-2), rest.slice(1, 3)); for (const line of closing) assert.ok(!topic.includes(line), line); const text = topic.join('\n'); for (const name of ['prompts/NAME.prompt.md', '## Dependencies', 'user_stories/STORY.md', 'Acceptance criteria', diff --git a/test/runtime-seam.test.mjs b/test/runtime-seam.test.mjs index 12969f0904..2438f6ee73 100644 --- a/test/runtime-seam.test.mjs +++ b/test/runtime-seam.test.mjs @@ -841,7 +841,7 @@ registerHooks({ 'workflow-approve', 'workflow-resend', 'workflow-card', 'workflow-changes', 'workflow-open', 'workflow-view', 'workflow-cost', 'workflow-prove', 'workflow-suite', 'workflow-evidence', 'workflow-evidence-associate', 'workflow-park', 'workflow-yield', 'workflow-cancel', 'workflow-tidy', - 'autopilot-status', 'autopilot-doctor', 'autopilot-regressions', 'autopilot-alerts', 'autopilot-alert', + 'autopilot-status', 'autopilot-logs', 'autopilot-doctor', 'autopilot-regressions', 'autopilot-alerts', 'autopilot-alert', 'autopilot-start', 'autopilot-stop', 'autopilot-add', 'autopilot-release', 'autopilot-report', 'autopilot-intake', 'autopilot-audit', 'autopilot-check-base', 'autopilot.off', 'autopilot.observe', 'autopilot.auto', 'autopilot-trust', 'autopilot-untrust', 'accounts', 'upgrade', @@ -890,6 +890,7 @@ registerHooks({ ['cli:workflow-cost', [bin, 'workflow', 'cost', '1'], nonGit], ['cli:workflow-prove', [bin, 'workflow', 'prove', '1', '--test', 'true', '--expect', 'ok'], nonGit], ['cli:autopilot-status', [bin, 'autopilot', 'status'], nonGit], + ['cli:autopilot-logs', [bin, 'autopilot', 'logs'], nonGit], ['cli:autopilot-doctor', [bin, 'autopilot', 'doctor'], repo], ['cli:autopilot-regressions', [bin, 'autopilot', 'regressions'], nonGit], ['cli:autopilot-alerts', [bin, 'autopilot', 'alerts', 'clear'], nonGit], From 7d14ab9abcf0ccb34e63d320017a265c18b31172 Mon Sep 17 00:00:00 2001 From: Serhan Asad Date: Tue, 17 Nov 2026 14:02:06 -0800 Subject: [PATCH 2/4] fix(cli,autopilot): harden autopilot logs safety, redaction, pipes, and 80-col help (#3496, #3475) --- prompts/cli/autopilot-logs.prompt.md | 95 +++- prompts/cli/command-catalog.prompt.md | 16 +- prompts/cli/pdd-cli.prompt.md | 4 +- src/autopilot-logs.mjs | 736 +++++++++++++++++--------- src/command-catalog.mjs | 14 +- src/pdd-cli.mjs | 25 +- test/autopilot-logs.test.mjs | 348 +++++++++++- test/grouped-help.test.mjs | 16 +- test/help-teaches-pdd.test.mjs | 4 +- test/setup.test.mjs | 5 +- 10 files changed, 934 insertions(+), 329 deletions(-) diff --git a/prompts/cli/autopilot-logs.prompt.md b/prompts/cli/autopilot-logs.prompt.md index 2c9a9ed579..d3af7b9f92 100644 --- a/prompts/cli/autopilot-logs.prompt.md +++ b/prompts/cli/autopilot-logs.prompt.md @@ -1,11 +1,45 @@ # Autopilot worker logs Own `src/autopilot-logs.mjs`. Export `runAutopilotLogs(input, ports)`, -`inspectAutopilotWorkers(input, ports)` and `formatWorkerLogLine(line)`. -Give a person a supported read-only way to list headless Autopilot workers, -inspect a worker's stage, process state, queue position, blockers and saved -evidence, and follow live worker output from the terminal without knowing -internal state folders or touching running jobs. +`inspectAutopilotWorkers(input, ports)`, `formatWorkerLogLine(line, secrets)` +and `parseIssueSelector(raw)`. Give a person a supported read-only way to list +headless Autopilot workers, inspect a worker's stage, process state, queue +position, blockers and saved evidence, and follow live worker output from the +terminal without knowing internal state folders or touching running jobs. + +## Domain decisions + +- **Strictly read-only inspection and `observe`-mode preservation**: + Viewing worker logs never creates, modifies or deletes files in the checkout, + Autopilot state folders, validation folders, or user configuration, never + calls `gh`, and never approves gates or alters `observe`, `auto` or `off` + modes. +- **Same-user worker PID liveness boundary**: + Accept only safe integer PIDs with `pid > 1` across worker handles and + `suite.childPid`. In default liveness checks, any error from `kill(pid, 0)` + (both `ESRCH` and `EPERM`) returns `false` so system init (`pid 1`) or another + user's process is never reported as a running Autopilot worker; when a job + token is present, `ps` command output must also include that token. +- **End-to-end secret redaction and line-aligned UTF-8 reads**: + Derive caller secrets with `knownSecretValues(env)` (including injected + `input.env`), strip ANSI/control characters, and run `redactSecrets(..., secrets)` + across human snapshots, `--follow` streams, and `--json` payloads — covering + log lines, worker metadata (`agentKind`, `signal`, `wakeAt`, `holder`, + `verdict`, `head`, `repo`, `gitRoot`) and file path strings (`logPaths`, + `evidencePaths`, `streams[].path`, `suite.logPath`, `suite.receiptPath`). + Align tail and incremental follow reads on `\n` (`0x0a`) byte boundaries + (expanding read windows up to 16 MiB and ignoring a trailing EOF newline when + locating the start of the tail window) so multi-byte UTF-8 codepoints and + secret prefixes are never split mid-line and single-line tails ending in `\n` + are never dropped. +- **Bounded, pipe-safe `--follow` polling**: + Resolve `git rev-parse --show-toplevel` once and pass `gitRoot` into poll + iterations instead of spawning `git` on every poll. Attach `close` and `error` + (`EPIPE`) handlers on `stdout` and guard writes on `!stdout.destroyed && + !stdout.writableEnded` so piped commands (`| head -n 5`) detach cleanly with + exit `0`, no `EPIPE` crash, no trailing detach message to a closed pipe, and + no leaked poll timer. Enforce `maxDurationMs` (default `3_600_000` ms / 60 + minutes) so unattended follow sessions always terminate cleanly. ## Safety and observe mode @@ -16,22 +50,25 @@ Every operation in this module is strictly read-only: - Never approve gates, merge pull requests, claim or release issues, wake scheduler ticks, or call GitHub (`gh`). Viewing preserves `observe`, `auto` and `off` modes unchanged. -- Check process liveness read-only (`kill(pid, 0)` and `ps` command match on - the job's `.spec.json` token when present). Never send `SIGTERM`, `SIGKILL`, +- Check process liveness read-only (`pid > 1`, `kill(pid, 0)` returning `false` + on any error including `EPERM` and `ESRCH`, and `ps` command match on the + job's `.spec.json` token when present). Never send `SIGTERM`, `SIGKILL`, `SIGINT` or any stopping signal to a worker or test-suite process. -- Redact credentials and tokens in every displayed log line, error note and - path summary with `redactSecrets`. Strip terminal escape sequences so output - is safe in both interactive terminals and redirected files. +- Redact credentials and tokens in every displayed log line, JSON field, error + note and path summary with `redactSecrets(..., knownSecretValues(env))`. Strip + terminal escape and control sequences so output is safe in interactive + terminals, pipes and redirected files. ## CLI contract `runAutopilotLogs({cwd, env, issue, follow, lines, json}, ports)` accepts: - `issue`: optional issue selector from the positional `[ISSUE]` operand or - `--issue N` (`17`, `#17`, `owner/repo#17`, or a GitHub issue URL). Passing - two different selectors, a blank/invalid selector, or `--follow` together - with `--json` returns exit code `2` with one clear usage message before state - inspection. + `--issue N` (`17`, `#17`, `owner/repo#17`, or a GitHub issue URL). When both + positional and `--issue` selectors are supplied directly, compare their parsed + issue numbers and optional repository qualifiers; conflicting selectors, a + blank/invalid selector, or `--follow` together with `--json` returns exit code + `2` with one clear usage message before state inspection. - `follow`: Boolean from `--follow` or `-f`. Requires a selected issue; calling `--follow` with no issue returns exit code `2` explaining how to pass an issue (`pdd autopilot logs ISSUE --follow`). @@ -39,11 +76,13 @@ Every operation in this module is strictly read-only: `1` to `5000`). - `json`: Boolean from `--json` for structured machine-readable inspection. -Injectable `ports` provide `fs`, `git(args, {cwd, env})`, `now()`, `stateRoot`, -`coreRoot`, `isProcessAlive(pid, token)`, `readSuite({cwd, env})`, `stdout`, -`signal`, `pollMs` (default `250`) and `sleep(ms)`. Resolve the repository root -with `git rev-parse --show-toplevel` under `LC_ALL=C` and `LANG=C`. Outside a -Git repository, return `{exitCode: 1, message: "This folder is not a Git repository. cd into the repo you want Autopilot to work on, then run pdd autopilot logs again."}`. +Injectable `ports` provide `fs`, `git(args, {cwd, env})`, `gitRoot`, `now()`, +`stateRoot`, `coreRoot`, `isProcessAlive(pid, token)`, `readSuite({cwd, env})`, +`stdout`, `signal`, `pollMs` (default `250`), `maxDurationMs` (default +`3600000`) and `sleep(ms)`. Resolve the repository root with +`git rev-parse --show-toplevel` under `LC_ALL=C` and `LANG=C` unless +`ports.gitRoot` is already supplied. Outside a Git repository, return +`{exitCode: 1, message: "This folder is not a Git repository. cd into the repo you want Autopilot to work on, then run the command again."}`. Derive the state key from `sha256(gitToplevel).slice(0, 20)` under `stateRoot` (default `/.local/state/pdd/autopilot`), reading `.json`, `-core/core.json`, `-core/jobs/*.json`, @@ -123,12 +162,14 @@ waiting or stale state: test/command text lines intact and redacted. - **Live follow (`--follow` / `-f`)**: Stream the worker header, initial tail lines, and newly appended complete log - lines to `stdout` as the worker runs, emitting `[stage]` notices whenever the - worker transitions across stages or opens a new log (including live suite - validation logs). Stop cleanly with exit code `0` when the job finishes (or - has no live process while the Autopilot timer is off) or when `signal` / - `SIGINT` / `SIGTERM` detaches the viewer. Detaching prints a confirmation - that the background worker continues untouched. + lines to `stdout` as the worker runs, reusing the resolved `gitRoot` on poll + ticks and emitting `[stage]` notices whenever the worker transitions across + stages or opens a new log (including live suite validation logs). Stop cleanly + with exit code `0` when the job finishes (or has no live process while the + Autopilot timer is off), when `maxDurationMs` elapses, when `stdout` closes or + errors (`EPIPE`), or when `signal` / `SIGINT` / `SIGTERM` detaches the viewer. + When `stdout` is still writable on signal detach, print a confirmation that + the background worker continues untouched. ## Dependencies @@ -136,7 +177,5 @@ waiting or stale state: `core.json`, `logs/` and `history.jsonl` state shapes. - [Shared full-suite queue](test-suite-queue.prompt.md): required context for read-only `readSuiteProgress` queue and validation-log inspection. -- [Repository Autopilot settings](autopilot.prompt.md): required context for - `pdd.json` mode display and CLI subcommand routing. - [Secret redaction](secret-redaction.prompt.md): required for redacting - displayed log lines and diagnostics. + displayed log lines, JSON payloads, metadata and path summaries. diff --git a/prompts/cli/command-catalog.prompt.md b/prompts/cli/command-catalog.prompt.md index 387ee973b6..e17a2a12c6 100644 --- a/prompts/cli/command-catalog.prompt.md +++ b/prompts/cli/command-catalog.prompt.md @@ -55,7 +55,7 @@ Catalog four local routes before the product routes: `autopilot.start` (`autopil - `pdd autopilot start [--runs N] [--checks N] [--label NAME] [--mode auto|observe|off] [--report file|draft|off] [--decisions ask|decide] [--intake off|shadow|active] [--share PERCENT] [--agent codex|claude|gemini|agy] [--auto-update release|main|off]`: Start this repo with headless agent jobs (the core engine): check now and every 10 minutes, with no AI call on empty ticks. Autopilot works on issues with an opt-in label (--label NAME or autopilot.label in pdd.json) or on vetted ready cards when --intake active is enabled; without --intake active, a start with no label starts nothing. --runs and --checks override machine-sized run and heavy-check limits; --label (text), --mode (choice auto, observe or off) and --report (choice file, draft or off) save this machine's opt-in label, mode and report mode for this repo, over pdd.json (--mode observe runs every check but never merges; --report draft, the default, keeps problem reports on this machine); --decisions (choice ask or decide) saves this machine's decision mode (ask asks a person only for a big decision; decide, the default, never asks); --intake (choice off, shadow or active) saves this machine's intake mode (shadow writes local intake cards that never change what starts; active selects ready cards, refines improve cards via read-only repo inspection and groups related small work; off is the default). --share (text) saves the percent of this machine's CPU and memory that Autopilot may use (1-100, default 50; it sets the automatic slots, the room check and the timer's memory limit). --agent saves or replaces this machine's agent and sign-in profile. --auto-update (choice release, main or off; default release) saves this machine's between-tick self-update mode for a user-owned global pdd install and its skills when no job is publishing or merging (#2710). The route also accepts `--engine` (choice core or full) and hidden `--pool` (text) and shows neither in public help or completion. - `pdd autopilot stop`: Stop this machine's timer; let the current agent step finish. - `pdd autopilot status [--all] [--json]`: Show this machine's repo, folder, agent and next tick; --all lists every repository with Autopilot on this machine, from any folder. -- `pdd autopilot logs [ISSUE] [--follow|-f] [--lines N] [--json]` and `pdd autopilot logs --issue N [--follow|-f] [--lines N] [--json]` (route `autopilot.logs`, prefix `autopilot logs`, local `autopilot-logs`, optional issue operand `issue`, text option `--issue`, Boolean flags `--follow`, `-f` and `--json`, integer `--lines` from 1 to 5000): List current headless Autopilot workers for this repository with stage, owned process state, suite queue position, blockers and saved log/evidence paths, or inspect and follow one issue worker's live readable progress (`--follow` / `-f` streams live updates and detaches cleanly on Ctrl-C without stopping the worker or changing `observe` mode). Read-only; no GitHub write or approval effect. +- `pdd autopilot logs [ISSUE] [--follow|-f] [--lines N] [--json]` and `pdd autopilot logs --issue N [--follow|-f] [--lines N] [--json]` (route `autopilot.logs`, prefix `autopilot logs`, local `autopilot-logs`, optional text operand `issue`, text option `--issue`, Boolean flags `--follow`, `-f` and `--json`, integer `--lines` from 1 to 5000): List current headless Autopilot workers for this repository with stage, owned process state, suite queue position, blockers and saved log/evidence paths, or inspect and follow one issue worker's live readable progress (`--follow` / `-f` streams live updates and detaches cleanly on Ctrl-C without stopping the worker or changing `observe` mode). Read-only; no GitHub write or approval effect. - `pdd autopilot add N...`: Mark named old issues with pdd:autopilot so Autopilot may take them. - `pdd autopilot release ISSUE`: End this machine's idle run, release its claim, and remove pdd:working and pdd:stuck; keep the run folder, branch and PRs. A live worker, check, or another machine's claim prevents release. @@ -215,7 +215,7 @@ Catalog local disposition `accounts` ([Cloud accounts CLI](accounts-cli.prompt.m `PUBLIC_COMMAND_MANIFEST` owns every supported command form and its detailed command-specific description. Each route owns entries whose form starts with its prefix, ordered by human-first command groups: Core PDD workflow (`setup`, `check`, `lint`, `try`, `approve`, `files`, `owner`, `contracts`, `contracts.sync`, `jobs`, `mcp`, `upgrade`), Cloud accounts (`accounts` and its subcommands), Workflows & product (`product.*`, `workflow.list`, `workflow.run`, `workflow.status`, `workflow.view`, `workflow.card`, `workflow.approve`, `workflow.changes`, `workflow.open`, `workflow.prove`, `workflow.suite`, `workflow.done`, `workflow.publish`, `workflow.ask`, `workflow.request-uptake`, `workflow.resend`, `workflow.park`, `workflow.yield`, `workflow.tidy`, `workflow.cancel`, `workflow.cost`, `workflow.evidence`, `workflow.evidence-associate`, `graph`, `dependencies.*`), Autopilot (`autopilot.doctor`, `autopilot.start`, `autopilot.status`, `autopilot.logs`, `autopilot.stop`, `autopilot.observe`, `autopilot.auto`, `autopilot.off`, `autopilot.trust`, `autopilot.untrust`, `autopilot.add`, `autopilot.release`, `autopilot.intake`, `autopilot.report`, `autopilot.regressions`, `autopilot.alerts`, `autopilot.alert`, `autopilot.audit`, `autopilot.check-base`), and Metrics, shell & help (`metrics.*`, `completion`, `help`, `version`, `version.detailed`). After each approval entry in `PUBLIC_COMMAND_MANIFEST` (`pdd approve` and `pdd workflow approve`), include the shared policy's quoted-heredoc example with that route's command (`pdd approve PATH` or `pdd workflow approve N`) so command-specific help (`pdd approve --help`, `pdd workflow --help`, `pdd workflow approve --help`) shows the complete approval rules and heredoc template without duplicating them on the root `--help` page. The example preserves person text without shell interpolation. Tell the caller to choose a delimiter absent from the text. Both approval descriptions state that `--said -` reads all UTF-8 stdin, including trailing newlines; simple literal `--said` text remains supported. A person terminal uses y/N; workflow y/N covers the ready gate and all selected drafts in one call. -Root help (`pdd`, `pdd --help`, `pdd -h`, `pdd -help`, `pdd help`) uses concise grouped summaries (`PUBLIC_HELP_TEXT.groups`) preceded by `PUBLIC_HELP_TEXT.usageLine` (`Usage: pdd [options]`) and `PUBLIC_HELP_TEXT.quickStartLines` (practical starting examples using `pdd setup`, `pdd `, `pdd ` and `pdd help prompting`) and followed by `PUBLIC_HELP_TEXT.focusedHelpLines` (`Focused help: run pdd --help ...`), `learnLines` and `closingLines`. Keep every line in `usageLine`, `quickStartLines`, `groups` and `focusedHelpLines` within 80 columns, derive every `test`, `lint`, `simulate`, `run` and `requestUptake` command word from `NAMES`, and place `workflow.request-uptake` (`pdd workflow REQUEST_ID --summary TEXT`) immediately after `pdd workflow ask` (which follows `pdd workflow done` and `pdd workflow publish`). Command-specific and family-scoped help (`pdd --help`, such as `pdd test --help`, `pdd workflow --help`, `pdd autopilot --help`, `pdd accounts --help`) renders the complete `PUBLIC_COMMAND_MANIFEST` entries matching that prefix. +Root help (`pdd`, `pdd --help`, `pdd -h`, `pdd -help`, `pdd help`) uses concise grouped summaries (`PUBLIC_HELP_TEXT.groups`) preceded by `PUBLIC_HELP_TEXT.usageLine` (`Usage: pdd [options]`) and `PUBLIC_HELP_TEXT.quickStartLines` (practical starting examples using `pdd setup`, `pdd `, `pdd ` and `pdd help prompting`) and followed by `PUBLIC_HELP_TEXT.focusedHelpLines` (`Focused help: run pdd --help ...`), `learnLines` and `closingLines`. Keep every line in `usageLine`, `quickStartLines`, `groups`, `focusedHelpLines` and `closingLines` within 80 columns, derive every `test`, `lint`, `simulate`, `run` and `requestUptake` command word from `NAMES`, and place `workflow.request-uptake` (`pdd workflow REQUEST_ID --summary TEXT`) immediately after `pdd workflow ask` (which follows `pdd workflow done` and `pdd workflow publish`). Command-specific and family-scoped help (`pdd --help`, such as `pdd test --help`, `pdd workflow --help`, `pdd autopilot --help`, `pdd accounts --help`) renders the complete `PUBLIC_COMMAND_MANIFEST` entries matching that prefix. The `help` route owns the forms `pdd`, `pdd --help`, `pdd -h`, `pdd help` and `pdd help prompting`, and lists one help topic: `prompting`. A topic is no route prefix, so `prompting` alone is no command. The [Learn PDD](#learn-pdd) section owns the topic's text; the [parser](argument-parser.prompt.md#help-topics) owns its syntax. @@ -223,12 +223,16 @@ The `help` route owns the forms `pdd`, `pdd --help`, `pdd -h`, `pdd help` and `p Export the frozen `PUBLIC_HELP_TEXT` object with `heading`, `usageLine`, `quickStartLines`, `groups`, `focusedHelpLines`, `closingLines`, `learnLines` and `promptingLines`. The heading is exactly `PDD: prompt-driven development for your coding agent.` `groups` is a frozen array of `{title, lines}` objects for the five command groups (`Core PDD workflow`, `Cloud accounts (pdd accounts --help)`, `Workflows & product (pdd workflow --help, pdd product --help)`, `Autopilot (pdd autopilot --help)`, and `Metrics, shell & help (pdd metrics --help)`), where each line begins with two spaces and `pdd ` and stays within 80 columns. Keep `PACKAGE_ROOT` as a template marker in `learnLines`; the CLI substitutes its absolute package root. The topic uses the last two learn lines after its prompting lines. This catalog owns every help text template; the dispatcher owns composition and path substitution. -The closing lines are exactly: +The closing lines are wrapped to at most 80 columns and are exactly: ```text -Open Codex or Claude as usual and call a PDD skill: $pdd-feature in Codex, /pdd-feature in Claude Code (also pdd-bug, pdd-small-change, pdd-prompting). -workflow run opens the first area chat in Herdr session pdd and exits. Manual workflows follow RUNBOOK §2 and its person gates; pdd opens a real PR. -The CLI has no merge command. In auto mode, Autopilot merges its own pull request after CI, a fresh review and the full test suite pass; required human approvals still apply. +Open Codex or Claude as usual and call a PDD skill: $pdd-feature in Codex, +/pdd-feature in Claude Code (also pdd-bug, pdd-small-change, pdd-prompting). +workflow run opens the first area chat in Herdr session pdd and exits. +Manual workflows follow RUNBOOK §2 and its person gates; pdd opens a real PR. +The CLI has no merge command. In auto mode, Autopilot merges its own pull +request after CI, a fresh review and the full test suite pass; required +human approvals still apply. ``` (`run` is the [NAMES](#names) word. Codex calls a skill with `$name`, Claude Code with `/name`.) diff --git a/prompts/cli/pdd-cli.prompt.md b/prompts/cli/pdd-cli.prompt.md index dc51aae9df..120eba4528 100644 --- a/prompts/cli/pdd-cli.prompt.md +++ b/prompts/cli/pdd-cli.prompt.md @@ -186,7 +186,7 @@ operands in issues. Use the same reply and stream rules; no remote settings warn For catalog dispositions `autopilot-start`, `autopilot-stop`, `autopilot-status`, `autopilot-add`, `autopilot-release` and `autopilot-check-base`, dynamically import [Autopilot launcher](autopilot-launcher.prompt.md). Call its module function `runAutopilotLauncher({command, issues, runs, checks, share, all, cwd, packageRoot, env}, ports)`: command is the disposition suffix, issues are the operands unchanged, runs is the --runs text when present, checks is the --checks text when present, share is the --share text when present (#3231), and all is true only for `autopilot status --all`. Tests may inject `dependencies.autopilotLauncher` and `autopilotLauncherPorts`. Print its {exitCode,message} once, stdout on zero and stderr otherwise, and return that code. After `autopilot-start` or `autopilot-status` without `--all` with exit 0, call [Autopilot settings on GitHub](autopilot-github.prompt.md) `checkAutopilotSettings({cwd}, autopilotGithubPorts)` and print its nonempty warning as one stderr line; a throw prints nothing. This check never writes, never changes the exit code, and start never writes `pdd.json` to GitHub. Invalid replies or exceptions produce one finite diagnostic and exit 1 without retry. Help and parsing do not load the launcher or check sign-ins. Existing admission applies only to setup and workflow-run; the launcher owns its own startup checks. -For catalog disposition `autopilot-logs`, skip post-upgrade skill sync and GitHub settings checks on this read-only local viewer. Resolve the optional issue selector from `operands[0]` or `--issue` (rejecting conflicting selectors or `--follow`/`-f` combined with `--json` with exit 2 and one finite stderr line before importing execution). Dynamically delegate to `dependencies.autopilotLogs.runAutopilotLogs` when injected, else [Autopilot settings](autopilot.prompt.md) `runAutopilotSubcommand("logs", {cwd, env, issue, follow, lines, json}, {stdout, stderr, ...autopilotLogsPorts})`. When `streamed` is true, output has already been streamed to `stdout`; otherwise print nonempty `message` once to `stdout` on exit 0 and `stderr` otherwise, and return `exitCode`. An unexpected exception prints one finite safe failure and returns 1. +For catalog disposition `autopilot-logs`, skip post-upgrade skill sync and GitHub settings checks on this read-only local viewer. Parse `operands[0]` and `--issue` as issue selectors (`N`, `#N`, `owner/repo#N`, or GitHub issue URL), rejecting invalid selectors, conflicting parsed issue numbers or repository qualifiers, missing issue with `--follow`/`-f`, or `--follow`/`-f` combined with `--json` with exit 2 and one finite stderr line before importing execution. Dynamically delegate `{cwd, env, issue, follow, lines, json}` to `dependencies.autopilotLogs.runAutopilotLogs` when injected, else [Autopilot settings](autopilot.prompt.md) `runAutopilotSubcommand("logs", {cwd, env, issue, follow, lines, json}, {stdout, stderr, ...autopilotLogsPorts})`. When `streamed` is true, output has already been streamed to `stdout`; otherwise print nonempty `message` once to `stdout` on exit 0 and `stderr` otherwise, and return `exitCode`. An unexpected exception prints one finite safe failure and returns 1. For catalog dispositions `autopilot-alert` and `autopilot-alerts`, dynamically import [Autopilot alerts](autopilot-alerts.prompt.md) and call its module function `runAutopilotAlerts({action, cwd, env, text, issue, kind, update}, ports)`. The action is `alert` for `autopilot-alert`, else the `set`, `test` or `clear` operand. For `alert`, `--input` must be `-`; otherwise return 2 with one line before importing the module. Read all stdin as UTF-8 `text` for `alert` and `set` only, and not for `set` with `--token-command`; when `set` reads a terminal, first print one hint line to stderr. Pass `--issue`, `--kind` and the `--update` flag unchanged, pass `--destination` as `destination` only when given, and pass `--discord-channel` as `discordChannel` and `--token-command` as `tokenCommand` only when given. Either of these two options with `test` or `clear` returns 2 with one line. Tests may inject `dependencies.autopilotAlerts` and `autopilotAlertsPorts`. Print the reply once, stdout on zero and stderr otherwise. An invalid reply or exception prints one fixed line without the error text, so a webhook URL can never reach the output, and returns 1. @@ -311,7 +311,7 @@ reply. { "kind": "partial", "status": "approved", - "prose_sha256": "587b53290ec9051188fbcb75b536a6640f6c8a6a8b8a9805b0529d311cc47fd5", + "prose_sha256": "1032d91b7ac6d9296160b5b5136b8931f908896288cd0a3232585bb2bc1e0f46", "entries": [ { "operation": "runPdd", diff --git a/src/autopilot-logs.mjs b/src/autopilot-logs.mjs index f7dcac93f8..fdd14daaee 100644 --- a/src/autopilot-logs.mjs +++ b/src/autopilot-logs.mjs @@ -1,12 +1,12 @@ -// Generated from prompts/cli/autopilot-logs.prompt.md (sha256: 8b345c3f03e51f5c556ed65221ba2fe82d41490371f48304181f244a439d7588). +// Generated from prompts/cli/autopilot-logs.prompt.md (sha256: a237e3bf4be79bee24287f40095e81635eea35f44573885143660dc29ba5056d). import * as nativeFs from 'node:fs'; import { homedir } from 'node:os'; -import { basename, join, resolve } from 'node:path'; +import { basename, join } from 'node:path'; import { createHash } from 'node:crypto'; import { execFile, spawnSync } from 'node:child_process'; import { promisify } from 'node:util'; import { readSuiteProgress } from './test-suite-queue.mjs'; -import { redactSecrets } from './secret-redaction.mjs'; +import { knownSecretValues, redactSecrets } from './secret-redaction.mjs'; const execute = promisify(execFile); const ANSI_RE = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07]*(?:\x07|\x1b\\)/g; @@ -14,23 +14,57 @@ const CTRL_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g; const DEFAULT_LINES = 40; const MAX_LINES = 5000; const DEFAULT_POLL_MS = 250; +const DEFAULT_MAX_DURATION_MS = 60 * 60 * 1000; const MAX_CMD_PREVIEW_LINES = 6; const READ_CHUNK_LIMIT = 512 * 1024; +const MAX_LINE_WINDOW_BYTES = 16 * 1024 * 1024; const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value); const named = value => typeof value === 'string' && value.trim().length > 0; +const validPid = value => Number.isSafeInteger(value) && value > 1; -function cleanText(value, maxLen = 400) { - const sanitized = redactSecrets(String(value ?? '').replace(ANSI_RE, '').replace(/\r\n/g, '\n').replace(/\r/g, '\n').replace(CTRL_RE, '')); +function resolveSecrets(secretsInput) { + if (Array.isArray(secretsInput)) return knownSecretValues(process.env, secretsInput); + if (isObject(secretsInput)) return knownSecretValues(secretsInput.env ?? process.env, secretsInput.secrets ?? []); + return knownSecretValues(process.env); +} + +function sanitizeString(value, secrets = []) { + const stripped = String(value ?? '') + .replace(ANSI_RE, '') + .replace(/\r\n/g, '\n') + .replace(/\r/g, '\n') + .replace(CTRL_RE, ''); + return redactSecrets(stripped, secrets); +} + +function sanitizeJsonValue(value, secrets = []) { + if (typeof value === 'string') return sanitizeString(value, secrets); + if (Array.isArray(value)) return value.map(item => sanitizeJsonValue(item, secrets)); + if (isObject(value)) { + const out = {}; + for (const [key, item] of Object.entries(value)) { + out[key] = sanitizeJsonValue(item, secrets); + } + return out; + } + return value; +} + +function cleanText(value, maxLen = 400, secrets = []) { + const sanitized = sanitizeString(value, secrets); return sanitized.length > maxLen ? `${sanitized.slice(0, maxLen - 3)}...` : sanitized; } -function oneLine(value, maxLen = 200) { - return cleanText(value, maxLen * 2).replace(/\s+/g, ' ').trim().slice(0, maxLen); +function oneLine(value, maxLen = 200, secrets = []) { + const sanitized = sanitizeString(value, secrets).replace(/\s+/g, ' ').trim(); + return sanitized.length > maxLen ? `${sanitized.slice(0, maxLen - 3)}...` : sanitized; } -function shortSha(sha) { - return typeof sha === 'string' && sha.trim() ? sha.trim().slice(0, 8) : 'unknown'; +function shortSha(sha, secrets = []) { + if (!named(sha)) return 'unknown'; + const cleaned = oneLine(sha, 64, secrets); + return cleaned ? cleaned.slice(0, 8) : 'unknown'; } function formatAge(nowMs, atMs) { @@ -74,8 +108,12 @@ function listDir(fs, dirPath) { } function defaultIsProcessAlive(pid, token) { - if (!Number.isSafeInteger(pid) || pid <= 0) return false; - try { process.kill(pid, 0); } catch (error) { if (error?.code !== 'EPERM') return false; } + if (!validPid(pid)) return false; + try { + process.kill(pid, 0); + } catch { + return false; + } if (!named(token)) return true; const row = spawnSync('ps', ['-ww', '-o', 'command=', '-p', String(pid)], { encoding: 'utf8', @@ -116,9 +154,9 @@ export function parseIssueSelector(raw) { return { ok: false, issue: null, repo: null }; } -function previewCommandOutput(output) { +function previewCommandOutput(output, secrets = []) { if (!named(output)) return []; - const rawLines = cleanText(output, 4000) + const rawLines = sanitizeString(output, secrets) .split('\n') .map(line => line.trimEnd()) .filter(line => line.trim().length > 0); @@ -131,17 +169,18 @@ function previewCommandOutput(output) { ]; } -export function formatWorkerLogLine(rawLine) { +export function formatWorkerLogLine(rawLine, secretsInput = []) { if (typeof rawLine !== 'string') return ''; + const secrets = resolveSecrets(secretsInput); const stripped = rawLine.replace(ANSI_RE, '').replace(/\r/g, ''); const trimmed = stripped.trim(); if (!trimmed) return ''; if (!trimmed.startsWith('{') || !trimmed.endsWith('}')) { - return cleanText(stripped, 500); + return cleanText(stripped, 500, secrets); } let event; - try { event = JSON.parse(trimmed); } catch { return cleanText(stripped, 500); } - if (!isObject(event)) return cleanText(stripped, 500); + try { event = JSON.parse(trimmed); } catch { return cleanText(stripped, 500, secrets); } + if (!isObject(event)) return cleanText(stripped, 500, secrets); // Skip noisy token-count and delta heartbeats. if (event.type === 'token_count' || (event.type === 'event_msg' && event.payload?.type === 'token_count')) return ''; @@ -150,7 +189,7 @@ export function formatWorkerLogLine(rawLine) { // Codex thread/turn lifecycle if (event.type === 'thread.started' || event.type === 'session_meta') { const model = event.model ?? event.payload?.model; - return `[session] started${named(model) ? ` (${oneLine(model, 80)})` : ''}`; + return `[session] started${named(model) ? ` (${oneLine(model, 80, secrets)})` : ''}`; } if (event.type === 'turn.started' || event.type === 'message_start') return ''; if (event.type === 'turn.completed') { @@ -161,7 +200,7 @@ export function formatWorkerLogLine(rawLine) { } if (event.type === 'turn.failed' || event.type === 'error') { const msg = event.error?.message ?? event.message ?? JSON.stringify(event); - return `[error] ${oneLine(msg, 240)}`; + return `[error] ${oneLine(msg, 240, secrets)}`; } // Codex item.started / item.completed @@ -170,48 +209,48 @@ export function formatWorkerLogLine(rawLine) { const itemType = String(item.type ?? item.item_type ?? ''); const cmd = item.command ?? item.arguments?.command; if (event.type === 'item.started') { - if (itemType === 'command_execution' && named(cmd)) return `[run] $ ${oneLine(cmd, 180)}`; - if (named(item.tool ?? item.name)) return `[tool] ${oneLine(item.tool ?? item.name, 80)} started`; + if (itemType === 'command_execution' && named(cmd)) return `[run] $ ${oneLine(cmd, 180, secrets)}`; + if (named(item.tool ?? item.name)) return `[tool] ${oneLine(item.tool ?? item.name, 80, secrets)} started`; return ''; } if (itemType === 'agent_message' && named(item.text)) { - return cleanText(item.text, 800) + return cleanText(item.text, 800, secrets) .split('\n') .filter(line => line.trim()) .map(line => `[agent] ${line}`) .join('\n'); } if (itemType === 'reasoning') { - return named(item.text) ? `[think] ${oneLine(item.text, 160)}` : ''; + return named(item.text) ? `[think] ${oneLine(item.text, 160, secrets)}` : ''; } if (itemType === 'command_execution') { const code = Number.isInteger(item.exit_code) ? item.exit_code : 0; - const head = `[cmd exit=${code}] $ ${oneLine(cmd ?? '(command)', 170)}`; - return [head, ...previewCommandOutput(item.aggregated_output ?? item.output)].join('\n'); + const head = `[cmd exit=${code}] $ ${oneLine(cmd ?? '(command)', 170, secrets)}`; + return [head, ...previewCommandOutput(item.aggregated_output ?? item.output, secrets)].join('\n'); } if (itemType === 'file_change' || itemType === 'patch') { const paths = Array.isArray(item.changes) ? item.changes.map(c => c?.path).filter(named).join(', ') : (item.path ?? ''); - return `[edit] ${oneLine(paths || 'updated files', 180)}`; + return `[edit] ${oneLine(paths || 'updated files', 180, secrets)}`; } const toolName = item.tool ?? item.name ?? (itemType || 'item'); - return `[tool] ${oneLine(toolName, 120)}`; + return `[tool] ${oneLine(toolName, 120, secrets)}`; } // Claude stream-json events if (event.type === 'system' && event.subtype === 'init') { - return `[session] started${named(event.model) ? ` (${oneLine(event.model, 80)})` : ''}`; + return `[session] started${named(event.model) ? ` (${oneLine(event.model, 80, secrets)})` : ''}`; } if (event.type === 'assistant' && isObject(event.message)) { const parts = Array.isArray(event.message.content) ? event.message.content : []; const out = []; for (const part of parts) { if (part?.type === 'text' && named(part.text)) { - for (const l of cleanText(part.text, 800).split('\n').filter(s => s.trim())) out.push(`[agent] ${l}`); + for (const l of cleanText(part.text, 800, secrets).split('\n').filter(s => s.trim())) out.push(`[agent] ${l}`); } else if (part?.type === 'tool_use' && named(part.name)) { const detail = part.input?.command ?? part.input?.file_path ?? part.input?.path ?? part.input?.pattern ?? ''; - out.push(`[tool] ${oneLine(part.name, 60)}${named(detail) ? `: ${oneLine(detail, 150)}` : ''}`); + out.push(`[tool] ${oneLine(part.name, 60, secrets)}${named(detail) ? `: ${oneLine(detail, 150, secrets)}` : ''}`); } } return out.join('\n'); @@ -226,15 +265,15 @@ export function formatWorkerLogLine(rawLine) { : Array.isArray(part.content) ? part.content.map(c => c?.text ?? '').join('\n') : ''; - if (part.is_error) out.push(`[tool error] ${oneLine(raw || 'command failed', 200)}`); - else out.push(...previewCommandOutput(raw)); + if (part.is_error) out.push(`[tool error] ${oneLine(raw || 'command failed', 200, secrets)}`); + else out.push(...previewCommandOutput(raw, secrets)); } } return out.join('\n'); } if (event.type === 'result') { const status = event.subtype ?? (event.is_error ? 'error' : 'done'); - return `[result] ${oneLine(status, 40)}${named(event.result) ? `: ${oneLine(event.result, 180)}` : ''}`; + return `[result] ${oneLine(status, 40, secrets)}${named(event.result) ? `: ${oneLine(event.result, 180, secrets)}` : ''}`; } // Gemini / Agy stream-json events @@ -242,44 +281,57 @@ export function formatWorkerLogLine(rawLine) { const step = event.step_update; if (step.step_type === 'tool' && named(step.tool_name)) { const cmd = step.tool_info?.parameters?.command ?? step.tool_info?.parameters?.CommandLine ?? ''; - const head = `[tool] ${oneLine(step.tool_name, 60)}${named(cmd) ? `: ${oneLine(cmd, 150)}` : ''} (${oneLine(step.state ?? 'update', 20)})`; - return step.state === 'DONE' ? [head, ...previewCommandOutput(step.tool_info?.output)].join('\n') : head; + const head = `[tool] ${oneLine(step.tool_name, 60, secrets)}${named(cmd) ? `: ${oneLine(cmd, 150, secrets)}` : ''} (${oneLine(step.state ?? 'update', 20, secrets)})`; + return step.state === 'DONE' ? [head, ...previewCommandOutput(step.tool_info?.output, secrets)].join('\n') : head; } return ''; } if (event.type === 'tool_use' && named(event.tool_name)) { const cmd = event.parameters?.command ?? event.parameters?.cmd ?? event.parameters?.path ?? event.parameters?.file_path ?? ''; - return `[tool] ${oneLine(event.tool_name, 60)}${named(cmd) ? `: ${oneLine(cmd, 150)}` : ''}`; + return `[tool] ${oneLine(event.tool_name, 60, secrets)}${named(cmd) ? `: ${oneLine(cmd, 150, secrets)}` : ''}`; } if (event.type === 'tool_result') { const raw = typeof event.output === 'string' ? event.output : JSON.stringify(event.output ?? ''); - return previewCommandOutput(raw).join('\n'); + return previewCommandOutput(raw, secrets).join('\n'); } if (event.type === 'message' && named(event.content)) { - const prefix = event.role === 'assistant' ? '[agent]' : `[${oneLine(event.role ?? 'msg', 20)}]`; - return cleanText(event.content, 800).split('\n').filter(s => s.trim()).map(l => `${prefix} ${l}`).join('\n'); + const prefix = event.role === 'assistant' ? '[agent]' : `[${oneLine(event.role ?? 'msg', 20, secrets)}]`; + return cleanText(event.content, 800, secrets).split('\n').filter(s => s.trim()).map(l => `${prefix} ${l}`).join('\n'); } - if (named(event.type)) return `[event] ${oneLine(event.type, 80)}`; + if (named(event.type)) return `[event] ${oneLine(event.type, 80, secrets)}`; return ''; } -function formatLogTail(fs, filePath, maxLines) { +function formatLogTail(fs, filePath, maxLines, secrets = []) { if (!filePath) return []; - let raw; + let raw = ''; try { const st = fs.statSync(filePath); if (!st.isFile() || st.size <= 0) return []; - const readSize = Math.min(st.size, Math.max(64 * 1024, maxLines * 2048)); - const start = Math.max(0, st.size - readSize); + let readSize = Math.min(st.size, Math.max(64 * 1024, maxLines * 2048)); const fd = fs.openSync(filePath, 'r'); try { - const buf = Buffer.alloc(readSize); - const bytes = fs.readSync(fd, buf, 0, readSize, start); - raw = buf.subarray(0, bytes).toString('utf8'); - if (start > 0) { - const nl = raw.indexOf('\n'); - if (nl >= 0) raw = raw.slice(nl + 1); + while (true) { + const start = Math.max(0, st.size - readSize); + const buf = Buffer.alloc(readSize); + const bytes = fs.readSync(fd, buf, 0, readSize, start); + if (bytes <= 0) return []; + if (start === 0) { + raw = buf.subarray(0, bytes).toString('utf8'); + break; + } + // Exclude a trailing EOF newline so a single-line tail ending in '\n' is never dropped. + const searchEnd = buf[bytes - 1] === 0x0a ? bytes - 1 : bytes; + const firstNl = buf.subarray(0, searchEnd).indexOf(0x0a); + if (firstNl >= 0) { + raw = buf.subarray(firstNl + 1, bytes).toString('utf8'); + break; + } + if (readSize >= st.size || readSize >= MAX_LINE_WINDOW_BYTES) { + return ['[log line exceeds 16 MiB; omitted unaligned tail]']; + } + readSize = Math.min(st.size, Math.min(MAX_LINE_WINDOW_BYTES, readSize * 2)); } } finally { try { fs.closeSync(fd); } catch {} @@ -289,7 +341,7 @@ function formatLogTail(fs, filePath, maxLines) { } const formatted = []; for (const rawLine of raw.split('\n')) { - const rendered = formatWorkerLogLine(rawLine); + const rendered = formatWorkerLogLine(rawLine, secrets); if (!rendered) continue; for (const line of rendered.split('\n')) { if (line.trim()) formatted.push(line); @@ -305,28 +357,31 @@ function validExitRecord(value) { && Number.isFinite(value.at); } -function inspectPart(part, role, { fs, isProcessAlive }) { +function inspectPart(part, role, { fs, isProcessAlive, secrets }) { if (!isObject(part)) return null; const exitRecord = typeof part.exit === 'string' ? readJson(fs, part.exit, null) : null; const hasExit = validExitRecord(exitRecord); - const pid = Number.isSafeInteger(part.pid) && part.pid > 0 ? part.pid : null; + const pid = validPid(part.pid) ? part.pid : null; const alive = pid !== null ? Boolean(isProcessAlive(pid, part.token)) : false; const logStat = typeof part.log === 'string' ? statInfo(fs, part.log) : null; const hangsRaw = typeof part.hangs === 'string' ? readJson(fs, part.hangs, null) : null; const hangs = Array.isArray(hangsRaw) ? hangsRaw.filter(isObject) : []; + const safeRole = oneLine(role, 40, secrets) || 'worker'; + const safeAgentKind = named(part.agentKind) ? oneLine(part.agentKind, 60, secrets) : null; + const safeExitSignal = hasExit && named(exitRecord.signal) ? oneLine(exitRecord.signal, 40, secrets) : null; let state = 'idle'; - let summary = `${role}: idle`; + let summary = `${safeRole}: idle`; if (alive) { state = 'running'; - summary = `${role}: running (pid ${pid}${named(part.agentKind) ? `, ${part.agentKind}` : ''})`; + summary = `${safeRole}: running (pid ${pid}${safeAgentKind ? `, ${safeAgentKind}` : ''})`; } else if (hasExit) { state = 'exited'; - const why = exitRecord.signal ? `signal ${exitRecord.signal}` : `code ${exitRecord.code ?? 'null'}`; - summary = `${role}: exited (${why})`; + const why = safeExitSignal ? `signal ${safeExitSignal}` : `code ${exitRecord.code ?? 'null'}`; + summary = `${safeRole}: exited (${why})`; } else if (pid !== null) { state = 'stale'; - summary = `${role}: stale (pid ${pid} not running, no exit receipt)`; + summary = `${safeRole}: stale (pid ${pid} not running, no exit receipt)`; } const activityCandidates = [ @@ -337,14 +392,15 @@ function inspectPart(part, role, { fs, isProcessAlive }) { ].filter(n => Number.isFinite(n) && n > 0); return { - role, + role: safeRole, pid, - agentKind: named(part.agentKind) ? part.agentKind : null, + agentKind: safeAgentKind, state, summary, - logPath: typeof part.log === 'string' ? part.log : null, + rawLogPath: typeof part.log === 'string' ? part.log : null, + logPath: typeof part.log === 'string' ? sanitizeString(part.log, secrets) : null, logSize: logStat?.size ?? 0, - exit: hasExit ? exitRecord : null, + exit: hasExit ? { code: exitRecord.code, signal: safeExitSignal, at: exitRecord.at } : null, hangCount: hangs.length, lastHang: hangs.at(-1) ?? null, startedAt: Number.isFinite(part.started) ? part.started : null, @@ -352,7 +408,7 @@ function inspectPart(part, role, { fs, isProcessAlive }) { }; } -function classifySuite(job, coreRoot, { fs, env, readSuite }) { +function classifySuite(job, coreRoot, { fs, env, readSuite, secrets }) { const hasSuiteField = isObject(job?.suite) || job?.phase === 'pr'; if (!hasSuiteField) return null; const suiteCwd = named(job?.suite?.cwd) @@ -370,49 +426,59 @@ function classifySuite(job, coreRoot, { fs, env, readSuite }) { } if (!isObject(progress)) return null; - const logStat = typeof progress.logPath === 'string' ? statInfo(fs, progress.logPath) : null; + const rawLogPath = typeof progress.logPath === 'string' ? progress.logPath : null; + const rawReceiptPath = typeof progress.receiptPath === 'string' ? progress.receiptPath : null; + const safeLogPath = rawLogPath !== null ? sanitizeString(rawLogPath, secrets) : null; + const safeReceiptPath = rawReceiptPath !== null ? sanitizeString(rawReceiptPath, secrets) : null; + const logStat = rawLogPath !== null ? statInfo(fs, rawLogPath) : null; const recordedCommit = progress.source?.commit ?? job.suite?.head ?? null; const headMismatch = named(job.head) && named(recordedCommit) && !String(job.head).startsWith(String(recordedCommit)) && !String(recordedCommit).startsWith(String(job.head)); const deadRunner = typeof progress.reason === 'string' && /runner ended|recorder_not_running/i.test(progress.reason); + const attachRawPaths = view => { + Object.defineProperty(view, 'rawLogPath', { value: rawLogPath, enumerable: false }); + Object.defineProperty(view, 'rawReceiptPath', { value: rawReceiptPath, enumerable: false }); + return view; + }; + if (progress.state === 'unavailable') { - return { + return attachRawPaths({ kind: 'unavailable', - detail: `full test suite queue unavailable (${oneLine(progress.reason || 'unreadable queue', 140)})`, + detail: `full test suite queue unavailable (${oneLine(progress.reason || 'unreadable queue', 140, secrets)})`, position: null, childPid: null, logPath: null, receiptPath: null, lastActivityAt: null, - }; + }); } if (deadRunner || (progress.state === 'finished' && headMismatch)) { const why = deadRunner - ? oneLine(progress.reason, 140) - : `receipt commit ${shortSha(recordedCommit)} differs from current PR head ${shortSha(job.head)}`; - return { + ? oneLine(progress.reason, 140, secrets) + : `receipt commit ${shortSha(recordedCommit, secrets)} differs from current PR head ${shortSha(job.head, secrets)}`; + return attachRawPaths({ kind: 'stale-receipt', detail: `stale suite receipt (${why})`, position: null, childPid: null, - logPath: typeof progress.logPath === 'string' ? progress.logPath : null, - receiptPath: typeof progress.receiptPath === 'string' ? progress.receiptPath : null, + logPath: safeLogPath, + receiptPath: safeReceiptPath, lastActivityAt: logStat?.mtimeMs ?? progress.finishedAt ?? progress.queuedAt ?? null, - }; + }); } if (progress.state === 'waiting') { const pos = Number.isSafeInteger(progress.position) ? progress.position : 1; - return { + return attachRawPaths({ kind: 'queued', detail: `queued in shared test-suite queue (position ${pos})`, position: pos, childPid: null, - logPath: typeof progress.logPath === 'string' ? progress.logPath : null, - receiptPath: typeof progress.receiptPath === 'string' ? progress.receiptPath : null, + logPath: safeLogPath, + receiptPath: safeReceiptPath, lastActivityAt: progress.queuedAt ?? logStat?.mtimeMs ?? null, - }; + }); } if (progress.state === 'running') { const counts = isObject(progress.counts) @@ -420,31 +486,30 @@ function classifySuite(job, coreRoot, { fs, env, readSuite }) { && Number.isFinite(progress.counts.fail) ? ` [pass ${progress.counts.pass}, fail ${progress.counts.fail}]` : ''; - const pidPart = Number.isSafeInteger(progress.childPid) && progress.childPid > 0 - ? ` (pid ${progress.childPid})` - : ''; - return { + const childPid = validPid(progress.childPid) ? progress.childPid : null; + const pidPart = childPid !== null ? ` (pid ${childPid})` : ''; + return attachRawPaths({ kind: 'running', detail: `running full test suite${pidPart}${counts}`, position: null, - childPid: Number.isSafeInteger(progress.childPid) ? progress.childPid : null, - logPath: typeof progress.logPath === 'string' ? progress.logPath : null, - receiptPath: typeof progress.receiptPath === 'string' ? progress.receiptPath : null, + childPid, + logPath: safeLogPath, + receiptPath: safeReceiptPath, lastActivityAt: logStat?.mtimeMs ?? progress.startedAt ?? null, - }; + }); } - return { + return attachRawPaths({ kind: 'finished', - detail: `full test suite finished (${oneLine(progress.outcome ?? `exit ${progress.exitCode ?? 'unknown'}`, 60)})`, + detail: `full test suite finished (${oneLine(progress.outcome ?? `exit ${progress.exitCode ?? 'unknown'}`, 60, secrets)})`, position: null, childPid: null, - logPath: typeof progress.logPath === 'string' ? progress.logPath : null, - receiptPath: typeof progress.receiptPath === 'string' ? progress.receiptPath : null, + logPath: safeLogPath, + receiptPath: safeReceiptPath, lastActivityAt: progress.finishedAt ?? logStat?.mtimeMs ?? null, - }; + }); } -function collectIssueArtifacts(fs, logsDir, issue) { +function collectIssueArtifacts(fs, logsDir, issue, secrets = []) { const prefix = `${issue}-`; const logs = []; const evidence = []; @@ -453,60 +518,77 @@ function collectIssueArtifacts(fs, logsDir, issue) { const full = join(logsDir, name); if (name.endsWith('.log')) { const st = statInfo(fs, full); - if (st) logs.push({ path: full, mtimeMs: st.mtimeMs, size: st.size }); + if (st) logs.push({ rawPath: full, path: sanitizeString(full, secrets), mtimeMs: st.mtimeMs, size: st.size }); } else if (/^\d+-evidence-.*\.json$/.test(name)) { const st = statInfo(fs, full); - if (st) evidence.push({ path: full, mtimeMs: st.mtimeMs }); + if (st) evidence.push({ rawPath: full, path: sanitizeString(full, secrets), mtimeMs: st.mtimeMs }); } } - logs.sort((a, b) => b.mtimeMs - a.mtimeMs || b.path.localeCompare(a.path)); - evidence.sort((a, b) => b.mtimeMs - a.mtimeMs || b.path.localeCompare(a.path)); + logs.sort((a, b) => b.mtimeMs - a.mtimeMs || b.rawPath.localeCompare(a.rawPath)); + evidence.sort((a, b) => b.mtimeMs - a.mtimeMs || b.rawPath.localeCompare(a.rawPath)); return { + rawLogPaths: logs.map(item => item.rawPath), logPaths: logs.map(item => item.path), latestLogMtimeMs: logs[0]?.mtimeMs ?? null, + rawEvidencePaths: evidence.map(item => item.rawPath), evidencePaths: evidence.map(item => item.path), }; } -function readMachineBlockers(machine, state, nowMs) { +function readMachineBlockers(machine, state, nowMs, secrets = []) { const blockers = []; if (Number.isFinite(machine?.pausedUntil) && machine.pausedUntil > nowMs) { - blockers.push(`New jobs paused until ${new Date(machine.pausedUntil).toISOString()} (${machine.streak ?? 0} no-result runs in a row)`); + const streak = Number.isSafeInteger(machine.streak) ? machine.streak : 0; + blockers.push(`New jobs paused until ${new Date(machine.pausedUntil).toISOString()} (${streak} no-result runs in a row)`); } if (isObject(machine?.poolOut)) { const until = named(machine.poolOut.wakeAt) - ? machine.poolOut.wakeAt + ? oneLine(machine.poolOut.wakeAt, 80, secrets) : (Number.isFinite(machine.poolOut.resetAt) ? new Date(machine.poolOut.resetAt).toISOString() : null); blockers.push(`AI login pool exhausted${until ? ` until ${until}` : ''}`); } if (isObject(machine?.ciDown) && ['queued', 'billing'].includes(machine.ciDown.reason)) { - blockers.push(`GitHub Actions hold (${machine.ciDown.reason}) since ${new Date(machine.ciDown.since).toISOString()}`); + const sinceText = Number.isFinite(machine.ciDown.since) ? new Date(machine.ciDown.since).toISOString() : 'unknown'; + blockers.push(`GitHub Actions hold (${machine.ciDown.reason}) since ${sinceText}`); } const breaker = (isObject(state?.circuitBreaker) && state.circuitBreaker.active !== false ? state.circuitBreaker : null) ?? (isObject(machine?.circuitBreaker) && machine.circuitBreaker.active !== false ? machine.circuitBreaker : null); if (breaker && Number.isSafeInteger(breaker.pr)) { - blockers.push(`Safety circuit breaker tripped on PR #${breaker.pr}: mode downgraded to observe (${oneLine(breaker.reason ?? breaker.code ?? 'post-merge regression', 120)})`); + blockers.push(`Safety circuit breaker tripped on PR #${breaker.pr}: mode downgraded to observe (${oneLine(breaker.reason ?? breaker.code ?? 'post-merge regression', 120, secrets)})`); } return blockers; } +function makeStreamEntry(label, rawPath, secrets = []) { + const entry = { + label: oneLine(label, 40, secrets) || 'worker', + path: sanitizeString(rawPath, secrets), + }; + Object.defineProperty(entry, 'rawPath', { value: rawPath, enumerable: false }); + return entry; +} + function buildWorkerView(job, ctx) { - const { fs, coreRoot, logsDir, isProcessAlive, env, readSuite, machineBlockers } = ctx; + const { fs, coreRoot, logsDir, isProcessAlive, env, readSuite, machineBlockers, secrets } = ctx; const issue = job.issue; const isIntake = job.__intake === true; - const artifacts = collectIssueArtifacts(fs, logsDir, issue); + const artifacts = collectIssueArtifacts(fs, logsDir, issue, secrets); - const mainRole = isIntake ? 'intake' : (named(job.role) ? job.role : 'build'); - const mainPart = inspectPart(job.agent ?? (isIntake ? job : null), mainRole, { fs, isProcessAlive }); - const reviewPart = inspectPart(job.review?.agent, 'review', { fs, isProcessAlive }); - const suiteAgentPart = inspectPart(job.suite?.agent, 'suite-runner', { fs, isProcessAlive }); - const vectorsPart = inspectPart(job.vectors?.agent, 'vectors', { fs, isProcessAlive }); - const runtimePart = inspectPart(job.runtimeWait?.agent, 'interpreter-check', { fs, isProcessAlive }); - const suiteView = isIntake ? null : classifySuite(job, coreRoot, { fs, env, readSuite }); + const mainRole = isIntake ? 'intake' : (named(job.role) ? oneLine(job.role, 40, secrets) : 'build'); + const mainPart = inspectPart(job.agent ?? (isIntake ? job : null), mainRole, { fs, isProcessAlive, secrets }); + const reviewPart = inspectPart(job.review?.agent, 'review', { fs, isProcessAlive, secrets }); + const suiteAgentPart = inspectPart(job.suite?.agent, 'suite-runner', { fs, isProcessAlive, secrets }); + const vectorsPart = inspectPart(job.vectors?.agent, 'vectors', { fs, isProcessAlive, secrets }); + const runtimePart = inspectPart(job.runtimeWait?.agent, 'interpreter-check', { fs, isProcessAlive, secrets }); + const suiteView = isIntake ? null : classifySuite(job, coreRoot, { fs, env, readSuite, secrets }); const parts = [mainPart, reviewPart, suiteAgentPart, vectorsPart, runtimePart].filter(Boolean); const liveParts = parts.filter(part => part.state === 'running'); const staleParts = parts.filter(part => part.state === 'stale'); + const safeHolder = job.lane?.holder !== undefined && job.lane?.holder !== null + ? oneLine(String(job.lane.holder), 60, secrets) + : ''; + const safeVerdict = named(job.review?.verdict) ? oneLine(job.review.verdict, 60, secrets) : ''; let stage = mainRole; let stageDetail = mainRole; @@ -515,12 +597,12 @@ function buildWorkerView(job, ctx) { stageDetail = 'read-only intake card worker'; } else if (job.phase === 'ending') { stage = 'ending'; - stageDetail = `ending (${oneLine(job.end?.cause?.text ?? 'finishing cleanup', 140)})`; + stageDetail = `ending (${oneLine(job.end?.cause?.text ?? 'finishing cleanup', 140, secrets)})`; } else if (job.phase === 'released') { stage = 'release-pending'; stageDetail = `release pending (retry pdd autopilot release ${issue})`; } else if (job.phase === 'pr') { - const prLabel = Number.isSafeInteger(job.pr) ? `PR #${job.pr} (${shortSha(job.head)})` : 'PR check'; + const prLabel = Number.isSafeInteger(job.pr) ? `PR #${job.pr} (${shortSha(job.head, secrets)})` : 'PR check'; if (suiteView?.kind === 'queued') { stage = 'suite-queued'; stageDetail = `${prLabel}: ${suiteView.detail}`; @@ -541,13 +623,13 @@ function buildWorkerView(job, ctx) { stageDetail = `${prLabel}: PDD interpreter check running`; } else if (job.lane?.state === 'waiting') { stage = 'merge-lane'; - stageDetail = `${prLabel}: waiting in merge lane${job.lane.holder ? ` behind PR #${job.lane.holder}` : ''}`; + stageDetail = `${prLabel}: waiting in merge lane${safeHolder ? ` behind PR #${safeHolder}` : ''}`; } else if (job.lane?.state === 'final') { stage = 'merge-lane'; stageDetail = `${prLabel}: final merge check`; } else { stage = 'pr-check'; - const reviewNote = named(job.review?.verdict) ? `review ${job.review.verdict}` : 'review pending'; + const reviewNote = safeVerdict ? `review ${safeVerdict}` : 'review pending'; const suiteNote = suiteView?.detail ?? (job.suite ? 'suite started' : 'suite pending'); stageDetail = `${prLabel}: ${reviewNote}, ${suiteNote}`; } @@ -567,16 +649,16 @@ function buildWorkerView(job, ctx) { // Owned process summary let processState = 'idle'; let processSummary = 'no active worker process'; - if (suiteView?.kind === 'running' && (suiteView.childPid || suiteAgentPart?.state === 'running')) { + if (suiteView?.kind === 'running' && (validPid(suiteView.childPid) || suiteAgentPart?.state === 'running')) { processState = 'running'; const pieces = []; - if (suiteView.childPid) pieces.push(`suite pid ${suiteView.childPid}`); - else if (suiteAgentPart?.pid) pieces.push(`suite wrapper pid ${suiteAgentPart.pid}`); - if (reviewPart?.state === 'running') pieces.push(`review pid ${reviewPart.pid}`); + if (validPid(suiteView.childPid)) pieces.push(`suite pid ${suiteView.childPid}`); + else if (validPid(suiteAgentPart?.pid)) pieces.push(`suite wrapper pid ${suiteAgentPart.pid}`); + if (reviewPart?.state === 'running' && validPid(reviewPart.pid)) pieces.push(`review pid ${reviewPart.pid}`); processSummary = `running (${pieces.join(', ')})`; } else if (suiteView?.kind === 'queued' && suiteAgentPart?.state === 'running') { processState = 'waiting'; - processSummary = `waiting in suite queue (queue client pid ${suiteAgentPart.pid}${reviewPart?.state === 'running' ? `, review pid ${reviewPart.pid} running` : ''})`; + processSummary = `waiting in suite queue (queue client pid ${suiteAgentPart.pid}${reviewPart?.state === 'running' && validPid(reviewPart.pid) ? `, review pid ${reviewPart.pid} running` : ''})`; } else if (liveParts.length > 0) { processState = 'running'; processSummary = liveParts.map(part => part.summary).join('; '); @@ -607,25 +689,25 @@ function buildWorkerView(job, ctx) { blockers.push(`Recorded worker process exited without a receipt (${staleParts.map(p => `${p.role} pid ${p.pid}`).join(', ')})`); } if (job.lane?.state === 'waiting') { - blockers.push(`Waiting in merge lane${job.lane.holder ? ` for PR #${job.lane.holder}` : ''}${Number.isFinite(job.lane.since) ? ` since ${new Date(job.lane.since).toISOString()}` : ''}`); + blockers.push(`Waiting in merge lane${safeHolder ? ` for PR #${safeHolder}` : ''}${Number.isFinite(job.lane.since) ? ` since ${new Date(job.lane.since).toISOString()}` : ''}`); } if (job.runtimeWait?.state === 'waiting') { - blockers.push(`Waiting on PDD interpreter maintenance${job.runtimeWait.until ? ` until ${new Date(job.runtimeWait.until).toISOString()}` : ''}`); + blockers.push(`Waiting on PDD interpreter maintenance${Number.isFinite(job.runtimeWait.until) ? ` until ${new Date(job.runtimeWait.until).toISOString()}` : ''}`); } if (job.stepStop?.poolExhausted) { const wake = named(job.stepStop.wakeAt) - ? job.stepStop.wakeAt + ? oneLine(job.stepStop.wakeAt, 80, secrets) : (Number.isFinite(job.stepStop.until) ? new Date(job.stepStop.until).toISOString() : null); blockers.push(`Waiting on AI quota / login pool${wake ? ` until ${wake}` : ''}`); } for (const part of parts) { if (part.hangCount > 0) { - const cmd = oneLine(part.lastHang?.command ?? 'hung child command', 100); + const cmd = oneLine(part.lastHang?.command ?? 'hung child command', 100, secrets); blockers.push(`Watchdog stopped ${part.hangCount} hung command${part.hangCount === 1 ? '' : 's'} (${cmd})`); } } if (named(job.lastError)) { - blockers.push(`Last error: ${oneLine(job.lastError, 180)}`); + blockers.push(`Last error: ${oneLine(job.lastError, 180, secrets)}`); } for (const mb of machineBlockers) { if (!blockers.includes(mb)) blockers.push(mb); @@ -633,39 +715,39 @@ function buildWorkerView(job, ctx) { // Active streams to tail (prefer live suite validation log when running, plus active worker logs) const streams = []; - const addStream = (label, filePath) => { - if (!named(filePath)) return; - if (streams.some(s => s.path === filePath)) return; - if (statInfo(fs, filePath)) streams.push({ label, path: filePath }); + const addStream = (label, rawFilePath) => { + if (!named(rawFilePath)) return; + if (streams.some(s => (s.rawPath ?? s.path) === rawFilePath)) return; + if (statInfo(fs, rawFilePath)) streams.push(makeStreamEntry(label, rawFilePath, secrets)); }; if (job.phase === 'pr') { - if (suiteView?.kind === 'running' && suiteView.logPath) addStream('suite', suiteView.logPath); - if (reviewPart?.state === 'running') addStream('review', reviewPart.logPath); - if (suiteAgentPart?.state === 'running' && suiteView?.kind !== 'running') addStream('suite-queue', suiteAgentPart.logPath); - if (vectorsPart?.state === 'running') addStream('vectors', vectorsPart.logPath); - if (runtimePart?.state === 'running') addStream('interpreter', runtimePart.logPath); + if (suiteView?.kind === 'running' && suiteView.rawLogPath) addStream('suite', suiteView.rawLogPath); + if (reviewPart?.state === 'running') addStream('review', reviewPart.rawLogPath); + if (suiteAgentPart?.state === 'running' && suiteView?.kind !== 'running') addStream('suite-queue', suiteAgentPart.rawLogPath); + if (vectorsPart?.state === 'running') addStream('vectors', vectorsPart.rawLogPath); + if (runtimePart?.state === 'running') addStream('interpreter', runtimePart.rawLogPath); // Fallback to latest finished PR sub-logs when nothing is currently live if (!streams.length) { - if (suiteView?.logPath) addStream('suite', suiteView.logPath); - addStream('suite-queue', suiteAgentPart?.logPath); - addStream('review', reviewPart?.logPath); - addStream(mainRole, mainPart?.logPath); + if (suiteView?.rawLogPath) addStream('suite', suiteView.rawLogPath); + addStream('suite-queue', suiteAgentPart?.rawLogPath); + addStream('review', reviewPart?.rawLogPath); + addStream(mainRole, mainPart?.rawLogPath); } } else { - addStream(mainRole, mainPart?.logPath); + addStream(mainRole, mainPart?.rawLogPath); } - if (!streams.length && artifacts.logPaths.length) { - addStream('worker', artifacts.logPaths[0]); + if (!streams.length && artifacts.rawLogPaths.length) { + addStream('worker', artifacts.rawLogPaths[0]); } const evidencePaths = [ ...artifacts.evidencePaths, - ...(named(suiteView?.receiptPath) && statInfo(fs, suiteView.receiptPath) ? [suiteView.receiptPath] : []), + ...(named(suiteView?.rawReceiptPath) && statInfo(fs, suiteView.rawReceiptPath) ? [suiteView.receiptPath] : []), ]; const allLogPaths = [ ...new Set([ ...streams.map(s => s.path), - ...(named(suiteView?.logPath) && statInfo(fs, suiteView.logPath) ? [suiteView.logPath] : []), + ...(named(suiteView?.rawLogPath) && statInfo(fs, suiteView.rawLogPath) ? [suiteView.logPath] : []), ...artifacts.logPaths, ]), ]; @@ -679,12 +761,16 @@ function buildWorkerView(job, ctx) { ].filter(n => Number.isFinite(n) && n > 0); const lastActivityAt = activityTimes.length ? Math.max(...activityTimes) : null; + const safeIssues = Array.isArray(job.issues) + ? job.issues.filter(n => Number.isSafeInteger(n) && n > 0) + : []; + return { issue, - issues: Array.isArray(job.issues) && job.issues.length ? job.issues : [issue], - title: named(job.title) ? oneLine(job.title, 140) : null, + issues: safeIssues.length ? safeIssues : [issue], + title: named(job.title) ? oneLine(job.title, 140, secrets) : null, pr: Number.isSafeInteger(job.pr) ? job.pr : null, - head: named(job.head) ? job.head : null, + head: named(job.head) ? oneLine(job.head, 80, secrets) : null, active: true, liveProcess: processState === 'running' || processState === 'waiting', stage, @@ -721,7 +807,7 @@ function readJobsFromDir(fs, dirPath, intake = false) { return rows.sort((a, b) => a.issue - b.issue); } -function readRecentHistory(fs, coreRoot, logsDir) { +function readRecentHistory(fs, coreRoot, logsDir, secrets = []) { const historyPath = join(coreRoot, 'history.jsonl'); let raw = ''; try { raw = fs.readFileSync(historyPath, 'utf8'); } catch { return []; } @@ -742,13 +828,13 @@ function readRecentHistory(fs, coreRoot, logsDir) { for (const row of parsed) { if (seen.has(row.issue)) continue; seen.add(row.issue); - const artifacts = collectIssueArtifacts(fs, logsDir, row.issue); + const artifacts = collectIssueArtifacts(fs, logsDir, row.issue, secrets); unique.push({ issue: row.issue, - outcome: oneLine(row.outcome, 40), + outcome: oneLine(row.outcome, 40, secrets), at: Number.isFinite(row.at) ? row.at : null, pr: Number.isSafeInteger(row.pr) ? row.pr : null, - text: named(row.text) ? oneLine(row.text, 180) : '', + text: named(row.text) ? oneLine(row.text, 180, secrets) : '', logPaths: artifacts.logPaths, evidencePaths: artifacts.evidencePaths, }); @@ -774,6 +860,7 @@ function resolveEffectiveMode(fs, gitRoot, launcherState, machineState) { export async function inspectAutopilotWorkers(input = {}, ports = {}) { const fs = ports.fs ?? nativeFs; const env = input.env ?? process.env; + const secrets = knownSecretValues(env); const cwd = input.cwd ?? process.cwd(); const now = ports.now ?? Date.now; const nowMs = now(); @@ -781,8 +868,8 @@ export async function inspectAutopilotWorkers(input = {}, ports = {}) { const isProcessAlive = ports.isProcessAlive ?? defaultIsProcessAlive; const readSuite = ports.readSuite ?? ((suiteInput) => readSuiteProgress(suiteInput)); - let gitRoot = ports.gitRoot ?? null; - if (!gitRoot) { + let rawGitRoot = ports.gitRoot ?? null; + if (!rawGitRoot) { const reply = await git(['rev-parse', '--show-toplevel'], { cwd, env }); if (reply.code !== 0 || !named(reply.stdout)) { const notRepo = /not a git repository/i.test(String(reply.stderr ?? '')); @@ -790,52 +877,53 @@ export async function inspectAutopilotWorkers(input = {}, ports = {}) { ok: false, exitCode: 1, message: notRepo - ? 'This folder is not a Git repository. cd into the repo you want Autopilot to work on, then run pdd autopilot logs again.' + ? 'This folder is not a Git repository. cd into the repo you want Autopilot to work on, then run the command again.' : 'Autopilot logs could not read the Git repository; retry.', }; } - gitRoot = reply.stdout.trim(); + rawGitRoot = reply.stdout.trim(); } const stateRoot = ports.stateRoot ?? join(env.HOME || homedir(), '.local', 'state', 'pdd', 'autopilot'); - const stateId = createHash('sha256').update(gitRoot).digest('hex').slice(0, 20); - const stateFile = join(stateRoot, `${stateId}.json`); - const coreRoot = ports.coreRoot ?? join(stateRoot, `${stateId}-core`); - const logsDir = join(coreRoot, 'logs'); + const stateId = createHash('sha256').update(rawGitRoot).digest('hex').slice(0, 20); + const rawStateFile = join(stateRoot, `${stateId}.json`); + const rawCoreRoot = ports.coreRoot ?? join(stateRoot, `${stateId}-core`); + const logsDir = join(rawCoreRoot, 'logs'); - const launcherState = readJson(fs, stateFile, null); - const machineState = readJson(fs, join(coreRoot, 'core.json'), null); - const { mode, modeSource } = resolveEffectiveMode(fs, gitRoot, launcherState, machineState); - const machineBlockers = readMachineBlockers(machineState, launcherState, nowMs); + const launcherState = readJson(fs, rawStateFile, null); + const machineState = readJson(fs, join(rawCoreRoot, 'core.json'), null); + const { mode, modeSource } = resolveEffectiveMode(fs, rawGitRoot, launcherState, machineState); + const machineBlockers = readMachineBlockers(machineState, launcherState, nowMs, secrets); - const coreJobs = readJobsFromDir(fs, join(coreRoot, 'jobs'), false); + const coreJobs = readJobsFromDir(fs, join(rawCoreRoot, 'jobs'), false); const activeIssueIds = new Set(coreJobs.map(j => j.issue)); - const intakeJobs = readJobsFromDir(fs, join(coreRoot, 'intake', 'jobs'), true) + const intakeJobs = readJobsFromDir(fs, join(rawCoreRoot, 'intake', 'jobs'), true) .filter(j => !activeIssueIds.has(j.issue)); const ctx = { fs, - coreRoot, + coreRoot: rawCoreRoot, logsDir, isProcessAlive, env, readSuite, machineBlockers, + secrets, }; const workers = [...coreJobs, ...intakeJobs] .map(job => buildWorkerView(job, ctx)) .sort((a, b) => a.issue - b.issue); - const recent = readRecentHistory(fs, coreRoot, logsDir) + const recent = readRecentHistory(fs, rawCoreRoot, logsDir, secrets) .filter(row => !workers.some(w => w.issue === row.issue)); - return { + const snapshot = { ok: true, nowMs, - repo: named(launcherState?.repo) ? launcherState.repo : null, - gitRoot, + repo: named(launcherState?.repo) ? oneLine(launcherState.repo, 140, secrets) : null, + gitRoot: sanitizeString(rawGitRoot, secrets), stateId, - stateFile, - coreRoot, + stateFile: sanitizeString(rawStateFile, secrets), + coreRoot: sanitizeString(rawCoreRoot, secrets), mode, modeSource, timerEnabled: Boolean(launcherState?.enabled), @@ -843,12 +931,15 @@ export async function inspectAutopilotWorkers(input = {}, ports = {}) { workers, recent, }; + Object.defineProperty(snapshot, 'rawGitRoot', { value: rawGitRoot, enumerable: false }); + Object.defineProperty(snapshot, 'rawCoreRoot', { value: rawCoreRoot, enumerable: false }); + return snapshot; } -function buildHistoricalWorkerView(issue, snapshot, fs) { - const logsDir = join(snapshot.coreRoot, 'logs'); +function buildHistoricalWorkerView(issue, snapshot, fs, secrets = []) { + const logsDir = join(snapshot.rawCoreRoot ?? snapshot.coreRoot, 'logs'); const historyRow = snapshot.recent.find(row => row.issue === issue) ?? null; - const artifacts = collectIssueArtifacts(fs, logsDir, issue); + const artifacts = collectIssueArtifacts(fs, logsDir, issue, secrets); if (!historyRow && !artifacts.logPaths.length && !artifacts.evidencePaths.length) return null; const outcome = historyRow ? `${historyRow.outcome}${historyRow.text ? ` — ${historyRow.text}` : ''}` : 'saved log on disk'; @@ -868,7 +959,7 @@ function buildHistoricalWorkerView(issue, snapshot, fs) { blockers: [], lastActivityAt: historyRow?.at ?? artifacts.latestLogMtimeMs ?? null, startedAt: null, - streams: artifacts.logPaths.length ? [{ label: 'worker', path: artifacts.logPaths[0] }] : [], + streams: artifacts.rawLogPaths.length ? [makeStreamEntry('worker', artifacts.rawLogPaths[0], secrets)] : [], logPaths: artifacts.logPaths, evidencePaths: artifacts.evidencePaths, }; @@ -946,33 +1037,63 @@ function renderWorkerHeader(snapshot, worker) { return lines; } -function readAppendedCompleteLines(fs, filePath, offset) { +function readAppendedCompleteLines(fs, filePath, prevState) { + let offset = isObject(prevState) ? (prevState.offset ?? 0) : (Number.isInteger(prevState) ? prevState : 0); + let skip = isObject(prevState) ? Boolean(prevState.skip) : false; let fd; try { fd = fs.openSync(filePath, 'r'); const size = fs.fstatSync(fd).size; - if (size < offset) offset = 0; // Handle log truncation cleanly. - const length = Math.min(READ_CHUNK_LIMIT, size - offset); - if (length <= 0) return { nextOffset: offset, lines: [] }; - const buffer = Buffer.alloc(length); - const bytesRead = fs.readSync(fd, buffer, 0, length, offset); - if (bytesRead <= 0) return { nextOffset: offset, lines: [] }; - const text = buffer.subarray(0, bytesRead).toString('utf8'); - const lastNewline = text.lastIndexOf('\n'); - if (lastNewline < 0) { - if (bytesRead >= READ_CHUNK_LIMIT) { - return { nextOffset: offset + bytesRead, lines: [text] }; + if (size < offset) { + offset = 0; + skip = false; + } + const available = size - offset; + if (available <= 0) return { nextOffset: offset, skip, lines: [] }; + + if (skip) { + const scanLen = Math.min(READ_CHUNK_LIMIT, available); + const scanBuf = Buffer.alloc(scanLen); + const scanBytes = fs.readSync(fd, scanBuf, 0, scanLen, offset); + if (scanBytes <= 0) return { nextOffset: offset, skip: true, lines: [] }; + const firstNl = scanBuf.subarray(0, scanBytes).indexOf(0x0a); + if (firstNl < 0) return { nextOffset: offset + scanBytes, skip: true, lines: [] }; + offset = offset + firstNl + 1; + skip = false; + if (size - offset <= 0) return { nextOffset: offset, skip: false, lines: [] }; + } + + const remaining = size - offset; + let readLen = Math.min(READ_CHUNK_LIMIT, remaining); + while (true) { + const buffer = Buffer.alloc(readLen); + const bytesRead = fs.readSync(fd, buffer, 0, readLen, offset); + if (bytesRead <= 0) return { nextOffset: offset, skip: false, lines: [] }; + const slice = buffer.subarray(0, bytesRead); + const lastNlByte = slice.lastIndexOf(0x0a); + if (lastNlByte >= 0) { + const completeText = slice.subarray(0, lastNlByte).toString('utf8'); + return { + nextOffset: offset + lastNlByte + 1, + skip: false, + lines: completeText.split('\n'), + }; } - return { nextOffset: offset, lines: [] }; + if (bytesRead < remaining && readLen < MAX_LINE_WINDOW_BYTES) { + readLen = Math.min(remaining, Math.min(MAX_LINE_WINDOW_BYTES, readLen * 2)); + continue; + } + if (bytesRead >= MAX_LINE_WINDOW_BYTES) { + return { + nextOffset: offset + bytesRead, + skip: true, + lines: ['[log line exceeds 16 MiB; omitted]'], + }; + } + return { nextOffset: offset, skip: false, lines: [] }; } - const completeChunk = text.slice(0, lastNewline + 1); - const usedBytes = Buffer.byteLength(completeChunk, 'utf8'); - return { - nextOffset: offset + usedBytes, - lines: completeChunk.slice(0, -1).split('\n'), - }; } catch { - return { nextOffset: offset, lines: [] }; + return { nextOffset: offset, skip, lines: [] }; } finally { if (fd !== undefined) { try { fs.closeSync(fd); } catch {} @@ -982,6 +1103,8 @@ function readAppendedCompleteLines(fs, filePath, offset) { export async function runAutopilotLogs(input = {}, ports = {}) { const fs = ports.fs ?? nativeFs; + const env = input.env ?? process.env; + const secrets = knownSecretValues(env); const follow = Boolean(input.follow); const json = Boolean(input.json); const tailLines = input.lines === undefined ? DEFAULT_LINES : Number(input.lines); @@ -992,28 +1115,43 @@ export async function runAutopilotLogs(input = {}, ports = {}) { if (follow && json) { return { exitCode: 2, message: '--json prints one snapshot and cannot be combined with --follow.' }; } - if (input.positionalIssue !== undefined && input.optionIssue !== undefined && input.positionalIssue !== input.optionIssue) { - return { exitCode: 2, message: 'Pass the issue once: pdd autopilot logs ISSUE or pdd autopilot logs --issue ISSUE.' }; + if (input.positionalIssue !== undefined && input.optionIssue !== undefined) { + const posCheck = parseIssueSelector(input.positionalIssue); + const optCheck = parseIssueSelector(input.optionIssue); + if (!posCheck.ok) { + return { exitCode: 2, message: `"${oneLine(input.positionalIssue, 80, secrets)}" is not a valid issue number, owner/repo#N or GitHub issue URL.` }; + } + if (!optCheck.ok) { + return { exitCode: 2, message: `"${oneLine(input.optionIssue, 80, secrets)}" is not a valid issue number, owner/repo#N or GitHub issue URL.` }; + } + if (posCheck.issue !== optCheck.issue + || (posCheck.repo && optCheck.repo && posCheck.repo.toLowerCase() !== optCheck.repo.toLowerCase())) { + return { exitCode: 2, message: 'Pass the issue once: pdd autopilot logs ISSUE or pdd autopilot logs --issue ISSUE.' }; + } } - const rawIssue = input.issue ?? input.positionalIssue ?? input.optionIssue; + const rawIssue = input.issue ?? ( + input.positionalIssue !== undefined && input.optionIssue !== undefined + ? (parseIssueSelector(input.positionalIssue).repo ? input.positionalIssue : input.optionIssue) + : (input.positionalIssue ?? input.optionIssue) + ); const parsedIssue = parseIssueSelector(rawIssue); if (!parsedIssue.ok) { - return { exitCode: 2, message: `"${oneLine(rawIssue, 80)}" is not a valid issue number, owner/repo#N or GitHub issue URL.` }; + return { exitCode: 2, message: `"${oneLine(rawIssue, 80, secrets)}" is not a valid issue number, owner/repo#N or GitHub issue URL.` }; } if (follow && parsedIssue.issue === null) { return { exitCode: 2, message: 'Select an issue to follow: pdd autopilot logs ISSUE --follow.' }; } const snapshot = await inspectAutopilotWorkers(input, ports); - if (!snapshot.ok) return { exitCode: snapshot.exitCode, message: snapshot.message }; + if (!snapshot.ok) return { exitCode: snapshot.exitCode, message: sanitizeString(snapshot.message, secrets) }; if (parsedIssue.repo && snapshot.repo && parsedIssue.repo.toLowerCase() !== snapshot.repo.toLowerCase()) { - return { exitCode: 1, message: `Issue ${parsedIssue.repo}#${parsedIssue.issue} does not belong to ${snapshot.repo}.` }; + return { exitCode: 1, message: sanitizeString(`Issue ${parsedIssue.repo}#${parsedIssue.issue} does not belong to ${snapshot.repo}.`, secrets) }; } if (parsedIssue.issue === null) { if (json) { - const payload = { + const payload = sanitizeJsonValue({ schema: 'pdd.autopilot-logs.v1', repo: snapshot.repo, gitRoot: snapshot.gitRoot, @@ -1023,15 +1161,15 @@ export async function runAutopilotLogs(input = {}, ports = {}) { machineBlockers: snapshot.machineBlockers, workers: snapshot.workers, recent: snapshot.recent.slice(0, 10), - }; + }, secrets); return { exitCode: 0, message: JSON.stringify(payload, null, 2), data: payload }; } - return { exitCode: 0, message: renderWorkerList(snapshot) }; + return { exitCode: 0, message: sanitizeString(renderWorkerList(snapshot), secrets) }; } const issue = parsedIssue.issue; const findTarget = snap => snap.workers.find(w => w.issue === issue || w.issues.includes(issue)) - ?? buildHistoricalWorkerView(issue, snap, fs); + ?? buildHistoricalWorkerView(issue, snap, fs, secrets); const initialWorker = findTarget(snapshot); if (!initialWorker) { @@ -1042,10 +1180,11 @@ export async function runAutopilotLogs(input = {}, ports = {}) { } if (json) { - const tail = initialWorker.streams[0] - ? formatLogTail(fs, initialWorker.streams[0].path, tailLines) + const firstStream = initialWorker.streams[0]; + const tail = firstStream + ? formatLogTail(fs, firstStream.rawPath ?? firstStream.path, tailLines, secrets) : []; - const payload = { + const payload = sanitizeJsonValue({ schema: 'pdd.autopilot-logs.v1', repo: snapshot.repo, gitRoot: snapshot.gitRoot, @@ -1054,7 +1193,7 @@ export async function runAutopilotLogs(input = {}, ports = {}) { timerEnabled: snapshot.timerEnabled, worker: initialWorker, lines: tail, - }; + }, secrets); return { exitCode: 0, message: JSON.stringify(payload, null, 2), data: payload }; } @@ -1063,7 +1202,7 @@ export async function runAutopilotLogs(input = {}, ports = {}) { const multi = initialWorker.streams.length > 1; let printedAny = false; for (const stream of initialWorker.streams) { - const tail = formatLogTail(fs, stream.path, tailLines); + const tail = formatLogTail(fs, stream.rawPath ?? stream.path, tailLines, secrets); if (!tail.length) continue; printedAny = true; out.push('', `--- Recent progress${multi ? ` (${stream.label})` : ''} ---`); @@ -1075,50 +1214,67 @@ export async function runAutopilotLogs(input = {}, ports = {}) { if (initialWorker.active) { out.push('', `Follow live output: pdd autopilot logs ${initialWorker.issue} --follow`); } - return { exitCode: 0, message: out.join('\n') }; + return { exitCode: 0, message: sanitizeString(out.join('\n'), secrets) }; } // Live --follow streaming mode (strictly read-only; detaches without signaling worker) const stdout = ports.stdout ?? process.stdout; - const writeLine = text => stdout.write(`${text}\n`); - for (const headerLine of renderWorkerHeader(snapshot, initialWorker)) writeLine(headerLine); - - if (!initialWorker.active) { - const tail = initialWorker.streams[0] ? formatLogTail(fs, initialWorker.streams[0].path, tailLines) : []; - if (tail.length) { - writeLine(''); - writeLine('--- Saved progress ---'); - for (const l of tail) writeLine(l); - } - writeLine(''); - writeLine(`Worker #${initialWorker.issue} has already finished; nothing live to follow.`); - return { exitCode: 0, message: '', streamed: true }; - } - - writeLine('Following live output (press Ctrl-C to detach without stopping the worker)...'); - writeLine(''); - - const offsets = new Map(); - const multiInitial = initialWorker.streams.length > 1; - for (const stream of initialWorker.streams) { - const st = statInfo(fs, stream.path); - const tail = formatLogTail(fs, stream.path, tailLines); - for (const l of tail) writeLine(multiInitial ? `[${stream.label}] ${l}` : l); - offsets.set(stream.path, st?.size ?? 0); - } - - let lastStageSig = `${initialWorker.stageDetail}|${initialWorker.processSummary}`; - let lastBlockersSig = initialWorker.blockers.join('; '); - const pollMs = Math.max(10, Number.isFinite(ports.pollMs) ? ports.pollMs : DEFAULT_POLL_MS); + const now = ports.now ?? Date.now; + const startMs = now(); + const maxDurationMs = Number.isFinite(ports.maxDurationMs) && ports.maxDurationMs > 0 + ? ports.maxDurationMs + : DEFAULT_MAX_DURATION_MS; + const pollPorts = { ...ports, gitRoot: snapshot.rawGitRoot ?? snapshot.gitRoot }; + let streamClosed = Boolean(stdout?.destroyed || stdout?.writableEnded); let detached = false; + let timedOut = false; let wakeSleep = null; + const triggerDetach = () => { if (detached) return; detached = true; wakeSleep?.(); }; + const onStdoutClose = () => { + streamClosed = true; + triggerDetach(); + }; + const onStdoutError = () => { + streamClosed = true; + triggerDetach(); + }; + if (typeof stdout?.on === 'function') { + stdout.on('close', onStdoutClose); + stdout.on('error', onStdoutError); + } + + const canWrite = () => !streamClosed && !stdout?.destroyed && !stdout?.writableEnded; + const writeLine = text => { + if (!canWrite()) { + streamClosed = true; + triggerDetach(); + return false; + } + try { + stdout.write(`${sanitizeString(text, secrets)}\n`); + if (stdout?.destroyed || stdout?.writableEnded) { + streamClosed = true; + triggerDetach(); + return false; + } + return true; + } catch (error) { + if (error?.code === 'EPIPE' || error?.code === 'ERR_STREAM_DESTROYED' || error?.code === 'ERR_STREAM_WRITE_AFTER_END') { + streamClosed = true; + triggerDetach(); + return false; + } + throw error; + } + }; + const signal = ports.signal ?? null; const onSigint = () => triggerDetach(); const onSigterm = () => triggerDetach(); @@ -1132,11 +1288,11 @@ export async function runAutopilotLogs(input = {}, ports = {}) { const waitNext = ports.sleep ? async ms => { - if (detached) return; + if (detached || streamClosed) return; await ports.sleep(ms); } : ms => new Promise(resolveWait => { - if (detached) { resolveWait(); return; } + if (detached || streamClosed) { resolveWait(); return; } const timer = setTimeout(() => { wakeSleep = null; resolveWait(); }, ms); wakeSleep = () => { clearTimeout(timer); wakeSleep = null; resolveWait(); }; }); @@ -1145,12 +1301,63 @@ export async function runAutopilotLogs(input = {}, ports = {}) { let polls = 0; try { - while (!detached && polls < maxPolls) { - await waitNext(pollMs); - if (detached) break; + for (const headerLine of renderWorkerHeader(snapshot, initialWorker)) { + if (!writeLine(headerLine)) return { exitCode: 0, message: '', streamed: true }; + } + + if (!initialWorker.active) { + const firstStream = initialWorker.streams[0]; + const tail = firstStream ? formatLogTail(fs, firstStream.rawPath ?? firstStream.path, tailLines, secrets) : []; + if (tail.length) { + writeLine(''); + writeLine('--- Saved progress ---'); + for (const l of tail) { + if (!writeLine(l)) return { exitCode: 0, message: '', streamed: true }; + } + } + writeLine(''); + writeLine(`Worker #${initialWorker.issue} has already finished; nothing live to follow.`); + return { exitCode: 0, message: '', streamed: true }; + } + + if (!writeLine('Following live output (press Ctrl-C to detach without stopping the worker)...')) { + return { exitCode: 0, message: '', streamed: true }; + } + if (!writeLine('')) return { exitCode: 0, message: '', streamed: true }; + + const offsets = new Map(); + const multiInitial = initialWorker.streams.length > 1; + for (const stream of initialWorker.streams) { + const rawStreamPath = stream.rawPath ?? stream.path; + const st = statInfo(fs, rawStreamPath); + const tail = formatLogTail(fs, rawStreamPath, tailLines, secrets); + for (const l of tail) { + if (!writeLine(multiInitial ? `[${stream.label}] ${l}` : l)) { + return { exitCode: 0, message: '', streamed: true }; + } + } + offsets.set(rawStreamPath, { offset: st?.size ?? 0, skip: false }); + } + + let lastStageSig = `${initialWorker.stageDetail}|${initialWorker.processSummary}`; + let lastBlockersSig = initialWorker.blockers.join('; '); + const pollMs = Math.max(10, Number.isFinite(ports.pollMs) ? ports.pollMs : DEFAULT_POLL_MS); + + while (!detached && !streamClosed && polls < maxPolls) { + const elapsed = now() - startMs; + if (elapsed >= maxDurationMs) { + timedOut = true; + break; + } + await waitNext(Math.min(pollMs, Math.max(1, maxDurationMs - elapsed))); + if (detached || streamClosed) break; + if ((now() - startMs) >= maxDurationMs) { + timedOut = true; + break; + } polls++; - const currentSnap = await inspectAutopilotWorkers(input, ports); + const currentSnap = await inspectAutopilotWorkers(input, pollPorts); if (!currentSnap.ok) break; const currentWorker = findTarget(currentSnap); if (!currentWorker) { @@ -1161,32 +1368,36 @@ export async function runAutopilotLogs(input = {}, ports = {}) { const stageSig = `${currentWorker.stageDetail}|${currentWorker.processSummary}`; if (stageSig !== lastStageSig) { lastStageSig = stageSig; - writeLine(`[stage] ${currentWorker.stageDetail} · ${currentWorker.processSummary}`); + if (!writeLine(`[stage] ${currentWorker.stageDetail} · ${currentWorker.processSummary}`)) break; } const blockersSig = currentWorker.blockers.join('; '); if (blockersSig !== lastBlockersSig) { lastBlockersSig = blockersSig; - if (currentWorker.blockers.length) writeLine(`[blocker] ${blockersSig}`); + if (currentWorker.blockers.length && !writeLine(`[blocker] ${blockersSig}`)) break; } const multiNow = currentWorker.streams.length > 1; for (const stream of currentWorker.streams) { - const isNewStream = !offsets.has(stream.path); + if (streamClosed || detached) break; + const rawStreamPath = stream.rawPath ?? stream.path; + const isNewStream = !offsets.has(rawStreamPath); if (isNewStream) { - offsets.set(stream.path, 0); - writeLine(`[stage] Streaming ${stream.label} log: ${stream.path}`); + offsets.set(rawStreamPath, { offset: 0, skip: false }); + if (!writeLine(`[stage] Streaming ${stream.label} log: ${stream.path}`)) break; } - const prevOffset = offsets.get(stream.path) ?? 0; - const { nextOffset, lines } = readAppendedCompleteLines(fs, stream.path, prevOffset); - offsets.set(stream.path, nextOffset); + const prevState = offsets.get(rawStreamPath) ?? { offset: 0, skip: false }; + const { nextOffset, skip, lines } = readAppendedCompleteLines(fs, rawStreamPath, prevState); + offsets.set(rawStreamPath, { offset: nextOffset, skip }); for (const raw of lines) { - const rendered = formatWorkerLogLine(raw); + const rendered = formatWorkerLogLine(raw, secrets); if (!rendered) continue; for (const line of rendered.split('\n')) { - if (line.trim()) writeLine(multiNow ? `[${stream.label}] ${line}` : line); + if (line.trim() && !writeLine(multiNow ? `[${stream.label}] ${line}` : line)) break; } + if (streamClosed || detached) break; } } + if (streamClosed || detached) break; if (!currentWorker.active) { writeLine(`[stage] ${currentWorker.stageDetail}`); @@ -1197,6 +1408,14 @@ export async function runAutopilotLogs(input = {}, ports = {}) { return { exitCode: 0, message: '', streamed: true }; } } + + if (!streamClosed && canWrite()) { + if (timedOut) { + writeLine(`[stage] Reached follow time limit; detached from issue #${initialWorker.issue} (background worker continues untouched).`); + } else if (detached) { + writeLine(`Detached from issue #${initialWorker.issue} (background worker continues untouched).`); + } + } } finally { if (signal) { try { signal.removeEventListener('abort', triggerDetach); } catch {} @@ -1204,10 +1423,11 @@ export async function runAutopilotLogs(input = {}, ports = {}) { process.removeListener('SIGINT', onSigint); process.removeListener('SIGTERM', onSigterm); } + if (typeof stdout?.removeListener === 'function') { + stdout.removeListener('close', onStdoutClose); + stdout.removeListener('error', onStdoutError); + } } - if (detached) { - writeLine(`Detached from issue #${initialWorker.issue} (background worker continues untouched).`); - } return { exitCode: 0, message: '', streamed: true }; } diff --git a/src/command-catalog.mjs b/src/command-catalog.mjs index 4f8148fb35..79f9e57b33 100644 --- a/src/command-catalog.mjs +++ b/src/command-catalog.mjs @@ -1,4 +1,4 @@ -// Generated from prompts/cli/command-catalog.prompt.md (sha256: f0b12e421937140fc52987e2607420da7388ce5d35b780dec830c98efc1aaec8). +// Generated from prompts/cli/command-catalog.prompt.md (sha256: 52daaeaf210c1bc32a37bb9536cf7226b1f32f034d3dfbce4765d63f4beec793). const form = (form, description) => Object.freeze({ form, description }); // The one place for the words of five commands; a later rename changes only NAMES. export const NAMES = Object.freeze({ test: 'test', lint: 'lint', simulate: 'simulate', run: 'run', requestUptake: 'ack' }); @@ -74,7 +74,15 @@ export const PUBLIC_HELP_TEXT = Object.freeze({ "pdd approve --help, pdd workflow --help, or pdd autopilot --help) for", "all options, defaults, approval heredocs, and execution details.", ]), - closingLines: Object.freeze(["Open Codex or Claude as usual and call a PDD skill: $pdd-feature in Codex, /pdd-feature in Claude Code (also pdd-bug, pdd-small-change, pdd-prompting).", `workflow ${run} opens the first area chat in Herdr session pdd and exits. Manual workflows follow RUNBOOK §2 and its person gates; pdd opens a real PR.`, "The CLI has no merge command. In auto mode, Autopilot merges its own pull request after CI, a fresh review and the full test suite pass; required human approvals still apply."]), + closingLines: Object.freeze([ + "Open Codex or Claude as usual and call a PDD skill: $pdd-feature in Codex,", + "/pdd-feature in Claude Code (also pdd-bug, pdd-small-change, pdd-prompting).", + `workflow ${run} opens the first area chat in Herdr session pdd and exits.`, + "Manual workflows follow RUNBOOK §2 and its person gates; pdd opens a real PR.", + "The CLI has no merge command. In auto mode, Autopilot merges its own pull", + "request after CI, a fresh review and the full test suite pass; required", + "human approvals still apply.", + ]), learnLines: Object.freeze(["Learn PDD: run pdd help prompting, or read the Prompting guide and the RUNBOOK.", "Prompting guide: PACKAGE_ROOT/docs/prompting-guide.md", "RUNBOOK: PACKAGE_ROOT/RUNBOOK.md"]), promptingLines: Object.freeze(["In PDD, prompts are the source. Code follows the prompts.", "1. Prompt: prompts/NAME.prompt.md. Write what the program does in plain English, then ## Dependencies.", "2. Story: user_stories/STORY.md. Write one thing that a person can do, then a numbered ## Acceptance criteria list.", "3. Test: tests/STORY.json. When the repo keeps its own tests in tests/ or test/, use tests/runtime/ or test/runtime/. Write steps with an exact check for each criterion.", `4. Check: run pdd ${test} --files STORY && pdd ${test} STORY in one shell call. Test includes interpreter lint (0 AI calls); use pdd ${lint} for lint-only diagnosis.`, "5. Approve: a person reads each prompt and runs pdd approve PROMPT. New behavior needs a person."]) }); @@ -247,7 +255,7 @@ const routes = [ forms: [form('pdd autopilot start [--runs N] [--checks N] [--label NAME] [--mode auto|observe|off] [--report file|draft|off] [--decisions ask|decide] [--intake off|shadow|active] [--share PERCENT] [--agent codex|claude|gemini|agy] [--auto-update release|main|off]', 'Start this repo with headless agent jobs (the core engine): check now and every 10 minutes, with no AI call on empty ticks. Autopilot works on issues with an opt-in label (--label NAME or autopilot.label in pdd.json) or on vetted ready cards when --intake active is enabled; without --intake active, a start with no label starts nothing. --runs and --checks override machine-sized run and heavy-check limits; --label, --mode and --report save this machine\'s opt-in label, mode and report mode for this repo, over pdd.json (--mode observe runs every check but never merges; --report draft, the default, keeps problem reports on this machine); --decisions saves this machine\'s decision mode (ask asks a person only for a big decision; decide, the default, never asks); --intake saves this machine\'s intake mode (shadow writes local intake cards that never change what starts; active selects ready cards, refines improve cards via read-only repo inspection and groups related small work; off is the default). --share saves the percent of this machine\'s CPU and memory that Autopilot may use (1-100, default 50; it sets the automatic slots, the room check and the timer\'s memory limit). --agent saves or replaces this machine\'s agent and sign-in profile. --auto-update saves this machine\'s between-tick self-update mode for a user-owned global pdd install and its skills when no job is publishing or merging (release is the default; main tracks promptdriven/pdd main; off disables self-update).')] }, { id: 'autopilot.status', prefix: ['autopilot', 'status'], local: 'autopilot-status', operands: [], options: [{name:'--all',kind:'flag'},{name:'--json',kind:'flag'}], forms: [form('pdd autopilot status [--all] [--json]', "Show this machine's repo, folder, agent and next tick; --all lists every repository with Autopilot on this machine, from any folder.")] }, - { id: 'autopilot.logs', prefix: ['autopilot', 'logs'], local: 'autopilot-logs', operands: [{ name: 'issue', type: 'issue', optional: true }], + { id: 'autopilot.logs', prefix: ['autopilot', 'logs'], local: 'autopilot-logs', operands: [{ name: 'issue', type: 'text', optional: true }], options: [{ name: '--issue', kind: 'text' }, { name: '--follow', kind: 'flag' }, { name: '-f', kind: 'flag' }, { name: '--lines', kind: 'integer', min: 1, max: 5000 }, { name: '--json', kind: 'flag' }], forms: [ form('pdd autopilot logs [ISSUE] [--follow|-f] [--lines N] [--json]', 'List current headless Autopilot workers with stage, owned process state, suite queue position, blockers and saved log or evidence paths, or inspect and follow one issue worker live (--follow / -f detaches cleanly on Ctrl-C without stopping the worker or changing observe mode). Read-only; no GitHub write or approval effect.'), diff --git a/src/pdd-cli.mjs b/src/pdd-cli.mjs index fa5df08f2e..e29c8fb5d6 100644 --- a/src/pdd-cli.mjs +++ b/src/pdd-cli.mjs @@ -187,21 +187,38 @@ export async function runPdd(argv, { stdout = process.stdout, stderr = process.s } catch { line(stderr, 'Regression scan failed.'); return 1; } } case 'autopilot-logs': { + const parseSelector = raw => { + const text = String(raw ?? '').trim().replace(/\/$/, ''); + const plain = /^#?([1-9][0-9]*)$/.exec(text); + if (plain) return { ok: true, issue: Number(plain[1]), repo: null }; + const qualified = /^([A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9_.-]+)#([1-9][0-9]*)$/.exec(text); + if (qualified) return { ok: true, issue: Number(qualified[2]), repo: qualified[1] }; + const url = /^https:\/\/github\.com\/([A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9_.-]+)\/issues\/([1-9][0-9]*)$/.exec(text); + if (url) return { ok: true, issue: Number(url[2]), repo: url[1] }; + return { ok: false, issue: null, repo: null }; + }; const follow = Boolean(plan.options['--follow'] || plan.options['-f']); const json = plan.options['--json'] === true; if (follow && json) { line(stderr, '--json prints one snapshot and cannot be combined with --follow.'); return 2; } - if (plan.operands[0] !== undefined && plan.options['--issue'] !== undefined && plan.operands[0] !== plan.options['--issue']) { + const posRaw = plan.operands[0], optRaw = plan.options['--issue']; + const posParsed = posRaw !== undefined ? parseSelector(posRaw) : null; + const optParsed = optRaw !== undefined ? parseSelector(optRaw) : null; + if ((posParsed && !posParsed.ok) || (optParsed && !optParsed.ok)) { + line(stderr, 'Use a valid issue number, #N, owner/repo#N or GitHub issue URL.'); return 2; + } + if (posParsed && optParsed && (posParsed.issue !== optParsed.issue + || (posParsed.repo && optParsed.repo && posParsed.repo.toLowerCase() !== optParsed.repo.toLowerCase()))) { line(stderr, 'Pass the issue once: pdd autopilot logs ISSUE or pdd autopilot logs --issue ISSUE.'); return 2; } - if (follow && plan.operands[0] === undefined && plan.options['--issue'] === undefined) { + const issue = posParsed && optParsed ? (posParsed.repo ? posRaw : optRaw) : (posRaw ?? optRaw); + if (follow && issue === undefined) { line(stderr, 'Select an issue to follow: pdd autopilot logs ISSUE --follow.'); return 2; } try { const input = { cwd, env, - ...(plan.operands[0] !== undefined ? { positionalIssue: plan.operands[0] } : {}), - ...(plan.options['--issue'] !== undefined ? { optionIssue: plan.options['--issue'] } : {}), + ...(issue !== undefined ? { issue } : {}), follow, ...(plan.options['--lines'] !== undefined ? { lines: Number(plan.options['--lines']) } : {}), json, diff --git a/test/autopilot-logs.test.mjs b/test/autopilot-logs.test.mjs index f3342dbeab..266bad855e 100644 --- a/test/autopilot-logs.test.mjs +++ b/test/autopilot-logs.test.mjs @@ -1,6 +1,7 @@ import './helpers/test-home.mjs'; import test from 'node:test'; import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; import { createHash } from 'node:crypto'; import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -77,6 +78,9 @@ test('3475: pdd autopilot logs is discoverable in help and shell completion and ['autopilot', 'logs', '-f'], ['autopilot', 'logs', '12', '--follow', '--json'], ['autopilot', 'logs', '12', '--issue', '13'], + ['autopilot', 'logs', 'acme/widgets#12', '--issue', 'other/repo#12'], + ['autopilot', 'logs', 'not-an-issue'], + ['autopilot', 'logs', '--issue', 'not-an-issue'], ['autopilot', 'logs', '--lines', '0'], ]) { const stdout = sink(), stderr = sink(); @@ -86,11 +90,37 @@ test('3475: pdd autopilot logs is discoverable in help and shell completion and assert.ok(stderr.text.trim().length > 0); } + // CLI passes { issue } contract and accepts "#42", "owner/repo#42", and matching positional + --issue + const capturedInputs = []; + for (const argv of [ + ['autopilot', 'logs', '#42'], + ['autopilot', 'logs', 'acme/widgets#42'], + ['autopilot', 'logs', '#42', '--issue', '42'], + ]) { + const stdout = sink(), stderr = sink(); + const code = await runPdd(argv, { + stdout, + stderr, + cwd: '/tmp/repo', + autopilotLogs: { + runAutopilotLogs: async input => { + capturedInputs.push(input); + return { exitCode: 0, message: `ok ${input.issue}` }; + }, + }, + }); + assert.equal(code, 0, `${argv.join(' ')}: ${stderr.text}`); + } + assert.equal(capturedInputs[0].issue, '#42'); + assert.equal(capturedInputs[1].issue, 'acme/widgets#42'); + assert.equal(capturedInputs[2].issue, '42'); + assert.equal('positionalIssue' in capturedInputs[0], false); + const unknownSub = await runAutopilotSubcommand('unknown', {}); assert.equal(unknownSub.exitCode, 2); }); -test('3475: outside a Git repository pdd autopilot logs exits 1 with clear guidance', async () => { +test('3475: outside a Git repository pdd autopilot logs exits 1 with exact docs/cli.md guidance', async () => { const stdout = sink(), stderr = sink(); const code = await runPdd(['autopilot', 'logs'], { stdout, @@ -102,7 +132,10 @@ test('3475: outside a Git repository pdd autopilot logs exits 1 with clear guida }); assert.equal(code, 1); assert.equal(stdout.text, ''); - assert.match(stderr.text, /This folder is not a Git repository/); + assert.equal( + stderr.text.trim(), + 'This folder is not a Git repository. cd into the repo you want Autopilot to work on, then run the command again.', + ); }); test('3475: formatWorkerLogLine renders Codex, Claude, Gemini/agy JSONL and redacts secrets & ANSI codes', () => { @@ -310,19 +343,24 @@ test('3475: distinguishes queued suite, live running suite, repair worker, and s assert.match(listOut.text, /Recent finished workers[\s\S]*?#99 \(PR #199\): ready-observe/); assert.match(listOut.text, /Follow a worker live: pdd autopilot logs 101 --follow/); - // 2. Selected worker view via --issue N (`pdd autopilot logs --issue 102 --lines 5`) - const issueOut = sink(), issueErr = sink(); - const issueCode = await runPdd(['autopilot', 'logs', '--issue', '102', '--lines', '5'], { - stdout: issueOut, - stderr: issueErr, - cwd: sb.gitRoot, - autopilotLogsPorts: ports, - }); - assert.equal(issueCode, 0, issueErr.text); - assert.match(issueOut.text, /Stage: PR #211 \(cccc3333\): running full test suite \(pid 5202\) \[pass 2, fail 0\]/); - assert.match(issueOut.text, new RegExp(ev102.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))); - assert.match(issueOut.text, /ok 1 - first suite case/); - assert.match(issueOut.text, /ok 2 - second suite case/); + // 2. Selected worker view via "#102" (`pdd autopilot logs "#102" --lines 5`) and --issue 102 + for (const argv of [ + ['autopilot', 'logs', '#102', '--lines', '5'], + ['autopilot', 'logs', '--issue', '102', '--lines', '5'], + ]) { + const issueOut = sink(), issueErr = sink(); + const issueCode = await runPdd(argv, { + stdout: issueOut, + stderr: issueErr, + cwd: sb.gitRoot, + autopilotLogsPorts: ports, + }); + assert.equal(issueCode, 0, issueErr.text); + assert.match(issueOut.text, /Stage: PR #211 \(cccc3333\): running full test suite \(pid 5202\) \[pass 2, fail 0\]/); + assert.match(issueOut.text, new RegExp(ev102.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))); + assert.match(issueOut.text, /ok 1 - first suite case/); + assert.match(issueOut.text, /ok 2 - second suite case/); + } // 3. JSON snapshot (`pdd autopilot logs 101 --json`) const jsonOut = sink(), jsonErr = sink(); @@ -448,3 +486,283 @@ test('3475: --follow streams live updates across stage transitions and detaches assert.equal(postSnap.workers[0].issue, 77); assert.equal(postSnap.workers[0].liveProcess, true); }); + +test('3475: enforces pid > 1 and treats EPERM / non-owned PIDs as not running in default liveness check', async t => { + const sb = makeSandbox(t, { mode: 'observe' }); + const nowMs = Date.parse('2026-11-17T21:00:00Z'); + const logFile = join(sb.coreRoot, 'logs', '51-build-1.log'); + writeFileSync(logFile, 'Starting step\n'); + + // Job #51 has pid: 1 (system init/launchd — EPERM if probed) and suite childPid: 1 + writeFileSync(join(sb.coreRoot, 'jobs', '51.json'), JSON.stringify({ + issue: 51, + title: 'Reject pid 1 and invalid pids', + phase: 'pr', + pr: 88, + head: 'abcd1234', + agent: { pid: 1, log: logFile, started: nowMs - 5000 }, + review: { agent: { pid: 0, log: logFile, started: nowMs - 5000 } }, + vectors: { agent: { pid: -9, log: logFile, started: nowMs - 5000 } }, + suite: { cwd: sb.gitRoot, head: 'abcd1234', agent: { pid: 1, log: logFile } }, + })); + + // Omit isProcessAlive so real defaultIsProcessAlive runs! + const snap = await inspectAutopilotWorkers({ cwd: sb.gitRoot }, { + git: sb.git, + stateRoot: sb.stateRoot, + now: () => nowMs, + readSuite: () => ({ + ok: true, + state: 'running', + childPid: 1, + counts: { pass: 1, fail: 0 }, + logPath: logFile, + }), + }); + + assert.equal(snap.ok, true); + const worker = snap.workers.find(w => w.issue === 51); + assert.ok(worker); + assert.equal(worker.suite.childPid, null, 'childPid 1 must be rejected'); + assert.doesNotMatch(worker.suite.detail, /pid 1\b/); + assert.equal(worker.liveProcess, false, 'pid 1 must never be treated as a live worker'); + assert.equal(worker.processState, 'idle'); +}); + +test('3475: redacts input.env secrets and strips ANSI across --json, state/path fields, and long tail/follow lines without mid-line slicing', async t => { + const sb = makeSandbox(t, { mode: 'observe' }); + const nowMs = Date.parse('2026-11-17T21:10:00Z'); + const envSecret = 'custom-env-secret-value-998877'; + const inputEnv = { ...process.env, MY_WORKER_SECRET_TOKEN: envSecret }; + + // Put secret and ANSI codes in launcherState, machineState, worker metadata, and file path! + writeFileSync(join(sb.stateRoot, `${sb.stateId}.json`), JSON.stringify({ + repo: `acme/\x1b[31mwidgets-${envSecret}\x1b[0m`, + root: sb.gitRoot, + enabled: true, + mode: 'observe', + })); + writeFileSync(join(sb.coreRoot, 'core.json'), JSON.stringify({ + poolOut: { wakeAt: `2026-11-17T22:00:00Z-${envSecret}\x1b[33m` }, + })); + + const secretDir = join(sb.base, `dir-${envSecret}`); + mkdirSync(secretDir, { recursive: true }); + const longLogPath = join(secretDir, '60-build.log'); + const receiptPath = join(secretDir, '60-receipt.json'); + writeFileSync(receiptPath, '{"ok":true}\n'); + + // Create a 110 KiB single-line log ending in '\n' (exceeds initial 64 KiB readSize) + // with secret near the front and multi-byte UTF-8 characters throughout, to prove + // formatLogTail expands its window rather than dropping trailing-'\n' tails or slicing mid-line! + const utf8Pad = '🚀日本語テスト'.repeat(6500); // ~117 KiB of multi-byte UTF-8 + const singleLongLine = `${envSecret} start-marker ${utf8Pad} end-marker\n`; + writeFileSync(longLogPath, singleLongLine); + + const exitPath = join(sb.coreRoot, 'logs', '60.exit.json'); + writeFileSync(exitPath, JSON.stringify({ + code: null, + signal: `SIGTERM-${envSecret}\x1b[0m`, + at: nowMs - 1000, + })); + + writeFileSync(join(sb.coreRoot, 'jobs', '60.json'), JSON.stringify({ + issue: 60, + title: `Fix auth ${envSecret}`, + phase: 'pr', + pr: 310, + head: `${envSecret}abcdef`, + lane: { state: 'waiting', holder: `99-${envSecret}` }, + review: { verdict: `FAIL-${envSecret}`, agent: { pid: 6002, exit: exitPath, agentKind: `codex-${envSecret}` } }, + stepStop: { poolExhausted: true, wakeAt: `soon-${envSecret}` }, + lastError: `Auth failed with ${envSecret}`, + agent: { pid: 6001, agentKind: `codex-${envSecret}\x1b[35m`, log: longLogPath, started: nowMs - 5000 }, + suite: { cwd: sb.gitRoot, head: 'abcdef12' }, + })); + + const ports = { + git: sb.git, + stateRoot: sb.stateRoot, + now: () => nowMs, + isProcessAlive: pid => pid === 6001, + readSuite: () => ({ + ok: true, + state: 'waiting', + position: 1, + logPath: longLogPath, + receiptPath, + }), + }; + + // Check list --json, issue --json, and human snapshot: zero leaks of envSecret or ANSI! + for (const argv of [ + ['autopilot', 'logs', '--json'], + ['autopilot', 'logs', '60', '--json'], + ['autopilot', 'logs', '60', '--lines', '5'], + ]) { + const stdout = sink(), stderr = sink(); + const code = await runPdd(argv, { + stdout, + stderr, + cwd: sb.gitRoot, + env: inputEnv, + autopilotLogsPorts: ports, + }); + assert.equal(code, 0, `${argv.join(' ')}: ${stderr.text}`); + assert.equal(stdout.text.includes(envSecret), false, `leaked env secret in ${argv.join(' ')}:\n${stdout.text}`); + assert.doesNotMatch(stdout.text, /\x1b\[/, `leaked ANSI in ${argv.join(' ')}`); + assert.equal(stdout.text.includes('\ufffd'), false, `corrupted UTF-8 in ${argv.join(' ')}`); + } + + // Verify the single 117 KiB line ending in '\n' was NOT dropped by formatLogTail! + const issueJsonOut = sink(); + await runPdd(['autopilot', 'logs', '60', '--json'], { + stdout: issueJsonOut, + stderr: sink(), + cwd: sb.gitRoot, + env: inputEnv, + autopilotLogsPorts: ports, + }); + const issuePayload = JSON.parse(issueJsonOut.text); + assert.equal(issuePayload.lines.length, 1, 'single long line ending in EOF newline must not be dropped'); + assert.match(issuePayload.lines[0], /\[redacted\] start-marker 🚀日本語テスト/); + + // Also test readAppendedCompleteLines in --follow when a > 550 KiB line (> READ_CHUNK_LIMIT) is appended! + const followLog = join(sb.coreRoot, 'logs', '61-build.log'); + writeFileSync(followLog, 'initial line\n'); + writeFileSync(join(sb.coreRoot, 'jobs', '61.json'), JSON.stringify({ + issue: 61, + title: 'Large follow line', + role: 'build', + agent: { pid: 6101, log: followLog, started: nowMs - 2000 }, + })); + + const abort = new AbortController(); + let followTick = 0; + const followOut = sink(); + // Place envSecret right across the 512 KiB byte boundary inside a ~542 KiB line! + const prefixBytes = '🚀'.repeat(Math.floor((512 * 1024 - 12) / 4)); + const hugeAppendedLine = `big-line ${prefixBytes}${envSecret}-${'x'.repeat(30 * 1024)}-tail-ok\n`; + assert.ok(Buffer.byteLength(hugeAppendedLine, 'utf8') > 530 * 1024); + + const followCode = await runPdd(['autopilot', 'logs', '61', '--follow'], { + stdout: followOut, + stderr: sink(), + cwd: sb.gitRoot, + env: inputEnv, + autopilotLogsPorts: { + git: sb.git, + stateRoot: sb.stateRoot, + now: () => nowMs, + isProcessAlive: pid => pid === 6101, + signal: abort.signal, + pollMs: 10, + sleep: async () => { + followTick++; + if (followTick === 1) { + writeFileSync(followLog, readFileSync(followLog, 'utf8') + hugeAppendedLine); + } else { + abort.abort(); + } + }, + }, + }); + assert.equal(followCode, 0); + assert.equal(followOut.text.includes(envSecret), false, 'secret straddling 512 KiB boundary must be redacted'); + assert.equal(followOut.text.includes('\ufffd'), false, 'multi-byte UTF-8 straddling 512 KiB boundary must not corrupt'); + assert.match(followOut.text, /big-line 🚀/); +}); + +test('3475: --follow handles stdout EPIPE cleanly, reuses gitRoot across polls, and enforces maxDurationMs', async t => { + const sb = makeSandbox(t, { mode: 'observe' }); + let nowMs = Date.parse('2026-11-17T21:20:00Z'); + const logFile = join(sb.coreRoot, 'logs', '88-build.log'); + writeFileSync(logFile, 'line 1\nline 2\nline 3\n'); + writeFileSync(join(sb.coreRoot, 'jobs', '88.json'), JSON.stringify({ + issue: 88, + title: 'Pipe and maxDuration safety', + role: 'build', + agent: { pid: 8801, log: logFile, started: nowMs - 2000 }, + })); + + // 1. Simulate `pdd autopilot logs 88 --follow | head -n 5`: stdout emits EPIPE after 5 writes + class BrokenPipeStdout extends EventEmitter { + constructor(limit) { + super(); + this.limit = limit; + this.lines = []; + this.destroyed = false; + this.writableEnded = false; + } + write(chunk) { + if (this.destroyed) { + const err = new Error('write EPIPE'); + err.code = 'EPIPE'; + throw err; + } + this.lines.push(String(chunk)); + if (this.lines.length >= this.limit) { + this.destroyed = true; + const err = new Error('write EPIPE'); + err.code = 'EPIPE'; + this.emit('error', err); + this.emit('close'); + } + return true; + } + } + + const pipeStdout = new BrokenPipeStdout(5); + let gitCalls = 0; + let sleepCalls = 0; + const pipeCode = await runPdd(['autopilot', 'logs', '#88', '--follow'], { + stdout: pipeStdout, + stderr: sink(), + cwd: sb.gitRoot, + autopilotLogsPorts: { + git: async (args, opts) => { + gitCalls++; + return sb.git(args, opts); + }, + stateRoot: sb.stateRoot, + now: () => nowMs, + isProcessAlive: () => true, + pollMs: 10, + sleep: async () => { sleepCalls++; }, + }, + }); + assert.equal(pipeCode, 0, 'broken pipe must exit 0 cleanly'); + assert.equal(pipeStdout.lines.length, 5, 'must stop writing immediately once pipe closes'); + assert.equal(sleepCalls, 0, 'must not enter or leak polling loop after pipe closes'); + assert.equal(pipeStdout.listenerCount('close'), 0, 'must clean up close listener'); + assert.equal(pipeStdout.listenerCount('error'), 0, 'must clean up error listener'); + + // 2. Verify git rev-parse is called ONCE and reused across polls, and maxDurationMs stops follow cleanly + gitCalls = 0; + let pollCount = 0; + const boundedOut = sink(); + const boundedCode = await runPdd(['autopilot', 'logs', '88', '--follow'], { + stdout: boundedOut, + stderr: sink(), + cwd: sb.gitRoot, + autopilotLogsPorts: { + git: async (args, opts) => { + gitCalls++; + return sb.git(args, opts); + }, + stateRoot: sb.stateRoot, + now: () => nowMs, + isProcessAlive: () => true, + pollMs: 10, + maxDurationMs: 2500, + sleep: async () => { + pollCount++; + nowMs += 1000; + }, + }, + }); + assert.equal(boundedCode, 0); + assert.equal(gitCalls, 1, 'git rev-parse must run only once and reuse gitRoot on polls'); + assert.equal(pollCount, 3, 'maxDurationMs must bound unattended polling'); + assert.match(boundedOut.text, /Reached follow time limit; detached from issue #88/); +}); diff --git a/test/grouped-help.test.mjs b/test/grouped-help.test.mjs index 99bb12d35a..13ab5ad328 100644 --- a/test/grouped-help.test.mjs +++ b/test/grouped-help.test.mjs @@ -55,16 +55,12 @@ test('3496: root help is concise, grouped human-first, 80-column wrapped in its assert.doesNotMatch(baseline, /<<'PDD_SAID'/); assert.doesNotMatch(baseline, /removed full engine/i); - // Every line in usageLine, quickStartLines, groups, and focusedHelpLines fits in 80 columns - const wrappedLines = [ - PUBLIC_HELP_TEXT.usageLine, - 'Quick start:', - ...PUBLIC_HELP_TEXT.quickStartLines, - ...PUBLIC_HELP_TEXT.groups.flatMap(g => [`${g.title}:`, ...g.lines]), - ...PUBLIC_HELP_TEXT.focusedHelpLines, - ]; - for (const line of wrappedLines) { - assert.ok(line.length <= 80, `line exceeds 80 columns (${line.length}): "${line}"`); + // Every single line of root `pdd --help` (including heading, groups, learnLines, and closingLines) fits in <= 80 columns + for (const line of allLines) { + assert.ok(line.length <= 80, `root help line exceeds 80 columns (${line.length}): "${line}"`); + } + for (const line of PUBLIC_HELP_TEXT.closingLines) { + assert.ok(line.length <= 80, `closingLine exceeds 80 columns (${line.length}): "${line}"`); } // Preserves Focused help guidance and installed Prompting guide / RUNBOOK paths diff --git a/test/help-teaches-pdd.test.mjs b/test/help-teaches-pdd.test.mjs index db2f3218df..fef1d18165 100644 --- a/test/help-teaches-pdd.test.mjs +++ b/test/help-teaches-pdd.test.mjs @@ -115,10 +115,10 @@ test('root help keeps its first line, grouped commands, learn paths and closing for (const output of outputs) assert.equal(output.stdout, outputs[0].stdout); const rootHelp = lines(outputs[0].stdout), scoped = lines((await pdd(['test', '--help'])).stdout); const testRows = PUBLIC_COMMAND_MANIFEST.filter(({ form }) => form.split(' ')[1] === 'test').map(formLine); - // Command help: first line, empty line, its own forms, empty line and the three closing lines; no learn or path lines. + // Command help: first line, empty line, its own forms, empty line and closingLines; no learn or path lines. assert.equal(scoped[1], ''); assert.deepEqual(scoped.slice(2, 2 + testRows.length), testRows); assert.equal(scoped[2 + testRows.length], ''); const closing = scoped.slice(3 + testRows.length); - assert.equal(closing.length, 3); + assert.deepEqual(closing, PUBLIC_HELP_TEXT.closingLines); assert.doesNotMatch(scoped.join('\n'), /help prompting|prompting-guide\.md|RUNBOOK\.md/); // Root help: the same first line, usage, quick start, grouped summaries, focused help note, learn/path lines, and closing lines. const expectedBody = [ diff --git a/test/setup.test.mjs b/test/setup.test.mjs index 68b2e6b705..f7aa02028c 100644 --- a/test/setup.test.mjs +++ b/test/setup.test.mjs @@ -99,7 +99,10 @@ test('SETUP5: pdd help says how to call a PDD skill in Codex and in Claude Code' // --help writes nothing to HOME, so the real environment is safe here. const help = spawnSync(process.execPath, [join(root, 'bin/pdd.mjs'), '--help'], { encoding: 'utf8' }); assert.equal(help.status, 0, help.stderr); - assert.ok(help.stdout.includes('Open Codex or Claude as usual and call a PDD skill: $pdd-feature in Codex, /pdd-feature in Claude Code (also pdd-bug, pdd-small-change, pdd-prompting).'), help.stdout); + assert.ok( + help.stdout.includes('Open Codex or Claude as usual and call a PDD skill: $pdd-feature in Codex,\n/pdd-feature in Claude Code (also pdd-bug, pdd-small-change, pdd-prompting).'), + help.stdout, + ); }); // Wrong: setup leaves .pdd/ (the pdd test cache) open to a commit, adds the line twice, or loses the person's ignore rules. From ed651a58ed4d760779a691e796384b2c99bfc73a Mon Sep 17 00:00:00 2001 From: Serhan Asad Date: Tue, 17 Nov 2026 14:22:35 -0800 Subject: [PATCH 3/4] fix(test): align interpreter-version root --help check with grouped summary (#3496) --- test/interpreter-version.test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/interpreter-version.test.mjs b/test/interpreter-version.test.mjs index 77a1afe78f..14b0c0da42 100644 --- a/test/interpreter-version.test.mjs +++ b/test/interpreter-version.test.mjs @@ -126,7 +126,7 @@ test('real help, ordinary versions, invalid syntax and invalid origin never read } for (const args of [['-VV', '--help'], ['help', '-VV'], ['-V', '--help'], ['--help']]) { const result = await f.run(args, { PDD_RUNTIME_URL: s.origin }); assert.equal(result.code, 0); - assert.match(result.stdout, args[0] === '-V' ? /pdd --version/ : /pdd -VV/); + assert.match(result.stdout, args[0] === '-V' ? /pdd --version/ : args[0] === '--help' ? /pdd --version \| -V \| -VV/ : /pdd -VV/); } for (const args of [['-VV', 'extra'], ['-V', '-V'], ['-VVV'], ['--version', '--verbose'], ['--version', '-VV'], ['-VV', '--help', 'extra']]) { const result = await f.run(args, { PDD_RUNTIME_URL: s.origin }); assert.equal(result.code, 2); assert.equal(result.stdout, ''); From 780728f1af7d8848959900a88c8008a27da80802 Mon Sep 17 00:00:00 2001 From: Serhan Asad Date: Tue, 17 Nov 2026 14:35:56 -0800 Subject: [PATCH 4/4] fix(cli): address round-2 review findings on help summary, prompt DAG, and log sanitization (#3496, #3475) --- prompts/cli/autopilot-logs.prompt.md | 22 +++++-- prompts/cli/command-catalog.prompt.md | 2 +- src/autopilot-logs.mjs | 69 +++++++++++++--------- src/command-catalog.mjs | 4 +- test/autopilot-logs.test.mjs | 85 +++++++++++++++++++++++++++ test/grouped-help.test.mjs | 1 + test/interpreter-version.test.mjs | 2 +- 7 files changed, 146 insertions(+), 39 deletions(-) diff --git a/prompts/cli/autopilot-logs.prompt.md b/prompts/cli/autopilot-logs.prompt.md index d3af7b9f92..dc7c3331a7 100644 --- a/prompts/cli/autopilot-logs.prompt.md +++ b/prompts/cli/autopilot-logs.prompt.md @@ -20,13 +20,18 @@ terminal without knowing internal state folders or touching running jobs. (both `ESRCH` and `EPERM`) returns `false` so system init (`pid 1`) or another user's process is never reported as a running Autopilot worker; when a job token is present, `ps` command output must also include that token. -- **End-to-end secret redaction and line-aligned UTF-8 reads**: +- **End-to-end secret redaction, numeric coercion, and line-aligned UTF-8 reads**: Derive caller secrets with `knownSecretValues(env)` (including injected - `input.env`), strip ANSI/control characters, and run `redactSecrets(..., secrets)` + `input.env`), strip ANSI and control characters (`CTRL_RE`, including before + JSONL parsing in `formatWorkerLogLine`), and run `redactSecrets(..., secrets)` across human snapshots, `--follow` streams, and `--json` payloads — covering log lines, worker metadata (`agentKind`, `signal`, `wakeAt`, `holder`, `verdict`, `head`, `repo`, `gitRoot`) and file path strings (`logPaths`, `evidencePaths`, `streams[].path`, `suite.logPath`, `suite.receiptPath`). + Coerce `turn.completed` token counters (`input_tokens`, `output_tokens`) and + exit codes individually to finite numbers and guard every epoch timestamp with + `Number.isFinite(ts) && Math.abs(ts) <= 8.64e15` before `new Date(ts).toISOString()` + so malformed JSON fields never leak raw strings or throw `RangeError`. Align tail and incremental follow reads on `\n` (`0x0a`) byte boundaries (expanding read windows up to 16 MiB and ignoring a trailing EOF newline when locating the start of the tail window) so multi-byte UTF-8 codepoints and @@ -173,9 +178,14 @@ waiting or stale state: ## Dependencies -- [Autopilot core](autopilot-core.prompt.md): required context for `jobs/N.json`, - `core.json`, `logs/` and `history.jsonl` state shapes. -- [Shared full-suite queue](test-suite-queue.prompt.md): required context for - read-only `readSuiteProgress` queue and validation-log inspection. - [Secret redaction](secret-redaction.prompt.md): required for redacting displayed log lines, JSON payloads, metadata and path summaries. + +## Caller navigation + +[Repository Autopilot settings](autopilot.prompt.md) and the +[CLI](pdd-cli.prompt.md) route `pdd autopilot logs` here; +[Autopilot core](autopilot-core.prompt.md) owns the `jobs/N.json`, `core.json`, +`logs/` and `history.jsonl` files that this viewer reads, and +[Shared full-suite queue](test-suite-queue.prompt.md) supplies the read-only +`readSuiteProgress` queue and validation-log view. diff --git a/prompts/cli/command-catalog.prompt.md b/prompts/cli/command-catalog.prompt.md index e17a2a12c6..2d7cc677c6 100644 --- a/prompts/cli/command-catalog.prompt.md +++ b/prompts/cli/command-catalog.prompt.md @@ -221,7 +221,7 @@ The `help` route owns the forms `pdd`, `pdd --help`, `pdd -h`, `pdd help` and `p ## Help text -Export the frozen `PUBLIC_HELP_TEXT` object with `heading`, `usageLine`, `quickStartLines`, `groups`, `focusedHelpLines`, `closingLines`, `learnLines` and `promptingLines`. The heading is exactly `PDD: prompt-driven development for your coding agent.` `groups` is a frozen array of `{title, lines}` objects for the five command groups (`Core PDD workflow`, `Cloud accounts (pdd accounts --help)`, `Workflows & product (pdd workflow --help, pdd product --help)`, `Autopilot (pdd autopilot --help)`, and `Metrics, shell & help (pdd metrics --help)`), where each line begins with two spaces and `pdd ` and stays within 80 columns. Keep `PACKAGE_ROOT` as a template marker in `learnLines`; the CLI substitutes its absolute package root. The topic uses the last two learn lines after its prompting lines. This catalog owns every help text template; the dispatcher owns composition and path substitution. +Export the frozen `PUBLIC_HELP_TEXT` object with `heading`, `usageLine`, `quickStartLines`, `groups`, `focusedHelpLines`, `closingLines`, `learnLines` and `promptingLines`. The heading is exactly `PDD: prompt-driven development for your coding agent.` `groups` is a frozen array of `{title, lines}` objects for the five command groups (`Core PDD workflow`, `Cloud accounts (pdd accounts --help)`, `Workflows & product (pdd workflow --help, pdd product --help)`, `Autopilot (pdd autopilot --help)`, and `Metrics, shell & help (pdd metrics --help)`), where each line begins with two spaces and `pdd ` and stays within 80 columns (including `" pdd --version | -V | pdd -VV Show CLI version (and interpreter build)."` in `Metrics, shell & help` so root help names both `pdd --version` and `pdd -VV`). Keep `PACKAGE_ROOT` as a template marker in `learnLines`; the CLI substitutes its absolute package root. The topic uses the last two learn lines after its prompting lines. This catalog owns every help text template; the dispatcher owns composition and path substitution. The closing lines are wrapped to at most 80 columns and are exactly: diff --git a/src/autopilot-logs.mjs b/src/autopilot-logs.mjs index fdd14daaee..2474b221e2 100644 --- a/src/autopilot-logs.mjs +++ b/src/autopilot-logs.mjs @@ -1,4 +1,4 @@ -// Generated from prompts/cli/autopilot-logs.prompt.md (sha256: a237e3bf4be79bee24287f40095e81635eea35f44573885143660dc29ba5056d). +// Generated from prompts/cli/autopilot-logs.prompt.md (sha256: 85feb34d06c1be3f4f34af79c1a95b27bc23db5d24d2c6b57416a07bc50ee035). import * as nativeFs from 'node:fs'; import { homedir } from 'node:os'; import { basename, join } from 'node:path'; @@ -18,10 +18,14 @@ const DEFAULT_MAX_DURATION_MS = 60 * 60 * 1000; const MAX_CMD_PREVIEW_LINES = 6; const READ_CHUNK_LIMIT = 512 * 1024; const MAX_LINE_WINDOW_BYTES = 16 * 1024 * 1024; +const MAX_DATE_MS = 8.64e15; const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value); const named = value => typeof value === 'string' && value.trim().length > 0; const validPid = value => Number.isSafeInteger(value) && value > 1; +const validEpochMs = ts => typeof ts === 'number' && Number.isFinite(ts) && Math.abs(ts) <= MAX_DATE_MS; +const validPositiveEpochMs = ts => validEpochMs(ts) && ts > 0; +const safeIsoTimestamp = ts => validEpochMs(ts) ? new Date(ts).toISOString() : null; function resolveSecrets(secretsInput) { if (Array.isArray(secretsInput)) return knownSecretValues(process.env, secretsInput); @@ -68,7 +72,7 @@ function shortSha(sha, secrets = []) { } function formatAge(nowMs, atMs) { - if (!Number.isFinite(atMs) || atMs <= 0) return 'unknown'; + if (!validPositiveEpochMs(atMs)) return 'unknown'; const diffSec = Math.max(0, Math.round((nowMs - atMs) / 1000)); if (diffSec < 60) return `${diffSec}s ago`; const diffMin = Math.floor(diffSec / 60); @@ -79,7 +83,7 @@ function formatAge(nowMs, atMs) { } function formatStamp(nowMs, atMs) { - if (!Number.isFinite(atMs) || atMs <= 0) return 'unknown'; + if (!validPositiveEpochMs(atMs)) return 'unknown'; return `${formatAge(nowMs, atMs)} (${new Date(atMs).toISOString()})`; } @@ -172,7 +176,7 @@ function previewCommandOutput(output, secrets = []) { export function formatWorkerLogLine(rawLine, secretsInput = []) { if (typeof rawLine !== 'string') return ''; const secrets = resolveSecrets(secretsInput); - const stripped = rawLine.replace(ANSI_RE, '').replace(/\r/g, ''); + const stripped = rawLine.replace(ANSI_RE, '').replace(/\r/g, '').replace(CTRL_RE, ''); const trimmed = stripped.trim(); if (!trimmed) return ''; if (!trimmed.startsWith('{') || !trimmed.endsWith('}')) { @@ -194,9 +198,12 @@ export function formatWorkerLogLine(rawLine, secretsInput = []) { if (event.type === 'turn.started' || event.type === 'message_start') return ''; if (event.type === 'turn.completed') { const u = isObject(event.usage) ? event.usage : null; - return u && (Number.isFinite(u.input_tokens) || Number.isFinite(u.output_tokens)) - ? `[turn] completed (in ${u.input_tokens ?? 0}, out ${u.output_tokens ?? 0} tokens)` - : '[turn] completed'; + if (u && (Number.isFinite(u.input_tokens) || Number.isFinite(u.output_tokens))) { + const inTok = Number.isFinite(u.input_tokens) ? u.input_tokens : 0; + const outTok = Number.isFinite(u.output_tokens) ? u.output_tokens : 0; + return `[turn] completed (in ${inTok}, out ${outTok} tokens)`; + } + return '[turn] completed'; } if (event.type === 'turn.failed' || event.type === 'error') { const msg = event.error?.message ?? event.message ?? JSON.stringify(event); @@ -369,6 +376,7 @@ function inspectPart(part, role, { fs, isProcessAlive, secrets }) { const safeRole = oneLine(role, 40, secrets) || 'worker'; const safeAgentKind = named(part.agentKind) ? oneLine(part.agentKind, 60, secrets) : null; const safeExitSignal = hasExit && named(exitRecord.signal) ? oneLine(exitRecord.signal, 40, secrets) : null; + const safeExitCode = hasExit && Number.isSafeInteger(exitRecord.code) ? exitRecord.code : null; let state = 'idle'; let summary = `${safeRole}: idle`; @@ -377,7 +385,7 @@ function inspectPart(part, role, { fs, isProcessAlive, secrets }) { summary = `${safeRole}: running (pid ${pid}${safeAgentKind ? `, ${safeAgentKind}` : ''})`; } else if (hasExit) { state = 'exited'; - const why = safeExitSignal ? `signal ${safeExitSignal}` : `code ${exitRecord.code ?? 'null'}`; + const why = safeExitSignal ? `signal ${safeExitSignal}` : `code ${safeExitCode ?? 'null'}`; summary = `${safeRole}: exited (${why})`; } else if (pid !== null) { state = 'stale'; @@ -386,10 +394,10 @@ function inspectPart(part, role, { fs, isProcessAlive, secrets }) { const activityCandidates = [ logStat?.mtimeMs, - hasExit ? exitRecord.at : null, - Number.isFinite(part.watch?.at) ? part.watch.at : null, - Number.isFinite(part.started) ? part.started : null, - ].filter(n => Number.isFinite(n) && n > 0); + hasExit && validPositiveEpochMs(exitRecord.at) ? exitRecord.at : null, + validPositiveEpochMs(part.watch?.at) ? part.watch.at : null, + validPositiveEpochMs(part.started) ? part.started : null, + ].filter(validPositiveEpochMs); return { role: safeRole, @@ -400,10 +408,10 @@ function inspectPart(part, role, { fs, isProcessAlive, secrets }) { rawLogPath: typeof part.log === 'string' ? part.log : null, logPath: typeof part.log === 'string' ? sanitizeString(part.log, secrets) : null, logSize: logStat?.size ?? 0, - exit: hasExit ? { code: exitRecord.code, signal: safeExitSignal, at: exitRecord.at } : null, + exit: hasExit ? { code: safeExitCode, signal: safeExitSignal, at: validPositiveEpochMs(exitRecord.at) ? exitRecord.at : null } : null, hangCount: hangs.length, lastHang: hangs.at(-1) ?? null, - startedAt: Number.isFinite(part.started) ? part.started : null, + startedAt: validPositiveEpochMs(part.started) ? part.started : null, lastActivityAt: activityCandidates.length ? Math.max(...activityCandidates) : null, }; } @@ -454,6 +462,7 @@ function classifySuite(job, coreRoot, { fs, env, readSuite, secrets }) { lastActivityAt: null, }); } + const validSuiteStamp = ts => validPositiveEpochMs(ts) ? ts : null; if (deadRunner || (progress.state === 'finished' && headMismatch)) { const why = deadRunner ? oneLine(progress.reason, 140, secrets) @@ -465,7 +474,7 @@ function classifySuite(job, coreRoot, { fs, env, readSuite, secrets }) { childPid: null, logPath: safeLogPath, receiptPath: safeReceiptPath, - lastActivityAt: logStat?.mtimeMs ?? progress.finishedAt ?? progress.queuedAt ?? null, + lastActivityAt: logStat?.mtimeMs ?? validSuiteStamp(progress.finishedAt) ?? validSuiteStamp(progress.queuedAt) ?? null, }); } if (progress.state === 'waiting') { @@ -477,7 +486,7 @@ function classifySuite(job, coreRoot, { fs, env, readSuite, secrets }) { childPid: null, logPath: safeLogPath, receiptPath: safeReceiptPath, - lastActivityAt: progress.queuedAt ?? logStat?.mtimeMs ?? null, + lastActivityAt: validSuiteStamp(progress.queuedAt) ?? logStat?.mtimeMs ?? null, }); } if (progress.state === 'running') { @@ -495,7 +504,7 @@ function classifySuite(job, coreRoot, { fs, env, readSuite, secrets }) { childPid, logPath: safeLogPath, receiptPath: safeReceiptPath, - lastActivityAt: logStat?.mtimeMs ?? progress.startedAt ?? null, + lastActivityAt: logStat?.mtimeMs ?? validSuiteStamp(progress.startedAt) ?? null, }); } return attachRawPaths({ @@ -505,7 +514,7 @@ function classifySuite(job, coreRoot, { fs, env, readSuite, secrets }) { childPid: null, logPath: safeLogPath, receiptPath: safeReceiptPath, - lastActivityAt: progress.finishedAt ?? logStat?.mtimeMs ?? null, + lastActivityAt: validSuiteStamp(progress.finishedAt) ?? logStat?.mtimeMs ?? null, }); } @@ -537,18 +546,18 @@ function collectIssueArtifacts(fs, logsDir, issue, secrets = []) { function readMachineBlockers(machine, state, nowMs, secrets = []) { const blockers = []; - if (Number.isFinite(machine?.pausedUntil) && machine.pausedUntil > nowMs) { + if (validEpochMs(machine?.pausedUntil) && machine.pausedUntil > nowMs) { const streak = Number.isSafeInteger(machine.streak) ? machine.streak : 0; - blockers.push(`New jobs paused until ${new Date(machine.pausedUntil).toISOString()} (${streak} no-result runs in a row)`); + blockers.push(`New jobs paused until ${safeIsoTimestamp(machine.pausedUntil)} (${streak} no-result runs in a row)`); } if (isObject(machine?.poolOut)) { const until = named(machine.poolOut.wakeAt) ? oneLine(machine.poolOut.wakeAt, 80, secrets) - : (Number.isFinite(machine.poolOut.resetAt) ? new Date(machine.poolOut.resetAt).toISOString() : null); + : safeIsoTimestamp(machine.poolOut.resetAt); blockers.push(`AI login pool exhausted${until ? ` until ${until}` : ''}`); } if (isObject(machine?.ciDown) && ['queued', 'billing'].includes(machine.ciDown.reason)) { - const sinceText = Number.isFinite(machine.ciDown.since) ? new Date(machine.ciDown.since).toISOString() : 'unknown'; + const sinceText = safeIsoTimestamp(machine.ciDown.since) ?? 'unknown'; blockers.push(`GitHub Actions hold (${machine.ciDown.reason}) since ${sinceText}`); } const breaker = (isObject(state?.circuitBreaker) && state.circuitBreaker.active !== false ? state.circuitBreaker : null) @@ -689,15 +698,17 @@ function buildWorkerView(job, ctx) { blockers.push(`Recorded worker process exited without a receipt (${staleParts.map(p => `${p.role} pid ${p.pid}`).join(', ')})`); } if (job.lane?.state === 'waiting') { - blockers.push(`Waiting in merge lane${safeHolder ? ` for PR #${safeHolder}` : ''}${Number.isFinite(job.lane.since) ? ` since ${new Date(job.lane.since).toISOString()}` : ''}`); + const sinceIso = safeIsoTimestamp(job.lane.since); + blockers.push(`Waiting in merge lane${safeHolder ? ` for PR #${safeHolder}` : ''}${sinceIso ? ` since ${sinceIso}` : ''}`); } if (job.runtimeWait?.state === 'waiting') { - blockers.push(`Waiting on PDD interpreter maintenance${Number.isFinite(job.runtimeWait.until) ? ` until ${new Date(job.runtimeWait.until).toISOString()}` : ''}`); + const untilIso = safeIsoTimestamp(job.runtimeWait.until); + blockers.push(`Waiting on PDD interpreter maintenance${untilIso ? ` until ${untilIso}` : ''}`); } if (job.stepStop?.poolExhausted) { const wake = named(job.stepStop.wakeAt) ? oneLine(job.stepStop.wakeAt, 80, secrets) - : (Number.isFinite(job.stepStop.until) ? new Date(job.stepStop.until).toISOString() : null); + : safeIsoTimestamp(job.stepStop.until); blockers.push(`Waiting on AI quota / login pool${wake ? ` until ${wake}` : ''}`); } for (const part of parts) { @@ -757,8 +768,8 @@ function buildWorkerView(job, ctx) { suiteView?.lastActivityAt, artifacts.latestLogMtimeMs, job.__fileMtimeMs, - Number.isFinite(job.started) ? job.started : null, - ].filter(n => Number.isFinite(n) && n > 0); + validPositiveEpochMs(job.started) ? job.started : null, + ].filter(validPositiveEpochMs); const lastActivityAt = activityTimes.length ? Math.max(...activityTimes) : null; const safeIssues = Array.isArray(job.issues) @@ -780,7 +791,7 @@ function buildWorkerView(job, ctx) { suite: suiteView, blockers, lastActivityAt, - startedAt: Number.isFinite(job.started) ? job.started : (mainPart?.startedAt ?? null), + startedAt: validPositiveEpochMs(job.started) ? job.started : (mainPart?.startedAt ?? null), streams, logPaths: allLogPaths, evidencePaths, @@ -832,7 +843,7 @@ function readRecentHistory(fs, coreRoot, logsDir, secrets = []) { unique.push({ issue: row.issue, outcome: oneLine(row.outcome, 40, secrets), - at: Number.isFinite(row.at) ? row.at : null, + at: validPositiveEpochMs(row.at) ? row.at : null, pr: Number.isSafeInteger(row.pr) ? row.pr : null, text: named(row.text) ? oneLine(row.text, 180, secrets) : '', logPaths: artifacts.logPaths, diff --git a/src/command-catalog.mjs b/src/command-catalog.mjs index 79f9e57b33..5e4d60deeb 100644 --- a/src/command-catalog.mjs +++ b/src/command-catalog.mjs @@ -1,4 +1,4 @@ -// Generated from prompts/cli/command-catalog.prompt.md (sha256: 52daaeaf210c1bc32a37bb9536cf7226b1f32f034d3dfbce4765d63f4beec793). +// Generated from prompts/cli/command-catalog.prompt.md (sha256: db8d0050562a42604641c6dfcaa572363a7b81e7883bef6e9b1807402ff6db68). const form = (form, description) => Object.freeze({ form, description }); // The one place for the words of five commands; a later rename changes only NAMES. export const NAMES = Object.freeze({ test: 'test', lint: 'lint', simulate: 'simulate', run: 'run', requestUptake: 'ack' }); @@ -66,7 +66,7 @@ export const PUBLIC_HELP_TEXT = Object.freeze({ " pdd completion bash|zsh Print shell tab-completion script.", " pdd --help | pdd --help Show this overview or full command help.", " pdd help prompting Show the 5-step PDD authoring summary.", - " pdd --version | -V | -VV Show CLI version (and interpreter build).", + " pdd --version | -V | pdd -VV Show CLI version (and interpreter build).", ]), ]), focusedHelpLines: Object.freeze([ diff --git a/test/autopilot-logs.test.mjs b/test/autopilot-logs.test.mjs index 266bad855e..25e184ce73 100644 --- a/test/autopilot-logs.test.mjs +++ b/test/autopilot-logs.test.mjs @@ -766,3 +766,88 @@ test('3475: --follow handles stdout EPIPE cleanly, reuses gitRoot across polls, assert.equal(pollCount, 3, 'maxDurationMs must bound unattended polling'); assert.match(boundedOut.text, /Reached follow time limit; detached from issue #88/); }); + +test('3475: sanitizes non-numeric turn.completed token fields, strips CTRL_RE, and guards corrupt out-of-range timestamps', async t => { + const secret = 'ghp_SuperSecretTokenValue1234567890ABCD'; + // 1. Control-only line strips to empty; JSONL surrounded by control chars parses cleanly + assert.equal(formatWorkerLogLine('\x00\x07 \x1f'), ''); + assert.equal( + formatWorkerLogLine('\x00\x07{"type":"thread.started","model":"gpt-5.4"}\x08'), + '[session] started (gpt-5.4)', + ); + + // 2. turn.completed coerces non-numeric token fields individually so strings/secrets/\n never leak + const poisonedTurn = JSON.stringify({ + type: 'turn.completed', + usage: { input_tokens: 120, output_tokens: `${secret}\nINJECTED\x07` }, + }); + assert.equal(formatWorkerLogLine(poisonedTurn, [secret]), '[turn] completed (in 120, out 0 tokens)'); + const poisonedBoth = JSON.stringify({ + type: 'turn.completed', + usage: { input_tokens: `${secret}`, output_tokens: 'not-a-number' }, + }); + assert.equal(formatWorkerLogLine(poisonedBoth, [secret]), '[turn] completed'); + + // 3. Corrupt out-of-range timestamps (> 8.64e15 / -1e25) never throw RangeError: Invalid time value + const sb = makeSandbox(t, { mode: 'observe' }); + const nowMs = Date.parse('2026-11-17T21:30:00Z'); + writeFileSync(join(sb.coreRoot, 'core.json'), JSON.stringify({ + pausedUntil: 9e20, + streak: 4, + poolOut: { resetAt: 1e25 }, + ciDown: { reason: 'queued', since: -1e25 }, + })); + const log99 = join(sb.coreRoot, 'logs', '99-build.log'); + const exit99 = join(sb.coreRoot, 'logs', '99-build.exit.json'); + writeFileSync(log99, `${poisonedTurn}\n`); + writeFileSync(exit99, JSON.stringify({ code: `${secret}\nbad-code`, at: 9e20 })); + writeFileSync(join(sb.coreRoot, 'jobs', '99.json'), JSON.stringify({ + issue: 99, + title: 'Corrupt timestamps', + phase: 'pr', + pr: 3500, + head: 'abcdef123456', + started: 9e20, + lane: { state: 'waiting', holder: 3499, since: 9e20 }, + runtimeWait: { state: 'waiting', until: -9e20 }, + stepStop: { poolExhausted: true, until: 1e30 }, + agent: { pid: 9901, log: log99, exit: exit99, started: 9e20, watch: { at: 9e20 } }, + })); + writeFileSync( + join(sb.coreRoot, 'history.jsonl'), + `${JSON.stringify({ issue: 98, outcome: 'merged', pr: 3498, at: 9e20, text: 'Done' })}\n`, + ); + + const outList = sink(); + const codeList = await runPdd(['autopilot', 'logs'], { + stdout: outList, + stderr: sink(), + cwd: sb.gitRoot, + autopilotLogsPorts: { + git: sb.git, + stateRoot: sb.stateRoot, + now: () => nowMs, + isProcessAlive: () => false, + readSuite: () => ({ state: 'waiting', position: 1, queuedAt: 9e20 }), + }, + }); + assert.equal(codeList, 0); + assert.equal(outList.text.includes(secret), false); + + const outIssue = sink(); + const codeIssue = await runPdd(['autopilot', 'logs', '99'], { + stdout: outIssue, + stderr: sink(), + cwd: sb.gitRoot, + autopilotLogsPorts: { + git: sb.git, + stateRoot: sb.stateRoot, + now: () => nowMs, + isProcessAlive: () => false, + readSuite: () => ({ state: 'waiting', position: 1, queuedAt: 9e20 }), + }, + }); + assert.equal(codeIssue, 0); + assert.equal(outIssue.text.includes(secret), false); + assert.match(outIssue.text, /\[turn\] completed \(in 120, out 0 tokens\)/); +}); diff --git a/test/grouped-help.test.mjs b/test/grouped-help.test.mjs index 13ab5ad328..14bb3c0fb1 100644 --- a/test/grouped-help.test.mjs +++ b/test/grouped-help.test.mjs @@ -50,6 +50,7 @@ test('3496: root help is concise, grouped human-first, 80-column wrapped in its // Core commands come right at the top, not buried behind metrics/internals assert.ok(baseline.indexOf(' pdd setup [--yes]') < baseline.indexOf(' pdd metrics')); assert.ok(baseline.indexOf(' pdd autopilot logs [ISSUE] [-f]') > autopilotIdx); + assert.ok(baseline.includes(' pdd --version | -V | pdd -VV Show CLI version (and interpreter build).')); // No duplicate approval heredoc blocks or stale removed-engine migration note on root help assert.doesNotMatch(baseline, /<<'PDD_SAID'/); diff --git a/test/interpreter-version.test.mjs b/test/interpreter-version.test.mjs index 14b0c0da42..77a1afe78f 100644 --- a/test/interpreter-version.test.mjs +++ b/test/interpreter-version.test.mjs @@ -126,7 +126,7 @@ test('real help, ordinary versions, invalid syntax and invalid origin never read } for (const args of [['-VV', '--help'], ['help', '-VV'], ['-V', '--help'], ['--help']]) { const result = await f.run(args, { PDD_RUNTIME_URL: s.origin }); assert.equal(result.code, 0); - assert.match(result.stdout, args[0] === '-V' ? /pdd --version/ : args[0] === '--help' ? /pdd --version \| -V \| -VV/ : /pdd -VV/); + assert.match(result.stdout, args[0] === '-V' ? /pdd --version/ : /pdd -VV/); } for (const args of [['-VV', 'extra'], ['-V', '-V'], ['-VVV'], ['--version', '--verbose'], ['--version', '-VV'], ['-VV', '--help', 'extra']]) { const result = await f.run(args, { PDD_RUNTIME_URL: s.origin }); assert.equal(result.code, 2); assert.equal(result.stdout, '');