From 3477f78b8c387b6cccf1490a7a5abbe3e830f5a6 Mon Sep 17 00:00:00 2001 From: Raghu Betina Date: Sat, 21 Nov 2026 20:59:18 -0600 Subject: [PATCH 1/4] Add notes and record the written Compilation A person who agrees to reports also agrees to notes: short, fixed- field accounts of where First Draft itself fell short, so the service learns which requests a Plan cannot state, which guidance misled the agent, and which output was wrong. A note belongs to the Project, so an agent can send one during the interview, before any Compile. The three note commands reuse the report path: the account is read first and nothing is checked or sent with reports off, each field keeps only its shape, and the exact body is printed and sent once. start names notes only when reports are on, so the agent of a person who said no hears nothing about them. Reports and notes now cover the application's whole life. A later session no longer has the Compilation ID that plan compile printed, so plan compile and compilation download record it in a new file beside state.json, which keeps its format and moves with the planning state into the archive under root adoption. A report, or a note about generated code, uses that record unless an ID is given, and sends nothing when there is neither. --- CHANGELOG.md | 39 +- README.md | 2 +- docs/commands.md | 181 +++++-- docs/errors.md | 116 ++--- scripts/check-pack.js | 1 + scripts/smoke-package.js | 11 + src/agent-sentences.js | 23 +- src/api-response.js | 4 + src/cli.js | 387 +++++++++++++-- src/commands/note.js | 204 ++++++++ src/commands/report.js | 22 +- src/plan-state.js | 131 ++++- test/api-environments.test.js | 11 + test/cli.test.js | 1 + test/compilation.test.js | 22 + test/fixtures/note-shapes.json | 296 ++++++++++++ test/note-shapes.test.js | 219 +++++++++ test/note.test.js | 841 +++++++++++++++++++++++++++++++++ test/plan-compile.test.js | 55 +++ test/report.test.js | 126 ++++- test/start.test.js | 16 +- 21 files changed, 2542 insertions(+), 166 deletions(-) create mode 100644 src/commands/note.js create mode 100644 test/fixtures/note-shapes.json create mode 100644 test/note-shapes.test.js create mode 100644 test/note.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index a58d396..a061c4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,10 +11,10 @@ repository's [tags](https://github.com/firstdraft/cli/tags) identify the source ## 0.10.0 -Lets First Draft tell a setup that it is out of date, and adds the account, report, and `start` commands and a device -login in two steps, so a person working alone hears when to update, their agent can log them in, and it can send the -progress and failure reports the person agreed to. Moves the Rails target to profile `rails-sketch/2026-11` and the -accepted API contract to `0.9.x`. +Lets First Draft tell a setup that it is out of date, and adds the account, report, note, and `start` commands and a +device login in two steps, so a person working alone hears when to update, their agent can log them in, and it can send +the progress and failure reports and the notes the person agreed to, for the application's whole life. Moves the Rails +target to profile `rails-sketch/2026-11` and the accepted API contract to `0.9.x`. - `plan init` writes Plans that target `rails-sketch/2026-11`. `plan compile` and `compilation download` accept only artifacts for that profile; an artifact for `rails-sketch/2026-10` reports `invalid_artifact`. The CLI sends a @@ -59,12 +59,25 @@ accepted API contract to `0.9.x`. left out, a `Left out:` line names each field left out, counts the frames that are not in the application's files with a line number, and says when frames after the first 20 were dropped; the printed JSON is exactly what is sent. Both commands find the Project from the generated application's root after root adoption, or from the - Project's directory. + Project's directory. The Compilation ID is optional: without it, a report names the Compilation recorded below. +- `firstdraft note unstated_request`, `firstdraft note unclear_guidance`, and `firstdraft note wrong_output` send a + note about a problem with First Draft itself, with options named after the note's fields: `--request`; + `--page` or `--code` with `--unclear`; or `--source analysis` or `--source generated_code` with `--expected` and + `--actual`, and `--code`, `--compilation-id`, or `--file` as the source allows. Each takes `--workaround`. A note + belongs to the Project, so it needs only the Plan's first push, and goes to `POST /v1/projects/{project_id}/notes`. + Like a report, it reads the account first and sends nothing with reports off, keeps each field only in its shape + (plain words of at most 300 characters, a Skill page, a diagnostic code, a file in the application, or a lowercase + UUIDv7), prints the exact JSON and what it left out, sends it once, and never retries. A note about generated code + names the recorded Compilation unless `--compilation-id` names one. +- `plan compile` and `compilation download` record the Compilation whose code they wrote in `compilation.json` beside + the Project's `state.json`, in the archive at `.firstdraft/design/.firstdraft/` after root adoption, as + `{"format": "firstdraft.cli-compilation/1", "compilation_id": ""}`. `state.json` keeps its format. A record that + cannot be written leaves the command's result and adds one `First Draft:` line on standard error. - `firstdraft start`, which an agent runs once before other work, prints fixed sentences on standard output, one fact per line: the CLI version and, when `FIRSTDRAFT_PLUGIN_VERSION` holds one, the plugin's; the update line, when First Draft names a newer version; whether this computer has a saved login for the origin and whether a token in - the environment takes its place; and, when reports are on, when to send progress and failure reports and with - which command. With reports off, it says nothing about reports. With a token, it makes one request, an account + the environment takes its place; and, when reports are on, when to send progress and failure reports and notes, and + with which command. With reports off, it says nothing about reports or notes. With a token, it makes one request, an account read; without one, it makes none and names the two login steps below. It exits 0 only when First Draft accepted the token. A setup below the minimum or on another API contract fails with `update_required` or `api_contract_unsupported`, even though the account read was its only request. @@ -79,11 +92,13 @@ accepted API contract to `0.9.x`. what a `412` or `compilation_active` answer then means, instead of telling the caller to stop. The recovery for an unconfirmed Publication under `plan compile --github` is unchanged. - New `error` values, each with exit status 1: `update_required`, `api_contract_unsupported`, `rate_limited`, - `account_unavailable`, `report_rejected`, `report_unavailable`, and, from `login --finish`, `authorization_pending` - and `login_not_started`. `account`, `start`, and the report commands also report `authentication_required` and - `invalid_server_response` (exit status 1) and `invalid_arguments` and `invalid_configuration` (exit status 2). The - report commands also report `local_input_unreadable` and `project_not_pushed` (exit status 1). `login_failed` gains - the reasons `device_login_invalid` and `device_login_unavailable` for the waiting device login's file. + `account_unavailable`, `report_rejected`, `report_unavailable`, `note_rejected`, `note_unavailable`, + `compilation_not_recorded`, and, from `login --finish`, `authorization_pending` and `login_not_started`; and, from the + note commands, `note_incomplete` with exit status 2. `account`, `start`, and the report and note commands also report + `authentication_required` and `invalid_server_response` (exit status 1) and `invalid_arguments` and + `invalid_configuration` (exit status 2). The report and note commands also report `local_input_unreadable` and + `project_not_pushed` (exit status 1). `login_failed` gains the reasons `device_login_invalid` and + `device_login_unavailable` for the waiting device login's file. Use CLI 0.10.0 with a Service that serves API `0.9.x`. Once a response from an origin names API `0.8.x`, the CLI sends nothing more and says to use the CLI version that origin supports. A plugin's launcher should set diff --git a/README.md b/README.md index c432c52..8540244 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,7 @@ The published package: - has no runtime dependencies or install scripts; - sends nothing in the background or beyond the command the caller runs. [What the CLI sends](docs/commands.md#what-the-cli-sends) lists each command's requests and their `FirstDraft-Client` header: CLI and plugin versions, agent, and operating - system. `report` sends nothing while reports are off and prints its exact report before sending it; + system. `report` and `note` send nothing while reports are off and print exactly what they send before sending it; - makes no update check of its own: its update line comes from First Draft's answer to the command; - reads Bearer credentials from the environment or its private `firstdraft login` credentials file; and - carries npm provenance linking registry bytes to its GitHub workflow and commit. diff --git a/docs/commands.md b/docs/commands.md index 70ea79e..54d3abd 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -7,32 +7,35 @@ The current `0.10.x` source line contains the auditable command shell, the agent login in one command or in two steps that an agent runs, local Foundation Plan initialization, local application-key and UUID generation, conditional whole-document push, whole-graph analysis status polling, direct Compile-and-materialize and private publish orchestration, retained-Compilation inspection and -cancellation, the account's report setting, and progress and failure reports. It requires the service's `0.9.x` API +cancellation, the account's report setting, progress and failure reports, and notes. It requires the service's `0.9.x` API contract. The [changelog](https://github.com/firstdraft/cli/blob/main/CHANGELOG.md) describes each version. [What the CLI sends](#what-the-cli-sends) lists every request and what it carries. ## Command map -| Command | Network | Purpose | -| ------------------------------------- | ------- | ----------------------------------------------------------- | -| `firstdraft start` | Yes | Check versions, login, and reports before other work | -| `firstdraft plan init` | No | Create an empty local Foundation Plan and Project identity | -| `firstdraft generate application-key` | No | Preview deterministic name-to-key derivation | -| `firstdraft generate uuid` | No | Generate one or more Foundation Plan subject identities | -| `firstdraft login` | Yes | Approve the CLI in a browser and save a token for an origin | -| `firstdraft login --no-wait` | Yes | Start a device login for an agent and exit | -| `firstdraft login --finish` | Yes | Finish that device login once the person approved | -| `firstdraft logout` | Yes | Revoke and remove the saved token for an origin | -| `firstdraft plan push` | Yes | Conditionally submit the exact whole Plan | -| `firstdraft plan status` | Yes | Read or wait for the current whole-graph analysis | -| `firstdraft plan compile` | Yes | Push and analyze, then materialize in the current folder | -| `firstdraft plan compile --github` | Yes | Push and analyze, then publish to private GitHub | -| `firstdraft compilation status` | Yes | Inspect a retained Compilation by ID | -| `firstdraft compilation download` | Yes | Verify and materialize a successful retained Compilation | -| `firstdraft compilation cancel` | Yes | Cancel a queued or running Compilation by ID | -| `firstdraft account` | Yes | Show whether the account sends reports | -| `firstdraft report progress` | Yes | Print, then send, how far a generated application has come | -| `firstdraft report failure` | Yes | Print, then send, an unexpected failure in generated code | +| Command | Network | Purpose | +| ------------------------------------- | ------- | ------------------------------------------------------------- | +| `firstdraft start` | Yes | Check versions, login, and reports before other work | +| `firstdraft plan init` | No | Create an empty local Foundation Plan and Project identity | +| `firstdraft generate application-key` | No | Preview deterministic name-to-key derivation | +| `firstdraft generate uuid` | No | Generate one or more Foundation Plan subject identities | +| `firstdraft login` | Yes | Approve the CLI in a browser and save a token for an origin | +| `firstdraft login --no-wait` | Yes | Start a device login for an agent and exit | +| `firstdraft login --finish` | Yes | Finish that device login once the person approved | +| `firstdraft logout` | Yes | Revoke and remove the saved token for an origin | +| `firstdraft plan push` | Yes | Conditionally submit the exact whole Plan | +| `firstdraft plan status` | Yes | Read or wait for the current whole-graph analysis | +| `firstdraft plan compile` | Yes | Push and analyze, then materialize in the current folder | +| `firstdraft plan compile --github` | Yes | Push and analyze, then publish to private GitHub | +| `firstdraft compilation status` | Yes | Inspect a retained Compilation by ID | +| `firstdraft compilation download` | Yes | Verify and materialize a successful retained Compilation | +| `firstdraft compilation cancel` | Yes | Cancel a queued or running Compilation by ID | +| `firstdraft account` | Yes | Show whether the account sends reports | +| `firstdraft report progress` | Yes | Print, then send, how far a generated application has come | +| `firstdraft report failure` | Yes | Print, then send, an unexpected failure in generated code | +| `firstdraft note unstated_request` | Yes | Print, then send, a request the Plan could not state | +| `firstdraft note unclear_guidance` | Yes | Print, then send, a Skill page or diagnostic that was unclear | +| `firstdraft note wrong_output` | Yes | Print, then send, analysis or generated code that was wrong | ## Select an environment and authenticate @@ -224,6 +227,7 @@ Beyond the header, a command sends only what it needs: | `plan push`, `plan compile` | The exact local Plan bytes and the saved Head ETag | | `plan status`, `compilation *`, `account` | Only the IDs in the request path | | `report progress`, `report failure` | An account read; with reports on, the report printed just before | +| `note ` | An account read; with reports on, the note printed just before | ### Update line and refusals @@ -287,16 +291,24 @@ when `FIRSTDRAFT_PLUGIN_VERSION` holds a version. When First Draft names a newer Ready: First Draft accepted this computer's login. ``` -- **Ready, reports on** (exit 0). The same two lines, then the sentences that say when to send reports and with which - command: +- **Ready, reports on** (exit 0). The same two lines, then the sentences that say when to send reports and notes and + with which command. One yes covers both, so the agent of a person who said no hears about neither: ```text - Reports are on: this person agreed that you send First Draft progress and failure reports about the code it generates. - Progress: run 'firstdraft report progress --step ' when bin/setup finishes (setup), when the first spec run finishes (specs_first_run), when every item under the README's Behavior to write is written (behavior_written), when the specs pass (specs_passing), and when the preview starts (preview_started). Add the counts you have; 'firstdraft report progress --help' lists them. - Failure: when generated code fails in a way the README does not list, run 'firstdraft report failure --kind ' once you have fixed it or stopped trying, where is setup_failure, spec_failure, boot_error, or lint_failure; 'firstdraft report failure --help' lists the other fields. - Use compilation.id from 'firstdraft plan compile', and run each report command from the generated application's root, or from the Project's directory after --output. Each prints what it sends: pass only text that may leave this computer, never secrets or the person's data. + Reports are on: this person agreed that you send First Draft progress and failure reports about the code it generates, and notes about problems with First Draft itself. + Progress: run 'firstdraft report progress --step ' when bin/setup finishes (setup), when the first spec run finishes (specs_first_run), when every item under the README's Behavior to write is written (behavior_written), when the specs pass (specs_passing), and when the preview starts (preview_started). Add the counts you have; 'firstdraft report progress --help' lists them. + Failure: when generated code fails in a way the README does not list, run 'firstdraft report failure --kind ' once you have fixed it or stopped trying, where is setup_failure, spec_failure, boot_error, or lint_failure; 'firstdraft report failure --help' lists the other fields. + Each report names the Compilation whose code 'firstdraft plan compile' or 'firstdraft compilation download' last wrote for this Project, which the CLI records; to name a different one, put its compilation.id right after 'report progress' or 'report failure'. + Run each report and note command from the generated application's root, or from the Project's directory before the code is written or after --output. Each prints what it sends: pass only text that may leave this computer, never secrets or the person's data. + Notes: send a note only when a problem with First Draft cost you a real detour and is likely to happen again, never for routine debugging, and only after the Plan has been pushed once with 'firstdraft plan push' or 'firstdraft plan compile'. + Unstated request: when the person asked for something the Plan could not state, run 'firstdraft note unstated_request --request ', adding --workaround for what you wrote in the Plan instead or left for later. + Unclear guidance: when a Skill page or a diagnostic was unclear, run 'firstdraft note unclear_guidance --page --unclear ', where is the page's path inside the Skill, such as SKILL.md or references/plan/policies.md; for a diagnostic code or a CLI error value, give --code in place of or beside --page, and add --workaround for what you did instead. + Wrong output: when analysis or generated code was wrong, run 'firstdraft note wrong_output --source --expected --actual ', where is analysis or generated_code; a note about generated code names the recorded Compilation as a report does, and 'firstdraft note wrong_output --help' lists --code, --file, and --workaround. + Write each note in your own plain words, at most 300 characters a field: never secrets, credentials, personal data, or code from the person's project. ``` + The first five are `REPORTS_ON_LINES` and the rest `NOTES_ON_LINES` in `src/agent-sentences.js`. + - **An environment token** (exit 0 when accepted). The login lines say which token is used: ```text @@ -567,6 +579,29 @@ inside another Git worktree, initialize the application as its own repository be inspect Git; otherwise Git resolves to the parent worktree. Progress on stderr reports analysis and Compilation only. +### Record the Compilation whose code was written + +After `plan compile` or `compilation download` writes and verifies a Compilation's code, the CLI records that +Compilation's ID in `compilation.json` beside the Project's `state.json`, so a later session's +[report](#send-progress-and-failure-reports) or [note](#send-notes) about generated code names it without being told. +When the command writes to an absent `--output`, that is `.firstdraft/compilation.json` in the directory the command +ran from. After root adoption, it is `.firstdraft/design/.firstdraft/compilation.json`, beside the archived state, where commands +run from the application root find it. The file is a new one rather than a change to the `firstdraft.cli-state/1` +format of `state.json`, and it sits in the same planning folder, whose ignore file keeps it out of Git: + +```json +{ + "format": "firstdraft.cli-compilation/1", + "compilation_id": "" +} +``` + +The CLI writes it with mode `0600` through a temporary file and a rename, replacing the previous record, so it names +the Compilation whose code the CLI wrote last for the Project, wherever that code went. `plan compile --github` writes +no code into the folder and records nothing. If the record cannot be written, the command keeps its result, and one +`First Draft:` line on standard error names the Compilation to pass to later reports and notes. A record that is not +exactly this shape stops a report or note with `local_input_unreadable`. + ### Publish through GitHub Use the explicit GitHub option for the Publication journey: @@ -640,8 +675,9 @@ An earlier format or profile is rejected before materialization, even when the r Successful root adoption is intentionally one-way. The original `.firstdraft` authoring state moves under `.firstdraft/design/.firstdraft`; run later Plan and Compilation commands from `.firstdraft/design`. Run ordinary -Rails setup, preview, and tests, and `report`, from the generated application root, where -the CLI finds the archived Project and failure frames are relative to the application. Retain the archive when further First Draft +Rails setup, preview, and tests, and `report` and `note`, from the generated application root, where +the CLI finds the archived Project and failure frames are relative to the application. A successful download +[records](#record-the-compilation-whose-code-was-written) the Compilation it wrote, as `plan compile` does. Retain the archive when further First Draft authoring is useful. The CLI does not run or qualify the generated application's setup, preview, or test commands. Compiling a later Plan revision does not overwrite an already adopted root: choose a new absent output and deliberately reconcile it with application work. @@ -712,15 +748,20 @@ failure in generated code. Run these from the generated application's root after the Project's state archived at `.firstdraft/design`, or from the Project's directory: ```sh -firstdraft report progress --step specs_first_run --examples 120 --failures 14 \ +firstdraft report progress --step specs_first_run --examples 120 --failures 14 \ --behavior-to-write-failures 12 --items-remaining 9 -firstdraft report failure --kind spec_failure \ +firstdraft report failure --kind spec_failure \ --rerun "bin/rspec ./spec/models/movie_spec.rb:42" --error-class NoMethodError \ --message "undefined method 'stars' for nil" --frame "app/models/movie.rb:12:in 'Movie#average'" \ --fix-summary "Guarded a nil rating in Movie#average" ``` -`` is `compilation.id` from `plan compile`. `--step` is `setup`, `specs_first_run`, +The full forms are `firstdraft report progress [] --step [counts]` and +`firstdraft report failure [] --kind [options]`. A report names one Compilation: the +`` given, which is `compilation.id` from `plan compile`, or else the one the CLI +[recorded](#record-the-compilation-whose-code-was-written) when it last wrote a Compilation's code for the Project. +So an agent can report in a later session, after another Compile, or during maintenance without carrying the ID. With +none given and none recorded, the command sends nothing and ends with `compilation_not_recorded`. `--step` is `setup`, `specs_first_run`, `behavior_written`, `specs_passing`, or `preview_started`. The counts are optional whole numbers of at most 1000000: examples in the spec run, failing examples, failing examples that the README's Behavior to write names, and Behavior to write items still @@ -747,7 +788,7 @@ the plain words of a message or fix summary it is given can still quote code, so Each command first reads the account with a `GET` of `/v1/account` at the origin pinned by a successful push. Unless First Draft answers `{"reports": "on"}`, no report is sent. With reports off, the command writes a line that says so -and exits 0, so the agent's work continues. When the account read fails, no report is sent either. The command then +and exits 0, so the agent's work continues; it reads no Compilation record first. When the account read fails, no report is sent either. The command then ends with `account_unavailable`, with `invalid_server_response` when the answer breaks the account's contract, or with an error that any request can give: [`authentication_required`](errors.md#environment-and-credential-errors), or `rate_limited` or an update refusal ([update and limit errors](errors.md#update-and-limit-errors)). @@ -755,14 +796,80 @@ an error that any request can give: [`authentication_required`](errors.md#enviro With reports on, the command writes `Sending this report for Compilation to :`, the exact JSON body, and, when a field did not fit its shape, a `Left out:` line naming it, on standard output. It then sends that body once in a `POST` to the same origin, and writes `Sent.` once First Draft acknowledges the stored report -with `201`; any other success is `report_unavailable`. If the person turns reports off between the two requests, First +with `201` and names the same Compilation; any other success is `report_unavailable`. If the person turns reports off between the two requests, First Draft answers `403 reports_off` and keeps nothing, and the command writes the same line and exits 0. Neither command retries. +## Send notes + +When reports are on, an agent also sends First Draft a note about a problem with First Draft itself: a request the Plan +could not state, guidance that was unclear, or output that was wrong. One yes covers reports and notes. A note belongs to +the Project, so the agent can send one during the interview, before any Compile, once the Plan's first push has pinned +the Project; before that push the command ends with `project_not_pushed`. Run it from the Project's directory, or from +the generated application's root after root adoption, as a report: + +```sh +firstdraft note unstated_request --request "A weekly digest email of new movies" \ + --workaround "Left it for later" +firstdraft note unclear_guidance --page references/plan/policies.md#roles \ + --unclear "It never says whether a role can be empty" +firstdraft note wrong_output --source analysis --code foundation_plan.identity.reserved_constant_collision \ + --expected "The Plan is valid" --actual "Analysis refused it" +firstdraft note wrong_output --source generated_code --file app/policies/movie_policy.rb:12 \ + --expected "Only the owner edits a movie" --actual "Any member can edit it" +``` + +Each kind is a command, and its options are named after its fields: + +| Kind | Option | Field | Needed | What it may contain | +| ------------------ | ------------------ | ---------------- | ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `unstated_request` | `--request` | `request` | Yes | Plain words: what the person asked for. | +| | `--workaround` | `workaround` | No | Plain words: what the agent wrote in the Plan instead, or left for later. | +| `unclear_guidance` | `--page` | `page` | `--page`, `--code`, or both | A Skill page: `SKILL.md` or a path inside the Skill ending in `.md`, such as `references/plan/policies.md`, with an optional `#anchor`. At most 200 characters. | +| | `--code` | `code` | See `--page` | A diagnostic code or CLI error value, such as `invalid_output_path`. At most 120 characters. | +| | `--unclear` | `unclear` | Yes | Plain words: what it says or leaves out, and what the agent needed. | +| | `--workaround` | `workaround` | No | Plain words: what the agent did instead. | +| `wrong_output` | `--source` | `source` | Yes | `analysis` or `generated_code`. | +| | `--code` | `code` | No; `analysis` only | A diagnostic code, as above. | +| | `--compilation-id` | `compilation_id` | `generated_code` only; the recorded one when not given | A lowercase UUIDv7: the Compilation the code came from. | +| | `--file` | `file` | No; `generated_code` only | A file in the generated application: a relative path with an optional `:LINE`, such as `app/models/movie.rb:12`. At most 300 characters. | +| | `--expected` | `expected` | Yes | Plain words: what the Plan or the page says should happen. | +| | `--actual` | `actual` | Yes | Plain words: what happened. | +| | `--workaround` | `workaround` | No | Plain words: what the agent changed. | + +Plain words follow the [failure report's rule](#send-progress-and-failure-reports), at most 300 characters each. A page +is made of letters, digits, `_`, `.`, and `-` in parts separated by single slashes, and its anchor of letters, digits, +`_`, and `-`. A code is lowercase letters, digits, and `_`, in parts separated by single dots. A file is made of the +same characters as a page, without an anchor. Neither a page nor a file may have a `..` part. An option the kind does +not have, a needed option left out, a source other than the two, an option the source does not take, or a Compilation +that is not a lowercase UUIDv7 is `invalid_arguments`, and nothing is read or sent. + +Like a report, each note command first reads the account at the pinned origin, and with reports off it writes the same +line and exits 0, having checked nothing else. With reports on: + +1. A note about generated code takes its Compilation from `--compilation-id`, or else from the + [record](#record-the-compilation-whose-code-was-written); with neither, the command sends nothing and ends with + `compilation_not_recorded`. Other notes name no Compilation. +2. It shapes each field. A field that does not fit its shape is left out. When a field the note needs is left with + nothing, such as a request whose first line is blank, or guidance with neither a page nor a code left, the command + sends nothing and ends with `note_incomplete`, which names each such field. +3. It writes `Sending this note to :`, with ` for Compilation ` before ` to` for a note about + generated code, then the exact JSON body, `{"note": {...}}` with `kind` first, and a `Left out:` line when a field was + left out. +4. It sends that body once in a `POST` to `/v1/projects/{project_id}/notes` at the same origin, and writes `Sent.` once + First Draft acknowledges the stored note with `201` and names the same Compilation, or none. Any other success is + `note_unavailable`. + +First Draft answers `403 reports_off` when the person turned reports off after the account read, and the command writes +the reports-off line and exits 0. A refusal, such as `invalid_note`, `compilation_not_found`, or +`compilation_not_succeeded`, is `note_rejected`; a network failure or server error is `note_unavailable`; and an +account's limit of 30 notes an hour is `rate_limited`. The command never retries. It reads no file and no conversation: +a note holds only what its options give, so pass only text that may be sent, and never code from the person's project. + ## Service endpoints The CLI calls these Service API routes. The `/v1` routes send the selected token as a Bearer credential; -`account` and `start` read `/v1/account` at the origin selected as for `login`; the report commands read it, and every other +`account` and `start` read `/v1/account` at the origin selected as for `login`; the report and note commands read it, and every other `/v1` request goes, to the origin pinned for the Project. The `/oauth` routes go to the origin selected for `login` or `logout` and send form-encoded OAuth parameters without a Bearer credential. Every request refuses redirects and has a bounded timeout. Each request takes its method and path from one @@ -782,6 +889,7 @@ timeout. Each request takes its method and path from one | `GET` | `/v1/account` | Read whether the account reports | | `POST` | `/v1/projects/{project_id}/compilations/{compilation_id}/progress-reports` | Send a progress report | | `POST` | `/v1/projects/{project_id}/compilations/{compilation_id}/failure-reports` | Send a failure report | +| `POST` | `/v1/projects/{project_id}/notes` | Send a note | | `POST` | `/oauth/token` | Exchange a login grant for a token | | `POST` | `/oauth/device_authorization` | Start a device-flow login | | `POST` | `/oauth/revoke` | Revoke a saved token | @@ -790,7 +898,8 @@ timeout. Each request takes its method and path from one Compilation, polls it, and downloads its artifact. With `--github`, it starts and polls the Publication instead. `compilation status` reads one retained Compilation. `compilation download` reads it and downloads its artifact. `compilation cancel` cancels it. `account` reads `/v1/account`, and `start` reads it when it has a token. -`report progress` and `report failure` read it and, with reports on, post their report. +`report progress` and `report failure` read it and, with reports on, post their report. Each `note` command reads it +and, with reports on, posts its note. `login` exchanges its authorization code at `/oauth/token`. With `--interactive`, it starts at `/oauth/device_authorization` and then polls `/oauth/token`. `login --no-wait` makes only the first request, and `login --finish` only the polls. `logout` calls `/oauth/revoke`. The browser, not the diff --git a/docs/errors.md b/docs/errors.md index 272a9c8..3dab8e0 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -9,8 +9,8 @@ Every handled subcommand failure ends with exactly one JSON object on standard e write one [update or stop line](commands.md#update-line-and-refusals), and `plan compile` may first write progress lines; both begin with the exact `First Draft: ` prefix, so machine consumers can remove only those lines and parse the remaining JSON document. `login` may first write its human-readable authorization instructions; its JSON object -starts on the line after them. `report` prints what it sends on standard output before sending it, so standard -output may hold that preview when it fails. `start`, `login --no-wait`, and `login --finish` print their plain +starts on the line after them. `report` and `note` print what they send on standard output before sending it, so +standard output may hold that preview when they fail. `start`, `login --no-wait`, and `login --finish` print their plain sentences for the agent on standard output, which holds them when the command fails. Branch on the stable `error` value rather than the human-readable `detail`. @@ -219,20 +219,27 @@ Cancel never changes a succeeded or failed Compilation, and repeating it is safe - `invalid_compilation_status` means the response violated the Compilation contract, so the cancellation may or may not have happened. Check with `compilation status` rather than repeating the unchanged request. -## Report errors - -`report progress` and `report failure` never stop an agent's work. Each reads the account first and sends no report -unless it has reports on. With reports off, the command exits 0 with a line that says so; that is not an error. - -- `report_rejected`: First Draft refused the report and kept nothing. `response.code` says why, for example - `compilation_not_found` when the Compilation is not in this Project, or `invalid_report` when a field breaks the - report's shape. Continue without the report. -- `report_unavailable`: a network failure, timeout, server error, or a success without First Draft's `201` - acknowledgment left the outcome unconfirmed, and First Draft may hold the report. Continue without it rather than - sending it again. +## Report and note errors + +`report progress`, `report failure`, and the `note` commands never stop an agent's work. Each reads the account first +and sends nothing unless it has reports on. With reports off, the command exits 0 with a line that says so; that is not +an error. + +- `report_rejected`, `note_rejected`: First Draft refused the report or note and kept nothing. `response.code` says + why, for example `compilation_not_found` when the Compilation is not in this Project, `compilation_not_succeeded` + when it produced no code, or `invalid_report` or `invalid_note` when a field breaks its shape. Continue without it. +- `report_unavailable`, `note_unavailable`: a network failure, timeout, server error, or a success without First + Draft's `201` acknowledgment left the outcome unconfirmed, and First Draft may hold the report or note. Continue + without it rather than sending it again. +- `compilation_not_recorded`: a report, or a note about generated code, named no Compilation, and the CLI has none + [recorded](commands.md#record-the-compilation-whose-code-was-written) for this Project, so nothing was sent. Name the + Compilation the code came from: put `compilation.id` from `plan compile` right after `report progress` or + `report failure`, or pass it to a note with `--compilation-id`. +- `note_incomplete` (exit 2): a field the note needs had nothing left after shaping, so nothing was sent. `detail` names + each such field and why. Write the field again in plain words, or give a page or code in its shape. - `account_unavailable`: `account` could not read the account. This read-only request is safe to retry. - `invalid_server_response` from `account` means the response broke its contract. From a report command, either - error means the account read failed, so no report was sent; continue without it. + `invalid_server_response` from `account` means the response broke its contract. From a report or note command, + either error means the account read failed, so nothing was sent; continue without it. ## Publication recovery @@ -251,44 +258,47 @@ stopped without following the replacement. ## Error index -| Commands | `error` | Exit | Meaning | -| -------------------------------------------- | -------------------------------------------------------------------------------------------------- | ---: | --------------------------------------------------------------------------------------------------------------- | -| Any leaf command | `invalid_arguments` | 2 | Syntax was invalid; no request was made. | -| Network commands except `logout` | `update_required`, `api_contract_unsupported` | 1 | First Draft needs a newer plugin or CLI, or serves another API contract ([recovery](#update-and-limit-errors)). | -| Network commands except `logout` | `rate_limited` | 1 | First Draft refused a request at a limit; `retry_at` says when to try again. | -| `plan init` | `local_initialization_failed` | 1 | Initialization failed without overwriting an existing path. | -| Network commands | `invalid_configuration` | 2 | API origin or saved Head state is incompatible. | -| `login` | `authorization_denied`, `authorization_expired` | 1 | The approval was denied, or the callback wait or device code ended before the CLI received a token. | -| `login --finish` | `authorization_pending`, `login_not_started` | 1 | First Draft has not confirmed an approval yet, or no device login is waiting for the origin. | -| `login` | `login_failed` | 1 | Nothing was saved; `phase: "write"` means a token was issued ([recovery](#login-and-logout-errors)). | -| `logout` | `logout_failed` | 1 | Check `phase` and `revoked`; revocation may have happened ([recovery](#login-and-logout-errors)). | -| Network commands | `authentication_required` | 1 | No environment or saved token exists for the origin, or First Draft rejected it. | -| Plan, `compilation *`, `report` | `local_input_unreadable` | 1 | Required local Plan or private state could not be read. | -| Status, Compile, Compilation, `report` | `project_not_pushed` | 1 | No API origin is pinned for the local Project. | -| `plan push`, `plan compile` | `request_outcome_unknown` | 1 | A mutation or its response could not be verified; `plan compile` identifies its mutation phase. | -| `plan push`, `plan compile` | `local_state_not_saved` | 1 | The Plan was accepted but the private ETag state could not be replaced; includes `recovery_state`. | -| `plan push`, `plan compile` | `server_rejected` | 1 | First Draft returned validated Plan diagnostics or rejected the request with a validated problem. | -| `plan status` | `server_rejected` | 1 | First Draft rejected the analysis status request with a validated non-authentication problem. | -| `plan status` | `status_unavailable`, `invalid_server_response` | 1 | The analysis read failed or violated its protocol. | -| `plan compile` | `analysis_status_unavailable`, `invalid_analysis_status`, `analysis_status_rejected` | 1 | The bounded analysis read failed, was invalid, or was rejected. | -| Analysis waits | `analysis_changed`, `wait_timed_out`, `analysis_wait_timed_out` | 1 | The pinned analysis changed or remained processing at the deadline. | -| `plan compile` | `plan_not_valid` | 1 | Analysis completed without `valid`; `current` contains diagnostics and status. | -| `plan compile` | `local_plan_changed` | 1 | Local bytes or saved state changed after acceptance, before the selected mutation. | -| `plan compile` | `compilation_start_rejected`, `compilation_status_unavailable`, `invalid_compilation_status` | 1 | Direct start was rejected or retained status failed; post-start errors include `current`. | -| `plan compile` | `compilation_changed`, `compilation_wait_timed_out`, `compilation_failed`, `compilation_cancelled` | 1 | The pinned direct Compilation changed, timed out, failed, or was cancelled. | -| `plan compile --github` | `publication_start_rejected`, `publication_status_unavailable`, `invalid_publication_status` | 1 | Publication start or status failed its validated transport contract. | -| `plan compile --github` | `publication_changed`, `publication_wait_timed_out`, `publication_failed`, `publication_cancelled` | 1 | The pinned Publication changed, timed out, or reached a non-success terminal state. | -| `compilation status`, `compilation download` | `compilation_status_unavailable`, `invalid_compilation_status` | 1 | The retained status could not be read or violated its exact contract. | -| `compilation status --wait` | `compilation_changed`, `compilation_wait_timed_out` | 1 | Retained identity/provenance changed or the wait ended. | -| `compilation download` | `compilation_not_succeeded` | 1 | Status was not `succeeded`; no artifact request was made. | -| `compilation cancel` | `compilation_cancel_rejected` | 1 | Nothing was cancelled; `response.code` says why ([recovery](#stuck-compilation-recovery)). | -| `compilation cancel` | `compilation_cancel_unavailable` | 1 | The cancellation could not be confirmed; repeating it is safe. | -| `compilation cancel` | `invalid_compilation_status` | 1 | The response violated the Compilation contract; check status before repeating. | -| Download commands | `artifact_unavailable`, `invalid_artifact` | 1 | Artifact transport or integrity validation failed; direct Compile post-start errors include `current`. | -| Download commands | `invalid_output_path` | 2 | The absent destination or root-adoption preconditions failed; `reason` identifies the stable refusal. | -| Download commands | `materialization_failed` | 1 | The output changed or its transaction failed; `reason` identifies incomplete rollback when applicable. | -| `account`, `start` | `account_unavailable`, `invalid_server_response` | 1 | The account read failed or violated its contract. | -| `report progress`, `report failure` | `report_rejected`, `report_unavailable`, `account_unavailable`, `invalid_server_response` | 1 | The report was refused or its outcome is unconfirmed, or the account read failed; continue without it. | +| Commands | `error` | Exit | Meaning | +| ---------------------------------------------- | -------------------------------------------------------------------------------------------------- | ---: | --------------------------------------------------------------------------------------------------------------- | +| Any leaf command | `invalid_arguments` | 2 | Syntax was invalid; no request was made. | +| Network commands except `logout` | `update_required`, `api_contract_unsupported` | 1 | First Draft needs a newer plugin or CLI, or serves another API contract ([recovery](#update-and-limit-errors)). | +| Network commands except `logout` | `rate_limited` | 1 | First Draft refused a request at a limit; `retry_at` says when to try again. | +| `plan init` | `local_initialization_failed` | 1 | Initialization failed without overwriting an existing path. | +| Network commands | `invalid_configuration` | 2 | API origin or saved Head state is incompatible. | +| `login` | `authorization_denied`, `authorization_expired` | 1 | The approval was denied, or the callback wait or device code ended before the CLI received a token. | +| `login --finish` | `authorization_pending`, `login_not_started` | 1 | First Draft has not confirmed an approval yet, or no device login is waiting for the origin. | +| `login` | `login_failed` | 1 | Nothing was saved; `phase: "write"` means a token was issued ([recovery](#login-and-logout-errors)). | +| `logout` | `logout_failed` | 1 | Check `phase` and `revoked`; revocation may have happened ([recovery](#login-and-logout-errors)). | +| Network commands | `authentication_required` | 1 | No environment or saved token exists for the origin, or First Draft rejected it. | +| Plan, `compilation *`, `report`, `note` | `local_input_unreadable` | 1 | Required local Plan or private state, or the Compilation record, could not be read. | +| Status, Compile, Compilation, `report`, `note` | `project_not_pushed` | 1 | No API origin is pinned for the local Project. | +| `plan push`, `plan compile` | `request_outcome_unknown` | 1 | A mutation or its response could not be verified; `plan compile` identifies its mutation phase. | +| `plan push`, `plan compile` | `local_state_not_saved` | 1 | The Plan was accepted but the private ETag state could not be replaced; includes `recovery_state`. | +| `plan push`, `plan compile` | `server_rejected` | 1 | First Draft returned validated Plan diagnostics or rejected the request with a validated problem. | +| `plan status` | `server_rejected` | 1 | First Draft rejected the analysis status request with a validated non-authentication problem. | +| `plan status` | `status_unavailable`, `invalid_server_response` | 1 | The analysis read failed or violated its protocol. | +| `plan compile` | `analysis_status_unavailable`, `invalid_analysis_status`, `analysis_status_rejected` | 1 | The bounded analysis read failed, was invalid, or was rejected. | +| Analysis waits | `analysis_changed`, `wait_timed_out`, `analysis_wait_timed_out` | 1 | The pinned analysis changed or remained processing at the deadline. | +| `plan compile` | `plan_not_valid` | 1 | Analysis completed without `valid`; `current` contains diagnostics and status. | +| `plan compile` | `local_plan_changed` | 1 | Local bytes or saved state changed after acceptance, before the selected mutation. | +| `plan compile` | `compilation_start_rejected`, `compilation_status_unavailable`, `invalid_compilation_status` | 1 | Direct start was rejected or retained status failed; post-start errors include `current`. | +| `plan compile` | `compilation_changed`, `compilation_wait_timed_out`, `compilation_failed`, `compilation_cancelled` | 1 | The pinned direct Compilation changed, timed out, failed, or was cancelled. | +| `plan compile --github` | `publication_start_rejected`, `publication_status_unavailable`, `invalid_publication_status` | 1 | Publication start or status failed its validated transport contract. | +| `plan compile --github` | `publication_changed`, `publication_wait_timed_out`, `publication_failed`, `publication_cancelled` | 1 | The pinned Publication changed, timed out, or reached a non-success terminal state. | +| `compilation status`, `compilation download` | `compilation_status_unavailable`, `invalid_compilation_status` | 1 | The retained status could not be read or violated its exact contract. | +| `compilation status --wait` | `compilation_changed`, `compilation_wait_timed_out` | 1 | Retained identity/provenance changed or the wait ended. | +| `compilation download` | `compilation_not_succeeded` | 1 | Status was not `succeeded`; no artifact request was made. | +| `compilation cancel` | `compilation_cancel_rejected` | 1 | Nothing was cancelled; `response.code` says why ([recovery](#stuck-compilation-recovery)). | +| `compilation cancel` | `compilation_cancel_unavailable` | 1 | The cancellation could not be confirmed; repeating it is safe. | +| `compilation cancel` | `invalid_compilation_status` | 1 | The response violated the Compilation contract; check status before repeating. | +| Download commands | `artifact_unavailable`, `invalid_artifact` | 1 | Artifact transport or integrity validation failed; direct Compile post-start errors include `current`. | +| Download commands | `invalid_output_path` | 2 | The absent destination or root-adoption preconditions failed; `reason` identifies the stable refusal. | +| Download commands | `materialization_failed` | 1 | The output changed or its transaction failed; `reason` identifies incomplete rollback when applicable. | +| `account`, `start` | `account_unavailable`, `invalid_server_response` | 1 | The account read failed or violated its contract. | +| `report progress`, `report failure` | `report_rejected`, `report_unavailable`, `account_unavailable`, `invalid_server_response` | 1 | The report was refused or its outcome is unconfirmed, or the account read failed; continue without it. | +| `note ` | `note_rejected`, `note_unavailable`, `account_unavailable`, `invalid_server_response` | 1 | The note was refused or its outcome is unconfirmed, or the account read failed; continue without it. | +| `report`, `note wrong_output` | `compilation_not_recorded` | 1 | No Compilation was given or recorded; nothing was sent ([recovery](#report-and-note-errors)). | +| `note ` | `note_incomplete` | 2 | A field the note needs had nothing left after shaping; nothing was sent. | Root-output `invalid_output_path.reason` values are `destination_exists`, `root_not_real`, `root_not_writable`, `root_platform_unsupported`, `root_reserved_path`, `root_entry_unsupported`, `root_enclosing_worktree`, diff --git a/scripts/check-pack.js b/scripts/check-pack.js index 4aaeb8e..7319e00 100644 --- a/scripts/check-pack.js +++ b/scripts/check-pack.js @@ -45,6 +45,7 @@ if (result.status !== 0) { "src/commands/compilation.js", "src/commands/login.js", "src/commands/logout.js", + "src/commands/note.js", "src/commands/plan-compile.js", "src/commands/plan-init.js", "src/commands/plan-publish.js", diff --git a/scripts/smoke-package.js b/scripts/smoke-package.js index dfa0017..4872ab0 100644 --- a/scripts/smoke-package.js +++ b/scripts/smoke-package.js @@ -302,6 +302,17 @@ try { "Invalid arguments. Run 'firstdraft report failure --help' for usage.", }); + for (const kind of ["unstated_request", "unclear_guidance", "wrong_output"]) { + const invalidNote = spawnPackedCli( + ["note", kind, "--canary-secret-option"], + installationDirectory, + ); + assertHandledFailure(invalidNote, 2, { + error: "invalid_arguments", + detail: `Invalid arguments. Run 'firstdraft note ${kind} --help' for usage.`, + }); + } + const invalidLogin = spawnPackedCli( ["login", "--canary-secret-option"], installationDirectory, diff --git a/src/agent-sentences.js b/src/agent-sentences.js index dfbe34a..3049652 100644 --- a/src/agent-sentences.js +++ b/src/agent-sentences.js @@ -78,14 +78,25 @@ export function rejectedLoginLines(origin, environmentVariable) { /** * Printed when the person said yes to reports, and only then: the agent of a - * person who said no hears nothing about reports. Any command that tells the - * agent about reports prints these same sentences. + * person who said no hears nothing about reports or notes. One yes covers + * both, so any command that tells the agent about reports prints these same + * sentences, followed by NOTES_ON_LINES. */ export const REPORTS_ON_LINES = Object.freeze([ - "Reports are on: this person agreed that you send First Draft progress and failure reports about the code it generates.", - "Progress: run 'firstdraft report progress --step ' when bin/setup finishes (setup), when the first spec run finishes (specs_first_run), when every item under the README's Behavior to write is written (behavior_written), when the specs pass (specs_passing), and when the preview starts (preview_started). Add the counts you have; 'firstdraft report progress --help' lists them.", - "Failure: when generated code fails in a way the README does not list, run 'firstdraft report failure --kind ' once you have fixed it or stopped trying, where is setup_failure, spec_failure, boot_error, or lint_failure; 'firstdraft report failure --help' lists the other fields.", - "Use compilation.id from 'firstdraft plan compile', and run each report command from the generated application's root, or from the Project's directory after --output. Each prints what it sends: pass only text that may leave this computer, never secrets or the person's data.", + "Reports are on: this person agreed that you send First Draft progress and failure reports about the code it generates, and notes about problems with First Draft itself.", + "Progress: run 'firstdraft report progress --step ' when bin/setup finishes (setup), when the first spec run finishes (specs_first_run), when every item under the README's Behavior to write is written (behavior_written), when the specs pass (specs_passing), and when the preview starts (preview_started). Add the counts you have; 'firstdraft report progress --help' lists them.", + "Failure: when generated code fails in a way the README does not list, run 'firstdraft report failure --kind ' once you have fixed it or stopped trying, where is setup_failure, spec_failure, boot_error, or lint_failure; 'firstdraft report failure --help' lists the other fields.", + "Each report names the Compilation whose code 'firstdraft plan compile' or 'firstdraft compilation download' last wrote for this Project, which the CLI records; to name a different one, put its compilation.id right after 'report progress' or 'report failure'.", + "Run each report and note command from the generated application's root, or from the Project's directory before the code is written or after --output. Each prints what it sends: pass only text that may leave this computer, never secrets or the person's data.", +]); + +/** The notes half of what REPORTS_ON_LINES introduces, printed right after it. */ +export const NOTES_ON_LINES = Object.freeze([ + "Notes: send a note only when a problem with First Draft cost you a real detour and is likely to happen again, never for routine debugging, and only after the Plan has been pushed once with 'firstdraft plan push' or 'firstdraft plan compile'.", + "Unstated request: when the person asked for something the Plan could not state, run 'firstdraft note unstated_request --request ', adding --workaround for what you wrote in the Plan instead or left for later.", + "Unclear guidance: when a Skill page or a diagnostic was unclear, run 'firstdraft note unclear_guidance --page --unclear ', where is the page's path inside the Skill, such as SKILL.md or references/plan/policies.md; for a diagnostic code or a CLI error value, give --code in place of or beside --page, and add --workaround for what you did instead.", + "Wrong output: when analysis or generated code was wrong, run 'firstdraft note wrong_output --source --expected --actual ', where is analysis or generated_code; a note about generated code names the recorded Compilation as a report does, and 'firstdraft note wrong_output --help' lists --code, --file, and --workaround.", + "Write each note in your own plain words, at most 300 characters a field: never secrets, credentials, personal data, or code from the person's project.", ]); /** diff --git a/src/api-response.js b/src/api-response.js index ddece59..b604906 100644 --- a/src/api-response.js +++ b/src/api-response.js @@ -71,6 +71,10 @@ export const SERVICE_ROUTES = { method: "POST", path: "/v1/projects/{project_id}/compilations/{compilation_id}/failure-reports", }, + sendNote: { + method: "POST", + path: "/v1/projects/{project_id}/notes", + }, requestOAuthToken: { method: "POST", path: "/oauth/token", diff --git a/src/cli.js b/src/cli.js index 2285edf..6a745bf 100644 --- a/src/cli.js +++ b/src/cli.js @@ -7,6 +7,7 @@ import { isValidApplicationName, } from "./application-identity.js"; import { + NOTES_ON_LINES, REPORTS_ON_LINES, commandLine, deviceLoginExpiredLines, @@ -117,15 +118,26 @@ import { progressReportBody, sendReport, } from "./commands/report.js"; +import { + NOTE_FIELDS, + NOTE_KINDS, + NoteIncompleteError, + noteArgumentsValid, + noteBody, +} from "./commands/note.js"; import { readLoginState, readReadiness } from "./commands/start.js"; import { SERVICE_ROUTES } from "./api-response.js"; import { storedTokenReader } from "./credentials.js"; import { isFileSystemError } from "./file-system.js"; import { createPlanCompileProgressReporter } from "./plan-compile-progress.js"; import { + CompilationNotRecordedError, + CompilationRecordWriteError, PlanStateNotPushedError, isUuidV7, readPinnedProject, + readRecordedCompilation, + recordCompilation, } from "./plan-state.js"; import { API_CONTRACT_RANGE, @@ -152,6 +164,7 @@ Commands: generate Generate local values login Log in to First Draft and save a token logout Revoke and remove the saved token + note Send a note about a problem with First Draft plan Work with Foundation Plans report Send a progress or failure report to First Draft start Check versions, login, and reports before other work @@ -218,7 +231,7 @@ Options: const REPORT_PROGRESS_HELP = `First Draft CLI Usage: - firstdraft report progress --step [counts] + firstdraft report progress [] --step [counts] Options: --staging Use staging; reject a different saved origin @@ -237,13 +250,15 @@ Environment: The command first reads the account at the origin pinned by a successful plan push. With reports on, it prints the exact report, then sends it once there. -With reports off, it sends no report and still exits 0. +With reports off, it sends no report and still exits 0. Without +, the report names the Compilation whose code plan compile or +compilation download last wrote for the Project. `; const REPORT_FAILURE_HELP = `First Draft CLI Usage: - firstdraft report failure --kind [options] + firstdraft report failure [] --kind [options] Options: --staging Use staging; reject a different saved origin @@ -269,9 +284,99 @@ version numbers, and the plain words of free text. It first reads the account at the origin pinned by a successful plan push. With reports on, it prints the exact report and what it left out, then sends it once there. With reports off, it sends no report and still exits 0. Run it from the generated application's -root. +root. Without , the report names the Compilation whose code +plan compile or compilation download last wrote for the Project. +`; + +const NOTE_HELP = `First Draft CLI + +Usage: + firstdraft note [options] + +Commands: + unstated_request The person asked for something the Plan could not state + unclear_guidance A Skill page or a diagnostic was unclear + wrong_output Analysis or generated code was wrong + +Options: + -h, --help Show help + +A note belongs to the Project, so it can be sent only after the Plan's first +push. Each note command reads the account first and sends nothing while +reports are off. +`; + +const NOTE_TRAILER = `Each text keeps the plain words of its first line, at most 300 characters. +The command first reads the account at the origin pinned by a successful plan +push. With reports on, it prints the exact note and what it left out, then +sends it once there. With reports off, it sends no note and still exits 0. +`; + +const NOTE_ENVIRONMENT = `Environment: + FIRSTDRAFT_API_TOKEN Authenticate production or custom API origins + FIRSTDRAFT_STAGING_API_TOKEN Authenticate staging.firstdraft.com `; +const NOTE_UNSTATED_REQUEST_HELP = `First Draft CLI + +Usage: + firstdraft note unstated_request --request [--workaround ] + +Options: + --staging Use staging; reject a different saved origin + --request What the person asked for + --workaround What you wrote in the Plan instead, or left for later + -h, --help Show help + +${NOTE_ENVIRONMENT} +${NOTE_TRAILER}`; + +const NOTE_UNCLEAR_GUIDANCE_HELP = `First Draft CLI + +Usage: + firstdraft note unclear_guidance --page --unclear [options] + firstdraft note unclear_guidance --code --unclear [options] + +Options: + --staging Use staging; reject a different saved origin + --page The Skill page: SKILL.md or a path inside the Skill + ending in .md, with an optional #anchor + --code The diagnostic code or CLI error value + --unclear What it says or leaves out, and what you needed + --workaround What you did instead + -h, --help Show help + +${NOTE_ENVIRONMENT} +Give --page, --code, or both. +${NOTE_TRAILER}`; + +const NOTE_WRONG_OUTPUT_HELP = `First Draft CLI + +Usage: + firstdraft note wrong_output --source analysis --expected + --actual [--code ] [--workaround ] + firstdraft note wrong_output --source generated_code --expected + --actual [--compilation-id ] [--file ] + [--workaround ] + +Options: + --staging Use staging; reject a different saved origin + --source analysis or generated_code + --code The diagnostic code (analysis only) + --compilation-id The Compilation the code came from (generated_code + only; default: the one the CLI recorded) + --file The file in the generated application + (generated_code only) + --expected What the Plan or the page says should happen + --actual What happened + --workaround What you changed + -h, --help Show help + +${NOTE_ENVIRONMENT} +Without --compilation-id, a note about generated code names the Compilation +whose code plan compile or compilation download last wrote for the Project. +${NOTE_TRAILER}`; + const PLAN_HELP = `First Draft CLI Usage: @@ -702,6 +807,18 @@ const REPORT_ACCOUNT_UNAVAILABLE_DETAIL = "Could not read whether this account sends reports, so no report was sent. Continue without it."; const REPORT_ACCOUNT_INVALID_RESPONSE_DETAIL = "First Draft returned an invalid account response, so no report was sent. Continue without it."; +const REPORT_NOT_RECORDED_DETAIL = + "No Compilation is recorded for this Project, so nothing was sent. 'firstdraft plan compile' and 'firstdraft compilation download' record the one whose code they write; to name one yourself, put its compilation.id right after 'report progress' or 'report failure'."; +const NOTE_NOT_RECORDED_DETAIL = + "No Compilation is recorded for this Project, so nothing was sent. 'firstdraft plan compile' and 'firstdraft compilation download' record the one whose code they write; to name one yourself, pass its compilation.id with --compilation-id."; +const NOTE_REJECTED_DETAIL = + "First Draft rejected the note, so it was not kept; response.code says why. Continue without it."; +const NOTE_UNAVAILABLE_DETAIL = + "Could not confirm that First Draft received the note, and First Draft may hold it already. Continue without it rather than sending it again."; +const NOTE_ACCOUNT_UNAVAILABLE_DETAIL = + "Could not read whether this account sends reports and notes, so no note was sent. Continue without it."; +const NOTE_ACCOUNT_INVALID_RESPONSE_DETAIL = + "First Draft returned an invalid account response, so no note was sent. Continue without it."; const PINNED_LOCAL_INPUT_UNREADABLE_DETAIL = "Could not read valid local First Draft state, so nothing was sent. Run the command from the generated application's root after root adoption, or from the Project's directory."; const PINNED_NOT_PUSHED_DETAIL = @@ -886,9 +1003,15 @@ export async function run({ }); } - if (argv[0] === "account" || argv[0] === "report" || argv[0] === "start") { + if ( + argv[0] === "account" || + argv[0] === "note" || + argv[0] === "report" || + argv[0] === "start" + ) { const commands = { account: runAccount, + note: runNote, report: runReport, start: runStart, }; @@ -1435,6 +1558,7 @@ async function runCompilationDownload({ createRequestSignal, }), ); + recordWrittenCompilation(stderr, cwd, result.compilation.id); writeJson(stdout, result); return 0; } catch (error) { @@ -2721,6 +2845,7 @@ async function runPlanCompile({ compile: planCompileDownload, }), ); + recordWrittenCompilation(stderr, cwd, result.compilation.id); writeJson(stdout, result); return 0; } catch (error) { @@ -3473,7 +3598,9 @@ async function runStart({ writeLines(stdout, [ ...loginSentences, readyLine(login.environmentVariable), - ...(account.reports === "on" ? REPORTS_ON_LINES : []), + ...(account.reports === "on" + ? [...REPORTS_ON_LINES, ...NOTES_ON_LINES] + : []), ]); return 0; } catch (error) { @@ -3615,8 +3742,8 @@ async function runReportProgress(options) { counts[key] = count; } if ( - parsed.positionals.length !== 1 || - !isUuidV7(compilationId) || + parsed.positionals.length > 1 || + (compilationId !== undefined && !isUuidV7(compilationId)) || step === undefined || !PROGRESS_STEPS.includes(step) ) { @@ -3626,11 +3753,16 @@ async function runReportProgress(options) { return sendReportCommand( { ...options, staging: staging || parsed.values.staging }, { + ...REPORT_OUTGOING, noun: "progress report", wrapper: "progress_report", route: SERVICE_ROUTES.sendProgressReport, compilationId, - body: () => ({ body: progressReportBody(step, counts), omitted: [] }), + body: () => ({ + body: progressReportBody(step, counts), + omitted: [], + missing: [], + }), }, ); } @@ -3687,8 +3819,8 @@ async function runReportFailure(options) { "rails-version": railsVersion, } = parsed.values; if ( - parsed.positionals.length !== 1 || - !isUuidV7(compilationId) || + parsed.positionals.length > 1 || + (compilationId !== undefined && !isUuidV7(compilationId)) || kind === undefined || !FAILURE_KINDS.includes(kind) ) { @@ -3698,12 +3830,13 @@ async function runReportFailure(options) { return sendReportCommand( { ...options, staging: staging || parsed.values.staging }, { + ...REPORT_OUTGOING, noun: "failure report", wrapper: "failure_report", route: SERVICE_ROUTES.sendFailureReport, compilationId, - body: (cwd) => - failureReportBody( + body: (cwd) => ({ + ...failureReportBody( { kind, rerun, @@ -3716,6 +3849,102 @@ async function runReportFailure(options) { }, cwd, ), + missing: [], + }), + }, + ); +} + +/** @param {ServiceCommandOptions} options */ +async function runNote(options) { + const [kind, ...rest] = options.argv; + if ( + kind !== undefined && + /** @type {readonly string[]} */ (NOTE_KINDS).includes(kind) + ) { + return runNoteKind( + { ...options, argv: rest }, + /** @type {import("./commands/note.js").NoteKind} */ (kind), + ); + } + + return runCommandGroup(options, "note", NOTE_HELP); +} + +const NOTE_KIND_HELP = { + unstated_request: NOTE_UNSTATED_REQUEST_HELP, + unclear_guidance: NOTE_UNCLEAR_GUIDANCE_HELP, + wrong_output: NOTE_WRONG_OUTPUT_HELP, +}; + +/** + * @param {ServiceCommandOptions} options + * @param {import("./commands/note.js").NoteKind} kind + */ +async function runNoteKind(options, kind) { + const { argv, stdout, stderr, staging } = options; + const fieldNames = NOTE_FIELDS[kind]; + /** @type {Record} */ + const optionTypes = { + staging: { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }; + for (const field of fieldNames) { + optionTypes[field.replaceAll("_", "-")] = { type: "string" }; + } + const parsed = parseArguments(() => + parseArgs({ + args: [...argv], + options: optionTypes, + allowPositionals: false, + strict: true, + tokens: true, + }), + ); + + const invalid = () => { + writeJson(stderr, { + error: "invalid_arguments", + detail: `Invalid arguments. Run 'firstdraft note ${kind} --help' for usage.`, + }); + return 2; + }; + if (!parsed || repeatedValueOption(parsed.tokens)) return invalid(); + + if (parsed.values.help) { + stdout.write(NOTE_KIND_HELP[kind]); + return 0; + } + + /** @type {Record} */ + const fields = {}; + for (const field of fieldNames) { + const value = parsed.values[field.replaceAll("_", "-")]; + if (typeof value === "string") fields[field] = value; + } + if (!noteArgumentsValid(kind, fields)) return invalid(); + + const namesCompilation = + kind === "wrong_output" && fields.source === "generated_code"; + return sendReportCommand( + { + ...options, + staging: staging || parsed.values.staging === true, + }, + { + ...NOTE_OUTGOING, + noun: `${kind} note`, + wrapper: "note", + route: SERVICE_ROUTES.sendNote, + namesCompilation, + compilationInPath: false, + compilationId: fields.compilation_id, + help: `firstdraft note ${kind} --help`, + body: (_cwd, compilationId) => + noteBody(kind, { + ...fields, + ...(compilationId === null ? {} : { compilation_id: compilationId }), + }), }, ); } @@ -3734,18 +3963,65 @@ function parseReportCount(value) { // First Draft refuses a larger count. const MAX_REPORT_COUNT = 1_000_000; +/** + * What a report or note command sends, and the words of its errors. + * + * @typedef {object} OutgoingReport + * @property {string} noun such as "progress report", for the preview + * @property {string} wrapper the key of First Draft's acknowledgment + * @property {{method: string, path: string}} route + * @property {boolean} namesCompilation whether it names a Compilation: the + * given one, or else the one the CLI recorded + * @property {boolean} compilationInPath whether the route's path names it + * @property {string | undefined} compilationId the one the caller gave + * @property {(cwd: string, compilationId: string | null) => {body: unknown, omitted: string[], missing: string[]}} body + * `missing` names the left-out fields it needs, so nothing is sent + * @property {string} help the command that describes each field + * @property {"report_rejected" | "note_rejected"} rejected + * @property {string} rejectedDetail + * @property {"report_unavailable" | "note_unavailable"} unavailable + * @property {string} unavailableDetail + * @property {string} accountUnavailableDetail + * @property {string} accountInvalidDetail + * @property {string} notRecordedDetail + */ + +/** @satisfies {Partial} */ +const REPORT_OUTGOING = { + namesCompilation: true, + compilationInPath: true, + help: "firstdraft report --help", + rejected: /** @type {const} */ ("report_rejected"), + rejectedDetail: REPORT_REJECTED_DETAIL, + unavailable: /** @type {const} */ ("report_unavailable"), + unavailableDetail: REPORT_UNAVAILABLE_DETAIL, + accountUnavailableDetail: REPORT_ACCOUNT_UNAVAILABLE_DETAIL, + accountInvalidDetail: REPORT_ACCOUNT_INVALID_RESPONSE_DETAIL, + notRecordedDetail: REPORT_NOT_RECORDED_DETAIL, +}; + +/** @satisfies {Partial} */ +const NOTE_OUTGOING = { + rejected: /** @type {const} */ ("note_rejected"), + rejectedDetail: NOTE_REJECTED_DETAIL, + unavailable: /** @type {const} */ ("note_unavailable"), + unavailableDetail: NOTE_UNAVAILABLE_DETAIL, + accountUnavailableDetail: NOTE_ACCOUNT_UNAVAILABLE_DETAIL, + accountInvalidDetail: NOTE_ACCOUNT_INVALID_RESPONSE_DETAIL, + notRecordedDetail: NOTE_NOT_RECORDED_DETAIL, +}; + /** * Reads the account at the Project's pinned origin and, only when it has - * reports on, prints the exact report and sends those bytes once there. + * reports on, prints the exact report or note and sends those bytes once + * there. One yes covers reports and notes. * * @param {ServiceCommandOptions} options - * @param {{noun: string, wrapper: string, route: {method: string, path: string}, compilationId: string, body: (cwd: string) => {body: unknown, omitted: string[]}}} report + * @param {OutgoingReport} outgoing */ -async function sendReportCommand( - options, - { noun, wrapper, route, compilationId, body }, -) { +async function sendReportCommand(options, outgoing) { const { stdout, stderr, createRequestSignal, service } = options; + const { noun, wrapper, route, namesCompilation, body } = outgoing; try { const pinned = authenticatePinnedProject(options); if (pinned === null) { @@ -3753,12 +4029,10 @@ async function sendReportCommand( return 1; } - const shaped = body(pinned.cwd); - const text = `${JSON.stringify(shaped.body, null, 2)}\n`; const outcome = await service.settle( (async () => { - // Reports are off until the person says yes, so with them off no - // report body leaves this machine. + // Reports are off until the person says yes, so with them off nothing + // leaves this machine, and nothing else is checked. const account = await readAccount({ origin: pinned.apiUrl, fetchFunction: pinned.fetchFunction, @@ -3767,8 +4041,17 @@ async function sendReportCommand( if (account.reports !== "on") return "reports_off"; service.throwIfStopped(); + const compilationId = namesCompilation + ? (outgoing.compilationId ?? + readRecordedCompilation({ stateDirectory: pinned.stateDirectory })) + : null; + const shaped = body(pinned.cwd, compilationId); + if (shaped.missing.length > 0) { + throw new NoteIncompleteError(shaped.missing); + } + const text = `${JSON.stringify(shaped.body, null, 2)}\n`; stdout.write( - `Sending this ${noun} for Compilation ${compilationId} to ${pinned.apiUrl}:\n${text}` + + `Sending this ${noun}${compilationId === null ? "" : ` for Compilation ${compilationId}`} to ${pinned.apiUrl}:\n${text}` + (shaped.omitted.length === 0 ? "" : `Left out: ${shaped.omitted.join("; ")}.\n`), @@ -3778,7 +4061,12 @@ async function sendReportCommand( const sent = await sendReport({ origin: pinned.apiUrl, route, - projectId: pinned.projectId, + parameters: { + project_id: pinned.projectId, + ...(outgoing.compilationInPath && compilationId !== null + ? { compilation_id: compilationId } + : {}), + }, compilationId, body: text, wrapper, @@ -3794,19 +4082,35 @@ async function sendReportCommand( const status = writePinnedProjectError(stderr, error) ?? writeAccountReadError(stderr, error, { - unavailable: REPORT_ACCOUNT_UNAVAILABLE_DETAIL, - invalid: REPORT_ACCOUNT_INVALID_RESPONSE_DETAIL, + unavailable: outgoing.accountUnavailableDetail, + invalid: outgoing.accountInvalidDetail, }); if (status !== null) return status; + if (error instanceof CompilationNotRecordedError) { + writeJson(stderr, { + error: "compilation_not_recorded", + detail: outgoing.notRecordedDetail, + }); + return 1; + } + + if (error instanceof NoteIncompleteError) { + writeJson(stderr, { + error: "note_incomplete", + detail: `Nothing was sent, because a field the note needs did not fit its shape: ${error.missing.join("; ")}. Run '${outgoing.help}' for what each field may hold.`, + }); + return 2; + } + if (error instanceof ReportRejectedError) { if (isAuthenticationProblem(error.status, error.response)) { writeAuthenticationRequired(stderr, error.status, error.response); return 1; } writeJson(stderr, { - error: "report_rejected", - detail: REPORT_REJECTED_DETAIL, + error: outgoing.rejected, + detail: outgoing.rejectedDetail, status: error.status, response: error.response, }); @@ -3815,8 +4119,8 @@ async function sendReportCommand( if (error instanceof ReportUnavailableError) { writeJson(stderr, { - error: "report_unavailable", - detail: REPORT_UNAVAILABLE_DETAIL, + error: outgoing.unavailable, + detail: outgoing.unavailableDetail, ...(typeof error.status === "number" ? { status: error.status } : {}), ...(error.response ? { response: error.response } : {}), }); @@ -3827,6 +4131,27 @@ async function sendReportCommand( } } +/** + * Records the Compilation whose code the command just wrote, so a later + * report or note names it. The code is already in place, so a record that + * cannot be written leaves the command's result as it is and says so. + * + * @param {Writer} stderr + * @param {string} cwd + * @param {string} compilationId + */ +function recordWrittenCompilation(stderr, cwd, compilationId) { + try { + recordCompilation({ cwd, compilationId }); + } catch (error) { + if (!(error instanceof CompilationRecordWriteError)) throw error; + + stderr.write( + `First Draft: the code is in place, but the CLI could not record Compilation ${compilationId} for later reports and notes. Name it in each: put it right after 'report progress' or 'report failure', and pass it with --compilation-id to a note about generated code.\n`, + ); + } +} + /** * Reads the Project that a successful push pinned and authenticates its * origin, before a command prints what it will send there. Returns null when diff --git a/src/commands/note.js b/src/commands/note.js new file mode 100644 index 0000000..4d6ec4f --- /dev/null +++ b/src/commands/note.js @@ -0,0 +1,204 @@ +import { isUuidV7 } from "../plan-state.js"; +import { PARENT_SEGMENT, plainWords } from "./report.js"; + +// A note carries only fields of a known shape, as a failure report does: the +// plain words of free text, and identifiers that fit their patterns. The +// Service refuses the same shapes. + +export const NOTE_KINDS = Object.freeze([ + "unstated_request", + "unclear_guidance", + "wrong_output", +]); +/** + * Each kind's fields, in the order a note carries them. A field the kind does + * not list is no option of its command. + */ +export const NOTE_FIELDS = Object.freeze({ + unstated_request: Object.freeze(["request", "workaround"]), + unclear_guidance: Object.freeze(["page", "code", "unclear", "workaround"]), + wrong_output: Object.freeze([ + "source", + "code", + "compilation_id", + "file", + "expected", + "actual", + "workaround", + ]), +}); + +const PLAIN_WORD_FIELDS = new Set([ + "request", + "unclear", + "expected", + "actual", + "workaround", +]); +const REQUIRED_PLAIN_WORDS = Object.freeze({ + unstated_request: ["request"], + unclear_guidance: ["unclear"], + wrong_output: ["expected", "actual"], +}); +const MAX_PLAIN_WORDS = 300; +const MAX_PAGE = 200; +const MAX_CODE = 120; +const MAX_FILE = 300; +// SKILL.md, references/plan/policies.md, references/interview.md#scope +const SKILL_PAGE = + /^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*\.md(?:#[A-Za-z0-9_-]+)?$/; +// foundation_plan.identity.reserved_constant_collision, invalid_output_path +const CODE = /^[a-z0-9_]+(?:\.[a-z0-9_]+)*$/; +// app/models/movie.rb, app/models/movie.rb:12 +const APPLICATION_FILE = /^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*(?::\d{1,7})?$/; + +export class NoteIncompleteError extends Error { + /** @param {readonly string[]} missing what noteBody said the note needs */ + constructor(missing) { + super("A field the note needs did not fit its shape."); + this.missing = missing; + } +} + +/** @typedef {"unstated_request" | "unclear_guidance" | "wrong_output"} NoteKind */ +/** @typedef {Partial>} NoteFields */ + +/** + * Whether these fields, as given, can make a note of `kind`: each required + * field is given, `wrong_output` names a source and only the fields that + * source takes, and a Compilation is a lowercase UUIDv7. A note about + * generated code may still lack its Compilation, which the command reads + * from its record. + * + * @param {NoteKind} kind + * @param {NoteFields} fields + */ +export function noteArgumentsValid(kind, fields) { + const allowed = /** @type {readonly string[]} */ (NOTE_FIELDS[kind]); + if (Object.keys(fields).some((field) => !allowed.includes(field))) { + return false; + } + if (REQUIRED_PLAIN_WORDS[kind].some((field) => fields[field] === undefined)) { + return false; + } + if (kind === "unclear_guidance") { + return fields.page !== undefined || fields.code !== undefined; + } + if (kind === "wrong_output") { + if (fields.source === "analysis") { + return fields.compilation_id === undefined && fields.file === undefined; + } + return ( + fields.source === "generated_code" && + fields.code === undefined && + (fields.compilation_id === undefined || isUuidV7(fields.compilation_id)) + ); + } + return true; +} + +/** + * Shapes the note that is printed and sent. Each field keeps only what fits + * its shape; `omitted` says, for the preview, what was left out, and + * `missing` says which left-out fields the note needs, so it cannot be sent. + * + * @param {NoteKind} kind + * @param {NoteFields} fields valid for noteArgumentsValid + */ +export function noteBody(kind, fields) { + /** @type {Record} */ + const note = { kind }; + /** @type {[string, string][]} */ + const leftOut = []; + for (const field of NOTE_FIELDS[kind]) { + const value = fields[field]; + if (value === undefined) continue; + + const shaped = shapeField(field, value); + if (shaped) { + note[field] = shaped; + } else { + leftOut.push([field, `${field}, which ${SHAPE_REASONS[field]}`]); + } + } + + /** @type {Set} */ + const needed = new Set(REQUIRED_PLAIN_WORDS[kind]); + // Guidance that was unclear needs a page or a code to say which. + if ( + kind === "unclear_guidance" && + note.page === undefined && + note.code === undefined + ) { + needed.add("page").add("code"); + } + return { + body: { note }, + omitted: leftOut + .filter(([field]) => !needed.has(field)) + .map(([, reason]) => reason), + missing: leftOut + .filter(([field]) => needed.has(field)) + .map(([, reason]) => reason), + }; +} + +const NO_PLAIN_WORDS = "has no plain words on its first line"; +/** @type {Readonly>} */ +const SHAPE_REASONS = { + request: NO_PLAIN_WORDS, + unclear: NO_PLAIN_WORDS, + expected: NO_PLAIN_WORDS, + actual: NO_PLAIN_WORDS, + workaround: NO_PLAIN_WORDS, + page: "is not SKILL.md or another path ending in .md", + code: "is not a diagnostic code or CLI error value", + file: "is not a relative path in the application", +}; + +/** + * One field in its shape, or an empty string when nothing of it fits. + * + * @param {string} field + * @param {string} value + */ +function shapeField(field, value) { + if (PLAIN_WORD_FIELDS.has(field)) return plainWords(value, MAX_PLAIN_WORDS); + if (field === "page") return skillPage(value) ?? ""; + if (field === "code") return diagnosticCode(value) ?? ""; + if (field === "file") return applicationFile(value) ?? ""; + // source and compilation_id were checked as arguments. + return value; +} + +/** + * @param {string} value + * @returns {string | undefined} + */ +export function skillPage(value) { + return value.length <= MAX_PAGE && + SKILL_PAGE.test(value) && + !PARENT_SEGMENT.test(value.replace(/#.*$/, "")) + ? value + : undefined; +} + +/** + * @param {string} value + * @returns {string | undefined} + */ +export function diagnosticCode(value) { + return value.length <= MAX_CODE && CODE.test(value) ? value : undefined; +} + +/** + * @param {string} value + * @returns {string | undefined} + */ +export function applicationFile(value) { + return value.length <= MAX_FILE && + APPLICATION_FILE.test(value) && + !PARENT_SEGMENT.test(value) + ? value + : undefined; +} diff --git a/src/commands/report.js b/src/commands/report.js index 2623b8f..ed2dda0 100644 --- a/src/commands/report.js +++ b/src/commands/report.js @@ -47,7 +47,7 @@ const FRAME = new RegExp( String.raw`^(?:\./)?((?:app|lib|config|db|spec)/${SAFE_PATH}):(\d{1,7})(?::in .*)?$`, ); // Checked in every argument and frame: spec/.. spec/models has one too. -const PARENT_SEGMENT = /(?:^|[/\s:])\.\.(?=[/\s:]|$)/; +export const PARENT_SEGMENT = /(?:^|[/\s:])\.\.(?=[/\s:]|$)/; // 4.0.6, 8.1.4.1, 8.2.0.beta1, 3.4.0-preview2 const VERSION_NUMBER = /^\d{1,4}(?:\.\d{1,4}){0,3}(?:[.-](?:alpha|beta|rc|pre|preview)\d{0,3})?$/; @@ -353,17 +353,18 @@ export function plainWords(text, limit) { * @typedef {object} SendReportOptions * @property {string} origin * @property {{method: string, path: string}} route - * @property {string} projectId - * @property {string} compilationId + * @property {Record} parameters the route's path parameters + * @property {string | null} compilationId the Compilation the stored report + * or note names, which a note may leave null * @property {string} body the exact JSON text that was printed - * @property {string} wrapper the key, such as progress_report, under which - * First Draft acknowledges the stored report with its id and Compilation + * @property {string} wrapper the key, such as progress_report or note, under + * which First Draft acknowledges what it stored with its id and Compilation * @property {typeof globalThis.fetch} [fetchFunction] * @property {(timeoutMs: number) => AbortSignal} [createRequestSignal] */ /** - * Sends one report once. A report is never retried: First Draft may already + * Sends one report or note once. Neither is retried: First Draft may already * hold it when the outcome is unconfirmed. * * @param {SendReportOptions} options @@ -372,17 +373,14 @@ export function plainWords(text, limit) { export async function sendReport({ origin, route, - projectId, + parameters, compilationId, body, wrapper, fetchFunction = globalThis.fetch, createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs), }) { - const endpoint = serviceEndpoint(route, origin, { - project_id: projectId, - compilation_id: compilationId, - }); + const endpoint = serviceEndpoint(route, origin, parameters); let response; try { response = await sendRequest(fetchFunction, endpoint, { @@ -448,7 +446,7 @@ function isRecord(value) { /** * @param {Record} report - * @param {string} compilationId + * @param {string | null} compilationId */ function isStoredReport(report, compilationId) { return ( diff --git a/src/plan-state.js b/src/plan-state.js index 0f4dd2e..33288d0 100644 --- a/src/plan-state.js +++ b/src/plan-state.js @@ -1,4 +1,5 @@ -import { lstatSync, readFileSync } from "node:fs"; +import { randomUUID } from "node:crypto"; +import { lstatSync, readFileSync, renameSync, writeFileSync } from "node:fs"; import path from "node:path"; import { isFileSystemError } from "./file-system.js"; @@ -50,23 +51,135 @@ export function readPlanState({ cwd, fileSystem = DEFAULT_FILE_SYSTEM }) { * @param {PlanStateFileSystem} [options.fileSystem] */ export function readPinnedProject({ cwd, fileSystem }) { + const projectDirectory = pinnedProjectDirectory(cwd, fileSystem); + const state = readPlanState({ cwd: projectDirectory, fileSystem }); + if (state.api_url === undefined) { + throw new PlanStateNotPushedError( + "The local Foundation Plan has not been pushed.", + ); + } + + return { + apiUrl: state.api_url, + projectId: state.project_id, + stateDirectory: path.join(projectDirectory, ".firstdraft"), + }; +} + +/** + * The directory whose .firstdraft holds the Project's state: `cwd`, or the + * archive at .firstdraft/design when `cwd` is an adopted application root. + * + * @param {string} cwd + * @param {PlanStateFileSystem} [fileSystem] + */ +function pinnedProjectDirectory(cwd, fileSystem) { // Only an adopted root, whose real .firstdraft holds no state.json, falls // back; any other local problem is reported for this directory. const adoptedRoot = isDirectory(path.join(cwd, ".firstdraft"), fileSystem) && isAbsent(path.join(cwd, ".firstdraft", "state.json"), fileSystem) && isDirectory(path.join(cwd, ".firstdraft", "design"), fileSystem); - const state = readPlanState({ - cwd: adoptedRoot ? path.join(cwd, ".firstdraft", "design") : cwd, - fileSystem, - }); - if (state.api_url === undefined) { - throw new PlanStateNotPushedError( - "The local Foundation Plan has not been pushed.", + return adoptedRoot ? path.join(cwd, ".firstdraft", "design") : cwd; +} + +// The Compilation whose code the CLI last wrote for the Project, kept in its +// own file beside state.json so the state format stays as it is. It moves +// with the planning state into an adopted root's archive. +const COMPILATION_RECORD_NAME = "compilation.json"; +const COMPILATION_RECORD_FORMAT = "firstdraft.cli-compilation/1"; + +export class CompilationRecordWriteError extends Error {} +export class CompilationNotRecordedError extends Error {} + +/** + * Records `compilationId` as the Compilation whose code the CLI just wrote, + * beside the state of the Project found from `cwd` as readPinnedProject + * finds it, replacing any earlier record. + * + * @param {object} options + * @param {string} options.cwd + * @param {string} options.compilationId + * @param {() => string} [options.createTemporaryId] + * @returns {string} the record's path + */ +export function recordCompilation({ + cwd, + compilationId, + createTemporaryId = randomUUID, +}) { + const recordPath = path.join( + pinnedProjectDirectory(cwd), + ".firstdraft", + COMPILATION_RECORD_NAME, + ); + const temporaryPath = `${recordPath}.${createTemporaryId()}.tmp`; + const source = `${JSON.stringify( + { format: COMPILATION_RECORD_FORMAT, compilation_id: compilationId }, + null, + 2, + )}\n`; + try { + writeFileSync(temporaryPath, source, { + flag: "wx", + mode: 0o600, + flush: true, + }); + renameSync(temporaryPath, recordPath); + } catch (error) { + if (!isFileSystemError(error)) throw error; + + throw new CompilationRecordWriteError( + "The Compilation record could not be written.", + { cause: error }, + ); + } + return recordPath; +} + +/** + * The Compilation that recordCompilation recorded in `stateDirectory`. + * + * @param {object} options + * @param {string} options.stateDirectory from readPinnedProject + * @param {PlanStateFileSystem} [options.fileSystem] + * @returns {string} + */ +export function readRecordedCompilation({ + stateDirectory, + fileSystem = DEFAULT_FILE_SYSTEM, +}) { + const recordPath = path.join(stateDirectory, COMPILATION_RECORD_NAME); + if (isAbsent(recordPath, fileSystem)) { + throw new CompilationNotRecordedError( + "No Compilation is recorded for this Project.", ); } - return { apiUrl: state.api_url, projectId: state.project_id }; + const source = readLocalFile(recordPath, MAX_STATE_BYTES, fileSystem); + let record; + try { + record = JSON.parse( + new TextDecoder("utf-8", { fatal: true }).decode(source), + ); + } catch (error) { + if (!(error instanceof SyntaxError || error instanceof TypeError)) { + throw error; + } + + throw new PlanStateLocalError("The Compilation record is invalid.", { + cause: error, + }); + } + if ( + !isRecord(record) || + !arraysEqual(Object.keys(record).sort(), ["compilation_id", "format"]) || + record.format !== COMPILATION_RECORD_FORMAT || + !isUuidV7(record.compilation_id) + ) { + throw new PlanStateLocalError("The Compilation record is invalid."); + } + return record.compilation_id; } /** @param {string} value */ diff --git a/test/api-environments.test.js b/test/api-environments.test.js index 30abc70..07cd5ee 100644 --- a/test/api-environments.test.js +++ b/test/api-environments.test.js @@ -36,6 +36,17 @@ const REMOTE_COMMANDS = [ "--error-class", "Rails/Delegate", ], + ["note", "unstated_request", "--request", "A weekly digest email"], + [ + "note", + "wrong_output", + "--source", + "generated_code", + "--expected", + "Only the owner edits", + "--actual", + "Anyone edits", + ], ]; test("production and staging credentials follow the pinned origin on every remote command", async (context) => { diff --git a/test/cli.test.js b/test/cli.test.js index fa04150..39c78ef 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -20,6 +20,7 @@ Commands: generate Generate local values login Log in to First Draft and save a token logout Revoke and remove the saved token + note Send a note about a problem with First Draft plan Work with Foundation Plans report Send a progress or failure report to First Draft start Check versions, login, and reports before other work diff --git a/test/compilation.test.js b/test/compilation.test.js index 1b48f06..1f79f96 100644 --- a/test/compilation.test.js +++ b/test/compilation.test.js @@ -297,6 +297,10 @@ test("compilation download distinguishes Head and Plan provenance without starti assert.equal(body.compilation.head_source_sha256, RETAINED_HEAD); assert.equal(body.output.path, output); assert.equal(body.output.file_count, 1); + assert.equal( + readFileSync(path.join(cwd, ".firstdraft", "compilation.json"), "utf8"), + compilationRecord(), + ); }); test("compilation download adopts the current directory without starting work", async (context) => { @@ -368,6 +372,19 @@ test("compilation download adopts the current directory without starting work", ); assert.equal(existsSync(path.join(cwd, ".firstdraft/state.json")), false); assert.equal(existsSync(path.join(cwd, "design")), false); + // The record sits beside the archived state, where reports from the + // application root find it, and not among the generated files. + assert.equal( + readFileSync( + path.join(cwd, ".firstdraft/design/.firstdraft/compilation.json"), + "utf8", + ), + compilationRecord(), + ); + assert.equal( + existsSync(path.join(cwd, ".firstdraft/compilation.json")), + false, + ); }); test("download requires succeeded status and validates historical Head provenance", async (context) => { @@ -760,6 +777,11 @@ function authenticationProblem() { ); } +/** The record a download leaves, naming the Compilation whose code it wrote. */ +function compilationRecord() { + return `{\n "format": "firstdraft.cli-compilation/1",\n "compilation_id": "${COMPILATION_ID}"\n}\n`; +} + /** @param {import("node:test").TestContext} context */ function remoteDirectory(context) { const cwd = mkdtempSync(path.join(tmpdir(), "firstdraft-compilation-")); diff --git a/test/fixtures/note-shapes.json b/test/fixtures/note-shapes.json new file mode 100644 index 0000000..73ba726 --- /dev/null +++ b/test/fixtures/note-shapes.json @@ -0,0 +1,296 @@ +{ + "about": "Examples of what the First Draft service accepts and refuses in each note field and in whole notes, written from the notes contract's rules. The service tests its own copy of these cases, and the CLI tests its shaping against this one. limit is a field's longest accepted length in characters.", + "fields": { + "kind": { + "accepted": ["unstated_request", "unclear_guidance", "wrong_output"], + "refused": ["", "unstated-request", "Wrong_output", "bug", "progress"] + }, + "request": { + "accepted": [ + "A weekly digest email of new movies", + "Members invite others by […]", + "Validation failed: Email has already been taken", + "[…] […] expected 3, got 4" + ], + "refused": [ + "Send mail to sam@example.com", + "Use the 'owner' role", + "Setting \"secret value\"", + "run `make`", + "it's broken", + "DATABASE_URL=postgres://db failed", + "Read /tmp/sample.log", + "see https://example.com", + "path C:\\Users", + "token abcdefghijklmnopqrstuvwxyz", + "two\nlines", + "two\rlines", + "two\u2028lines", + "two\u2029lines", + "two\u0085lines", + "one\ttab" + ], + "limit": 300 + }, + "workaround": { + "accepted": ["Left it for later", "Wrote a […] field instead"], + "refused": [ + "Set TOKEN=abc in […]", + "Moved it to app/models", + "Used 'admin'" + ], + "limit": 300 + }, + "unclear": { + "accepted": [ + "It never says whether a role can be empty", + "It names no fix" + ], + "refused": ["It says `role: owner`", "See references/plan/policies.md"], + "limit": 300 + }, + "expected": { + "accepted": ["Only the owner edits a movie", "The Plan is valid"], + "refused": ["owner_id == current_user.id", "scope = Movie.mine"], + "limit": 300 + }, + "actual": { + "accepted": ["Any member can edit it", "Analysis refused it"], + "refused": ["raise 'not allowed'", "user@example.com could edit"], + "limit": 300 + }, + "page": { + "accepted": [ + "SKILL.md", + "references/interview.md", + "references/plan/policies.md", + "references/plan/policies.md#roles", + "references/modeling-guide.md#state_machines-2" + ], + "refused": [ + "", + "../SKILL.md", + "references/../SKILL.md", + "/Users/sam/skills/SKILL.md", + "references/plan/policies", + "references/plan/policies.txt", + "references\\plan\\policies.md", + "references/plan policies.md", + "references//policies.md", + "SKILL.md#", + "SKILL.md#a.b", + "SKILL.md#roles#more", + "https://example.com/SKILL.md" + ], + "limit": 200 + }, + "code": { + "accepted": [ + "invalid_output_path", + "report_rejected", + "foundation_plan.identity.reserved_constant_collision", + "x1.y2_z" + ], + "refused": [ + "", + "Foundation_plan.identity", + "foundation-plan.identity", + "foundation_plan..identity", + ".identity", + "identity.", + "invalid output path", + "foundation_plan/identity", + "Rails/Delegate" + ], + "limit": 120 + }, + "source": { + "accepted": ["analysis", "generated_code"], + "refused": ["", "Analysis", "generated-code", "code", "plan"] + }, + "compilation_id": { + "accepted": [ + "01900000-0000-7000-8000-000000000001", + "0190ab12-cdef-7abc-9def-0123456789ab" + ], + "refused": [ + "", + "0190AB12-CDEF-7ABC-9DEF-0123456789AB", + "01900000-0000-4000-8000-000000000001", + "01900000-0000-7000-c000-000000000001", + "01900000000070008000000000000001", + "not-a-uuid" + ] + }, + "file": { + "accepted": [ + "app/models/movie.rb", + "app/models/movie.rb:12", + "app/views/movies/_form.html.erb:9", + "db/migrate/20261121000000_create_movies.rb", + "Gemfile", + ".github/workflows/ci.yml", + "./app/models/movie.rb" + ], + "refused": [ + "", + "/Users/sam/app/models/movie.rb", + "../secrets.rb", + "app/../config/master.key", + "app/models/movie.rb:12:in 'Movie#rate'", + "app/models/movie.rb:12:3", + "app/models/movie.rb:", + "app/models/movie.rb:12345678", + "app\\models\\movie.rb", + "app/models/my movie.rb", + "app//models/movie.rb", + "app/models/", + "C:/Users/sam/movie.rb" + ], + "limit": 300 + } + }, + "notes": { + "accepted": [ + { + "kind": "unstated_request", + "request": "A weekly digest email of new movies" + }, + { + "kind": "unstated_request", + "request": "Members invite others by […]", + "workaround": "Left it for later" + }, + { + "kind": "unclear_guidance", + "page": "SKILL.md", + "unclear": "It never says when to push" + }, + { + "kind": "unclear_guidance", + "code": "foundation_plan.identity.reserved_constant_collision", + "unclear": "It names no fix" + }, + { + "kind": "unclear_guidance", + "page": "references/plan/policies.md#roles", + "code": "invalid_output_path", + "unclear": "It never says whether a role can be empty", + "workaround": "Wrote a […] field instead" + }, + { + "kind": "wrong_output", + "source": "analysis", + "expected": "The Plan is valid", + "actual": "Analysis refused it" + }, + { + "kind": "wrong_output", + "source": "analysis", + "code": "foundation_plan.identity.reserved_constant_collision", + "expected": "The Plan is valid", + "actual": "Analysis refused it", + "workaround": "Renamed the entity" + }, + { + "kind": "wrong_output", + "source": "generated_code", + "compilation_id": "01900000-0000-7000-8000-000000000001", + "expected": "Only the owner edits a movie", + "actual": "Any member can edit it" + }, + { + "kind": "wrong_output", + "source": "generated_code", + "compilation_id": "01900000-0000-7000-8000-000000000001", + "file": "app/policies/movie_policy.rb:12", + "expected": "Only the owner edits a movie", + "actual": "Any member can edit it", + "workaround": "Checked the owner in the policy" + } + ], + "refused": [ + {}, + { "request": "A weekly digest email" }, + { "kind": "bug", "request": "A weekly digest email" }, + { "kind": "unstated_request" }, + { "kind": "unstated_request", "workaround": "Left it for later" }, + { + "kind": "unstated_request", + "request": "A weekly digest email", + "page": "SKILL.md" + }, + { "kind": "unstated_request", "request": "Use the 'owner' role" }, + { "kind": "unclear_guidance", "unclear": "It names no fix" }, + { "kind": "unclear_guidance", "page": "SKILL.md" }, + { + "kind": "unclear_guidance", + "page": "../SKILL.md", + "unclear": "It names no fix" + }, + { + "kind": "unclear_guidance", + "code": "invalid_output_path", + "unclear": "It names no fix", + "file": "app/models/movie.rb" + }, + { + "kind": "wrong_output", + "expected": "The Plan is valid", + "actual": "Analysis refused it" + }, + { + "kind": "wrong_output", + "source": "plan", + "expected": "The Plan is valid", + "actual": "Analysis refused it" + }, + { + "kind": "wrong_output", + "source": "analysis", + "expected": "The Plan is valid" + }, + { + "kind": "wrong_output", + "source": "analysis", + "actual": "Analysis refused it" + }, + { + "kind": "wrong_output", + "source": "analysis", + "compilation_id": "01900000-0000-7000-8000-000000000001", + "expected": "The Plan is valid", + "actual": "Analysis refused it" + }, + { + "kind": "wrong_output", + "source": "analysis", + "file": "app/models/movie.rb", + "expected": "The Plan is valid", + "actual": "Analysis refused it" + }, + { + "kind": "wrong_output", + "source": "generated_code", + "expected": "Only the owner edits", + "actual": "Anyone edits" + }, + { + "kind": "wrong_output", + "source": "generated_code", + "compilation_id": "01900000-0000-7000-8000-000000000001", + "code": "invalid_output_path", + "expected": "Only the owner edits", + "actual": "Anyone edits" + }, + { + "kind": "wrong_output", + "source": "generated_code", + "compilation_id": "01900000-0000-7000-8000-000000000001", + "file": "/Users/sam/app/models/movie.rb", + "expected": "Only the owner edits", + "actual": "Anyone edits" + } + ] + } +} diff --git a/test/note-shapes.test.js b/test/note-shapes.test.js new file mode 100644 index 0000000..a97da15 --- /dev/null +++ b/test/note-shapes.test.js @@ -0,0 +1,219 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; + +import { + NOTE_FIELDS, + NOTE_KINDS, + noteArgumentsValid, + noteBody, +} from "../src/commands/note.js"; + +// Examples written from the notes contract's rules. The First Draft service +// keeps its own copy of the same cases; when the two are reconciled into one +// file, copy it here unchanged so both sides test the same strings. +const shapes = JSON.parse( + readFileSync(new URL("fixtures/note-shapes.json", import.meta.url), "utf8"), +); +const COMPILATION_ID = "01900000-0000-7000-8000-000000000001"; + +/** + * A field of a note the CLI would otherwise send, or undefined when the CLI + * refuses or leaves it out. + * + * @param {import("../src/commands/note.js").NoteKind} kind + * @param {Record} fields + * @param {string} field + */ +function shaped(kind, fields, field) { + if (!noteArgumentsValid(kind, fields)) return undefined; + return noteBody(kind, fields).body.note[field]; +} + +/** @type {Record string | undefined>} */ +const SHAPERS = { + kind: (value) => + /** @type {readonly string[]} */ (NOTE_KINDS).includes(value) + ? value + : undefined, + request: (value) => shaped("unstated_request", { request: value }, "request"), + workaround: (value) => + shaped( + "unstated_request", + { request: "A weekly digest email", workaround: value }, + "workaround", + ), + unclear: (value) => + shaped("unclear_guidance", { page: "SKILL.md", unclear: value }, "unclear"), + expected: (value) => + shaped( + "wrong_output", + { source: "analysis", expected: value, actual: "Refused" }, + "expected", + ), + actual: (value) => + shaped( + "wrong_output", + { source: "analysis", expected: "Valid", actual: value }, + "actual", + ), + page: (value) => + shaped( + "unclear_guidance", + { page: value, code: "invalid_output_path", unclear: "Unclear" }, + "page", + ), + code: (value) => + shaped( + "unclear_guidance", + { page: "SKILL.md", code: value, unclear: "Unclear" }, + "code", + ), + source: (value) => + shaped( + "wrong_output", + { source: value, expected: "Valid", actual: "Refused" }, + "source", + ), + compilation_id: (value) => + shaped( + "wrong_output", + { + source: "generated_code", + compilation_id: value, + expected: "Valid", + actual: "Refused", + }, + "compilation_id", + ), + file: (value) => + shaped( + "wrong_output", + { + source: "generated_code", + compilation_id: COMPILATION_ID, + file: value, + expected: "Valid", + actual: "Refused", + }, + "file", + ), +}; + +test("the examples name exactly the fields a note may carry", () => { + const fields = new Set(["kind", ...Object.values(NOTE_FIELDS).flat()]); + assert.deepEqual(Object.keys(shapes.fields).sort(), [...fields].sort()); + assert.deepEqual(Object.keys(SHAPERS).sort(), [...fields].sort()); +}); + +test("every accepted example passes through the CLI's shaping unchanged", () => { + for (const [field, { accepted }] of Object.entries(shapes.fields)) { + const shape = /** @type {(value: string) => string | undefined} */ ( + SHAPERS[field] + ); + for (const example of /** @type {string[]} */ (accepted)) { + assert.equal(shape(example), example, `${field}: ${example}`); + } + } +}); + +test("the CLI turns every refused example into an accepted value or leaves it out", () => { + for (const [field, { refused }] of Object.entries(shapes.fields)) { + const shape = /** @type {(value: string) => string | undefined} */ ( + SHAPERS[field] + ); + for (const example of /** @type {string[]} */ (refused)) { + const result = shape(example); + if (result === undefined || result === "") continue; + + assert.ok( + !refused.includes(result), + `${field}: ${JSON.stringify(example)} became a refused value`, + ); + // What the CLI sends is already in its final shape. + assert.equal( + shape(result), + result, + `${field}: ${JSON.stringify(example)} became ${JSON.stringify(result)}`, + ); + } + } +}); + +test("each field's limit is the longest value the CLI sends", () => { + for (const [ + field, + filler, + suffix, + ] of /** @type {[string, string, string][]} */ ([ + ["page", "references/", ".md"], + ["code", "foundation_plan.", ""], + ["file", "app/models/", ".rb"], + ])) { + const { limit } = shapes.fields[field]; + const shape = /** @type {(value: string) => string | undefined} */ ( + SHAPERS[field] + ); + const longest = `${filler}${"a".repeat(limit - filler.length - suffix.length)}${suffix}`; + assert.equal(shape(longest), longest, field); + const tooLong = `${filler}${"a".repeat(limit + 1 - filler.length - suffix.length)}${suffix}`; + assert.equal(shape(tooLong), undefined, field); + } + + for (const field of [ + "request", + "workaround", + "unclear", + "expected", + "actual", + ]) { + const { limit } = shapes.fields[field]; + const shape = /** @type {(value: string) => string | undefined} */ ( + SHAPERS[field] + ); + const text = `words ${Array(59).fill("word").join(" ")}`; + assert.equal(text.length, limit); + assert.equal(shape(text), text, field); + const cut = shape(`${text}s`); + assert.ok(cut !== undefined && Array.from(cut).length <= limit, field); + } +}); + +test("accepted notes pass through unchanged, and refused ones do not leave as they are", () => { + for (const note of shapes.notes.accepted) { + const { kind, ...fields } = note; + assert.ok(noteArgumentsValid(kind, fields), JSON.stringify(note)); + assert.deepEqual(noteBody(kind, fields), { + body: { note }, + omitted: [], + missing: [], + }); + } + + for (const note of shapes.notes.refused) { + const { kind, ...fields } = note; + // There is no command for a missing or unknown kind, and an option the + // kind does not have, or a combination it does not take, is refused + // before anything is read or sent. + if (!NOTE_KINDS.includes(kind) || !noteArgumentsValid(kind, fields)) { + continue; + } + // A note about generated code that names no Compilation takes the one + // the CLI recorded; with none recorded, it sends nothing. + if (fields.source === "generated_code" && !fields.compilation_id) continue; + + const result = noteBody(kind, fields); + if (result.missing.length > 0) continue; + + assert.notDeepEqual(result.body.note, note, JSON.stringify(note)); + // What the CLI would send is already in its final shape. + const sent = Object.fromEntries( + Object.entries(result.body.note).filter(([key]) => key !== "kind"), + ); + assert.deepEqual(noteBody(kind, sent), { + body: result.body, + omitted: [], + missing: [], + }); + } +}); diff --git a/test/note.test.js b/test/note.test.js new file mode 100644 index 0000000..741d6d6 --- /dev/null +++ b/test/note.test.js @@ -0,0 +1,841 @@ +import assert from "node:assert/strict"; +import { + mkdirSync, + mkdtempSync, + realpathSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { run } from "../src/cli.js"; + +const PRODUCTION = "https://firstdraft.com"; +const STAGING = "https://staging.firstdraft.com"; +const PROJECT_ID = "01900000-0000-7000-8000-000000009300"; +const COMPILATION_ID = "01900000-0000-7000-8000-000000009301"; +const RECORDED_ID = "01900000-0000-7000-8000-000000009302"; +const STORED_ID = "01900000-0000-7000-8000-000000009303"; +const TOKEN = "canary-note-token"; +const STAGING_TOKEN = "canary-staging-note-token"; +const CWD = path.resolve("/work/movie_catalog"); +const NOTES_PATH = `/v1/projects/${PROJECT_ID}/notes`; +const REPORTS_OFF = + "Not kept: this account has reports off, so First Draft kept nothing. Continue without sending reports.\n"; +const UNSTATED = [ + "note", + "unstated_request", + "--request", + "A weekly digest email of new movies", +]; +const GENERATED = [ + "note", + "wrong_output", + "--source", + "generated_code", + "--expected", + "Only the owner edits a movie", + "--actual", + "Any member can edit it", +]; + +test("note help lists the three kinds and each kind's options", async () => { + for (const argv of [["note"], ["note", "--help"], ["note", "-h"]]) { + const result = await invoke(argv); + assert.equal(result.status, 0); + assert.match(result.stdout, /firstdraft note /); + assert.match(result.stdout, /unstated_request {2}The person asked/); + assert.match(result.stdout, /unclear_guidance {2}A Skill page/); + assert.match(result.stdout, /wrong_output {6}Analysis or generated code/); + } + + for (const [kind, options] of /** @type {[string, string[]][]} */ ([ + ["unstated_request", ["--request ", "--workaround "]], + [ + "unclear_guidance", + ["--page ", "--code ", "--unclear ", "--workaround"], + ], + [ + "wrong_output", + [ + "--source ", + "--code ", + "--compilation-id ", + "--file ", + "--expected ", + "--actual ", + "--workaround ", + ], + ], + ])) { + const result = await invoke(["note", kind, "--help"]); + assert.equal(result.status, 0); + assert.match(result.stdout, new RegExp(`firstdraft note ${kind} `)); + for (const option of options) { + assert.match(result.stdout, new RegExp(option), `${kind} ${option}`); + } + } + + for (const argv of [ + ["note", "canary"], + ["note", "--canary"], + ["note", "unstated-request"], + ]) { + const result = await invoke(argv); + assert.equal(result.status, 2); + assert.match(result.stderr, /Run 'firstdraft note --help' for usage\.\n$/); + assert.doesNotMatch(result.stderr, /canary/); + } +}); + +test("each note kind validates its arguments before any request", async () => { + for (const argv of [ + ["note", "unstated_request"], + ["note", "unstated_request", "--workaround", "Left it out"], + [...UNSTATED, "--request", "Twice"], + [...UNSTATED, "--page", "SKILL.md"], + [...UNSTATED, "--canary"], + [...UNSTATED, "positional"], + ["note", "unclear_guidance", "--unclear", "Says nothing about roles"], + ["note", "unclear_guidance", "--page", "SKILL.md"], + [ + "note", + "unclear_guidance", + "--code", + "x", + "--unclear", + "x", + "--file", + "x", + ], + ["note", "wrong_output", "--expected", "a", "--actual", "b"], + [ + "note", + "wrong_output", + "--source", + "code", + "--expected", + "a", + "--actual", + "b", + ], + ["note", "wrong_output", "--source", "analysis", "--expected", "a"], + ["note", "wrong_output", "--source", "analysis", "--actual", "b"], + [ + "note", + "wrong_output", + "--source", + "analysis", + "--expected", + "a", + "--actual", + "b", + "--compilation-id", + COMPILATION_ID, + ], + [ + "note", + "wrong_output", + "--source", + "analysis", + "--expected", + "a", + "--actual", + "b", + "--file", + "app/models/movie.rb", + ], + [...GENERATED, "--code", "foundation_plan.policy.unknown"], + [...GENERATED, "--compilation-id", "0190000A-0000-7000-8000-000000009301"], + [...GENERATED, "--compilation-id", "01900000-0000-4000-8000-000000009301"], + [...GENERATED, "--compilation-id", ""], + [...GENERATED, "--request", "x"], + ]) { + const kind = argv[1]; + const result = await invoke(argv); + assert.equal(result.status, 2, argv.join(" ")); + assert.equal(result.stdout, ""); + assert.deepEqual(JSON.parse(result.stderr), { + error: "invalid_arguments", + detail: `Invalid arguments. Run 'firstdraft note ${kind} --help' for usage.`, + }); + } +}); + +test("an unstated request reads the account, prints the exact note, then sends those bytes once", async (context) => { + const cwd = projectDirectory(context, PRODUCTION); + /** @type {{url: string, init: RequestInit | undefined}[]} */ + const requests = []; + const result = await invoke( + [ + ...UNSTATED, + "--workaround", + "Left it for later in the README's Behavior to write", + ], + { + cwd, + fetchFunction: async (input, init) => { + requests.push({ url: String(input), init }); + if (requests.length === 1) return account("on"); + return stored({ kind: "unstated_request", compilation_id: null }); + }, + }, + ); + + const body = `${JSON.stringify( + { + note: { + kind: "unstated_request", + request: "A weekly digest email of new movies", + workaround: "Left it for later in the […]", + }, + }, + null, + 2, + )}\n`; + assert.deepEqual(result, { + status: 0, + stdout: `Sending this unstated_request note to ${PRODUCTION}:\n${body}Sent.\n`, + stderr: "", + }); + assert.equal(requests.length, 2); + const [read, request] = requests; + assert(read && request); + assert.equal(read.url, `${PRODUCTION}/v1/account`); + assert.equal(read.init?.method ?? "GET", "GET"); + assert.equal(read.init?.body, undefined); + assert.equal(request.url, `${PRODUCTION}${NOTES_PATH}`); + assert.equal(request.init?.method, "POST"); + assert.equal(request.init?.body, body); + const headers = new Headers(request.init?.headers); + assert.equal(headers.get("content-type"), "application/json"); + assert.equal(headers.get("authorization"), `Bearer ${TOKEN}`); + assert.match(String(headers.get("firstdraft-client")), /^cli\//); +}); + +test("a note keeps each field only in its shape and says what it left out", async (context) => { + const cwd = projectDirectory(context, PRODUCTION); + for (const [ + argv, + note, + leftOut, + ] of /** @type {[string[], Record, string][]} */ ([ + [ + [ + "note", + "unclear_guidance", + "--page", + "references/plan/policies.md#roles", + "--code", + "foundation_plan.policy.unknown_role", + "--unclear", + "It never says whether a role can be empty", + "--workaround", + "Tried 'owner' and \"admin\" until one passed", + ], + { + kind: "unclear_guidance", + page: "references/plan/policies.md#roles", + code: "foundation_plan.policy.unknown_role", + unclear: "It never says whether a role can be empty", + workaround: "Tried […]", + }, + "", + ], + [ + [ + "note", + "unclear_guidance", + "--page", + "../secrets.md", + "--code", + "invalid_output_path", + "--unclear", + "It names no fix", + ], + { + kind: "unclear_guidance", + code: "invalid_output_path", + unclear: "It names no fix", + }, + "Left out: page, which is not SKILL.md or another path ending in .md.\n", + ], + [ + [ + "note", + "wrong_output", + "--source", + "analysis", + "--code", + "Foundation Plan", + "--expected", + "The Plan is valid", + "--actual", + "Analysis refused it", + "--workaround", + "\nsecond line", + ], + { + kind: "wrong_output", + source: "analysis", + expected: "The Plan is valid", + actual: "Analysis refused it", + }, + "Left out: code, which is not a diagnostic code or CLI error value; workaround, which has no plain words on its first line.\n", + ], + ])) { + /** @type {string | undefined} */ + let sent; + const result = await invoke(argv, { + cwd, + fetchFunction: reportsOn(async (_input, init) => { + sent = String(init?.body); + return stored({ kind: note.kind ?? "", compilation_id: null }); + }), + }); + assert.equal(result.status, 0, result.stderr); + assert(sent); + assert.deepEqual(JSON.parse(sent), { note }); + assert.equal( + result.stdout, + `Sending this ${note.kind} note to ${PRODUCTION}:\n${sent}${leftOut}Sent.\n`, + ); + } +}); + +test("a note about generated code names the recorded Compilation unless one is given", async (context) => { + const root = adoptedRoot(context); + writeRecord(path.join(root, ".firstdraft", "design", ".firstdraft")); + for (const [argv, expected] of /** @type {[string[], string][]} */ ([ + [[...GENERATED, "--file", "app/policies/movie_policy.rb:12"], RECORDED_ID], + [[...GENERATED, "--compilation-id", COMPILATION_ID], COMPILATION_ID], + ])) { + /** @type {string | undefined} */ + let sent; + const result = await invoke(argv, { + cwd: root, + fetchFunction: reportsOn(async (input, init) => { + assert.equal(String(input), `${PRODUCTION}${NOTES_PATH}`); + sent = String(init?.body); + return stored({ kind: "wrong_output", compilation_id: expected }); + }), + }); + assert.equal(result.status, 0, result.stderr); + assert(sent); + assert.equal(JSON.parse(sent).note.compilation_id, expected); + assert.equal( + result.stdout, + `Sending this wrong_output note for Compilation ${expected} to ${PRODUCTION}:\n${sent}Sent.\n`, + ); + } +}); + +test("a note about generated code with no Compilation given or recorded sends nothing", async (context) => { + const cwd = projectDirectory(context, PRODUCTION); + /** @type {string[]} */ + const urls = []; + const result = await invoke(GENERATED, { + cwd, + fetchFunction: async (input) => { + urls.push(String(input)); + return account("on"); + }, + }); + assert.deepEqual(urls, [`${PRODUCTION}/v1/account`]); + assert.equal(result.status, 1); + assert.equal(result.stdout, ""); + assert.deepEqual(JSON.parse(result.stderr), { + error: "compilation_not_recorded", + detail: + "No Compilation is recorded for this Project, so nothing was sent. 'firstdraft plan compile' and 'firstdraft compilation download' record the one whose code they write; to name one yourself, pass its compilation.id with --compilation-id.", + }); + + // Only a note about generated code names a Compilation. + const analysis = await invoke( + [ + "note", + "wrong_output", + "--source", + "analysis", + "--expected", + "Valid", + "--actual", + "Refused", + ], + { + cwd, + fetchFunction: reportsOn(async () => + stored({ kind: "wrong_output", compilation_id: null }), + ), + }, + ); + assert.equal(analysis.status, 0, analysis.stderr); +}); + +test("a required field with nothing left after shaping is refused locally", async (context) => { + const cwd = projectDirectory(context, PRODUCTION); + for (const [argv, detail] of /** @type {[string[], string][]} */ ([ + [ + ["note", "unstated_request", "--request", "\nThe person's email"], + "Nothing was sent, because a field the note needs did not fit its shape: request, which has no plain words on its first line. Run 'firstdraft note unstated_request --help' for what each field may hold.", + ], + [ + [ + "note", + "unclear_guidance", + "--page", + "references/../canary.md", + "--unclear", + " ", + ], + "Nothing was sent, because a field the note needs did not fit its shape: page, which is not SKILL.md or another path ending in .md; unclear, which has no plain words on its first line. Run 'firstdraft note unclear_guidance --help' for what each field may hold.", + ], + [ + [ + ...GENERATED.slice(0, 6), + "--actual", + "", + "--compilation-id", + COMPILATION_ID, + ], + "Nothing was sent, because a field the note needs did not fit its shape: actual, which has no plain words on its first line. Run 'firstdraft note wrong_output --help' for what each field may hold.", + ], + ])) { + /** @type {string[]} */ + const urls = []; + const result = await invoke(argv, { + cwd, + fetchFunction: async (input) => { + urls.push(String(input)); + return account("on"); + }, + }); + assert.deepEqual(urls, [`${PRODUCTION}/v1/account`], argv.join(" ")); + assert.equal(result.status, 2); + assert.equal(result.stdout, ""); + assert.deepEqual(JSON.parse(result.stderr), { + error: "note_incomplete", + detail, + }); + assert.doesNotMatch(result.stderr, /canary|email/); + } +}); + +test("with reports off, a note command sends nothing but the account read", async (context) => { + const cwd = projectDirectory(context, PRODUCTION); + for (const argv of [ + UNSTATED, + GENERATED, + ["note", "unstated_request", "--request", ""], + ]) { + /** @type {{url: string, init: RequestInit | undefined}[]} */ + const requests = []; + const result = await invoke(argv, { + cwd, + fetchFunction: async (input, init) => { + requests.push({ url: String(input), init }); + return account("off"); + }, + }); + assert.deepEqual(result, { status: 0, stdout: REPORTS_OFF, stderr: "" }); + assert.equal(requests.length, 1, argv.join(" ")); + assert.equal(requests[0]?.url, `${PRODUCTION}/v1/account`); + assert.equal(requests[0]?.init?.body, undefined); + } + + const turnedOff = await invoke(UNSTATED, { + cwd, + fetchFunction: reportsOn(async () => + problem(403, "reports_off", "Reports are off for this account."), + ), + }); + assert.equal(turnedOff.status, 0); + assert.equal(turnedOff.stderr, ""); + assert.match(turnedOff.stdout, /^Sending this unstated_request note /); + assert.ok(turnedOff.stdout.endsWith(REPORTS_OFF), turnedOff.stdout); +}); + +test("a note is not sent when the account cannot be read", async (context) => { + const cwd = projectDirectory(context, PRODUCTION); + const unavailable = + "Could not read whether this account sends reports and notes, so no note was sent. Continue without it."; + const invalid = + "First Draft returned an invalid account response, so no note was sent. Continue without it."; + for (const [ + response, + expected, + ] of /** @type {[() => Response, Record][]} */ ([ + [ + () => { + throw new TypeError("canary socket hang up"); + }, + { error: "account_unavailable", detail: unavailable }, + ], + [ + () => + new Response('{"reports":"canary"}', { + status: 200, + headers: { "Content-Type": "application/json" }, + }), + { error: "invalid_server_response", detail: invalid, status: 200 }, + ], + [ + () => + new Response(null, { status: 429, headers: { "Retry-After": "60" } }), + { error: "rate_limited", status: 429 }, + ], + ])) { + /** @type {string[]} */ + const urls = []; + const result = await invoke(UNSTATED, { + cwd, + fetchFunction: async (input) => { + urls.push(String(input)); + return response(); + }, + }); + assert.deepEqual(urls, [`${PRODUCTION}/v1/account`]); + assert.equal(result.status, 1); + assert.equal(result.stdout, ""); + const error = JSON.parse(result.stderr); + for (const [key, value] of Object.entries(expected)) { + assert.deepEqual(error[key], value, key); + } + assert.doesNotMatch(result.stderr, /canary/); + } +}); + +test("note refusals and unconfirmed outcomes are handled without retrying", async (context) => { + const cwd = projectDirectory(context, PRODUCTION); + const rejected = + "First Draft rejected the note, so it was not kept; response.code says why. Continue without it."; + const unavailable = + "Could not confirm that First Draft received the note, and First Draft may hold it already. Continue without it rather than sending it again."; + for (const [ + argv, + response, + expected, + ] of /** @type {[string[], () => Response, Record][]} */ ([ + [ + UNSTATED, + () => problem(400, "invalid_note", "request is not plain words."), + { + error: "note_rejected", + detail: rejected, + status: 400, + response: { + type: "about:blank", + title: "Bad Request", + status: 400, + code: "invalid_note", + detail: "request is not plain words.", + }, + }, + ], + [ + [...GENERATED, "--compilation-id", COMPILATION_ID], + () => + problem( + 409, + "compilation_not_succeeded", + "This Compilation produced no code.", + ), + { + error: "note_rejected", + detail: rejected, + status: 409, + response: { + type: "about:blank", + title: "Conflict", + status: 409, + code: "compilation_not_succeeded", + detail: "This Compilation produced no code.", + }, + }, + ], + [ + UNSTATED, + () => new Response("canary", { status: 502 }), + { error: "note_unavailable", detail: unavailable, status: 502 }, + ], + [ + UNSTATED, + () => { + throw new TypeError("canary socket hang up"); + }, + { error: "note_unavailable", detail: unavailable }, + ], + // A success without First Draft's acknowledgment confirms nothing. + [ + UNSTATED, + () => new Response("canary", { status: 200 }), + { error: "note_unavailable", detail: unavailable, status: 200 }, + ], + [ + UNSTATED, + () => + stored({ kind: "unstated_request", compilation_id: COMPILATION_ID }), + { error: "note_unavailable", detail: unavailable, status: 201 }, + ], + [ + UNSTATED, + () => + new Response( + JSON.stringify({ + progress_report: { id: STORED_ID, compilation_id: null }, + }), + { status: 201, headers: { "Content-Type": "application/json" } }, + ), + { error: "note_unavailable", detail: unavailable, status: 201 }, + ], + [ + [...GENERATED, "--compilation-id", COMPILATION_ID], + () => stored({ kind: "wrong_output", compilation_id: null }), + { error: "note_unavailable", detail: unavailable, status: 201 }, + ], + ])) { + let requests = 0; + const result = await invoke(argv, { + cwd, + fetchFunction: reportsOn(async () => { + requests += 1; + return response(); + }), + }); + assert.equal(requests, 1); + assert.equal(result.status, 1); + assert.match(result.stdout, /^Sending this /); + assert.doesNotMatch(result.stdout, /Sent\./); + assert.deepEqual(JSON.parse(result.stderr), expected); + assert.doesNotMatch(result.stderr, /canary/); + } + + const limited = await invoke(UNSTATED, { + cwd, + fetchFunction: reportsOn( + async () => + new Response(null, { status: 429, headers: { "Retry-After": "60" } }), + ), + }); + assert.equal(limited.status, 1); + assert.equal(JSON.parse(limited.stderr).error, "rate_limited"); + + const unauthenticated = await invoke(UNSTATED, { + cwd, + fetchFunction: reportsOn(async () => + problem(401, "authentication_required", "A valid token is required."), + ), + }); + assert.equal(unauthenticated.status, 1); + assert.equal( + JSON.parse(unauthenticated.stderr).error, + "authentication_required", + ); +}); + +test("notes stop on local problems before printing anything", async (context) => { + for (const [cwd, error] of [ + [projectDirectory(context), "project_not_pushed"], + [temporaryDirectory(context), "local_input_unreadable"], + ]) { + const result = await invoke(UNSTATED, { cwd }); + assert.equal(result.status, 1); + assert.equal(result.stdout, ""); + assert.equal(JSON.parse(result.stderr).error, error); + } + + const mismatch = await invoke([...UNSTATED, "--staging"], { + cwd: projectDirectory(context, PRODUCTION), + }); + assert.equal(mismatch.status, 2); + assert.equal(JSON.parse(mismatch.stderr).error, "invalid_configuration"); + + const noToken = await invoke(UNSTATED, { + cwd: projectDirectory(context, STAGING), + stagingApiToken: "", + }); + assert.equal(noToken.status, 1); + assert.equal(noToken.stdout, ""); + assert.equal(JSON.parse(noToken.stderr).error, "authentication_required"); +}); + +test("a staging Project's note goes to staging with its token", async (context) => { + /** @type {unknown} */ + let sent; + const result = await invoke(["--staging", ...UNSTATED], { + cwd: projectDirectory(context, STAGING), + fetchFunction: async (input, init) => { + assert.equal(new URL(String(input)).origin, STAGING); + assert.equal( + new Headers(init?.headers).get("authorization"), + `Bearer ${STAGING_TOKEN}`, + ); + if (new URL(String(input)).pathname === "/v1/account") { + return account("on"); + } + sent = JSON.parse(String(init?.body)); + return stored({ kind: "unstated_request", compilation_id: null }); + }, + }); + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(sent, { + note: { + kind: "unstated_request", + request: "A weekly digest email of new movies", + }, + }); +}); + +/** + * Answers the account read at the pinned production origin with reports on, + * and hands every other request to `note`. + * + * @param {(input: string | URL | Request, init?: RequestInit) => Promise} note + * @returns {typeof globalThis.fetch} + */ +function reportsOn(note) { + return async (input, init) => { + if (new URL(String(input)).pathname !== "/v1/account") { + return note(input, init); + } + assert.equal(String(input), `${PRODUCTION}/v1/account`); + return account("on"); + }; +} + +/** @param {"on" | "off"} reports */ +function account(reports) { + return new Response(JSON.stringify({ reports }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); +} + +/** + * First Draft's acknowledgment of a stored note. + * + * @param {{kind: string, compilation_id: string | null}} note + */ +function stored({ kind, compilation_id }) { + return new Response( + JSON.stringify({ + note: { + id: STORED_ID, + project_id: PROJECT_ID, + kind, + compilation_id, + created_at: "2026-11-21T12:00:00Z", + }, + }), + { status: 201, headers: { "Content-Type": "application/json" } }, + ); +} + +/** + * @param {number} status + * @param {string} code + * @param {string} detail + */ +function problem(status, code, detail) { + const titles = /** @type {Record} */ ({ + 400: "Bad Request", + 401: "Unauthorized", + 403: "Forbidden", + 404: "Not Found", + 409: "Conflict", + }); + return new Response( + JSON.stringify({ + type: "about:blank", + title: titles[status], + status, + code, + detail, + }), + { status, headers: { "Content-Type": "application/problem+json" } }, + ); +} + +/** @param {string} stateDirectory */ +function writeRecord(stateDirectory) { + writeFileSync( + path.join(stateDirectory, "compilation.json"), + `${JSON.stringify({ format: "firstdraft.cli-compilation/1", compilation_id: RECORDED_ID }, null, 2)}\n`, + ); +} + +/** + * @param {import("node:test").TestContext} context + * @param {string} [origin] + */ +function projectDirectory(context, origin) { + const cwd = temporaryDirectory(context); + mkdirSync(path.join(cwd, ".firstdraft")); + writeState(path.join(cwd, ".firstdraft"), origin); + return cwd; +} + +/** + * An application root that adopted its Project's directory: the Project's + * state is archived at .firstdraft/design/.firstdraft. + * + * @param {import("node:test").TestContext} context + */ +function adoptedRoot(context) { + const root = temporaryDirectory(context); + const design = path.join(root, ".firstdraft", "design", ".firstdraft"); + mkdirSync(design, { recursive: true }); + writeFileSync(path.join(root, ".firstdraft", "gaps.json"), "{}\n"); + writeState(design, PRODUCTION); + return root; +} + +/** + * @param {string} stateDirectory + * @param {string} [origin] + */ +function writeState(stateDirectory, origin) { + writeFileSync( + path.join(stateDirectory, "state.json"), + `${JSON.stringify({ + format: "firstdraft.cli-state/1", + project_id: PROJECT_ID, + ...(origin + ? { + api_url: origin, + foundation_plan_etag: '"sha256:' + "1".repeat(64) + '"', + } + : {}), + })}\n`, + ); +} + +/** @param {import("node:test").TestContext} context */ +function temporaryDirectory(context) { + const cwd = realpathSync( + mkdtempSync(path.join(tmpdir(), "firstdraft-note-")), + ); + context.after(() => rmSync(cwd, { recursive: true, force: true })); + return cwd; +} + +/** @param {readonly string[]} argv @param {Partial} [options] */ +async function invoke(argv, options = {}) { + let stdout = ""; + let stderr = ""; + const status = await run({ + argv, + stdout: { write: (text) => (stdout += text) }, + stderr: { write: (text) => (stderr += text) }, + cwd: CWD, + apiToken: TOKEN, + stagingApiToken: STAGING_TOKEN, + apiUrl: undefined, + env: { XDG_CONFIG_HOME: "/nonexistent/firstdraft-test-config" }, + fetchFunction: async () => assert.fail("No network request was expected"), + ...options, + }); + return { status, stdout, stderr }; +} diff --git a/test/plan-compile.test.js b/test/plan-compile.test.js index cbede3e..28b5a2a 100644 --- a/test/plan-compile.test.js +++ b/test/plan-compile.test.js @@ -7,6 +7,7 @@ import { readFileSync, realpathSync, rmSync, + statSync, writeFileSync, } from "node:fs"; import { createServer } from "node:http"; @@ -243,6 +244,21 @@ test("plan compile --output completes the HTTP journey without GitHub Publicatio readFileSync(path.join(cwd, "application", "README.md"), "utf8"), "Movie Catalog\n", ); + // Reports and notes from the Project's directory name this Compilation. + const record = path.join(cwd, ".firstdraft", "compilation.json"); + assert.equal( + readFileSync(record, "utf8"), + `{\n "format": "firstdraft.cli-compilation/1",\n "compilation_id": "${COMPILATION_ID}"\n}\n`, + ); + if (process.platform !== "win32") { + assert.equal(statSync(record).mode & 0o777, 0o600); + } + assert.equal( + existsSync( + path.join(cwd, "application", ".firstdraft", "compilation.json"), + ), + false, + ); assert.equal( result.stderr, `First Draft: Analyzing Foundation Plan...\nFirst Draft: Foundation Plan analysis valid.\nFirst Draft: Compiling application...\nFirst Draft: Application compiled.\n`, @@ -293,6 +309,11 @@ test("plan compile may push unchanged bytes before analysis and Publication", as assert.deepEqual(order, [["push", cwd], ["analysis", true], ["publication"]]); assert.equal(result.stdout, `${REPOSITORY_URL}\n`); assert.equal(result.stderr, SUCCESS_PROGRESS); + // Publication writes no code into this folder, so nothing is recorded. + assert.equal( + existsSync(path.join(cwd, ".firstdraft", "compilation.json")), + false, + ); }); test("plan compile --output starts a direct Compilation without Publication", async (context) => { @@ -357,6 +378,40 @@ test("plan compile --output starts a direct Compilation without Publication", as ); }); +test("a Compilation record that cannot be written leaves the result and says so", async (context) => { + const cwd = localDirectory(context, PLAN_SOURCE, { + api_url: "https://api.example.test", + foundation_plan_etag: ETAG, + }); + // A directory in the record's place makes the rename fail. + mkdirSync(path.join(cwd, ".firstdraft", "compilation.json")); + const directResult = { + project: { id: PROJECT_ID, graph_version: 1 }, + compilation: { id: COMPILATION_ID, status: "succeeded" }, + output: { path: path.join(cwd, "application"), file_count: 1 }, + }; + const result = await invoke( + ["plan", "compile", "--output", "./application"], + { + cwd, + planCompilePush: async () => successfulPush(), + planCompileReadStatus: async () => ({ + status: 200, + body: analysisBody("valid"), + }), + planCompileDownload: async () => directResult, + }, + ); + + assert.equal(result.status, 0); + assert.deepEqual(JSON.parse(result.stdout), directResult); + assert.equal( + result.stderr, + `First Draft: Analyzing Foundation Plan...\nFirst Draft: Foundation Plan analysis valid.\n` + + `First Draft: the code is in place, but the CLI could not record Compilation ${COMPILATION_ID} for later reports and notes. Name it in each: put it right after 'report progress' or 'report failure', and pass it with --compilation-id to a note about generated code.\n`, + ); +}); + test("plan compile root output locks before push and releases after invalid analysis", async (context) => { if (process.platform === "win32") return context.skip(); const cwd = localDirectory(context, PLAN_SOURCE); diff --git a/test/report.test.js b/test/report.test.js index 3ccec7e..037f3a4 100644 --- a/test/report.test.js +++ b/test/report.test.js @@ -90,8 +90,15 @@ test("report help lists both reports and each report's options", async () => { test("report progress validates its arguments before any request", async () => { for (const argv of [ - ["report", "progress", "--step", "setup"], ["report", "progress", "not-a-uuid", "--step", "setup"], + [ + "report", + "progress", + "0190000A-0000-7000-8000-000000009101", + "--step", + "setup", + ], + ["report", "progress", "--step", "setup", "--examples", "x"], ["report", "progress", COMPILATION_ID], ["report", "progress", COMPILATION_ID, "--step", "canary"], [...PROGRESS, "--step", "setup"], @@ -836,6 +843,123 @@ test("reports run from an adopted application root find the archived Project", a ); }); +test("a report without an id names the Compilation the CLI recorded", async (context) => { + const recorded = "01900000-0000-7000-8000-000000009102"; + const root = temporaryDirectory(context); + const design = path.join(root, ".firstdraft", "design", ".firstdraft"); + mkdirSync(design, { recursive: true }); + writeFileSync( + path.join(design, "state.json"), + `${JSON.stringify({ + format: "firstdraft.cli-state/1", + project_id: PROJECT_ID, + api_url: PRODUCTION, + foundation_plan_etag: '"sha256:' + "1".repeat(64) + '"', + })}\n`, + ); + writeRecord(design, recorded); + + for (const [argv, expected] of /** @type {[string[], string][]} */ ([ + [["report", "progress", "--step", "setup"], recorded], + [["report", "failure", "--kind", "boot_error"], recorded], + // A given id takes the place of the recorded one. + [PROGRESS, COMPILATION_ID], + ])) { + /** @type {string[]} */ + const urls = []; + const result = await invoke(argv, { + cwd: root, + fetchFunction: reportsOn(async (input) => { + urls.push(String(input)); + return new Response( + JSON.stringify({ + [String(input).endsWith("/progress-reports") + ? "progress_report" + : "failure_report"]: { id: STORED_ID, compilation_id: expected }, + }), + { status: 201, headers: { "Content-Type": "application/json" } }, + ); + }), + }); + assert.equal(result.status, 0, result.stderr); + assert.equal(urls.length, 1); + assert.match( + String(urls[0]), + new RegExp(`/v1/projects/${PROJECT_ID}/compilations/${expected}/`), + ); + assert.match(result.stdout, new RegExp(`for Compilation ${expected} to `)); + assert.ok(result.stdout.endsWith("Sent.\n")); + } +}); + +test("a report with no Compilation given or recorded sends nothing", async (context) => { + const cwd = projectDirectory(context, PRODUCTION); + for (const argv of [ + ["report", "progress", "--step", "setup"], + ["report", "failure", "--kind", "boot_error"], + ]) { + /** @type {string[]} */ + const urls = []; + const result = await invoke(argv, { + cwd, + fetchFunction: reportsOn(async (input) => { + urls.push(String(input)); + return acknowledgment("progress_report"); + }), + }); + assert.deepEqual(urls, []); + assert.equal(result.status, 1); + assert.equal(result.stdout, ""); + assert.deepEqual(JSON.parse(result.stderr), { + error: "compilation_not_recorded", + detail: + "No Compilation is recorded for this Project, so nothing was sent. 'firstdraft plan compile' and 'firstdraft compilation download' record the one whose code they write; to name one yourself, put its compilation.id right after 'report progress' or 'report failure'.", + }); + + // With reports off, the account read settles it first. + const off = await invoke(argv, { + cwd, + fetchFunction: async () => account("off"), + }); + assert.deepEqual(off, { status: 0, stdout: REPORTS_OFF, stderr: "" }); + } +}); + +test("a malformed Compilation record is reported, and nothing is sent", async (context) => { + const cwd = projectDirectory(context, PRODUCTION); + for (const source of [ + "{canary\n", + `${JSON.stringify({ format: "firstdraft.cli-compilation/1", compilation_id: "canary" })}\n`, + `${JSON.stringify({ format: "firstdraft.cli-state/1", compilation_id: COMPILATION_ID })}\n`, + `${JSON.stringify({ format: "firstdraft.cli-compilation/1", compilation_id: COMPILATION_ID, canary: 1 })}\n`, + ]) { + writeFileSync(path.join(cwd, ".firstdraft", "compilation.json"), source); + const result = await invoke(["report", "progress", "--step", "setup"], { + cwd, + fetchFunction: reportsOn(async () => + assert.fail("No report was expected"), + ), + }); + assert.equal(result.status, 1); + assert.equal(result.stdout, ""); + assert.equal(JSON.parse(result.stderr).error, "local_input_unreadable"); + assert.doesNotMatch(result.stderr, /canary/); + } +}); + +/** + * Writes the record that plan compile and compilation download leave. + * + * @param {string} stateDirectory + * @param {string} compilationId + */ +function writeRecord(stateDirectory, compilationId) { + writeFileSync( + path.join(stateDirectory, "compilation.json"), + `${JSON.stringify({ format: "firstdraft.cli-compilation/1", compilation_id: compilationId }, null, 2)}\n`, + ); +} + /** * Answers the account read at the pinned production origin with reports on, * and hands every other request to `report`. diff --git a/test/start.test.js b/test/start.test.js index 3564987..4ae064f 100644 --- a/test/start.test.js +++ b/test/start.test.js @@ -34,10 +34,16 @@ when First Draft accepted the login. `; const REPORTS_ON = [ - "Reports are on: this person agreed that you send First Draft progress and failure reports about the code it generates.", - "Progress: run 'firstdraft report progress --step ' when bin/setup finishes (setup), when the first spec run finishes (specs_first_run), when every item under the README's Behavior to write is written (behavior_written), when the specs pass (specs_passing), and when the preview starts (preview_started). Add the counts you have; 'firstdraft report progress --help' lists them.", - "Failure: when generated code fails in a way the README does not list, run 'firstdraft report failure --kind ' once you have fixed it or stopped trying, where is setup_failure, spec_failure, boot_error, or lint_failure; 'firstdraft report failure --help' lists the other fields.", - "Use compilation.id from 'firstdraft plan compile', and run each report command from the generated application's root, or from the Project's directory after --output. Each prints what it sends: pass only text that may leave this computer, never secrets or the person's data.", + "Reports are on: this person agreed that you send First Draft progress and failure reports about the code it generates, and notes about problems with First Draft itself.", + "Progress: run 'firstdraft report progress --step ' when bin/setup finishes (setup), when the first spec run finishes (specs_first_run), when every item under the README's Behavior to write is written (behavior_written), when the specs pass (specs_passing), and when the preview starts (preview_started). Add the counts you have; 'firstdraft report progress --help' lists them.", + "Failure: when generated code fails in a way the README does not list, run 'firstdraft report failure --kind ' once you have fixed it or stopped trying, where is setup_failure, spec_failure, boot_error, or lint_failure; 'firstdraft report failure --help' lists the other fields.", + "Each report names the Compilation whose code 'firstdraft plan compile' or 'firstdraft compilation download' last wrote for this Project, which the CLI records; to name a different one, put its compilation.id right after 'report progress' or 'report failure'.", + "Run each report and note command from the generated application's root, or from the Project's directory before the code is written or after --output. Each prints what it sends: pass only text that may leave this computer, never secrets or the person's data.", + "Notes: send a note only when a problem with First Draft cost you a real detour and is likely to happen again, never for routine debugging, and only after the Plan has been pushed once with 'firstdraft plan push' or 'firstdraft plan compile'.", + "Unstated request: when the person asked for something the Plan could not state, run 'firstdraft note unstated_request --request ', adding --workaround for what you wrote in the Plan instead or left for later.", + "Unclear guidance: when a Skill page or a diagnostic was unclear, run 'firstdraft note unclear_guidance --page --unclear ', where is the page's path inside the Skill, such as SKILL.md or references/plan/policies.md; for a diagnostic code or a CLI error value, give --code in place of or beside --page, and add --workaround for what you did instead.", + "Wrong output: when analysis or generated code was wrong, run 'firstdraft note wrong_output --source --expected --actual ', where is analysis or generated_code; a note about generated code names the recorded Compilation as a report does, and 'firstdraft note wrong_output --help' lists --code, --file, and --workaround.", + "Write each note in your own plain words, at most 300 characters a field: never secrets, credentials, personal data, or code from the person's project.", ]; test("start help is printed without a request", async (context) => { @@ -180,7 +186,7 @@ test("with reports off, start says nothing about reports", async (context) => { "Ready: First Draft accepted this computer's login.", ), ); - assert.doesNotMatch(result.stdout + result.stderr, /report/i); + assert.doesNotMatch(result.stdout + result.stderr, /report|note/i); }); test("start says when an environment token takes the place of the saved login", async (context) => { From ea2b52e34e3ef877762d037b345e8b7561dcf9e1 Mon Sep 17 00:00:00 2001 From: Raghu Betina Date: Sat, 21 Nov 2026 21:15:33 -0600 Subject: [PATCH 2/4] Say what report and note read and send The command reference said a note reads no file, but it reads the Project's state and, for generated code without an ID, the Compilation record. The README said both commands send nothing with reports off, but each still reads the account. And when the record cannot be written, the earlier one stays, so the warning and the reference now say a later report may name an earlier Compilation. --- README.md | 2 +- docs/commands.md | 16 ++++++++++------ src/cli.js | 2 +- test/plan-compile.test.js | 2 +- 4 files changed, 13 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 8540244..e5f9eb5 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,7 @@ The published package: - has no runtime dependencies or install scripts; - sends nothing in the background or beyond the command the caller runs. [What the CLI sends](docs/commands.md#what-the-cli-sends) lists each command's requests and their `FirstDraft-Client` header: CLI and plugin versions, agent, and operating - system. `report` and `note` send nothing while reports are off and print exactly what they send before sending it; + system. `report` and `note` read the account first and, only with reports on, print their exact body and then send it; - makes no update check of its own: its update line comes from First Draft's answer to the command; - reads Bearer credentials from the environment or its private `firstdraft login` credentials file; and - carries npm provenance linking registry bytes to its GitHub workflow and commit. diff --git a/docs/commands.md b/docs/commands.md index 54d3abd..6175639 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -598,9 +598,10 @@ format of `state.json`, and it sits in the same planning folder, whose ignore fi The CLI writes it with mode `0600` through a temporary file and a rename, replacing the previous record, so it names the Compilation whose code the CLI wrote last for the Project, wherever that code went. `plan compile --github` writes -no code into the folder and records nothing. If the record cannot be written, the command keeps its result, and one -`First Draft:` line on standard error names the Compilation to pass to later reports and notes. A record that is not -exactly this shape stops a report or note with `local_input_unreadable`. +no code into the folder and records nothing. If the record cannot be written, the command keeps its result, any earlier +record stays as it was, and one `First Draft:` line on standard error names the Compilation to pass to later reports +and notes. Only a report, or a note about generated code, that names no Compilation reads the record; one that is not +exactly this shape stops it with `local_input_unreadable`. ### Publish through GitHub @@ -783,7 +784,8 @@ Free text keeps plain words only: the CLI takes the first line, replaces everyth quote character (`'`, `"`, or a backtick, including an apostrophe inside a word) to the end of the line with one `[…]`, replaces each earlier word that contains `=`, `/`, `\`, or `@` or is longer than 24 characters with `[…]`, and keeps the words that fit the length limit. A `lint_failure` therefore sends no rule name, and a rerun command that is not an -RSpec run is left out. The CLI reads no file for a failure report and attaches no diff or environment variable, but +RSpec run is left out. Besides the Project's state and the Compilation record, the CLI reads no file for a failure +report and attaches no diff or environment variable, but the plain words of a message or fix summary it is given can still quote code, so pass only text that may be sent. Each command first reads the account with a `GET` of `/v1/account` at the origin pinned by a successful push. Unless @@ -863,8 +865,10 @@ line and exits 0, having checked nothing else. With reports on: First Draft answers `403 reports_off` when the person turned reports off after the account read, and the command writes the reports-off line and exits 0. A refusal, such as `invalid_note`, `compilation_not_found`, or `compilation_not_succeeded`, is `note_rejected`; a network failure or server error is `note_unavailable`; and an -account's limit of 30 notes an hour is `rate_limited`. The command never retries. It reads no file and no conversation: -a note holds only what its options give, so pass only text that may be sent, and never code from the person's project. +account's limit of 30 notes an hour is `rate_limited`. The command never retries. It reads the Project's state, and the +Compilation record only for a note about generated code without `--compilation-id`; it reads no file of the +application and no conversation. A note holds only what its options give, plus that recorded ID, so pass only text +that may be sent, and never code from the person's project. ## Service endpoints diff --git a/src/cli.js b/src/cli.js index 6a745bf..e398ba0 100644 --- a/src/cli.js +++ b/src/cli.js @@ -4147,7 +4147,7 @@ function recordWrittenCompilation(stderr, cwd, compilationId) { if (!(error instanceof CompilationRecordWriteError)) throw error; stderr.write( - `First Draft: the code is in place, but the CLI could not record Compilation ${compilationId} for later reports and notes. Name it in each: put it right after 'report progress' or 'report failure', and pass it with --compilation-id to a note about generated code.\n`, + `First Draft: the code is in place, but the CLI could not record Compilation ${compilationId}, so later reports and notes may name an earlier Compilation or none. Name it in each: put it right after 'report progress' or 'report failure', and pass it with --compilation-id to a note about generated code.\n`, ); } } diff --git a/test/plan-compile.test.js b/test/plan-compile.test.js index 28b5a2a..57e2ae2 100644 --- a/test/plan-compile.test.js +++ b/test/plan-compile.test.js @@ -408,7 +408,7 @@ test("a Compilation record that cannot be written leaves the result and says so" assert.equal( result.stderr, `First Draft: Analyzing Foundation Plan...\nFirst Draft: Foundation Plan analysis valid.\n` + - `First Draft: the code is in place, but the CLI could not record Compilation ${COMPILATION_ID} for later reports and notes. Name it in each: put it right after 'report progress' or 'report failure', and pass it with --compilation-id to a note about generated code.\n`, + `First Draft: the code is in place, but the CLI could not record Compilation ${COMPILATION_ID}, so later reports and notes may name an earlier Compilation or none. Name it in each: put it right after 'report progress' or 'report failure', and pass it with --compilation-id to a note about generated code.\n`, ); }); From 196eca03376d7e2fce33f8049721b74f24a79701 Mon Sep 17 00:00:00 2001 From: Raghu Betina Date: Sat, 21 Nov 2026 21:19:43 -0600 Subject: [PATCH 3/4] Name the last recorded Compilation as the default After a record write fails, the record still names an earlier Compilation, so start, the report help, and the wrong_output help now say that omitting the ID uses the Compilation the CLI last recorded, not the one it last wrote. --- docs/commands.md | 4 ++-- src/agent-sentences.js | 2 +- src/cli.js | 12 +++++++----- src/plan-state.js | 6 +++--- test/start.test.js | 2 +- 5 files changed, 14 insertions(+), 12 deletions(-) diff --git a/docs/commands.md b/docs/commands.md index 6175639..b66b1b3 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -298,7 +298,7 @@ when `FIRSTDRAFT_PLUGIN_VERSION` holds a version. When First Draft names a newer Reports are on: this person agreed that you send First Draft progress and failure reports about the code it generates, and notes about problems with First Draft itself. Progress: run 'firstdraft report progress --step ' when bin/setup finishes (setup), when the first spec run finishes (specs_first_run), when every item under the README's Behavior to write is written (behavior_written), when the specs pass (specs_passing), and when the preview starts (preview_started). Add the counts you have; 'firstdraft report progress --help' lists them. Failure: when generated code fails in a way the README does not list, run 'firstdraft report failure --kind ' once you have fixed it or stopped trying, where is setup_failure, spec_failure, boot_error, or lint_failure; 'firstdraft report failure --help' lists the other fields. - Each report names the Compilation whose code 'firstdraft plan compile' or 'firstdraft compilation download' last wrote for this Project, which the CLI records; to name a different one, put its compilation.id right after 'report progress' or 'report failure'. + Each report names the Compilation that the CLI last recorded for this Project when 'firstdraft plan compile' or 'firstdraft compilation download' wrote its code; to name a different one, put its compilation.id right after 'report progress' or 'report failure'. Run each report and note command from the generated application's root, or from the Project's directory before the code is written or after --output. Each prints what it sends: pass only text that may leave this computer, never secrets or the person's data. Notes: send a note only when a problem with First Draft cost you a real detour and is likely to happen again, never for routine debugging, and only after the Plan has been pushed once with 'firstdraft plan push' or 'firstdraft plan compile'. Unstated request: when the person asked for something the Plan could not state, run 'firstdraft note unstated_request --request ', adding --workaround for what you wrote in the Plan instead or left for later. @@ -760,7 +760,7 @@ firstdraft report failure --kind spec_failure \ The full forms are `firstdraft report progress [] --step [counts]` and `firstdraft report failure [] --kind [options]`. A report names one Compilation: the `` given, which is `compilation.id` from `plan compile`, or else the one the CLI -[recorded](#record-the-compilation-whose-code-was-written) when it last wrote a Compilation's code for the Project. +[last recorded](#record-the-compilation-whose-code-was-written) for the Project when it wrote a Compilation's code. So an agent can report in a later session, after another Compile, or during maintenance without carrying the ID. With none given and none recorded, the command sends nothing and ends with `compilation_not_recorded`. `--step` is `setup`, `specs_first_run`, `behavior_written`, `specs_passing`, or `preview_started`. The counts are optional whole numbers of at most 1000000: diff --git a/src/agent-sentences.js b/src/agent-sentences.js index 3049652..b586b64 100644 --- a/src/agent-sentences.js +++ b/src/agent-sentences.js @@ -86,7 +86,7 @@ export const REPORTS_ON_LINES = Object.freeze([ "Reports are on: this person agreed that you send First Draft progress and failure reports about the code it generates, and notes about problems with First Draft itself.", "Progress: run 'firstdraft report progress --step ' when bin/setup finishes (setup), when the first spec run finishes (specs_first_run), when every item under the README's Behavior to write is written (behavior_written), when the specs pass (specs_passing), and when the preview starts (preview_started). Add the counts you have; 'firstdraft report progress --help' lists them.", "Failure: when generated code fails in a way the README does not list, run 'firstdraft report failure --kind ' once you have fixed it or stopped trying, where is setup_failure, spec_failure, boot_error, or lint_failure; 'firstdraft report failure --help' lists the other fields.", - "Each report names the Compilation whose code 'firstdraft plan compile' or 'firstdraft compilation download' last wrote for this Project, which the CLI records; to name a different one, put its compilation.id right after 'report progress' or 'report failure'.", + "Each report names the Compilation that the CLI last recorded for this Project when 'firstdraft plan compile' or 'firstdraft compilation download' wrote its code; to name a different one, put its compilation.id right after 'report progress' or 'report failure'.", "Run each report and note command from the generated application's root, or from the Project's directory before the code is written or after --output. Each prints what it sends: pass only text that may leave this computer, never secrets or the person's data.", ]); diff --git a/src/cli.js b/src/cli.js index e398ba0..5002f8f 100644 --- a/src/cli.js +++ b/src/cli.js @@ -251,8 +251,8 @@ Environment: The command first reads the account at the origin pinned by a successful plan push. With reports on, it prints the exact report, then sends it once there. With reports off, it sends no report and still exits 0. Without -, the report names the Compilation whose code plan compile or -compilation download last wrote for the Project. +, the report names the Compilation the CLI last recorded for +the Project when plan compile or compilation download wrote its code. `; const REPORT_FAILURE_HELP = `First Draft CLI @@ -284,8 +284,9 @@ version numbers, and the plain words of free text. It first reads the account at the origin pinned by a successful plan push. With reports on, it prints the exact report and what it left out, then sends it once there. With reports off, it sends no report and still exits 0. Run it from the generated application's -root. Without , the report names the Compilation whose code -plan compile or compilation download last wrote for the Project. +root. Without , the report names the Compilation the CLI last +recorded for the Project when plan compile or compilation download wrote its +code. `; const NOTE_HELP = `First Draft CLI @@ -374,7 +375,8 @@ Options: ${NOTE_ENVIRONMENT} Without --compilation-id, a note about generated code names the Compilation -whose code plan compile or compilation download last wrote for the Project. +the CLI last recorded for the Project when plan compile or compilation +download wrote its code. ${NOTE_TRAILER}`; const PLAN_HELP = `First Draft CLI diff --git a/src/plan-state.js b/src/plan-state.js index 33288d0..f21a756 100644 --- a/src/plan-state.js +++ b/src/plan-state.js @@ -83,9 +83,9 @@ function pinnedProjectDirectory(cwd, fileSystem) { return adoptedRoot ? path.join(cwd, ".firstdraft", "design") : cwd; } -// The Compilation whose code the CLI last wrote for the Project, kept in its -// own file beside state.json so the state format stays as it is. It moves -// with the planning state into an adopted root's archive. +// The Compilation whose code the CLI last recorded writing for the Project, +// kept in its own file beside state.json so the state format stays as it +// is. It moves with the planning state into an adopted root's archive. const COMPILATION_RECORD_NAME = "compilation.json"; const COMPILATION_RECORD_FORMAT = "firstdraft.cli-compilation/1"; diff --git a/test/start.test.js b/test/start.test.js index 4ae064f..7b3ad6f 100644 --- a/test/start.test.js +++ b/test/start.test.js @@ -37,7 +37,7 @@ const REPORTS_ON = [ "Reports are on: this person agreed that you send First Draft progress and failure reports about the code it generates, and notes about problems with First Draft itself.", "Progress: run 'firstdraft report progress --step ' when bin/setup finishes (setup), when the first spec run finishes (specs_first_run), when every item under the README's Behavior to write is written (behavior_written), when the specs pass (specs_passing), and when the preview starts (preview_started). Add the counts you have; 'firstdraft report progress --help' lists them.", "Failure: when generated code fails in a way the README does not list, run 'firstdraft report failure --kind ' once you have fixed it or stopped trying, where is setup_failure, spec_failure, boot_error, or lint_failure; 'firstdraft report failure --help' lists the other fields.", - "Each report names the Compilation whose code 'firstdraft plan compile' or 'firstdraft compilation download' last wrote for this Project, which the CLI records; to name a different one, put its compilation.id right after 'report progress' or 'report failure'.", + "Each report names the Compilation that the CLI last recorded for this Project when 'firstdraft plan compile' or 'firstdraft compilation download' wrote its code; to name a different one, put its compilation.id right after 'report progress' or 'report failure'.", "Run each report and note command from the generated application's root, or from the Project's directory before the code is written or after --output. Each prints what it sends: pass only text that may leave this computer, never secrets or the person's data.", "Notes: send a note only when a problem with First Draft cost you a real detour and is likely to happen again, never for routine debugging, and only after the Plan has been pushed once with 'firstdraft plan push' or 'firstdraft plan compile'.", "Unstated request: when the person asked for something the Plan could not state, run 'firstdraft note unstated_request --request ', adding --workaround for what you wrote in the Plan instead or left for later.", From effb9b58a17e34eaa16925c7b4b301edec5c9551 Mon Sep 17 00:00:00 2001 From: Raghu Betina Date: Sat, 21 Nov 2026 21:58:52 -0600 Subject: [PATCH 4/4] Test notes against the service's shape cases The CLI and the First Draft service had each written their own examples of what a note's fields may hold. Each side passed the other's, but two files can drift apart unseen. The fixture is now a copy of the service's file, byte for byte, as the failure-report fixture is, so both sides test the same strings. Prettier leaves it alone for the same reason. --- .prettierignore | 1 + test/fixtures/note-shapes.json | 251 ++++++++++++++++++++++++++------- test/note-shapes.test.js | 5 +- 3 files changed, 203 insertions(+), 54 deletions(-) diff --git a/.prettierignore b/.prettierignore index 7fa036a..213891d 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1 +1,2 @@ test/fixtures/failure-report-shapes.json +test/fixtures/note-shapes.json diff --git a/test/fixtures/note-shapes.json b/test/fixtures/note-shapes.json index 73ba726..527df89 100644 --- a/test/fixtures/note-shapes.json +++ b/test/fixtures/note-shapes.json @@ -1,18 +1,36 @@ { - "about": "Examples of what the First Draft service accepts and refuses in each note field and in whole notes, written from the notes contract's rules. The service tests its own copy of these cases, and the CLI tests its shaping against this one. limit is a field's longest accepted length in characters.", + "about": "Examples of what the service accepts and refuses in each field of a note, and in whole notes. The service tests Project::Note against this file, and the CLI tests its own shaping against a copy. A compilation_id that does not fit is answered with invalid_compilation_id; every other refusal here is invalid_note. Every example here is a string; the service also refuses a field that is not one. docs/architecture/reference/README.md#current-account-and-report-http states the rules.", "fields": { "kind": { "accepted": ["unstated_request", "unclear_guidance", "wrong_output"], - "refused": ["", "unstated-request", "Wrong_output", "bug", "progress"] + "refused": [ + "", + "praise", + "Unstated_request", + "unstated request", + "wrong-output", + "unstated-request", + "Wrong_output", + "bug", + "progress" + ] }, "request": { "accepted": [ + "A waitlist when an event is full", + "Let guests pay at the door […]", + "Send a reminder 24 hours before the party, and again […]", "A weekly digest email of new movies", "Members invite others by […]", "Validation failed: Email has already been taken", "[…] […] expected 3, got 4" ], "refused": [ + "Import guests from 'Airtable'", + "Sync with https://example.com", + "Email sam@example.com when a guest signs up", + "two\nlines", + "token abcdefghijklmnopqrstuvwxyz", "Send mail to sam@example.com", "Use the 'owner' role", "Setting \"secret value\"", @@ -22,8 +40,6 @@ "Read /tmp/sample.log", "see https://example.com", "path C:\\Users", - "token abcdefghijklmnopqrstuvwxyz", - "two\nlines", "two\rlines", "two\u2028lines", "two\u2029lines", @@ -33,8 +49,16 @@ "limit": 300 }, "workaround": { - "accepted": ["Left it for later", "Wrote a […] field instead"], + "accepted": [ + "Left the waitlist for later in the README.", + "Used a yes-or-no Field instead […]", + "Left it for later", + "Wrote a […] field instead" + ], "refused": [ + "Set API_KEY=abc in […]", + "Wrote it in app/models/event.rb", + "Ran `bin/rails db:seed`", "Set TOKEN=abc in […]", "Moved it to app/models", "Used 'admin'" @@ -43,34 +67,75 @@ }, "unclear": { "accepted": [ + "It does not say whether a Reference can point at the Account Entity.", + "The fix names a key the Plan does not have.", "It never says whether a role can be empty", "It names no fix" ], - "refused": ["It says `role: owner`", "See references/plan/policies.md"], + "refused": [ + "It says \"use owner\" without an example", + "two\u2028lines", + "one\ttab", + "It says `role: owner`", + "See references/plan/policies.md" + ], "limit": 300 }, "expected": { - "accepted": ["Only the owner edits a movie", "The Plan is valid"], - "refused": ["owner_id == current_user.id", "scope = Movie.mine"], + "accepted": [ + "Deleting a Movie deletes its Credits", + "The index page lists every Post.", + "Only the owner edits a movie", + "The Plan is valid" + ], + "refused": [ + "Visit /posts to see the list", + "It returns 'none'", + "owner_id == current_user.id", + "scope = Movie.mine" + ], "limit": 300 }, "actual": { - "accepted": ["Any member can edit it", "Analysis refused it"], - "refused": ["raise 'not allowed'", "user@example.com could edit"], + "accepted": [ + "Deleting a Movie raised […]", + "The page showed 3 of 4 posts", + "Any member can edit it", + "Analysis refused it" + ], + "refused": [ + "Raised NoMethodError at app/models/post.rb:12", + "Failed in C:\\app", + "two\rlines", + "raise 'not allowed'", + "user@example.com could edit" + ], "limit": 300 }, "page": { "accepted": [ "SKILL.md", + "references/modeling-guide.md", + "references/modeling-guide.md#associations", + "references/foundation-plan-023.md#field_types", "references/interview.md", "references/plan/policies.md", "references/plan/policies.md#roles", "references/modeling-guide.md#state_machines-2" ], "refused": [ + "SKILL", "", + "references/modeling-guide.txt", + "/references/interview.md", "../SKILL.md", "references/../SKILL.md", + "references/interview.md#", + "references/interview.md#a.b", + "references/interview.md#a b", + "https://example.com/SKILL.md", + "references\\interview.md", + "SKILL.md\n", "/Users/sam/skills/SKILL.md", "references/plan/policies", "references/plan/policies.txt", @@ -79,13 +144,16 @@ "references//policies.md", "SKILL.md#", "SKILL.md#a.b", - "SKILL.md#roles#more", - "https://example.com/SKILL.md" + "SKILL.md#roles#more" ], "limit": 200 }, "code": { "accepted": [ + "foundation_plan.association.cycle", + "reports_off", + "compilation.render_failed", + "invalid_note", "invalid_output_path", "report_rejected", "foundation_plan.identity.reserved_constant_collision", @@ -93,6 +161,13 @@ ], "refused": [ "", + "Foundation_plan.association.cycle", + "foundation-plan.association.cycle", + "foundation_plan..cycle", + ".cycle", + "cycle.", + "foundation_plan.association.cycle extra", + "reports_off\n", "Foundation_plan.identity", "foundation-plan.identity", "foundation_plan..identity", @@ -106,37 +181,54 @@ }, "source": { "accepted": ["analysis", "generated_code"], - "refused": ["", "Analysis", "generated-code", "code", "plan"] + "refused": ["", "Analysis", "generated code", "compiler", "generated-code", "code", "plan"] }, "compilation_id": { "accepted": [ + "01900000-0000-7000-8000-000000000002", + "019a8c3e-5f1b-7c2d-8e4f-0123456789ab", "01900000-0000-7000-8000-000000000001", "0190ab12-cdef-7abc-9def-0123456789ab" ], "refused": [ "", + "01900000-0000-4000-8000-000000000002", + "01900000-0000-7000-8000-00000000000A", + "01900000000070008000000000000002", + "not-a-uuid", "0190AB12-CDEF-7ABC-9DEF-0123456789AB", "01900000-0000-4000-8000-000000000001", "01900000-0000-7000-c000-000000000001", - "01900000000070008000000000000001", - "not-a-uuid" + "01900000000070008000000000000001" ] }, "file": { "accepted": [ + "Gemfile", + "app/models/post.rb", + "app/models/post.rb:12", + "app/views/posts/_form.html.erb:7", + "spec/system/posts_spec.rb:42", "app/models/movie.rb", "app/models/movie.rb:12", "app/views/movies/_form.html.erb:9", "db/migrate/20261121000000_create_movies.rb", - "Gemfile", ".github/workflows/ci.yml", "./app/models/movie.rb" ], "refused": [ "", + "/app/models/post.rb", + "app/../config/master.key", + "app/models/post.rb:12:3", + "app/models/post.rb:", + "app/models/post.rb:12345678", + "app/models/my post.rb", + "app\\models\\post.rb", + "~/app/models/post.rb", + "C:/app/models/post.rb", "/Users/sam/app/models/movie.rb", "../secrets.rb", - "app/../config/master.key", "app/models/movie.rb:12:in 'Movie#rate'", "app/models/movie.rb:12:3", "app/models/movie.rb:", @@ -152,20 +244,56 @@ }, "notes": { "accepted": [ + {"kind": "unstated_request", "request": "A waitlist when an event is full"}, { "kind": "unstated_request", - "request": "A weekly digest email of new movies" + "request": "A waitlist when an event is full", + "workaround": "Left the waitlist for later in the README." }, { - "kind": "unstated_request", - "request": "Members invite others by […]", - "workaround": "Left it for later" + "kind": "unclear_guidance", + "page": "references/modeling-guide.md#associations", + "unclear": "It does not say whether a Reference can point at the Account Entity." + }, + { + "kind": "unclear_guidance", + "code": "foundation_plan.association.cycle", + "unclear": "The fix names a key the Plan does not have.", + "workaround": "Removed the Association." }, { "kind": "unclear_guidance", "page": "SKILL.md", - "unclear": "It never says when to push" + "code": "reports_off", + "unclear": "It does not say what to tell the person." }, + {"kind": "wrong_output", "source": "analysis", "expected": "No diagnostic", "actual": "A cycle diagnostic"}, + { + "kind": "wrong_output", + "source": "analysis", + "code": "foundation_plan.association.cycle", + "expected": "No diagnostic for a self Reference", + "actual": "A cycle diagnostic" + }, + { + "kind": "wrong_output", + "source": "generated_code", + "compilation_id": "01900000-0000-7000-8000-000000000002", + "expected": "Deleting a Movie deletes its Credits", + "actual": "Deleting a Movie raised […]" + }, + { + "kind": "wrong_output", + "source": "generated_code", + "compilation_id": "01900000-0000-7000-8000-000000000002", + "file": "app/models/movie.rb:12", + "expected": "Deleting a Movie deletes its Credits", + "actual": "Deleting a Movie raised […]", + "workaround": "Added the missing dependent option." + }, + {"kind": "unstated_request", "request": "A weekly digest email of new movies"}, + {"kind": "unstated_request", "request": "Members invite others by […]", "workaround": "Left it for later"}, + {"kind": "unclear_guidance", "page": "SKILL.md", "unclear": "It never says when to push"}, { "kind": "unclear_guidance", "code": "foundation_plan.identity.reserved_constant_collision", @@ -211,50 +339,71 @@ ], "refused": [ {}, - { "request": "A weekly digest email" }, - { "kind": "bug", "request": "A weekly digest email" }, - { "kind": "unstated_request" }, - { "kind": "unstated_request", "workaround": "Left it for later" }, - { - "kind": "unstated_request", - "request": "A weekly digest email", - "page": "SKILL.md" - }, - { "kind": "unstated_request", "request": "Use the 'owner' role" }, - { "kind": "unclear_guidance", "unclear": "It names no fix" }, - { "kind": "unclear_guidance", "page": "SKILL.md" }, + {"kind": "praise"}, + {"kind": "unstated_request"}, + {"kind": "unstated_request", "request": ""}, + {"kind": "unstated_request", "request": "A waitlist", "page": "SKILL.md"}, + {"kind": "unstated_request", "request": "A waitlist", "compilation_id": "01900000-0000-7000-8000-000000000002"}, + {"kind": "unstated_request", "request": "Import from 'Airtable'"}, + {"kind": "unclear_guidance", "unclear": "It does not say."}, + {"kind": "unclear_guidance", "page": "SKILL.md"}, + {"kind": "unclear_guidance", "page": "SKILL.md", "unclear": "It does not say.", "source": "analysis"}, + {"kind": "wrong_output", "expected": "No diagnostic", "actual": "A cycle diagnostic"}, + {"kind": "wrong_output", "source": "analysis", "expected": "No diagnostic"}, + {"kind": "wrong_output", "source": "compiler", "expected": "No diagnostic", "actual": "A cycle diagnostic"}, { - "kind": "unclear_guidance", - "page": "../SKILL.md", - "unclear": "It names no fix" + "kind": "wrong_output", + "source": "analysis", + "compilation_id": "01900000-0000-7000-8000-000000000002", + "expected": "No diagnostic", + "actual": "A cycle diagnostic" }, { - "kind": "unclear_guidance", - "code": "invalid_output_path", - "unclear": "It names no fix", - "file": "app/models/movie.rb" + "kind": "wrong_output", + "source": "analysis", + "file": "app/models/movie.rb", + "expected": "No diagnostic", + "actual": "A cycle diagnostic" }, { "kind": "wrong_output", - "expected": "The Plan is valid", - "actual": "Analysis refused it" + "source": "generated_code", + "expected": "Deleting a Movie deletes its Credits", + "actual": "Deleting a Movie raised […]" }, { "kind": "wrong_output", - "source": "plan", - "expected": "The Plan is valid", - "actual": "Analysis refused it" + "source": "generated_code", + "compilation_id": "01900000-0000-7000-8000-000000000002", + "code": "foundation_plan.association.cycle", + "expected": "Deleting a Movie deletes its Credits", + "actual": "Deleting a Movie raised […]" }, { "kind": "wrong_output", - "source": "analysis", - "expected": "The Plan is valid" + "source": "generated_code", + "compilation_id": "01900000-0000-7000-8000-000000000002", + "file": "/Users/sam/app/app/models/movie.rb", + "expected": "Deleting a Movie deletes its Credits", + "actual": "Deleting a Movie raised […]" }, + {"request": "A weekly digest email"}, + {"kind": "bug", "request": "A weekly digest email"}, + {"kind": "unstated_request", "workaround": "Left it for later"}, + {"kind": "unstated_request", "request": "A weekly digest email", "page": "SKILL.md"}, + {"kind": "unstated_request", "request": "Use the 'owner' role"}, + {"kind": "unclear_guidance", "unclear": "It names no fix"}, + {"kind": "unclear_guidance", "page": "../SKILL.md", "unclear": "It names no fix"}, { - "kind": "wrong_output", - "source": "analysis", - "actual": "Analysis refused it" + "kind": "unclear_guidance", + "code": "invalid_output_path", + "unclear": "It names no fix", + "file": "app/models/movie.rb" }, + {"kind": "wrong_output", "expected": "The Plan is valid", "actual": "Analysis refused it"}, + {"kind": "wrong_output", "source": "plan", "expected": "The Plan is valid", "actual": "Analysis refused it"}, + {"kind": "wrong_output", "source": "analysis", "expected": "The Plan is valid"}, + {"kind": "wrong_output", "source": "analysis", "actual": "Analysis refused it"}, { "kind": "wrong_output", "source": "analysis", diff --git a/test/note-shapes.test.js b/test/note-shapes.test.js index a97da15..e0f1819 100644 --- a/test/note-shapes.test.js +++ b/test/note-shapes.test.js @@ -9,9 +9,8 @@ import { noteBody, } from "../src/commands/note.js"; -// Examples written from the notes contract's rules. The First Draft service -// keeps its own copy of the same cases; when the two are reconciled into one -// file, copy it here unchanged so both sides test the same strings. +// A copy of the service's note examples, kept unchanged so the two sides test +// the same strings. Refresh it whenever the service's copy changes. const shapes = JSON.parse( readFileSync(new URL("fixtures/note-shapes.json", import.meta.url), "utf8"), );