From 0cab54fa313831ea7a88c1f0a64a099bf7b93d5d Mon Sep 17 00:00:00 2001 From: Raghu Betina Date: Tue, 24 Nov 2026 09:37:38 -0600 Subject: [PATCH] Remove plan compile --github First Draft is dropping GitHub publication (firstdraft/firstdraft has gh to create and push a repository, so publication only kept the GitHub App on Administration, Contents, and Workflows write and the service on a publication ledger, executor, and recovery job. The service removes its github-publication routes in the same release, inside API contract 0.9.0, as the owner decided on 2026-11-24. The CLI drops the --github flag, the Publication client, its seven error values and the "publication" phase of request_outcome_unknown, and the GitHub progress lines. --github now fails like any unknown option. The push and analysis tests that ran through --github now run through --output, and the exact plan compile help and rejected argument checks move over from the deleted Publication suite, so the shared guarantees keep their coverage. The changelog tells a --github caller to compile into an absent --output directory, which works on every platform and holds only the application, then push it with git and gh. Review also corrected where the update line appears among compile's progress lines. --- AGENTS.md | 4 +- CHANGELOG.md | 15 +- README.md | 9 +- docs/README.md | 2 +- docs/commands.md | 93 +- docs/errors.md | 33 +- scripts/check-pack.js | 1 - scripts/smoke-package.js | 76 -- src/api-response.js | 8 - src/cli.js | 245 +---- src/commands/plan-compile.js | 58 +- src/commands/plan-publish.js | 1146 ----------------------- src/plan-compile-progress.js | 89 +- test/api-environments.test.js | 1 - test/plan-compile.test.js | 407 +++----- test/plan-publish.test.js | 1641 --------------------------------- 16 files changed, 205 insertions(+), 3623 deletions(-) delete mode 100644 src/commands/plan-publish.js delete mode 100644 test/plan-publish.test.js diff --git a/AGENTS.md b/AGENTS.md index 0ac53b2..e7c28fb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,8 +15,8 @@ handled-error recovery in `docs/errors.md`, publication mechanics in `RELEASING. `.codex/config.toml` get an independent review through the `cross-review` Skill, with `codex` as the reviewer from Claude Code and `claude` from Codex. Pass the service repository's `docs/review-focus.md` as `--focus-file` (see `CONTRIBUTING.md`). Put the reviewer, verdict, and finding counts in the pull request body, not the findings. -- `firstdraft plan compile` defaults to local output in the current directory. GitHub publication requires - `--github`; Codespaces is a fallback. Keep Skill callers and recovery instructions aligned with this boundary. +- `firstdraft plan compile` defaults to local output in the current directory; Codespaces is a fallback. Keep Skill + callers and recovery instructions aligned with this boundary. - The service repository coordinates releases and owns their approval and smoke policy. One approved coordinated release covers its named CLI steps; do not ask again between them. A merge alone does not authorize a release. `RELEASING.md` covers the publication steps. diff --git a/CHANGELOG.md b/CHANGELOG.md index c9fa40c..f29357c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,7 +15,8 @@ Lets First Draft tell a setup that it is out of date, and adds the account, repo commands and a device login in two steps, so a person working alone hears when to update, their agent can log them in, it can send the progress and failure reports and the notes the person agreed to, for the application's whole life, and it can work through what needs attention in the deployed application. Moves the Rails -target to profile `rails-sketch/2026-11` and the accepted API contract to `0.9.x`. +target to profile `rails-sketch/2026-11` and the accepted API contract to `0.9.x`. Removes GitHub publication, which +First Draft no longer offers. - `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 @@ -101,8 +102,12 @@ target to profile `rails-sketch/2026-11` and the accepted API contract to `0.9.x `maintain resolve` traced to code First Draft generated. It names the item and takes no `--message`. - After an ambiguous push, from `plan push` or `plan compile`, or an ambiguous direct Compilation start, `request_outcome_unknown` now says to run the same command once more with the same options and environment, and - 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. + what a `412` or `compilation_active` answer then means, instead of telling the caller to stop. +- `plan compile --github` is gone: `--github` fails with `invalid_arguments` (exit status 2), like any unknown option, + and the CLI no longer calls `/v1/projects/{project_id}/github-publication`. `request_outcome_unknown` no longer has + `phase: "publication"`, and these `error` values are gone: `publication_start_rejected`, + `publication_status_unavailable`, `invalid_publication_status`, `publication_changed`, `publication_wait_timed_out`, + `publication_failed`, and `publication_cancelled`. - New `error` values, each with exit status 1: `update_required`, `api_contract_unsupported`, `rate_limited`, `account_unavailable`, `report_rejected`, `report_unavailable`, `note_rejected`, `note_unavailable`, `compilation_not_recorded`, `maintain_rejected`, `maintain_unavailable`, `invalid_maintain_response`, and, from @@ -118,7 +123,9 @@ nothing more and says to use the CLI version that origin supports. A plugin's la `FIRSTDRAFT_PLUGIN_VERSION` and `FIRSTDRAFT_AGENT`; without the first, the CLI compares its own version with the CLI versions. Callers that parse standard error should drop the `First Draft: ` lines, which any network command may now write before its result; `start` writes its update line on standard output instead. A Skill that checked -`firstdraft --help` runs `firstdraft start` in its place and may run the two login steps itself. +`firstdraft --help` runs `firstdraft start` in its place and may run the two login steps itself. A caller that ran +`plan compile --github` runs `plan compile --output `, which works on every platform and writes only +the application, then initializes, commits, and pushes that directory with `git` and `gh`. ## 0.9.0 diff --git a/README.md b/README.md index e5f9eb5..a200753 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,22 @@ # First Draft CLI firstdraft is the command-line client shared by First Draft agents and automation. It manages local Foundation Plan -files, calls the versioned Service API, exposes reviewed analysis and GapSets, materializes verified Compilations, -and coordinates private GitHub publication. +files, calls the versioned Service API, exposes reviewed analysis and GapSets, and materializes verified +Compilations. Start with the [local development guide](https://firstdraft.github.io/firstdraft/docs/guides/local-app.html): install the CLI and Skill, then compile into your current folder with `firstdraft plan compile --output .`. No Drawing Board clone or GitHub push is required. The [Drawing Board guide](https://github.com/firstdraft/drawing-board#build-an-app-with-first-draft) is the Codespaces fallback. -`--output .` is also the default, so `firstdraft plan compile` alone writes to the current folder. GitHub publication -requires `--github`. +`--output .` is also the default, so `firstdraft plan compile` alone writes to the current folder. ## What this repository owns - local Plan initialization, UUIDs, application keys, and source hashing; - conditional whole-document push and conflict reporting; - analysis polling and complete GapSet output; -- direct Compile-and-materialize and private publish orchestration; +- direct Compile-and-materialize; - retained Compilation inspection, cancellation, and artifact download; - terminal output, exit status, and recovery contracts; - the dependency-free npm package; and diff --git a/docs/README.md b/docs/README.md index 4827eaf..8914edb 100644 --- a/docs/README.md +++ b/docs/README.md @@ -50,7 +50,7 @@ npm pack --dry-run --json --ignore-scripts Pass Node test options through `npm test` to focus a run while retaining discovery under `test/`: ```sh -npm test -- --test-name-pattern="publication" +npm test -- --test-name-pattern="compilation" ``` To reproduce the length-delimited SHA-256 used by external evidence to identify packaged JavaScript runtime inputs diff --git a/docs/commands.md b/docs/commands.md index 0b7ae86..8c63f24 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -6,7 +6,7 @@ group's `--help` for concise executable syntax. See [Errors and recovery](errors The current `0.10.x` source line contains the auditable command shell, the agent's `start` check, browser and device 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 +status polling, direct Compile-and-materialize, retained-Compilation inspection and cancellation, the account's report setting, progress and failure reports, notes, and maintenance-item listing, inspection, and resolution. 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. @@ -26,7 +26,6 @@ inspection, and resolution. It requires the service's `0.9.x` API contract. The | `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 | @@ -453,25 +452,25 @@ firstdraft plan compile ``` This is equivalent to `firstdraft plan compile --output .`. Use `--output ./application` for another absent -directory, or `--github` to publish to a private GitHub repository. `--github` and `--output` are mutually exclusive. -No GitHub connection, repository clone, or push is required for local compilation. Compilation runs on the First -Draft service; output and the application runtime are local. +directory. No GitHub connection, repository clone, or push is required. Compilation runs on the First Draft service; +output and the application runtime are local. To put the application on GitHub, create and push a repository with +`git` and `gh` after it is written. -Both `plan compile` modes first push the exact current bytes in -`.firstdraft/foundation-plan.json`, even when those bytes are unchanged, and save the accepted ETag using the same +`plan compile` first pushes the exact current bytes in +`.firstdraft/foundation-plan.json`, even when those bytes are unchanged, and saves the accepted ETag using the same contract as `plan push`. It then waits up to two minutes for an analysis whose graph version and `head_source_sha256` exactly match that accepted push, polling past a terminal result retained for an older Head. Invalid JSON, schema diagnostics, semantic diagnostics, a failed analysis, a superseded analysis, or a recurring -diagnostic stop the command with structured output; no Compilation or Publication is requested. +diagnostic stop the command with structured output; no Compilation is requested. -Only a `valid` analysis proceeds to the selected completion mode. Immediately before either conditional mutation, -the CLI re-reads the local Plan and requires its exact bytes and saved state to match the accepted Head. It extracts +Only a `valid` analysis proceeds to Compilation. Immediately before the conditional Compilation start, the CLI +re-reads the local Plan and requires its exact bytes and saved state to match the accepted Head. It extracts the accepted source SHA-256 from the saved ETag, hashes the current local bytes, and sends that complete ETag in `If-Match`. ### Materialize a direct Compilation -Without `--github`, the CLI accepts either an explicit absent destination beneath an existing real directory or a path +The CLI accepts either an explicit absent destination beneath an existing real directory or a path that resolves to the physical current directory. It validates either destination before pushing the Plan. An absent destination is checked again after analysis; root adoption instead holds its owned lock and performs the exact pre-move identity recheck described below. Other existing destinations remain invalid, so @@ -564,8 +563,7 @@ path identities, and verify its original snapshot before removing the transactio reports `root_busy` until that state is reconciled; a foreign preexisting directory with the same reserved name reports `root_reserved_path`. -After valid analysis, the CLI requests one Compilation for that exact reviewed Head and never starts GitHub -Publication. It validates that the `202` response identifies the same Project, graph version, Head, Analysis, +After valid analysis, the CLI requests one Compilation for that exact reviewed Head. It validates that the `202` response identifies the same Project, graph version, Head, Analysis, Compiler release, and target; polls only that retained Compilation for up to ten minutes; downloads its exact artifact; and applies the same integrity and atomic materialization contract as `compilation download`. An ambiguous Compilation start is not retried automatically. After a validated `202`, later status, artifact, authentication, @@ -582,8 +580,13 @@ archive and retained Git/transaction paths; it still checks every generated file `.firstdraft/submitted-foundation-plan.json` and `.firstdraft/gaps.json`, and rejects unexpected generated paths. The CLI does not add a Git repository, run a formatter, or repair generated source. When an absent output is nested inside another Git worktree, initialize the application as its own repository before running generated checks that -inspect Git; otherwise Git resolves to the parent worktree. Progress on stderr reports analysis and Compilation -only. +inspect Git; otherwise Git resolves to the parent worktree. + +Progress lines go to stderr, each prefixed by `First Draft:`. They report analysis and Compilation only and never +include IDs, hashes, raw server projections, local paths, or environment values. One +[update line](#update-line-and-refusals) can follow them on stderr, before the result or the error envelope; that +section says what it names. If the command fails after progress has begun, its structured JSON error envelope is the +final stderr document. ### Record the Compilation whose code was written @@ -603,55 +606,15 @@ 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, any earlier +the Compilation whose code the CLI wrote last for the Project, wherever that code went. 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 - -Use the explicit GitHub option for the Publication journey: - -```sh -firstdraft plan compile --github -``` - -Invoking this form authorizes the internal GitHub Publication lifecycle. The command writes stable human-readable -progress to stderr, with every line prefixed by `First Draft:`. It reports analysis, Compilation completion or -terminal failure or cancellation, the current GitHub phase, and an allowlisted reason, retry count, and exact UTC -retry time when a GitHub preflight check is delayed. A retained retry with no next time is reported as paused and -requiring operator recovery. Progress never includes IDs, hashes, repository names or URLs, raw server projections, -local paths, or environment values. The [update line](#update-line-and-refusals), which can appear among the -progress lines, names only versions and the public update page. Success writes exactly the validated private GitHub repository URL plus a -newline to stdout. If the command fails after progress has begun, its structured JSON error envelope is the final -stderr document after the progress lines. - -The closed API `0.9.x` progress-reason allowlist is `github.configuration_missing`, `github.oauth_unavailable`, -`github.api_unavailable`, `github.reauthorization_required`, `github.account_mismatch`, -`github.installation_unavailable`, `github.installation_not_ready`, `github.preflight_unavailable`, the legacy-only -`github.preflight_unclassified`, and these stage-specific fallbacks: `github.preflight_unavailable.configuration`, -`github.preflight_unavailable.authorization`, `github.preflight_unavailable.repository_client`, -`github.preflight_unavailable.artifact_preparation`, `github.preflight_unavailable.installation_token`, -`github.preflight_unavailable.publication_preparation`, and `github.preflight_unavailable.repository_ref_client`. -Other values make the response invalid rather than becoming terminal output. - -The internal Publication is a Project singleton in this release. A repeat safely receives the same Publication -instead of creating another. If the first conditional `PUT` has an ambiguous result, the CLI reconciles it with one -read-only singleton `GET` and never automatically repeats the mutation within that invocation. Publication polling -is sequential, bounded to ten minutes, and pinned to the retained Project Head, Compilation input, Publication -identity, and repository identity. Do not run concurrent Compile commands; use the -[publication recovery procedure](errors.md#publication-recovery) after an invocation exits. - -This release cannot repoint a Project's Publication to a later accepted Head. The public CLI therefore has no -`plan publish` command. Direct local Compilation and GitHub Publication are separate completion modes after the same -exact Plan push and valid Analysis. - ## Inspect a retained Compilation These lower-level commands are for callers that already hold a retained Compilation ID from authenticated API -metadata or operational tooling. `plan compile --github` prints only the final repository URL, while the default -`plan compile` form waits for and downloads its own direct Compilation: +metadata or operational tooling. `plan compile` waits for and downloads its own direct Compilation: ```sh firstdraft compilation status 01900000-0000-7000-8000-000000000001 @@ -732,10 +695,6 @@ Compilation. First Draft never changes a succeeded or failed Compilation: it ans safe, an outcome the CLI cannot confirm is `compilation_cancel_unavailable` rather than `request_outcome_unknown`. See [stuck Compilation recovery](errors.md#stuck-compilation-recovery). -If the Compilation was started by `plan compile --github`, Cancel also cancels the Project's Publication. The -Publication is a Project singleton in this release, so `plan compile --github` cannot start another one for that -Project. - ## Read the account ```sh @@ -979,8 +938,6 @@ timeout. Each request takes its method and path from one | `GET` | `/v1/projects/{project_id}/compilations/{compilation_id}` | Read one retained Compilation | | `POST` | `/v1/projects/{project_id}/compilations/{compilation_id}/cancel` | Cancel that Compilation | | `GET` | `/v1/projects/{project_id}/compilations/{compilation_id}/artifact` | Download that Compilation's artifact | -| `PUT` | `/v1/projects/{project_id}/github-publication` | Start or rejoin the Publication | -| `GET` | `/v1/projects/{project_id}/github-publication` | Poll or reconcile the Publication | | `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 | @@ -993,7 +950,7 @@ timeout. Each request takes its method and path from one | `POST` | `/oauth/revoke` | Revoke a saved token | `plan push` sends the Plan `PUT`, and `plan status` reads the analysis. `plan compile` does both. It then starts a -Compilation, polls it, and downloads its artifact. With `--github`, it starts and polls the Publication instead. +Compilation, polls it, and downloads its artifact. `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. Each `note` command reads it @@ -1005,9 +962,9 @@ and, with reports on, posts its note. `login --finish` only the polls. `logout` calls `/oauth/revoke`. The browser, not the CLI, opens `/oauth/authorize` and `/device`, so they have no rows. -The first push sends `If-None-Match: *`. Later pushes, the Compilation start `POST`, and the Publication `PUT` send -the saved Head ETag in `If-Match`. The cancel `POST` sends no precondition header. The resolution `POST` sends a JSON -body and no precondition header. +The first push sends `If-None-Match: *`. Later pushes and the Compilation start `POST` send the saved Head ETag in +`If-Match`. The cancel `POST` sends no precondition header. The resolution `POST` sends a JSON body and no precondition +header. The `/v1` routes belong to API contract `0.9.x`. `API_CONTRACT_RANGE` in `src/service-client.js` declares that range, `release/compatibility.json` declares it for the Service's release compatibility check, and @@ -1026,7 +983,7 @@ keeps the Plan's meaning still makes a new Head, although the Project's `graph_v A successful Plan `PUT` returns a strong `ETag` of the form `"sha256:"`, quotes included. `` is the 64-character lowercase SHA-256 of the Head bytes. The CLI saves the complete header value in `.firstdraft/state.json` and replays it in `If-Match`. `plan compile` also extracts `` to check that the local Plan still matches the -Head before it starts a Compilation or Publication. A saved ETag in any other form stops that check with +Head before it starts a Compilation. A saved ETag in any other form stops that check with `invalid_configuration`. The same digest appears as `head_source_sha256` in analysis and Compilation responses. To tell whether the local Plan diff --git a/docs/errors.md b/docs/errors.md index 7b174f8..5333d8a 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -110,7 +110,7 @@ is reported as itself, with its recovery data, after the stop line. ## Ambiguous mutations -`plan compile` supplies `phase: "push" | "compilation" | "publication"` when `request_outcome_unknown` requires +`plan compile` supplies `phase: "push" | "compilation"` when `request_outcome_unknown` requires phase-specific recovery: - `phase: "push"`, and `request_outcome_unknown` from `plan push`, mean the Plan may have been accepted, but the @@ -125,15 +125,11 @@ phase-specific recovery: `--staging` for staging, or the same `FIRSTDRAFT_API_URL` for a custom origin. A new folder has no pinned origin, so without one the push goes to production. Never construct an ETag from the Plan digest or edit `.firstdraft/state.json`. -- `phase: "compilation"` means a local Compilation (the default mode, with optional `--output`) may have started, - but its identity is unknown. The CLI never repeats that `POST` itself. Run the same `plan compile` command, with - the same options and environment, once more. If a Compilation is still active, First Draft refuses with - `compilation_active` and names it; follow [stuck Compilation recovery](#stuck-compilation-recovery). Otherwise the - rerun starts a new Compilation; one that the first attempt may have started costs only service time and one of the - day's Compilations. -- `phase: "publication"` means the singleton Publication mutation was not resolved. Do not run concurrent Compile - commands. After the prior invocation exits, wait and rerun `plan compile --github` with unchanged Plan bytes to safely - reconcile or resume the retained singleton. +- `phase: "compilation"` means the Compilation may have started, but its identity is unknown. The CLI never repeats that + `POST` itself. Run the same `plan compile` command, with the same options and environment, once more. If a Compilation + is still active, First Draft refuses with `compilation_active` and names it; follow + [stuck Compilation recovery](#stuck-compilation-recovery). Otherwise the rerun starts a new Compilation; one that the + first attempt may have started costs only service time and one of the day's Compilations. If a verified Plan response cannot replace local state, preserve the printed `recovery_state`; an adjacent `.tmp` file may contain the same private recovery copy. Do not push again until the accepted ETag state is repaired. @@ -241,21 +237,6 @@ an error. `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 - -The Publication is a Project singleton. If its initial conditional `PUT` is ambiguous, the CLI attempts one -read-only singleton `GET` and never automatically repeats the mutation in that invocation. - -After `publication_status_unavailable` or `publication_wait_timed_out`, retained work may still continue. Do not run -concurrent Compile commands. Wait, then rerun `plan compile --github` with unchanged Plan bytes; the conditional request -safely reconciles or resumes the same retained singleton without creating another Compilation, repository, or push. -The same recovery applies when an invocation exits after an unresolved Publication start. - -A GitHub preflight retry with no `retry_at` is paused and requires operator recovery. `publication_failed` and -`publication_cancelled` are terminal; inspect the validated phase and failure information rather than blindly -retrying. `publication_changed` means the pinned Publication identity or provenance changed, so the CLI deliberately -stopped without following the replacement. - ## Maintenance recovery The index and `show` only read, so they are safe to retry a bounded number of times. A resolution is not. When its @@ -306,8 +287,6 @@ resolve an item that is still resolved, with `maintain_rejected` and `409 item_a | `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. | diff --git a/scripts/check-pack.js b/scripts/check-pack.js index 0fc4dec..92553fe 100644 --- a/scripts/check-pack.js +++ b/scripts/check-pack.js @@ -49,7 +49,6 @@ if (result.status !== 0) { "src/commands/note.js", "src/commands/plan-compile.js", "src/commands/plan-init.js", - "src/commands/plan-publish.js", "src/commands/plan-push.js", "src/commands/plan-status.js", "src/commands/report.js", diff --git a/scripts/smoke-package.js b/scripts/smoke-package.js index 2d3663e..849ab1f 100644 --- a/scripts/smoke-package.js +++ b/scripts/smoke-package.js @@ -529,7 +529,6 @@ async function exercisePackedCompilation(projectDirectory) { const projectId = "01900000-0000-7000-8000-000000000901"; const compilationId = "01900000-0000-7000-8000-000000000902"; const analysisId = "01900000-0000-7000-8000-000000000903"; - const publicationId = "01900000-0000-7000-8000-000000000904"; const plan = readFileSync( path.join(projectDirectory, ".firstdraft", "foundation-plan.json"), ); @@ -670,51 +669,6 @@ async function exercisePackedCompilation(projectDirectory) { completed_at: "2026-07-30T12:00:01.000Z", }, }; - const publication = { - project: { - id: projectId, - graph_version: 1, - head_source_sha256: headSha256, - }, - compilation: { - id: compilationId, - analysis_run_id: analysisId, - graph_version: 1, - head_source_sha256: headSha256, - status: "succeeded", - compiler_release: compilerRelease, - target, - artifact: { - sha256: artifactSha256, - manifest_sha256: manifestSha256, - file_count: 3, - }, - }, - publication: { - id: publicationId, - status: "succeeded", - repository: { - id: 1_234_567, - private: true, - owner: { id: 7_654_321, login: "octocat", type: "User" }, - full_name: "octocat/oscar-party", - default_branch: "main", - html_url: "https://github.com/octocat/oscar-party", - tree_sha: "5".repeat(40), - commit_sha: "6".repeat(40), - }, - failure: null, - progress: { - phase: "completed", - retry_at: null, - retry_count: 0, - reason_code: null, - }, - created_at: "2026-07-30T12:00:00.000Z", - started_at: "2026-07-30T12:00:01.000Z", - completed_at: "2026-07-30T12:00:02.000Z", - }, - }; const itemId = "3f2c9a4e-8d1b-4c7a-9e5f-0a1b2c3d4e5f"; const itemsPath = `/v1/projects/${projectId}/environments/production/items`; const environment = { project_id: projectId, name: "production" }; @@ -772,7 +726,6 @@ async function exercisePackedCompilation(projectDirectory) { const seen = { plan: false, analysis: false, - publication: 0, compilationStarts: 0, status: false, cancel: false, @@ -814,16 +767,6 @@ async function exercisePackedCompilation(projectDirectory) { respondJson(response, 200, analysis); return; } - if ( - request.method === "PUT" && - request.url === `/v1/projects/${projectId}/github-publication` - ) { - assert.equal(request.headers["if-match"], `"sha256:${headSha256}"`); - assert.equal(requestBody.byteLength, 0); - seen.publication += 1; - respondJson(response, 201, publication); - return; - } if ( request.method === "POST" && request.url === `/v1/projects/${projectId}/compilations` @@ -913,23 +856,6 @@ async function exercisePackedCompilation(projectDirectory) { { mode: 0o600 }, ); - const compiled = await spawnPackedCliAsync( - ["plan", "compile", "--github"], - projectDirectory, - ); - assert.deepEqual(compiled, { - status: 0, - stdout: `${publication.publication.repository.html_url}\n`, - stderr: `First Draft: Analyzing Foundation Plan... -First Draft: Foundation Plan analysis valid. -First Draft: Compiling application... -First Draft: Application compiled. -First Draft: GitHub publication complete. -`, - }); - assert.equal(seen.publication, 1); - assert.equal(seen.compilationStarts, 0); - const directOutput = path.join(projectDirectory, "application"); const direct = await spawnPackedCliAsync( ["plan", "compile", "--output", directOutput], @@ -945,7 +871,6 @@ First Draft: Application compiled. `, ); assert.equal(JSON.parse(direct.stdout).output.path, directOutput); - assert.equal(seen.publication, 1); assert.equal(seen.compilationStarts, 1); assert.equal( readFileSync(path.join(directOutput, "app/models/movie.rb"), "utf8"), @@ -1112,7 +1037,6 @@ First Draft: Application compiled. assert.deepEqual(seen, { plan: true, analysis: true, - publication: 1, compilationStarts: expectedCompilationStarts, status: true, cancel: true, diff --git a/src/api-response.js b/src/api-response.js index 3d6f991..d096bdc 100644 --- a/src/api-response.js +++ b/src/api-response.js @@ -51,14 +51,6 @@ export const SERVICE_ROUTES = { method: "GET", path: "/v1/projects/{project_id}/compilations/{compilation_id}/artifact", }, - startPublication: { - method: "PUT", - path: "/v1/projects/{project_id}/github-publication", - }, - readPublication: { - method: "GET", - path: "/v1/projects/{project_id}/github-publication", - }, readAccount: { method: "GET", path: "/v1/account", diff --git a/src/cli.js b/src/cli.js index 6405e67..4194eba 100644 --- a/src/cli.js +++ b/src/cli.js @@ -63,7 +63,6 @@ import { PlanCompileAnalysisRejectedError, PlanCompileAnalysisUnavailableError, PlanCompilePushRejectedError, - compilePlanToGitHub, compilePlanToDirectory, } from "./commands/plan-compile.js"; import { @@ -93,19 +92,6 @@ import { showMaintenanceItem, } from "./commands/maintain.js"; import { initializePlan } from "./commands/plan-init.js"; -import { - PublicationCancelledError, - PublicationChangedError, - PublicationFailedError, - PublicationLocalPlanChangedError, - PublicationLocalStateError, - PublicationNotPushedError, - PublicationRequestOutcomeUnknownError, - PublicationStartRejectedError, - PublicationStatusInvalidError, - PublicationStatusUnavailableError, - PublicationTimeoutError, -} from "./commands/plan-publish.js"; import { PlanPushConfigurationError, PlanPushLocalError, @@ -495,12 +481,10 @@ const PLAN_COMPILE_HELP = `First Draft CLI Usage: firstdraft plan compile firstdraft plan compile --output - firstdraft plan compile --github Options: --staging Use staging; reject a different saved origin --output Materialize here (default: .) - --github Publish to a private GitHub repository -h, --help Show help Environment: @@ -512,8 +496,7 @@ The command submits the exact current whole-file Plan, waits for its analysis, and proceeds only when that analysis is valid. By default it materializes the verified application in the current directory, preserving existing root material under .firstdraft/design. --output can select another absent directory. ---github selects the GitHub Publication lifecycle and prints the private repository -URL; it cannot be combined with --output. Progress is written to stderr. +Progress is written to stderr. `; const COMPILATION_HELP = `First Draft CLI @@ -819,27 +802,6 @@ const PLAN_COMPILE_DIRECT_FAILED_DETAIL = "The pinned Compilation failed. No artifact was downloaded or materialized."; const PLAN_COMPILE_DIRECT_CANCELLED_DETAIL = "The pinned Compilation was cancelled. No artifact was downloaded or materialized."; -const PLAN_PUBLISH_INCOMPATIBLE_STATE_DETAIL = - "The saved Foundation Plan ETag is incompatible with publication. No network request was made; reconcile the CLI and server contract."; -const PLAN_PUBLISH_NOT_PUSHED_DETAIL = - "The current Foundation Plan was not retained before the Publication request."; -const PLAN_PUBLISH_LOCAL_PLAN_CHANGED_DETAIL = - "The local Foundation Plan changed after validation. Run 'firstdraft plan compile --github' again to submit the current bytes."; -const PLAN_PUBLISH_REQUEST_OUTCOME_UNKNOWN_DETAIL = - "The Publication may have started, but its retained singleton status could not be verified. No mutation was retried. Do not run concurrent Compile commands. Wait, then rerun 'firstdraft plan compile --github' with unchanged Plan bytes to safely reconcile or resume the retained singleton."; -const PLAN_PUBLISH_START_REJECTED_DETAIL = - "First Draft rejected the publication request."; -const PLAN_PUBLISH_STATUS_UNAVAILABLE_DETAIL = - "Could not read the retained Publication status. The command stopped without starting another Publication. Do not run concurrent Compile commands. Wait, then rerun 'firstdraft plan compile --github' with unchanged Plan bytes to safely resume the retained singleton."; -const PLAN_PUBLISH_STATUS_INVALID_DETAIL = - "First Draft returned an invalid publication status response. Retrying unchanged will not repair this protocol mismatch."; -const PLAN_PUBLISH_CHANGED_DETAIL = - "The pinned Publication changed while being polled. The command stopped without following a replacement."; -const PLAN_PUBLISH_TIMEOUT_DETAIL = - "The retained Publication is still processing after the bounded ten-minute wait. This invocation stopped waiting, but retained work may continue. Do not run concurrent Compile commands. Wait, then rerun 'firstdraft plan compile --github' with unchanged Plan bytes to safely resume the retained singleton."; -const PLAN_PUBLISH_FAILED_DETAIL = - "The pinned Publication failed. Its validated status identifies the failed phase."; -const PLAN_PUBLISH_CANCELLED_DETAIL = "The pinned Publication was cancelled."; const COMPILATION_STATUS_INVALID_ARGUMENTS_DETAIL = "Invalid arguments. Run 'firstdraft compilation status --help' for usage."; const COMPILATION_DOWNLOAD_INVALID_ARGUMENTS_DETAIL = @@ -964,13 +926,10 @@ const PINNED_NOT_PUSHED_DETAIL = * @property {() => number} [planStatusNow] * @property {(delayMs: number) => Promise} [planCompileSleep] * @property {() => number} [planCompileNow] - * @property {(delayMs: number) => Promise} [planPublishSleep] - * @property {() => number} [planPublishNow] * @property {(delayMs: number) => Promise} [compilationSleep] * @property {() => number} [compilationNow] * @property {typeof pushPlan} [planCompilePush] * @property {typeof readPlanStatus} [planCompileReadStatus] - * @property {typeof import("./commands/plan-publish.js").publishPlan} [planCompilePublish] * @property {typeof import("./commands/compilation.js").compileAndDownload} [planCompileDownload] * @property {string} [apiUrl] * @property {string} [apiToken] @@ -1002,13 +961,10 @@ const PINNED_NOT_PUSHED_DETAIL = * @property {() => number} [planStatusNow] * @property {(delayMs: number) => Promise} [planCompileSleep] * @property {() => number} [planCompileNow] - * @property {(delayMs: number) => Promise} [planPublishSleep] - * @property {() => number} [planPublishNow] * @property {(delayMs: number) => Promise} [compilationSleep] * @property {() => number} [compilationNow] * @property {typeof pushPlan} [planCompilePush] * @property {typeof readPlanStatus} [planCompileReadStatus] - * @property {typeof import("./commands/plan-publish.js").publishPlan} [planCompilePublish] * @property {typeof import("./commands/compilation.js").compileAndDownload} [planCompileDownload] * @property {string} [apiUrl] * @property {string} [apiToken] @@ -1030,7 +986,7 @@ const PINNED_NOT_PUSHED_DETAIL = */ /** - * @typedef {Omit & {cwd?: string, getCwd: () => string}} CompilationCommandOptions + * @typedef {Omit & {cwd?: string, getCwd: () => string}} CompilationCommandOptions */ /** @@ -1063,13 +1019,10 @@ export async function run({ planStatusNow, planCompileSleep, planCompileNow, - planPublishSleep, - planPublishNow, compilationSleep, compilationNow, planCompilePush, planCompileReadStatus, - planCompilePublish, planCompileDownload, apiUrl = process.env.FIRSTDRAFT_API_URL, apiToken = process.env.FIRSTDRAFT_API_TOKEN, @@ -1176,13 +1129,10 @@ export async function run({ planStatusNow, planCompileSleep, planCompileNow, - planPublishSleep, - planPublishNow, compilationSleep, compilationNow, planCompilePush, planCompileReadStatus, - planCompilePublish, planCompileDownload, apiUrl, apiToken, @@ -1295,13 +1245,10 @@ async function runPlan({ planStatusNow, planCompileSleep, planCompileNow, - planPublishSleep, - planPublishNow, compilationSleep, compilationNow, planCompilePush, planCompileReadStatus, - planCompilePublish, planCompileDownload, apiUrl, apiToken, @@ -1372,13 +1319,10 @@ async function runPlan({ createRequestSignal, planCompileSleep, planCompileNow, - planPublishSleep, - planPublishNow, compilationSleep, compilationNow, planCompilePush, planCompileReadStatus, - planCompilePublish, planCompileDownload, apiUrl, apiToken, @@ -3171,7 +3115,7 @@ async function runPlanStatus({ } /** - * @param {Pick} options + * @param {Pick} options */ async function runPlanCompile({ argv, @@ -3184,13 +3128,10 @@ async function runPlanCompile({ createRequestSignal, planCompileSleep, planCompileNow, - planPublishSleep, - planPublishNow, compilationSleep, compilationNow, planCompilePush, planCompileReadStatus, - planCompilePublish, planCompileDownload, apiUrl, apiToken, @@ -3205,7 +3146,6 @@ async function runPlanCompile({ options: { staging: { type: "boolean" }, output: { type: "string" }, - github: { type: "boolean" }, help: { type: "boolean", short: "h" }, }, allowPositionals: false, @@ -3227,8 +3167,8 @@ async function runPlanCompile({ return 0; } - const { output, github } = parsed.values; - if (output !== undefined && (output.length === 0 || github)) { + const { output } = parsed.values; + if (output === "") { writeJson(stderr, { error: "invalid_arguments", detail: PLAN_COMPILE_INVALID_ARGUMENTS_DETAIL, @@ -3254,53 +3194,28 @@ async function runPlanCompile({ return writePlanCompileError(stderr, error); } - const reportProgress = createPlanCompileProgressReporter(stderr); - const shared = { - cwd, - apiUrl: authentication.apiUrl, - fetchFunction: authentication.fetchFunction, - fileSystem: planPushFileSystem, - createTemporaryId, - createRequestSignal, - analysisSleep: planCompileSleep, - analysisNow: planCompileNow, - push: planCompilePush, - readStatus: planCompileReadStatus, - onProgress: reportProgress, - }; - if (!github) { - try { - const result = await service.settle( - compilePlanToDirectory({ - ...shared, - output: output ?? ".", - compilationSleep, - compilationNow, - compile: planCompileDownload, - }), - ); - recordWrittenCompilation(stderr, cwd, result.compilation.id); - writeJson(stdout, result); - return 0; - } catch (error) { - return writePlanCompileError(stderr, error); - } - } - try { const result = await service.settle( - compilePlanToGitHub({ - ...shared, - publicationSleep: planPublishSleep, - publicationNow: planPublishNow, - publish: planCompilePublish, + compilePlanToDirectory({ + cwd, + output: output ?? ".", + apiUrl: authentication.apiUrl, + fetchFunction: authentication.fetchFunction, + fileSystem: planPushFileSystem, + createTemporaryId, + createRequestSignal, + analysisSleep: planCompileSleep, + analysisNow: planCompileNow, + compilationSleep, + compilationNow, + onProgress: createPlanCompileProgressReporter(stderr), + push: planCompilePush, + readStatus: planCompileReadStatus, + compile: planCompileDownload, }), ); - const repository = - /** @type {NonNullable} */ ( - result.publication.repository - ); - stdout.write(`${repository.html_url}\n`); + recordWrittenCompilation(stderr, cwd, result.compilation.id); + writeJson(stdout, result); return 0; } catch (error) { return writePlanCompileError(stderr, error); @@ -3656,120 +3571,6 @@ function writePlanCompileError(writer, error) { return 1; } - if (error instanceof PublicationLocalStateError) { - writeJson(writer, { - error: "invalid_configuration", - detail: PLAN_PUBLISH_INCOMPATIBLE_STATE_DETAIL, - }); - return 2; - } - - if (error instanceof PublicationNotPushedError) { - writeJson(writer, { - error: "project_not_pushed", - detail: PLAN_PUBLISH_NOT_PUSHED_DETAIL, - }); - return 1; - } - - if (error instanceof PublicationLocalPlanChangedError) { - writeJson(writer, { - error: "local_plan_changed", - detail: PLAN_PUBLISH_LOCAL_PLAN_CHANGED_DETAIL, - }); - return 1; - } - - if ( - (error instanceof PublicationStartRejectedError || - error instanceof PublicationStatusUnavailableError) && - isAuthenticationProblem(error.status, error.response) - ) { - writeAuthenticationRequired( - writer, - error.status, - /** @type {Record} */ (error.response), - ); - return 1; - } - - if (error instanceof PublicationRequestOutcomeUnknownError) { - writeJson(writer, { - error: "request_outcome_unknown", - phase: "publication", - detail: PLAN_PUBLISH_REQUEST_OUTCOME_UNKNOWN_DETAIL, - ...(typeof error.status === "number" ? { status: error.status } : {}), - ...(error.response ? { response: error.response } : {}), - }); - return 1; - } - - if (error instanceof PublicationStartRejectedError) { - writeJson(writer, { - error: "publication_start_rejected", - detail: PLAN_PUBLISH_START_REJECTED_DETAIL, - status: error.status, - response: error.response, - }); - return 1; - } - - if (error instanceof PublicationStatusUnavailableError) { - writeJson(writer, { - error: "publication_status_unavailable", - detail: PLAN_PUBLISH_STATUS_UNAVAILABLE_DETAIL, - ...(typeof error.status === "number" ? { status: error.status } : {}), - ...(error.response ? { response: error.response } : {}), - }); - return 1; - } - - if (error instanceof PublicationStatusInvalidError) { - writeJson(writer, { - error: "invalid_publication_status", - detail: PLAN_PUBLISH_STATUS_INVALID_DETAIL, - status: error.status, - }); - return 1; - } - - if (error instanceof PublicationChangedError) { - writeJson(writer, { - error: "publication_changed", - detail: PLAN_PUBLISH_CHANGED_DETAIL, - current: error.current, - rejected: error.rejected, - }); - return 1; - } - - if (error instanceof PublicationTimeoutError) { - writeJson(writer, { - error: "publication_wait_timed_out", - detail: PLAN_PUBLISH_TIMEOUT_DETAIL, - current: error.current, - }); - return 1; - } - - if (error instanceof PublicationFailedError) { - writeJson(writer, { - error: "publication_failed", - detail: PLAN_PUBLISH_FAILED_DETAIL, - current: error.current, - }); - return 1; - } - - if (error instanceof PublicationCancelledError) { - writeJson(writer, { - error: "publication_cancelled", - detail: PLAN_PUBLISH_CANCELLED_DETAIL, - current: error.current, - }); - return 1; - } - throw error; } diff --git a/src/commands/plan-compile.js b/src/commands/plan-compile.js index 1eec749..871d650 100644 --- a/src/commands/plan-compile.js +++ b/src/commands/plan-compile.js @@ -1,4 +1,3 @@ -import { publishPlan } from "./plan-publish.js"; import { compileAndDownload } from "./compilation.js"; import { prepareCompilationOutputTarget, @@ -65,63 +64,11 @@ export class PlanCompileAnalysisInvalidError extends Error { * @property {(timeoutMs?: number) => AbortSignal} [createRequestSignal] * @property {(delayMs: number) => Promise} [analysisSleep] * @property {() => number} [analysisNow] - * @property {(delayMs: number) => Promise} [publicationSleep] - * @property {() => number} [publicationNow] * @property {(progress: import("../plan-compile-progress.js").PlanCompileProgress) => void} [onProgress] * @property {typeof pushPlan} [push] * @property {typeof readPlanStatus} [readStatus] - * @property {typeof publishPlan} [publish] */ -/** - * Submit and analyze the exact current local Plan before invoking the internal - * GitHub Publication lifecycle. The Publication function performs the final - * local-byte check immediately before its conditional mutation. - * - * @param {CompilePlanOptions} options - */ -export async function compilePlanToGitHub({ - cwd, - apiUrl, - fetchFunction, - fileSystem, - createTemporaryId, - createRequestSignal, - analysisSleep, - analysisNow, - publicationSleep, - publicationNow, - onProgress = () => {}, - push = pushPlan, - readStatus = readPlanStatus, - publish = publishPlan, -}) { - const prepared = await preparePlan({ - cwd, - apiUrl, - fetchFunction, - fileSystem, - createTemporaryId, - createRequestSignal, - analysisSleep, - analysisNow, - onProgress, - push, - readStatus, - }); - - return publish({ - cwd, - fetchFunction, - fileSystem, - createRequestSignal, - sleep: publicationSleep, - now: publicationNow, - expectedEtag: prepared.pushed.etag, - onProgress, - }); -} - /** * @typedef {CompilePlanOptions & { * output: string, @@ -134,8 +81,7 @@ export async function compilePlanToGitHub({ /** * Submit and analyze the exact current local Plan, then start one direct * Compilation and materialize its verified artifact into an absent directory - * or the eligible current directory. GitHub Publication is the explicit - * --github mode owned by compilePlanToGitHub. + * or the eligible current directory. * * @param {CompilePlanToDirectoryOptions} options */ @@ -199,7 +145,7 @@ export async function compilePlanToDirectory({ } /** - * @param {Omit} options + * @param {CompilePlanOptions} options */ async function preparePlan({ cwd, diff --git a/src/commands/plan-publish.js b/src/commands/plan-publish.js deleted file mode 100644 index 1564125..0000000 --- a/src/commands/plan-publish.js +++ /dev/null @@ -1,1146 +0,0 @@ -import { createHash } from "node:crypto"; -import { lstatSync, readFileSync } from "node:fs"; -import path from "node:path"; - -import { isAuthenticationProblem } from "../api-authentication.js"; -import { - FirstDraftNetworkError, - FirstDraftProtocolError, - SERVICE_ROUTES, - isProblemBody, - readResponseBody, - responseMediaType, - sendRequest, - serviceEndpoint, -} from "../api-response.js"; -import { isUuidV7, readLocalFile, readPlanState } from "../plan-state.js"; - -const MAX_PLAN_BYTES = 1024 * 1024; -const REQUEST_TIMEOUT_MS = 30_000; -const WAIT_TIMEOUT_MS = 10 * 60_000; -const POLL_INTERVAL_MS = 1_000; -const MAX_IDENTIFIER_BYTES = 256; -const MAX_REPOSITORY_NAME_BYTES = 100; -const MAX_LOGIN_BYTES = 39; -const MAX_FAILURE_CODE_BYTES = 256; -const HEAD_ETAG_PATTERN = /^"sha256:([0-9a-f]{64})"$/; -const SHA256_PATTERN = /^[0-9a-f]{64}$/; -const GIT_SHA_PATTERN = /^[0-9a-f]{40}$/; -const RELEASE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/; -const GITHUB_NAME_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/; -const COMPILATION_STATUSES = new Set([ - "queued", - "running", - "succeeded", - "failed", - "cancelled", -]); -const PUBLICATION_STATUSES = new Set([ - "compiling", - "provisioning_repository", - "repository_unknown", - "publishing", - "publication_unknown", - "succeeded", - "repository_conflict", - "failed", - "cancelled", -]); -const TERMINAL_PUBLICATION_STATUSES = new Set([ - "succeeded", - "repository_conflict", - "failed", - "cancelled", -]); -const RESPONSE_KEYS = ["compilation", "project", "publication"]; -const PROJECT_KEYS = ["graph_version", "head_source_sha256", "id"]; -const COMPILATION_KEYS = [ - "analysis_run_id", - "artifact", - "compiler_release", - "graph_version", - "head_source_sha256", - "id", - "status", - "target", -]; -const TARGET_KEYS = ["id", "profile"]; -const ARTIFACT_KEYS = ["file_count", "manifest_sha256", "sha256"]; -const PUBLICATION_KEYS = [ - "completed_at", - "created_at", - "failure", - "id", - "progress", - "repository", - "started_at", - "status", -]; -const FAILURE_KEYS = ["code", "phase"]; -const PROGRESS_KEYS = ["phase", "reason_code", "retry_at", "retry_count"]; -const REPOSITORY_KEYS = [ - "commit_sha", - "default_branch", - "full_name", - "html_url", - "id", - "owner", - "private", - "tree_sha", -]; -const OWNER_KEYS = ["id", "login", "type"]; -const PROGRESS_PHASES = new Set([ - "compiling", - "preparing_repository", - "github_preflight", - "creating_repository", - "preparing_repository_reconciliation", - "reconciling_repository", - "preparing_artifact", - "publishing_artifact", - "preparing_publication_reconciliation", - "reconciling_publication", - "completed", - "failed", - "cancelled", -]); -const PROGRESS_REASON_CODES = new Set([ - "github.configuration_missing", - "github.oauth_unavailable", - "github.api_unavailable", - "github.reauthorization_required", - "github.account_mismatch", - "github.installation_unavailable", - "github.installation_not_ready", - "github.preflight_unavailable", - "github.preflight_unclassified", - "github.preflight_unavailable.configuration", - "github.preflight_unavailable.authorization", - "github.preflight_unavailable.repository_client", - "github.preflight_unavailable.artifact_preparation", - "github.preflight_unavailable.installation_token", - "github.preflight_unavailable.publication_preparation", - "github.preflight_unavailable.repository_ref_client", -]); -const MAX_PROGRESS_RETRY_COUNT = 7; -const RETRY_TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/; - -/** - * @typedef {object} PlanPublishFileSystem - * @property {typeof lstatSync} lstatSync - * @property {typeof readFileSync} readFileSync - */ - -/** @type {PlanPublishFileSystem} */ -const DEFAULT_FILE_SYSTEM = { lstatSync, readFileSync }; - -export class PublicationNotPushedError extends Error {} -export class PublicationLocalStateError extends Error {} -export class PublicationLocalPlanChangedError extends Error {} - -export class PublicationRequestOutcomeUnknownError extends Error { - /** - * @param {number | undefined} status - * @param {Record | null} [response] - */ - constructor(status, response = null) { - super("The publication request outcome is unknown."); - this.status = status; - this.response = response; - } -} - -export class PublicationStartRejectedError extends Error { - /** - * @param {number} status - * @param {Record} response - */ - constructor(status, response) { - super("First Draft rejected the publication request."); - this.status = status; - this.response = response; - } -} - -export class PublicationStatusUnavailableError extends Error { - /** - * @param {number | undefined} status - * @param {Record | null} [response] - */ - constructor(status, response = null) { - super("The publication status is unavailable."); - this.status = status; - this.response = response; - } -} - -export class PublicationStatusInvalidError extends Error { - /** @param {number} status */ - constructor(status) { - super("The publication status response is invalid."); - this.status = status; - } -} - -export class PublicationChangedError extends Error { - /** - * @param {PublicationResponse} current - * @param {PublicationResponse} rejected - */ - constructor(current, rejected) { - super("The pinned publication changed while it was being polled."); - this.current = current; - this.rejected = rejected; - } -} - -export class PublicationTimeoutError extends Error { - /** @param {PublicationResponse} current */ - constructor(current) { - super("The publication did not finish before the wait deadline."); - this.current = current; - } -} - -export class PublicationFailedError extends Error { - /** @param {PublicationResponse} current */ - constructor(current) { - super("The publication failed."); - this.current = current; - } -} - -export class PublicationCancelledError extends Error { - /** @param {PublicationResponse} current */ - constructor(current) { - super("The publication was cancelled."); - this.current = current; - } -} - -/** - * @typedef {object} PublicationResponse - * @property {{id: string, graph_version: number, head_source_sha256: string}} project - * @property {{id: string, analysis_run_id: string, graph_version: number, head_source_sha256: string, status: string, compiler_release: string, target: {id: string, profile: string}, artifact: null | {sha256: string, manifest_sha256: string, file_count: number}}} compilation - * @property {{id: string, status: string, repository: null | {id: number, private: true, owner: {id: number, login: string, type: "User"}, full_name: string, default_branch: string, html_url: string, tree_sha: string | null, commit_sha: string | null}, failure: null | {phase: string, code: string}, progress: {phase: string, retry_at: string | null, retry_count: number, reason_code: string | null}, created_at: string, started_at: string | null, completed_at: string | null}} publication - */ - -/** - * @typedef {object} PublishPlanOptions - * @property {string} cwd - * @property {string} [expectedEtag] - * @property {typeof globalThis.fetch} [fetchFunction] - * @property {PlanPublishFileSystem} [fileSystem] - * @property {(timeoutMs: number) => AbortSignal} [createRequestSignal] - * @property {(delayMs: number) => Promise} [sleep] - * @property {() => number} [now] - * @property {(progress: import("../plan-compile-progress.js").PlanCompileProgress) => void} [onProgress] - */ - -/** - * @param {PublishPlanOptions} options - * @returns {Promise} - */ -export async function publishPlan({ - cwd, - expectedEtag, - fetchFunction = globalThis.fetch, - fileSystem = DEFAULT_FILE_SYSTEM, - createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs), - sleep = sleepFor, - now = Date.now, - onProgress = () => {}, -}) { - const state = readPlanState({ cwd, fileSystem }); - if (state.api_url === undefined || state.foundation_plan_etag === undefined) { - throw new PublicationNotPushedError( - "The local Foundation Plan has not been pushed.", - ); - } - - if ( - expectedEtag !== undefined && - state.foundation_plan_etag !== expectedEtag - ) { - throw new PublicationLocalPlanChangedError( - "Local Plan state changed after this command accepted its Plan.", - ); - } - - const publicationEtag = expectedEtag ?? state.foundation_plan_etag; - const match = HEAD_ETAG_PATTERN.exec(publicationEtag); - if (match === null) { - throw new PublicationLocalStateError( - "The saved Foundation Plan ETag cannot identify its accepted source.", - ); - } - const headSourceSha256 = match[1] ?? ""; - const planSource = readLocalFile( - path.join(cwd, ".firstdraft", "foundation-plan.json"), - MAX_PLAN_BYTES, - fileSystem, - ); - if (sha256(planSource) !== headSourceSha256) { - throw new PublicationLocalPlanChangedError( - "The local Foundation Plan differs from the accepted Plan.", - ); - } - - const apiUrl = state.api_url; - const deadline = now() + WAIT_TIMEOUT_MS; - let initial; - - onProgress({ phase: "compilation", status: "waiting" }); - - try { - initial = await startPublication({ - apiUrl, - projectId: state.project_id, - headSourceSha256, - etag: publicationEtag, - fetchFunction, - createRequestSignal, - }); - } catch (error) { - if (!(error instanceof PublicationRequestOutcomeUnknownError)) throw error; - - try { - initial = await readPublicationStatus({ - apiUrl, - projectId: state.project_id, - headSourceSha256, - fetchFunction, - createRequestSignal, - requestTimeout: Math.max( - 1, - Math.min(REQUEST_TIMEOUT_MS, deadline - now()), - ), - }); - } catch (reconciliationError) { - if ( - reconciliationError instanceof PublicationStatusUnavailableError && - isAuthenticationProblem( - reconciliationError.status, - reconciliationError.response, - ) - ) { - throw reconciliationError; - } - if ( - reconciliationError instanceof PublicationStatusUnavailableError || - reconciliationError instanceof PublicationStatusInvalidError - ) { - let status = reconciliationError.status ?? error.status; - let response = error.response; - if ( - reconciliationError instanceof PublicationStatusUnavailableError && - reconciliationError.response !== null - ) { - status = reconciliationError.status; - response = reconciliationError.response; - } else if (error.response !== null) { - status = error.status; - } - throw new PublicationRequestOutcomeUnknownError(status, response); - } - - throw reconciliationError; - } - } - - let current = initial; - reportProgress(onProgress, current); - while (!TERMINAL_PUBLICATION_STATUSES.has(current.publication.status)) { - const remaining = deadline - now(); - if (remaining <= 0) throw new PublicationTimeoutError(current); - - await sleep(Math.min(POLL_INTERVAL_MS, remaining)); - if (now() >= deadline) throw new PublicationTimeoutError(current); - - const next = await readPublicationStatus({ - apiUrl, - projectId: state.project_id, - headSourceSha256, - fetchFunction, - createRequestSignal, - requestTimeout: Math.max( - 1, - Math.min(REQUEST_TIMEOUT_MS, deadline - now()), - ), - }); - if (!samePublication(initial, next) || !validTransition(current, next)) { - throw new PublicationChangedError(current, next); - } - current = next; - reportProgress(onProgress, current); - } - - if ( - current.publication.status === "failed" || - current.publication.status === "repository_conflict" - ) { - throw new PublicationFailedError(current); - } - if (current.publication.status === "cancelled") { - throw new PublicationCancelledError(current); - } - - return current; -} - -/** - * @param {object} options - * @param {string} options.apiUrl - * @param {string} options.projectId - * @param {string} options.headSourceSha256 - * @param {string} options.etag - * @param {typeof globalThis.fetch} options.fetchFunction - * @param {(timeoutMs: number) => AbortSignal} options.createRequestSignal - */ -async function startPublication({ - apiUrl, - projectId, - headSourceSha256, - etag, - fetchFunction, - createRequestSignal, -}) { - const endpoint = serviceEndpoint(SERVICE_ROUTES.startPublication, apiUrl, { - project_id: projectId, - }); - let response; - let body; - try { - response = await sendRequest(fetchFunction, endpoint, { - headers: { - Accept: "application/json, application/problem+json", - "If-Match": etag, - }, - redirect: "error", - signal: createRequestSignal(REQUEST_TIMEOUT_MS), - }); - body = await readResponseBody(response); - } catch (error) { - if ( - error instanceof FirstDraftNetworkError || - error instanceof FirstDraftProtocolError - ) { - throw new PublicationRequestOutcomeUnknownError(error.status); - } - - throw error; - } - - if (response.status !== 200 && response.status !== 201) { - const problem = safeProblem(response, body); - if (response.ok || problem === null) { - throw new PublicationRequestOutcomeUnknownError(response.status); - } - if (response.status === 408 || response.status >= 500) { - throw new PublicationRequestOutcomeUnknownError(response.status, problem); - } - - throw new PublicationStartRejectedError(response.status, problem); - } - - const parsed = parsePublicationResponse(body, projectId, headSourceSha256); - if (responseMediaType(response) !== "application/json" || parsed === null) { - throw new PublicationRequestOutcomeUnknownError(response.status); - } - - return parsed; -} - -/** - * @param {object} options - * @param {string} options.apiUrl - * @param {string} options.projectId - * @param {string} options.headSourceSha256 - * @param {typeof globalThis.fetch} options.fetchFunction - * @param {(timeoutMs: number) => AbortSignal} options.createRequestSignal - * @param {number} options.requestTimeout - */ -async function readPublicationStatus({ - apiUrl, - projectId, - headSourceSha256, - fetchFunction, - createRequestSignal, - requestTimeout, -}) { - const endpoint = serviceEndpoint(SERVICE_ROUTES.readPublication, apiUrl, { - project_id: projectId, - }); - let response; - let body; - try { - response = await sendRequest(fetchFunction, endpoint, { - headers: { Accept: "application/json, application/problem+json" }, - redirect: "error", - signal: createRequestSignal(requestTimeout), - }); - body = await readResponseBody(response); - } catch (error) { - if (error instanceof FirstDraftNetworkError) { - throw new PublicationStatusUnavailableError(error.status); - } - if (error instanceof FirstDraftProtocolError) { - throw new PublicationStatusInvalidError(error.status); - } - - throw error; - } - - if (response.status !== 200) { - if (!response.ok) { - throw new PublicationStatusUnavailableError( - response.status, - safeProblem(response, body), - ); - } - throw new PublicationStatusInvalidError(response.status); - } - - const parsed = parsePublicationResponse(body, projectId, headSourceSha256); - if (responseMediaType(response) !== "application/json" || parsed === null) { - throw new PublicationStatusInvalidError(response.status); - } - - return parsed; -} - -/** - * @param {unknown} value - * @param {string} projectId - * @param {string} headSourceSha256 - * @returns {PublicationResponse | null} - */ -function parsePublicationResponse(value, projectId, headSourceSha256) { - if ( - !hasExactKeySet(value, RESPONSE_KEYS) || - !hasExactKeySet(value.project, PROJECT_KEYS) || - !hasExactKeySet(value.compilation, COMPILATION_KEYS) || - !hasExactKeySet(value.publication, PUBLICATION_KEYS) - ) { - return null; - } - - const project = value.project; - const compilation = value.compilation; - const publication = value.publication; - if ( - project.id !== projectId || - !isGraphVersion(project.graph_version) || - project.head_source_sha256 !== headSourceSha256 || - !isUuidV7(compilation.id) || - !isUuidV7(compilation.analysis_run_id) || - compilation.graph_version !== project.graph_version || - compilation.head_source_sha256 !== headSourceSha256 || - typeof compilation.status !== "string" || - !COMPILATION_STATUSES.has(compilation.status) || - !isRelease(compilation.compiler_release) || - !hasExactKeySet(compilation.target, TARGET_KEYS) || - !isRelease(compilation.target.id) || - !isRelease(compilation.target.profile) || - !isNullableArtifact(compilation.artifact) || - !isUuidV7(publication.id) || - typeof publication.status !== "string" || - !PUBLICATION_STATUSES.has(publication.status) || - !isNullableRepository(publication.repository) || - !isNullableFailure(publication.failure) || - !isProgress(publication.progress, publication.status) || - !isTimestamp(publication.created_at) || - !isNullableTimestamp(publication.started_at) || - !isNullableTimestamp(publication.completed_at) || - !hasValidCompilationShape(compilation) || - !hasValidPublicationShape(compilation, publication) - ) { - return null; - } - - const target = /** @type {{id: string, profile: string}} */ ( - compilation.target - ); - const artifact = - /** @type {null | {sha256: string, manifest_sha256: string, file_count: number}} */ ( - compilation.artifact - ); - const repository = - /** @type {null | {id: number, private: true, owner: {id: number, login: string, type: "User"}, full_name: string, default_branch: string, html_url: string, tree_sha: string | null, commit_sha: string | null}} */ ( - publication.repository - ); - const failure = /** @type {null | {phase: string, code: string}} */ ( - publication.failure - ); - const progress = - /** @type {{phase: string, retry_at: string | null, retry_count: number, reason_code: string | null}} */ ( - publication.progress - ); - - return { - project: { - id: project.id, - graph_version: /** @type {number} */ (project.graph_version), - head_source_sha256: project.head_source_sha256, - }, - compilation: { - id: compilation.id, - analysis_run_id: compilation.analysis_run_id, - graph_version: /** @type {number} */ (compilation.graph_version), - head_source_sha256: compilation.head_source_sha256, - status: compilation.status, - compiler_release: /** @type {string} */ (compilation.compiler_release), - target: { id: target.id, profile: target.profile }, - artifact: - artifact === null - ? null - : { - sha256: artifact.sha256, - manifest_sha256: artifact.manifest_sha256, - file_count: artifact.file_count, - }, - }, - publication: { - id: publication.id, - status: publication.status, - repository: - repository === null - ? null - : { - id: repository.id, - private: true, - owner: { - id: repository.owner.id, - login: repository.owner.login, - type: "User", - }, - full_name: repository.full_name, - default_branch: repository.default_branch, - html_url: repository.html_url, - tree_sha: repository.tree_sha, - commit_sha: repository.commit_sha, - }, - failure: - failure === null ? null : { phase: failure.phase, code: failure.code }, - progress: { - phase: progress.phase, - retry_at: progress.retry_at, - retry_count: progress.retry_count, - reason_code: progress.reason_code, - }, - created_at: /** @type {string} */ (publication.created_at), - started_at: /** @type {string | null} */ (publication.started_at), - completed_at: /** @type {string | null} */ (publication.completed_at), - }, - }; -} - -/** @param {Record} compilation */ -function hasValidCompilationShape(compilation) { - return compilation.status === "succeeded" - ? compilation.artifact !== null - : compilation.artifact === null; -} - -/** - * @param {Record} compilation - * @param {Record} publication - */ -function hasValidPublicationShape(compilation, publication) { - const status = String(publication.status); - const terminal = TERMINAL_PUBLICATION_STATUSES.has(status); - const failureExpected = - status === "failed" || status === "repository_conflict"; - const created = timestampMilliseconds(String(publication.created_at)); - const started = - publication.started_at === null - ? null - : timestampMilliseconds(String(publication.started_at)); - const completed = - publication.completed_at === null - ? null - : timestampMilliseconds(String(publication.completed_at)); - const repository = /** @type {Record | null} */ ( - publication.repository - ); - - if ( - (terminal && completed === null) || - (!terminal && completed !== null) || - (failureExpected && publication.failure === null) || - (!failureExpected && publication.failure !== null) || - (status !== "compiling" && - started === null && - !( - (status === "failed" && compilation.status === "failed") || - (status === "cancelled" && compilation.status === "cancelled") - )) || - (started !== null && started < created) || - (completed !== null && completed < created) || - (started !== null && completed !== null && completed < started) || - (status === "compiling" && - !["queued", "running", "succeeded"].includes( - String(compilation.status), - )) || - (status === "failed" && - !["failed", "succeeded"].includes(String(compilation.status))) || - (status === "cancelled" && - !["cancelled", "succeeded"].includes(String(compilation.status))) || - (!["compiling", "failed", "cancelled"].includes(status) && - compilation.status !== "succeeded") || - (["publishing", "publication_unknown", "succeeded"].includes(status) && - repository === null) - ) { - return false; - } - - if (status !== "succeeded") return true; - - return ( - repository !== null && - typeof repository.tree_sha === "string" && - typeof repository.commit_sha === "string" - ); -} - -/** @param {unknown} value */ -function isNullableArtifact(value) { - return ( - value === null || - (hasExactKeySet(value, ARTIFACT_KEYS) && - typeof value.sha256 === "string" && - SHA256_PATTERN.test(value.sha256) && - typeof value.manifest_sha256 === "string" && - SHA256_PATTERN.test(value.manifest_sha256) && - Number.isSafeInteger(value.file_count) && - Number(value.file_count) >= 0) - ); -} - -/** @param {unknown} value */ -function isNullableFailure(value) { - return ( - value === null || - (hasExactKeySet(value, FAILURE_KEYS) && - isRelease(value.phase) && - isFailureCode(value.code)) - ); -} - -/** @param {unknown} value @param {unknown} publicationStatus */ -function isProgress(value, publicationStatus) { - if ( - !hasExactKeySet(value, PROGRESS_KEYS) || - typeof value.phase !== "string" || - !PROGRESS_PHASES.has(value.phase) || - !Number.isSafeInteger(value.retry_count) || - Number(value.retry_count) < 0 || - Number(value.retry_count) > MAX_PROGRESS_RETRY_COUNT || - !isNullableRetryTimestamp(value.retry_at) || - !( - value.reason_code === null || - (typeof value.reason_code === "string" && - PROGRESS_REASON_CODES.has(value.reason_code)) - ) || - !progressMatchesPublicationStatus(value.phase, publicationStatus) - ) { - return false; - } - - if (value.phase !== "github_preflight") { - return ( - value.retry_at === null && - value.retry_count === 0 && - value.reason_code === null - ); - } - - return value.retry_count === 0 - ? value.retry_at === null && value.reason_code === null - : value.reason_code !== null; -} - -/** @param {string} progressPhase @param {unknown} publicationStatus */ -function progressMatchesPublicationStatus(progressPhase, publicationStatus) { - if (progressPhase === "compiling") return publicationStatus === "compiling"; - if (progressPhase === "completed") return publicationStatus === "succeeded"; - if (progressPhase === "failed") { - return ( - publicationStatus === "failed" || - publicationStatus === "repository_conflict" - ); - } - if (progressPhase === "cancelled") return publicationStatus === "cancelled"; - if (progressPhase === "github_preflight") { - return [ - "provisioning_repository", - "repository_unknown", - "publishing", - "publication_unknown", - ].includes(String(publicationStatus)); - } - - const expectedStatus = new Map([ - ["preparing_repository", "provisioning_repository"], - ["creating_repository", "provisioning_repository"], - ["preparing_repository_reconciliation", "repository_unknown"], - ["reconciling_repository", "repository_unknown"], - ["preparing_artifact", "publishing"], - ["publishing_artifact", "publishing"], - ["preparing_publication_reconciliation", "publication_unknown"], - ["reconciling_publication", "publication_unknown"], - ]).get(progressPhase); - return publicationStatus === expectedStatus; -} - -/** @param {unknown} value */ -function isNullableRetryTimestamp(value) { - return ( - value === null || - (typeof value === "string" && - RETRY_TIMESTAMP_PATTERN.test(value) && - isTimestamp(value)) - ); -} - -/** @param {unknown} value */ -function isNullableRepository(value) { - if (value === null) return true; - if ( - !hasExactKeySet(value, REPOSITORY_KEYS) || - !isPositiveInteger(value.id) || - value.private !== true || - !hasExactKeySet(value.owner, OWNER_KEYS) || - !isPositiveInteger(value.owner.id) || - value.owner.type !== "User" || - !isGithubName(value.owner.login, MAX_LOGIN_BYTES) || - typeof value.full_name !== "string" || - typeof value.default_branch !== "string" || - typeof value.html_url !== "string" || - !isNullableGitSha(value.tree_sha) || - !isNullableGitSha(value.commit_sha) || - (value.tree_sha === null) !== (value.commit_sha === null) - ) { - return false; - } - - const prefix = `${value.owner.login}/`; - const repositoryName = value.full_name.startsWith(prefix) - ? value.full_name.slice(prefix.length) - : ""; - return ( - isGithubName(repositoryName, MAX_REPOSITORY_NAME_BYTES) && - isGitBranch(value.default_branch) && - value.html_url === `https://github.com/${value.full_name}` - ); -} - -/** @param {PublicationResponse} first @param {PublicationResponse} current */ -function samePublication(first, current) { - return ( - current.project.id === first.project.id && - current.project.graph_version === first.project.graph_version && - current.project.head_source_sha256 === first.project.head_source_sha256 && - current.compilation.id === first.compilation.id && - current.compilation.analysis_run_id === first.compilation.analysis_run_id && - current.compilation.graph_version === first.compilation.graph_version && - current.compilation.head_source_sha256 === - first.compilation.head_source_sha256 && - current.compilation.compiler_release === - first.compilation.compiler_release && - current.compilation.target.id === first.compilation.target.id && - current.compilation.target.profile === first.compilation.target.profile && - current.publication.id === first.publication.id && - current.publication.created_at === first.publication.created_at - ); -} - -/** @param {PublicationResponse} previous @param {PublicationResponse} current */ -function validTransition(previous, current) { - if (!validCompilationTransition(previous.compilation, current.compilation)) { - return false; - } - if (!validPublicationStatusTransition(previous, current)) return false; - if (!validRepositoryTransition(previous, current)) return false; - - return ( - (previous.publication.started_at === null || - current.publication.started_at === previous.publication.started_at) && - (previous.publication.completed_at === null || - current.publication.completed_at === previous.publication.completed_at) && - (previous.publication.failure === null || - JSON.stringify(current.publication.failure) === - JSON.stringify(previous.publication.failure)) - ); -} - -/** - * @param {PublicationResponse["compilation"]} previous - * @param {PublicationResponse["compilation"]} current - */ -function validCompilationTransition(previous, current) { - if (previous.status === current.status) { - return ( - JSON.stringify(previous.artifact) === JSON.stringify(current.artifact) - ); - } - - if (previous.status === "queued") { - return ["running", "succeeded", "failed", "cancelled"].includes( - current.status, - ); - } - return ( - previous.status === "running" && - ["succeeded", "failed", "cancelled"].includes(current.status) - ); -} - -/** @param {PublicationResponse} previous @param {PublicationResponse} current */ -function validPublicationStatusTransition(previous, current) { - const from = previous.publication.status; - const to = current.publication.status; - if (from === to) { - return ( - current.publication.started_at === previous.publication.started_at && - current.publication.completed_at === previous.publication.completed_at && - JSON.stringify(current.publication.failure) === - JSON.stringify(previous.publication.failure) - ); - } - - if ( - (from === "repository_unknown" && to === "provisioning_repository") || - (from === "publication_unknown" && to === "publishing") - ) { - return false; - } - - return publicationStage(to) >= publicationStage(from); -} - -/** @param {string} status */ -function publicationStage(status) { - if (status === "compiling") return 0; - if (status === "provisioning_repository" || status === "repository_unknown") { - return 1; - } - if (status === "publishing" || status === "publication_unknown") return 2; - return 3; -} - -/** @param {PublicationResponse} previous @param {PublicationResponse} current */ -function validRepositoryTransition(previous, current) { - const before = previous.publication.repository; - const after = current.publication.repository; - if (before === null) return true; - if (after === null) return false; - - return ( - after.id === before.id && - after.private === before.private && - after.owner.id === before.owner.id && - after.owner.login === before.owner.login && - after.owner.type === before.owner.type && - after.full_name === before.full_name && - after.default_branch === before.default_branch && - after.html_url === before.html_url && - (before.tree_sha === null || after.tree_sha === before.tree_sha) && - (before.commit_sha === null || after.commit_sha === before.commit_sha) - ); -} - -/** - * @param {(progress: import("../plan-compile-progress.js").PlanCompileProgress) => void} onProgress - * @param {PublicationResponse} current - */ -function reportProgress(onProgress, current) { - const progress = current.publication.progress; - onProgress({ - phase: "publication", - compilationStatus: - /** @type {"queued" | "running" | "succeeded" | "failed" | "cancelled"} */ ( - current.compilation.status - ), - publicationPhase: progress.phase, - retryAt: progress.retry_at, - retryCount: progress.retry_count, - reasonCode: progress.reason_code, - }); -} - -/** @param {Response} response @param {unknown} body */ -function safeProblem(response, body) { - if (!isProblemBody(response, body)) return null; - const problem = /** @type {Record} */ (body); - - return { - ...(problem.type === "about:blank" ? { type: problem.type } : {}), - title: problem.title, - status: problem.status, - code: problem.code, - detail: problem.detail, - }; -} - -/** @param {number} delayMs */ -function sleepFor(delayMs) { - return new Promise((resolve) => { - setTimeout(resolve, delayMs); - }); -} - -/** @param {Buffer} value */ -function sha256(value) { - return createHash("sha256").update(value).digest("hex"); -} - -/** @param {unknown} value */ -function isRelease(value) { - return ( - typeof value === "string" && - Buffer.byteLength(value) <= MAX_IDENTIFIER_BYTES && - RELEASE_PATTERN.test(value) - ); -} - -/** @param {unknown} value */ -function isFailureCode(value) { - return ( - typeof value === "string" && - Buffer.byteLength(value) <= MAX_FAILURE_CODE_BYTES && - RELEASE_PATTERN.test(value) - ); -} - -/** @param {unknown} value */ -function isGraphVersion(value) { - return Number.isSafeInteger(value) && Number(value) >= 1; -} - -/** @param {unknown} value */ -function isPositiveInteger(value) { - return Number.isSafeInteger(value) && Number(value) > 0; -} - -/** @param {unknown} value */ -function isNullableGitSha(value) { - return ( - value === null || (typeof value === "string" && GIT_SHA_PATTERN.test(value)) - ); -} - -/** @param {unknown} value @param {number} maximumBytes */ -function isGithubName(value, maximumBytes) { - return ( - typeof value === "string" && - Buffer.byteLength(value) <= maximumBytes && - GITHUB_NAME_PATTERN.test(value) - ); -} - -/** @param {unknown} value */ -function isGitBranch(value) { - return ( - typeof value === "string" && - Buffer.byteLength(value) <= MAX_IDENTIFIER_BYTES && - value.length > 0 && - !value.startsWith(".") && - !value.endsWith(".") && - !value.endsWith("/") && - !value.endsWith(".lock") && - !value.includes("..") && - !value.includes("//") && - ![...value].some((character) => { - const codePoint = character.codePointAt(0) ?? 0; - return codePoint <= 0x20 || "~^:?*[\\".includes(character); - }) - ); -} - -/** @param {unknown} value */ -function isNullableTimestamp(value) { - return value === null || isTimestamp(value); -} - -/** @param {unknown} value */ -function isTimestamp(value) { - return timestampParts(value) !== null; -} - -/** @param {string} value */ -function timestampMilliseconds(value) { - const parsed = Date.parse(value); - if (Number.isFinite(parsed)) return parsed; - - return Date.parse(value.replace(/:60(?=[.,Zz+-])/, ":59")) + 1_000; -} - -/** @param {unknown} value */ -function timestampParts(value) { - if (typeof value !== "string") return null; - - const match = - /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|([+-])(\d{2}):(\d{2}))$/.exec( - value, - ); - if (!match) return null; - - const year = Number(match[1]); - const month = Number(match[2]); - const day = Number(match[3]); - const hour = Number(match[4]); - const minute = Number(match[5]); - const second = Number(match[6]); - const offsetHour = match[8] === undefined ? 0 : Number(match[8]); - const offsetMinute = match[9] === undefined ? 0 : Number(match[9]); - if ( - month < 1 || - month > 12 || - day < 1 || - day > daysInMonth(year, month) || - hour > 23 || - minute > 59 || - second > 60 || - (second === 60 && (hour !== 23 || minute !== 59)) || - offsetHour > 23 || - offsetMinute > 59 - ) { - return null; - } - - return true; -} - -/** @param {number} year @param {number} month */ -function daysInMonth(year, month) { - if (month === 2) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28; - } - - return [4, 6, 9, 11].includes(month) ? 30 : 31; -} - -/** - * @param {unknown} value - * @param {string[]} keys - * @returns {value is Record} - */ -function hasExactKeySet(value, keys) { - return ( - isRecord(value) && arraysEqual(Object.keys(value).sort(), [...keys].sort()) - ); -} - -/** @param {unknown} value @returns {value is Record} */ -function isRecord(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} - -/** @param {unknown[]} left @param {unknown[]} right */ -function arraysEqual(left, right) { - return ( - left.length === right.length && - left.every((value, index) => value === right[index]) - ); -} diff --git a/src/plan-compile-progress.js b/src/plan-compile-progress.js index 7cb8a67..ebf40e7 100644 --- a/src/plan-compile-progress.js +++ b/src/plan-compile-progress.js @@ -1,23 +1,5 @@ const PREFIX = "First Draft: "; -const PUBLICATION_MESSAGES = new Map([ - ["preparing_repository", "Preparing private GitHub repository..."], - ["creating_repository", "Creating private GitHub repository..."], - [ - "preparing_repository_reconciliation", - "Preparing to verify GitHub repository creation...", - ], - ["reconciling_repository", "Verifying GitHub repository creation..."], - ["preparing_artifact", "Preparing compiled application..."], - ["publishing_artifact", "Publishing compiled application to GitHub..."], - [ - "preparing_publication_reconciliation", - "Preparing to verify GitHub publication...", - ], - ["reconciling_publication", "Verifying GitHub publication..."], - ["completed", "GitHub publication complete."], -]); - /** * @typedef {object} AnalysisProgress * @property {"analysis"} phase @@ -31,29 +13,18 @@ const PUBLICATION_MESSAGES = new Map([ */ /** - * @typedef {object} PublicationProgress - * @property {"publication"} phase - * @property {"queued" | "running" | "succeeded" | "failed" | "cancelled"} compilationStatus - * @property {string} publicationPhase - * @property {string | null} retryAt - * @property {number} retryCount - * @property {string | null} reasonCode - */ - -/** - * @typedef {AnalysisProgress | CompilationProgress | PublicationProgress} PlanCompileProgress + * @typedef {AnalysisProgress | CompilationProgress} PlanCompileProgress */ /** * Convert deliberately narrow lifecycle observations into stable progress. - * This boundary never receives response projections, identifiers, hashes, - * repository names, URLs, or local state. + * This boundary never receives response projections, identifiers, hashes, URLs, + * or local state. * * @param {{write: (text: string) => unknown}} writer * @returns {(progress: PlanCompileProgress) => void} */ export function createPlanCompileProgressReporter(writer) { - let compilationSucceeded = false; /** @type {string | null} */ let previousProgress = null; @@ -76,54 +47,10 @@ export function createPlanCompileProgressReporter(writer) { return; } - if (progress.phase === "compilation") { - write( - progress.status === "waiting" - ? "Compiling application..." - : "Application compiled.", - ); - return; - } - - if (progress.compilationStatus === "succeeded" && !compilationSucceeded) { - write("Application compiled."); - compilationSucceeded = true; - } - - if (progress.publicationPhase === "compiling") return; - if (progress.publicationPhase === "failed") { - write( - progress.compilationStatus === "failed" - ? "Application compilation failed." - : "GitHub publication failed.", - ); - return; - } - if (progress.publicationPhase === "cancelled") { - write( - progress.compilationStatus === "cancelled" - ? "Application compilation cancelled." - : "GitHub publication cancelled.", - ); - return; - } - if (progress.publicationPhase === "github_preflight") { - write(githubPreflightMessage(progress)); - return; - } - - const message = PUBLICATION_MESSAGES.get(progress.publicationPhase); - if (message !== undefined) write(message); + write( + progress.status === "waiting" + ? "Compiling application..." + : "Application compiled.", + ); }; } - -/** @param {PublicationProgress} progress */ -function githubPreflightMessage(progress) { - if (progress.retryCount === 0) return "Checking GitHub access..."; - - const retry = - progress.retryAt === null - ? "automatic retries paused; operator recovery required" - : `next retry: ${progress.retryAt}`; - return `Checking GitHub access (reason: ${progress.reasonCode}; retry count: ${progress.retryCount}; ${retry}).`; -} diff --git a/test/api-environments.test.js b/test/api-environments.test.js index a6e8f46..38f0cb4 100644 --- a/test/api-environments.test.js +++ b/test/api-environments.test.js @@ -21,7 +21,6 @@ const REMOTE_COMMANDS = [ ["plan", "push"], ["plan", "status"], ["plan", "compile", "--output", "application"], - ["plan", "compile", "--github"], ["compilation", "status", COMPILATION_ID], ["compilation", "download", COMPILATION_ID, "--output", "application"], ["compilation", "cancel", COMPILATION_ID], diff --git a/test/plan-compile.test.js b/test/plan-compile.test.js index 57e2ae2..e3b7fe0 100644 --- a/test/plan-compile.test.js +++ b/test/plan-compile.test.js @@ -27,80 +27,42 @@ const PROJECT_ID = "01900000-0000-7000-8000-000000002001"; const ANALYSIS_ID = "01900000-0000-7000-8000-000000002002"; const STALE_ANALYSIS_ID = "01900000-0000-7000-8000-000000002005"; const COMPILATION_ID = "01900000-0000-7000-8000-000000002003"; -const PUBLICATION_ID = "01900000-0000-7000-8000-000000002004"; const API_TOKEN = `fd_${"a".repeat(43)}`; const PLAN_SOURCE = Buffer.from( '{"format":"firstdraft.foundation-plan.sketch/0.23","application":{"key":"movie_catalog","name":"Movie Catalog"}}\n', ); const HEAD_SHA256 = sha256(PLAN_SOURCE); const ETAG = `"sha256:${HEAD_SHA256}"`; -const CREATED_AT = "2026-08-04T12:00:00.000Z"; const STARTED_AT = "2026-08-04T12:00:01.000Z"; const COMPLETED_AT = "2026-08-04T12:00:02.000Z"; -const REPOSITORY_URL = "https://github.com/octocat/movie-catalog"; const ANALYZER_RELEASE = "foundation-plan-rails/application-2026-09-27-bookmark-assets"; const COMPILER_RELEASE = "foundation-plan-rails/compiler-application-2026-09-27-bookmark-assets"; const TARGET = { id: "rails", profile: RAILS_TARGET_PROFILE }; -const SUCCESS_PROGRESS = `First Draft: Analyzing Foundation Plan... -First Draft: Foundation Plan analysis valid. -First Draft: Compiling application... -First Draft: Application compiled. -First Draft: GitHub publication complete. +const PLAN_COMPILE_HELP = `First Draft CLI + +Usage: + firstdraft plan compile + firstdraft plan compile --output + +Options: + --staging Use staging; reject a different saved origin + --output Materialize here (default: .) + -h, --help Show help + +Environment: + FIRSTDRAFT_API_TOKEN Authenticate production or custom API origins + FIRSTDRAFT_STAGING_API_TOKEN Authenticate staging.firstdraft.com + FIRSTDRAFT_API_URL Override the initial API origin + +The command submits the exact current whole-file Plan, waits for its analysis, +and proceeds only when that analysis is valid. By default it materializes the +verified application in the current directory, preserving existing root material +under .firstdraft/design. --output can select another absent directory. +Progress is written to stderr. `; -test("plan compile submits exact bytes, waits for valid analysis, and publishes once", async (context) => { - /** @type {{method: string | undefined, url: string | undefined, headers: import("node:http").IncomingHttpHeaders, body: Buffer}[]} */ - const requests = []; - const server = createServer(async (request, response) => { - const body = await readRequestBody(request); - requests.push({ - method: request.method, - url: request.url, - headers: request.headers, - body, - }); - - if (request.method === "PUT" && request.url === planPath()) { - respondJson(response, 201, acceptedPlanBody(), { ETag: ETAG }); - return; - } - if (request.method === "GET" && request.url === analysisPath()) { - respondJson(response, 200, analysisBody("valid")); - return; - } - if (request.method === "PUT" && request.url === publicationPath()) { - respondJson(response, 201, publicationBody()); - return; - } - response.writeHead(404).end(); - }); - const apiUrl = await listen(context, server); - const cwd = localDirectory(context, PLAN_SOURCE); - const result = await invoke(["plan", "compile", "--github"], { cwd, apiUrl }); - - assert.equal(result.status, 0); - assert.equal(result.stderr, SUCCESS_PROGRESS); - assert.deepEqual(result.stdoutWrites, [`${REPOSITORY_URL}\n`]); - assert.deepEqual( - requests.map(({ method, url }) => [method, url]), - [ - ["PUT", planPath()], - ["GET", analysisPath()], - ["PUT", publicationPath()], - ], - ); - assert.deepEqual(requests[0]?.body, PLAN_SOURCE); - assert.equal(requests[0]?.headers["if-none-match"], "*"); - assert.equal(requests[2]?.headers["if-match"], ETAG); - assert( - requests.every( - ({ headers }) => headers.authorization === `Bearer ${API_TOKEN}`, - ), - ); -}); - test("staging compilation keeps its own credential through push, analysis, start, and artifact", async (context) => { const cwd = localDirectory(context, PLAN_SOURCE); const artifact = directArtifactFixture(); @@ -152,7 +114,7 @@ test("staging compilation keeps its own credential through push, analysis, start assert.doesNotMatch(result.stdout + result.stderr, /canary/); }); -test("plan compile --output completes the HTTP journey without GitHub Publication", async (context) => { +test("plan compile --output submits exact bytes and completes the HTTP journey", async (context) => { /** @type {{method: string | undefined, url: string | undefined, headers: import("node:http").IncomingHttpHeaders, body: Buffer}[]} */ const requests = []; const artifact = directArtifactFixture(); @@ -229,6 +191,8 @@ test("plan compile --output completes the HTTP journey without GitHub Publicatio ["GET", directArtifactPath()], ], ); + assert.deepEqual(requests[0]?.body, PLAN_SOURCE); + assert.equal(requests[0]?.headers["if-none-match"], "*"); assert.equal(requests[2]?.body.byteLength, 0); assert.equal(requests[2]?.headers["if-match"], ETAG); assert( @@ -265,58 +229,7 @@ test("plan compile --output completes the HTTP journey without GitHub Publicatio ); }); -test("plan compile may push unchanged bytes before analysis and Publication", async (context) => { - const cwd = localDirectory(context, PLAN_SOURCE, { - api_url: "https://api.example.test", - foundation_plan_etag: ETAG, - }); - /** @type {unknown[]} */ - const order = []; - const expected = publicationBody(); - const result = await invoke(["plan", "compile", "--github"], { - cwd, - planCompilePush: async (/** @type {{cwd: string}} */ options) => { - order.push(["push", options.cwd]); - return { - status: 200, - etag: ETAG, - outcome: "updated", - body: acceptedPlanBody(), - }; - }, - planCompileReadStatus: async (/** @type {{wait?: boolean}} */ options) => { - order.push(["analysis", options.wait]); - return { status: 200, body: analysisBody("valid") }; - }, - planCompilePublish: async ( - /** @type {{onProgress: (progress: unknown) => void}} */ options, - ) => { - order.push(["publication"]); - options.onProgress({ phase: "compilation", status: "waiting" }); - options.onProgress({ - phase: "publication", - compilationStatus: "succeeded", - publicationPhase: "completed", - retryAt: null, - retryCount: 0, - reasonCode: null, - }); - return expected; - }, - }); - - assert.equal(result.status, 0); - 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) => { +test("plan compile --output pushes, waits for valid analysis, then compiles", async (context) => { const cwd = localDirectory(context, PLAN_SOURCE, { api_url: "https://api.example.test", foundation_plan_etag: ETAG, @@ -345,9 +258,6 @@ test("plan compile --output starts a direct Compilation without Publication", as order.push("analysis"); return { status: 200, body: analysisBody("valid") }; }, - planCompilePublish: async () => { - throw new Error("Publication must remain untouched"); - }, planCompileDownload: async ( /** @type {{expectedEtag: string, expected: Record, output: string, onProgress: (progress: unknown) => void}} */ options, ) => { @@ -443,7 +353,7 @@ test("plan compile root output locks before push and releases after invalid anal }); for (const outputArgs of [[], ["--output", "."]]) { - test(`plan compile ${outputArgs.join(" ")} materializes root output without Publication`, async (context) => { + test(`plan compile ${outputArgs.join(" ")} materializes root output`, async (context) => { if (process.platform === "win32") return context.skip(); const cwd = localDirectory(context, PLAN_SOURCE, { api_url: "https://api.example.test", @@ -460,9 +370,6 @@ for (const outputArgs of [[], ["--output", "."]]) { status: 200, body: analysisBody("valid"), }), - planCompilePublish: async () => { - throw new Error("Publication must remain untouched"); - }, fetchFunction: sequenceFetch( [ jsonResponse(directCompilationBody("succeeded", artifact), 202, { @@ -933,8 +840,8 @@ test("plan compile waits past a terminal analysis for the prior graph version", }); /** @type {unknown[]} */ const calls = []; - let publications = 0; - const result = await invoke(["plan", "compile", "--github"], { + let compilations = 0; + const result = await invoke(["plan", "compile", "--output", "application"], { cwd, planCompilePush: async () => ({ status: 200, @@ -950,15 +857,15 @@ test("plan compile waits past a terminal analysis for the prior graph version", calls, ), planCompileSleep: async () => {}, - planCompilePublish: async () => { - publications += 1; - return publicationBody(); + planCompileDownload: async () => { + compilations += 1; + return compiledResult(cwd); }, }); assert.equal(result.status, 0); assert.equal(calls.length, 2); - assert.equal(publications, 1); + assert.equal(compilations, 1); }); test("plan compile rejects an older Head at the accepted graph version", async (context) => { @@ -967,16 +874,16 @@ test("plan compile rejects an older Head at the accepted graph version", async ( foundation_plan_etag: ETAG, }); const olderHead = "0".repeat(64); - let publications = 0; - const result = await invoke(["plan", "compile", "--github"], { + let compilations = 0; + const result = await invoke(["plan", "compile", "--output", "application"], { cwd, planCompilePush: successfulPush, fetchFunction: sequenceFetch([ jsonResponse(analysisBody("valid", 1, ANALYSIS_ID, olderHead)), ]), - planCompilePublish: async () => { - publications += 1; - return publicationBody(); + planCompileDownload: async () => { + compilations += 1; + return compiledResult(cwd); }, }); @@ -985,10 +892,10 @@ test("plan compile rejects an older Head at the accepted graph version", async ( errorEnvelope(result.stderr).current.analysis.head_source_sha256, olderHead, ); - assert.equal(publications, 0); + assert.equal(compilations, 0); }); -test("invalid JSON and schema diagnostics stop before analysis or Publication", async (context) => { +test("invalid JSON and schema diagnostics stop before analysis or Compilation", async (context) => { for (const code of ["invalid_json", "schema_invalid"]) { const source = Buffer.from( code === "invalid_json" ? "{\n" : '{"format":"wrong"}\n', @@ -996,22 +903,25 @@ test("invalid JSON and schema diagnostics stop before analysis or Publication", const cwd = localDirectory(context, source); /** @type {unknown[]} */ const calls = []; - const result = await invoke(["plan", "compile", "--github"], { - cwd, - apiUrl: "https://api.example.test", - fetchFunction: sequenceFetch( - [ - jsonResponse( - { - source_sha256: sha256(source), - diagnostics: [diagnostic(code, `Rejected ${code}.`)], - }, - 422, - ), - ], - calls, - ), - }); + const result = await invoke( + ["plan", "compile", "--output", "application"], + { + cwd, + apiUrl: "https://api.example.test", + fetchFunction: sequenceFetch( + [ + jsonResponse( + { + source_sha256: sha256(source), + diagnostics: [diagnostic(code, `Rejected ${code}.`)], + }, + 422, + ), + ], + calls, + ), + }, + ); assertHandledFailure(result, "server_rejected"); assert.equal(calls.length, 1); @@ -1022,100 +932,67 @@ test("invalid JSON and schema diagnostics stop before analysis or Publication", } }); -test("semantic and failed analysis stop before Publication with structured status", async (context) => { +test("semantic and failed analysis stop before Compilation with structured status", async (context) => { for (const status of ["issues_found", "analysis_failed"]) { const cwd = localDirectory(context, PLAN_SOURCE, { api_url: "https://api.example.test", foundation_plan_etag: ETAG, }); - let publications = 0; + let compilations = 0; const current = analysisBody(status); - const result = await invoke(["plan", "compile", "--github"], { - cwd, - planCompilePush: successfulPush, - planCompileReadStatus: async () => ({ status: 200, body: current }), - planCompilePublish: async () => { - publications += 1; - return publicationBody(); + const result = await invoke( + ["plan", "compile", "--output", "application"], + { + cwd, + planCompilePush: successfulPush, + planCompileReadStatus: async () => ({ status: 200, body: current }), + planCompileDownload: async () => { + compilations += 1; + return compiledResult(cwd); + }, }, - }); + ); assertHandledFailure(result, "plan_not_valid"); assert.deepEqual(errorEnvelope(result.stderr).current, current); - assert.equal(publications, 0); + assert.equal(compilations, 0); } }); -test("recurring diagnostics remain repairable and never trigger Publication", async (context) => { +test("recurring diagnostics remain repairable and never start a Compilation", async (context) => { const cwd = localDirectory(context, PLAN_SOURCE, { api_url: "https://api.example.test", foundation_plan_etag: ETAG, }); - let publications = 0; + let compilations = 0; const current = analysisBody("issues_found"); const options = { cwd, planCompilePush: successfulPush, planCompileReadStatus: async () => ({ status: 200, body: current }), - planCompilePublish: async () => { - publications += 1; - return publicationBody(); + planCompileDownload: async () => { + compilations += 1; + return compiledResult(cwd); }, }; for (let attempt = 0; attempt < 2; attempt += 1) { - const result = await invoke(["plan", "compile", "--github"], options); + const result = await invoke( + ["plan", "compile", "--output", "application"], + options, + ); assertHandledFailure(result, "plan_not_valid"); assert.equal( errorEnvelope(result.stderr).current.analysis.diagnostics[0].code, "reference_missing", ); } - assert.equal(publications, 0); -}); - -test("the final local-byte check stops a stale analyzed Plan before Publication", async (context) => { - const cwd = localDirectory(context, PLAN_SOURCE, { - api_url: "https://api.example.test", - foundation_plan_etag: ETAG, - }); - let networkRequests = 0; - const result = await invoke(["plan", "compile", "--github"], { - cwd, - planCompilePush: successfulPush, - planCompileReadStatus: async () => { - const replacement = Buffer.concat([PLAN_SOURCE, Buffer.from(" ")]); - const replacementEtag = `"sha256:${sha256(replacement)}"`; - writeFileSync(planFilePath(cwd), replacement); - writeFileSync( - stateFilePath(cwd), - `${JSON.stringify( - { - format: "firstdraft.cli-state/1", - project_id: PROJECT_ID, - api_url: "https://api.example.test", - foundation_plan_etag: replacementEtag, - }, - null, - 2, - )}\n`, - { mode: 0o600 }, - ); - return { status: 200, body: analysisBody("valid") }; - }, - fetchFunction: async () => { - networkRequests += 1; - throw new Error("Publication must not start"); - }, - }); - - assertHandledFailure(result, "local_plan_changed"); - assert.equal(networkRequests, 0); + assert.equal(compilations, 0); }); test("push ambiguity, analysis failures, and rejected reads have distinct errors", async (context) => { const pushCwd = localDirectory(context, PLAN_SOURCE); - const push = await invoke(["plan", "compile", "--github"], { + const push = await invoke(["plan", "compile", "--output", "application"], { cwd: pushCwd, apiUrl: "https://api.example.test", fetchFunction: async () => { @@ -1148,14 +1025,17 @@ test("push ambiguity, analysis failures, and rejected reads have distinct errors ]; for (const [response, error] of analysisFailures) { const cwd = localDirectory(context, PLAN_SOURCE); - const result = await invoke(["plan", "compile", "--github"], { - cwd, - apiUrl: "https://api.example.test", - fetchFunction: sequenceFetch([ - jsonResponse(acceptedPlanBody(), 201, { ETag: ETAG }), - response, - ]), - }); + const result = await invoke( + ["plan", "compile", "--output", "application"], + { + cwd, + apiUrl: "https://api.example.test", + fetchFunction: sequenceFetch([ + jsonResponse(acceptedPlanBody(), 201, { ETag: ETAG }), + response, + ]), + }, + ); assertHandledFailure(result, error); assert.doesNotMatch(result.stderr, /canary|network failure/); } @@ -1176,24 +1056,30 @@ test("help and invalid direct-output syntax have no prerequisites", async () => const inaccessible = () => { throw new Error("dependency must remain inaccessible"); }; - const help = await invoke(["plan", "compile", "--help"], { - cwd: process.cwd(), - apiToken: undefined, - getCwd: inaccessible, - fetchFunction: inaccessible, - }); - assert.equal(help.status, 0); - assert.match( - help.stdout, - /firstdraft plan compile --output /, - ); + for (const argv of [ + ["plan", "compile", "--help"], + ["plan", "compile", "-h"], + ["plan", "compile", "--help", "--help"], + ]) { + const help = await invoke(argv, { + cwd: process.cwd(), + apiToken: undefined, + getCwd: inaccessible, + fetchFunction: inaccessible, + }); + assert.deepEqual( + { status: help.status, stdout: help.stdout, stderr: help.stderr }, + { status: 0, stdout: PLAN_COMPILE_HELP, stderr: "" }, + ); + } for (const argv of [ ["plan", "compile", "--output"], ["plan", "compile", "--output", "one", "--output", "two"], ["plan", "compile", "application"], - ["plan", "compile", "--github", "--output", "."], - ["plan", "compile", "--output", "app", "--github"], + ["plan", "compile", "--github"], + ["plan", "compile", "canary-secret"], + ["plan", "compile", "--canary-secret"], ]) { const invalid = await invoke(argv, { cwd: process.cwd(), @@ -1202,9 +1088,19 @@ test("help and invalid direct-output syntax have no prerequisites", async () => fetchFunction: inaccessible, }); assertHandledFailure(invalid, "invalid_arguments", 2); + assert.doesNotMatch(invalid.stderr, /canary-secret/); } }); +/** @param {string} cwd */ +function compiledResult(cwd) { + return { + project: { id: PROJECT_ID, graph_version: 1 }, + compilation: { id: COMPILATION_ID, status: "succeeded" }, + output: { path: path.join(cwd, "application"), file_count: 1 }, + }; +} + async function successfulPush() { return { status: 200, @@ -1275,54 +1171,6 @@ function emptyGapSet({ graphVersion, headSourceSha256 }) { }; } -function publicationBody() { - return { - project: { - id: PROJECT_ID, - graph_version: 1, - head_source_sha256: HEAD_SHA256, - }, - compilation: { - id: COMPILATION_ID, - analysis_run_id: ANALYSIS_ID, - graph_version: 1, - head_source_sha256: HEAD_SHA256, - status: "succeeded", - compiler_release: COMPILER_RELEASE, - target: TARGET, - artifact: { - sha256: "1".repeat(64), - manifest_sha256: "2".repeat(64), - file_count: 10, - }, - }, - publication: { - id: PUBLICATION_ID, - status: "succeeded", - repository: { - id: 123, - private: true, - owner: { id: 456, login: "octocat", type: "User" }, - full_name: "octocat/movie-catalog", - default_branch: "main", - html_url: REPOSITORY_URL, - tree_sha: "3".repeat(40), - commit_sha: "4".repeat(40), - }, - failure: null, - progress: { - phase: "completed", - retry_at: null, - retry_count: 0, - reason_code: null, - }, - created_at: CREATED_AT, - started_at: STARTED_AT, - completed_at: COMPLETED_AT, - }, - }; -} - /** @param {string} status @param {ReturnType} [artifact] */ function directCompilationBody(status, artifact) { const terminal = ["succeeded", "failed", "cancelled"].includes(status); @@ -1451,10 +1299,6 @@ function analysisPath() { return `/v1/projects/${PROJECT_ID}/analysis`; } -function publicationPath() { - return `/v1/projects/${PROJECT_ID}/github-publication`; -} - function compilationCollectionPath() { return `/v1/projects/${PROJECT_ID}/compilations`; } @@ -1486,11 +1330,6 @@ function planFilePath(cwd) { return path.join(cwd, ".firstdraft", "foundation-plan.json"); } -/** @param {string} cwd */ -function stateFilePath(cwd) { - return path.join(cwd, ".firstdraft", "state.json"); -} - /** @param {readonly string[]} argv @param {Record} [options] */ async function invoke(argv, options = {}) { /** @type {string[]} */ diff --git a/test/plan-publish.test.js b/test/plan-publish.test.js deleted file mode 100644 index 5cbf4f8..0000000 --- a/test/plan-publish.test.js +++ /dev/null @@ -1,1641 +0,0 @@ -import assert from "node:assert/strict"; -import { createHash } from "node:crypto"; -import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; -import { createServer } from "node:http"; -import { tmpdir } from "node:os"; -import path from "node:path"; -import test from "node:test"; - -import { run } from "../src/cli.js"; -import { RAILS_TARGET_PROFILE } from "../src/compilation-artifact.js"; - -const PROJECT_ID = "01900000-0000-7000-8000-000000001001"; -const COMPILATION_ID = "01900000-0000-7000-8000-000000001002"; -const OTHER_COMPILATION_ID = "01900000-0000-7000-8000-000000001003"; -const ANALYSIS_ID = "01900000-0000-7000-8000-000000001004"; -const PUBLICATION_ID = "01900000-0000-7000-8000-000000001005"; -const OTHER_PUBLICATION_ID = "01900000-0000-7000-8000-000000001006"; -const PLAN_SOURCE = Buffer.from( - '{"format":"firstdraft.foundation-plan.sketch/0.23"}\n', -); -const HEAD_SHA256 = sha256(PLAN_SOURCE); -const ETAG = `"sha256:${HEAD_SHA256}"`; -const API_TOKEN = `fd_${"a".repeat(43)}`; -const CREATED_AT = "2026-08-01T12:00:00.000Z"; -const STARTED_AT = "2026-08-01T12:00:01.000Z"; -const COMPLETED_AT = "2026-08-01T12:00:02.000Z"; -const RETRY_AT = "2026-08-07T16:15:00.000000Z"; -const ANALYZER_RELEASE = - "foundation-plan-rails/application-2026-09-27-bookmark-assets"; -const COMPILER_RELEASE = - "foundation-plan-rails/compiler-application-2026-09-27-bookmark-assets"; -const TARGET = { id: "rails", profile: RAILS_TARGET_PROFILE }; -const ARTIFACT = { - sha256: "1".repeat(64), - manifest_sha256: "2".repeat(64), - file_count: 197, -}; -const TREE_SHA = "3".repeat(40); -const COMMIT_SHA = "4".repeat(40); -const SAFE_PROGRESS_REASON_CODES = [ - "github.configuration_missing", - "github.oauth_unavailable", - "github.api_unavailable", - "github.reauthorization_required", - "github.account_mismatch", - "github.installation_unavailable", - "github.installation_not_ready", - "github.preflight_unavailable", - "github.preflight_unclassified", - "github.preflight_unavailable.configuration", - "github.preflight_unavailable.authorization", - "github.preflight_unavailable.repository_client", - "github.preflight_unavailable.artifact_preparation", - "github.preflight_unavailable.installation_token", - "github.preflight_unavailable.publication_preparation", - "github.preflight_unavailable.repository_ref_client", -]; -const REPOSITORY = { - id: 1_234_567, - private: true, - owner: { id: 7_654_321, login: "octocat", type: "User" }, - full_name: "octocat/oscar-party", - default_branch: "main", - html_url: "https://github.com/octocat/oscar-party", - tree_sha: TREE_SHA, - commit_sha: COMMIT_SHA, -}; -const REPOSITORY_URL = REPOSITORY.html_url; -const REPLAY_PROGRESS = `First Draft: Analyzing Foundation Plan... -First Draft: Foundation Plan analysis valid. -First Draft: Compiling application... -First Draft: Application compiled. -First Draft: GitHub publication complete. -`; -const LIFECYCLE_PROGRESS = `First Draft: Analyzing Foundation Plan... -First Draft: Foundation Plan analysis valid. -First Draft: Compiling application... -First Draft: Application compiled. -First Draft: Preparing private GitHub repository... -First Draft: Preparing to verify GitHub repository creation... -First Draft: Preparing compiled application... -First Draft: Preparing to verify GitHub publication... -First Draft: GitHub publication complete. -`; -const PLAN_COMPILE_HELP = `First Draft CLI - -Usage: - firstdraft plan compile - firstdraft plan compile --output - firstdraft plan compile --github - -Options: - --staging Use staging; reject a different saved origin - --output Materialize here (default: .) - --github Publish to a private GitHub repository - -h, --help Show help - -Environment: - FIRSTDRAFT_API_TOKEN Authenticate production or custom API origins - FIRSTDRAFT_STAGING_API_TOKEN Authenticate staging.firstdraft.com - FIRSTDRAFT_API_URL Override the initial API origin - -The command submits the exact current whole-file Plan, waits for its analysis, -and proceeds only when that analysis is valid. By default it materializes the -verified application in the current directory, preserving existing root material -under .firstdraft/design. --output can select another absent directory. ---github selects the GitHub Publication lifecycle and prints the private repository -URL; it cannot be combined with --output. Progress is written to stderr. -`; - -test("plan compile invokes Publication and one conditional singleton PUT and polls sequentially", async (context) => { - /** @type {{method: string | undefined, url: string | undefined, headers: import("node:http").IncomingHttpHeaders, body: Buffer}[]} */ - const requests = []; - let reads = 0; - const server = createServer(async (request, response) => { - const body = await readRequestBody(request); - requests.push({ - method: request.method, - url: request.url, - headers: request.headers, - body, - }); - - if (request.method === "PUT" && request.url === publicationPath()) { - respondJson(response, 201, publicationBody("compiling")); - return; - } - if (request.method === "GET" && request.url === publicationPath()) { - reads += 1; - respondJson( - response, - 200, - reads === 1 - ? publicationBody("compiling", { - compilation: { status: "succeeded", artifact: ARTIFACT }, - }) - : reads === 2 - ? publicationBody("provisioning_repository") - : reads === 3 - ? publicationBody("repository_unknown") - : reads === 4 - ? publicationBody("publishing") - : reads === 5 - ? publicationBody("publication_unknown") - : publicationBody("succeeded"), - ); - return; - } - - response.writeHead(404).end(); - }); - const apiUrl = await listen(context, server); - const cwd = remoteDirectory(context, apiUrl); - /** @type {number[]} */ - const timeouts = []; - /** @type {number[]} */ - const delays = []; - const result = await invoke(["plan", "compile", "--github"], { - cwd, - apiUrl: "https://canary-secret.example", - createRequestSignal: (/** @type {number} */ timeoutMs) => { - timeouts.push(timeoutMs); - return new AbortController().signal; - }, - planPublishSleep: async (/** @type {number} */ delayMs) => { - delays.push(delayMs); - }, - }); - - assert.deepEqual(result, { - status: 0, - stdout: `${REPOSITORY_URL}\n`, - stderr: LIFECYCLE_PROGRESS, - }); - assert.deepEqual(delays, [1000, 1000, 1000, 1000, 1000, 1000]); - assert.deepEqual( - timeouts, - [30_000, 30_000, 30_000, 30_000, 30_000, 30_000, 30_000], - ); - assert.deepEqual( - requests.map(({ method, url }) => [method, url]), - [ - ["PUT", publicationPath()], - ["GET", publicationPath()], - ["GET", publicationPath()], - ["GET", publicationPath()], - ["GET", publicationPath()], - ["GET", publicationPath()], - ["GET", publicationPath()], - ], - ); - const [start, ...polls] = requests; - assert(start); - assert.equal(start.body.byteLength, 0); - assert.equal(start.headers["if-match"], ETAG); - assert.equal(start.headers.authorization, `Bearer ${API_TOKEN}`); - assert.equal( - start.headers.accept, - "application/json, application/problem+json", - ); - assert.equal(start.headers["content-type"], undefined); - assert.equal(start.headers["idempotency-key"], undefined); - for (const poll of polls) { - assert.equal(poll.headers.authorization, `Bearer ${API_TOKEN}`); - assert.equal( - poll.headers.accept, - "application/json, application/problem+json", - ); - } - assert.doesNotMatch(result.stdout, /canary-secret/); -}); - -test("progress reports each safe GitHub phase, scheduled retry, and parked retry once", async (context) => { - const cwd = remoteDirectory(context, "https://api.example.test"); - const scheduled = { - phase: "github_preflight", - retry_at: RETRY_AT, - retry_count: 2, - reason_code: "github.api_unavailable", - }; - const parked = { - phase: "github_preflight", - retry_at: null, - retry_count: 7, - reason_code: "github.installation_not_ready", - }; - const responses = [ - jsonResponse(publicationBody("compiling"), 201), - jsonResponse( - publicationBody("compiling", { - compilation: { status: "running" }, - }), - ), - jsonResponse( - publicationBody("compiling", { - compilation: { status: "running" }, - }), - ), - jsonResponse( - publicationBody("compiling", { - compilation: { status: "succeeded", artifact: ARTIFACT }, - }), - ), - jsonResponse(publicationBody("provisioning_repository")), - jsonResponse( - publicationBody("provisioning_repository", { - publication: { - progress: { - phase: "github_preflight", - retry_at: null, - retry_count: 0, - reason_code: null, - }, - }, - }), - ), - jsonResponse( - publicationBody("provisioning_repository", { - publication: { - progress: { - phase: "github_preflight", - retry_at: null, - retry_count: 0, - reason_code: null, - }, - }, - }), - ), - jsonResponse( - publicationBody("provisioning_repository", { - publication: { progress: scheduled }, - }), - ), - jsonResponse( - publicationBody("provisioning_repository", { - publication: { progress: scheduled }, - }), - ), - jsonResponse( - publicationBody("provisioning_repository", { - publication: { progress: parked }, - }), - ), - jsonResponse( - publicationBody("provisioning_repository", { - publication: { - progress: defaultProgress("provisioning_repository", { - phase: "creating_repository", - }), - }, - }), - ), - jsonResponse(publicationBody("repository_unknown")), - jsonResponse( - publicationBody("repository_unknown", { - publication: { - progress: defaultProgress("repository_unknown", { - phase: "reconciling_repository", - }), - }, - }), - ), - jsonResponse(publicationBody("publishing")), - jsonResponse( - publicationBody("publishing", { - publication: { - progress: { - phase: "github_preflight", - retry_at: null, - retry_count: 0, - reason_code: null, - }, - }, - }), - ), - jsonResponse( - publicationBody("publishing", { - publication: { - progress: defaultProgress("publishing", { - phase: "publishing_artifact", - }), - }, - }), - ), - jsonResponse(publicationBody("publication_unknown")), - jsonResponse( - publicationBody("publication_unknown", { - publication: { - progress: defaultProgress("publication_unknown", { - phase: "reconciling_publication", - }), - }, - }), - ), - jsonResponse(publicationBody("succeeded")), - ]; - - const result = await invoke(["plan", "compile", "--github"], { - cwd, - fetchFunction: sequenceFetch(responses), - planPublishSleep: async () => {}, - }); - - assert.equal(result.status, 0); - assert.equal(result.stdout, `${REPOSITORY_URL}\n`); - assert.equal( - result.stderr, - `First Draft: Analyzing Foundation Plan... -First Draft: Foundation Plan analysis valid. -First Draft: Compiling application... -First Draft: Application compiled. -First Draft: Preparing private GitHub repository... -First Draft: Checking GitHub access... -First Draft: Checking GitHub access (reason: github.api_unavailable; retry count: 2; next retry: ${RETRY_AT}). -First Draft: Checking GitHub access (reason: github.installation_not_ready; retry count: 7; automatic retries paused; operator recovery required). -First Draft: Creating private GitHub repository... -First Draft: Preparing to verify GitHub repository creation... -First Draft: Verifying GitHub repository creation... -First Draft: Preparing compiled application... -First Draft: Checking GitHub access... -First Draft: Publishing compiled application to GitHub... -First Draft: Preparing to verify GitHub publication... -First Draft: Verifying GitHub publication... -First Draft: GitHub publication complete. -`, - ); - for (const privateValue of [ - PROJECT_ID, - COMPILATION_ID, - PUBLICATION_ID, - HEAD_SHA256, - TREE_SHA, - COMMIT_SHA, - REPOSITORY.full_name, - REPOSITORY_URL, - ]) { - assert.doesNotMatch(result.stderr, new RegExp(privateValue)); - } -}); - -test("progress accepts every coordinated safe reason code", async (context) => { - const cwd = remoteDirectory(context, "https://api.example.test"); - const responses = SAFE_PROGRESS_REASON_CODES.map((reasonCode) => - jsonResponse( - publicationBody("provisioning_repository", { - publication: { - progress: { - phase: "github_preflight", - retry_at: RETRY_AT, - retry_count: 1, - reason_code: reasonCode, - }, - }, - }), - ), - ); - responses.push(jsonResponse(publicationBody("succeeded"))); - - const result = await invoke(["plan", "compile", "--github"], { - cwd, - fetchFunction: sequenceFetch(responses), - planPublishSleep: async () => {}, - }); - - assert.equal(result.status, 0); - assert.equal(result.stdout, `${REPOSITORY_URL}\n`); - assert.equal( - result.stderr, - `First Draft: Analyzing Foundation Plan... -First Draft: Foundation Plan analysis valid. -First Draft: Compiling application... -First Draft: Application compiled. -${SAFE_PROGRESS_REASON_CODES.map( - (reasonCode) => - `First Draft: Checking GitHub access (reason: ${reasonCode}; retry count: 1; next retry: ${RETRY_AT}).`, -).join("\n")} -First Draft: GitHub publication complete. -`, - ); -}); - -test("a repeated singleton PUT accepts provenance matching local Plan state", async (context) => { - const cwd = remoteDirectory(context, "https://api.example.test"); - /** @type {FetchCall[]} */ - const calls = []; - const result = await invoke(["plan", "compile", "--github"], { - cwd, - fetchFunction: sequenceFetch( - [jsonResponse(publicationBody("succeeded"), 200)], - calls, - ), - }); - - assert.equal(result.status, 0); - assert.equal(result.stdout, `${REPOSITORY_URL}\n`); - assert.equal(result.stderr, REPLAY_PROGRESS); - assert.equal(calls.length, 1); - assert.equal(calls[0]?.init?.method, "PUT"); - assert.equal(new Headers(calls[0]?.init?.headers).get("if-match"), ETAG); -}); - -test("an ambiguous PUT is reconciled by one safe singleton GET", async (context) => { - const cwd = remoteDirectory(context, "https://api.example.test"); - /** @type {FetchCall[]} */ - const calls = []; - const result = await invoke(["plan", "compile", "--github"], { - cwd, - fetchFunction: sequenceFetch( - [ - async () => { - throw new TypeError("canary-secret-network"); - }, - jsonResponse(publicationBody("succeeded")), - ], - calls, - ), - }); - - assert.deepEqual(result, { - status: 0, - stdout: `${REPOSITORY_URL}\n`, - stderr: REPLAY_PROGRESS, - }); - assert.deepEqual( - calls.map(({ init }) => init?.method), - ["PUT", "GET"], - ); - assert.doesNotMatch(result.stdout, /canary-secret/); -}); - -test("an ambiguous PUT does not adopt a singleton from a different Plan Head", async (context) => { - const cwd = remoteDirectory(context, "https://api.example.test"); - const retainedHead = "a".repeat(64); - /** @type {FetchCall[]} */ - const calls = []; - const result = await invoke(["plan", "compile", "--github"], { - cwd, - fetchFunction: sequenceFetch( - [ - async () => { - throw new TypeError("ambiguous publication request"); - }, - jsonResponse( - publicationBody("succeeded", { - project: { - graph_version: 7, - head_source_sha256: retainedHead, - }, - compilation: { - graph_version: 7, - head_source_sha256: retainedHead, - }, - }), - ), - ], - calls, - ), - }); - - assertHandledFailure(result, "request_outcome_unknown"); - assert.equal(errorEnvelope(result.stderr).status, 200); - assert.match( - errorEnvelope(result.stderr).detail, - /Do not run concurrent Compile commands.*unchanged Plan bytes.*retained singleton/, - ); - assert.deepEqual( - calls.map(({ init }) => init?.method), - ["PUT", "GET"], - ); -}); - -test("an invalid successful PUT response can reconcile to the exact singleton", async (context) => { - const cwd = remoteDirectory(context, "https://api.example.test"); - /** @type {FetchCall[]} */ - const calls = []; - const result = await invoke(["plan", "compile", "--github"], { - cwd, - fetchFunction: sequenceFetch( - [ - jsonResponse( - { ...publicationBody("succeeded"), canary: "canary-secret" }, - 201, - ), - jsonResponse(publicationBody("succeeded")), - ], - calls, - ), - }); - - assert.deepEqual(result, { - status: 0, - stdout: `${REPOSITORY_URL}\n`, - stderr: REPLAY_PROGRESS, - }); - assert.deepEqual( - calls.map(({ init }) => init?.method), - ["PUT", "GET"], - ); - assert.doesNotMatch(result.stdout, /canary-secret/); -}); - -test("an unresolved ambiguous PUT remains outcome unknown without replaying the mutation", async (context) => { - const cwd = remoteDirectory(context, "https://api.example.test"); - /** @type {FetchCall[]} */ - const calls = []; - const result = await invoke(["plan", "compile", "--github"], { - cwd, - fetchFunction: sequenceFetch( - [ - async () => { - throw new TypeError("canary-secret-network"); - }, - problemResponse(404, "publication_not_found", "Not found."), - ], - calls, - ), - }); - - assertHandledFailure(result, "request_outcome_unknown"); - assert.equal(errorEnvelope(result.stderr).status, 404); - assert.equal( - errorEnvelope(result.stderr).response.code, - "publication_not_found", - ); - assert.deepEqual( - calls.map(({ init }) => init?.method), - ["PUT", "GET"], - ); - assert.doesNotMatch(result.stderr, /canary-secret/); -}); - -test("help and invalid arguments have no local or network prerequisites", async () => { - const inaccessible = () => { - throw new Error("dependency must remain inaccessible"); - }; - - for (const argv of [ - ["plan", "compile", "--help"], - ["plan", "compile", "-h"], - ["plan", "compile", "--help", "--help"], - ]) { - assert.deepEqual( - await invoke(argv, { - cwd: process.cwd(), - getCwd: inaccessible, - fetchFunction: inaccessible, - planPushFileSystem: inaccessibleFileSystem(), - apiToken: undefined, - }), - { status: 0, stdout: PLAN_COMPILE_HELP, stderr: "" }, - ); - } - - for (const argv of [ - ["plan", "compile", "canary-secret"], - ["plan", "compile", "--canary-secret"], - ]) { - const result = await invoke(argv, { - fetchFunction: inaccessible, - planPushFileSystem: inaccessibleFileSystem(), - }); - assertHandledFailure(result, "invalid_arguments", 2); - assert.doesNotMatch(result.stderr, /canary-secret/); - } - - assert.deepEqual( - await invoke(["plan", "publish"], { - getCwd: inaccessible, - fetchFunction: inaccessible, - planPushFileSystem: inaccessibleFileSystem(), - }), - { - status: 2, - stdout: "", - stderr: "Unknown command.\nRun 'firstdraft plan --help' for usage.\n", - }, - ); -}); - -test("local prerequisites reject before publication network access", async (context) => { - const inaccessible = inaccessibleFetch(); - const unpushed = localDirectory(context, { - format: "firstdraft.cli-state/1", - project_id: PROJECT_ID, - }); - assertHandledFailure( - await invoke(["plan", "compile", "--github"], { - cwd: unpushed, - fetchFunction: inaccessible, - }), - "project_not_pushed", - ); - - const opaque = localDirectory(context, { - format: "firstdraft.cli-state/1", - project_id: PROJECT_ID, - api_url: "https://api.example.test", - foundation_plan_etag: '"opaque"', - }); - assertHandledFailure( - await invoke(["plan", "compile", "--github"], { - cwd: opaque, - fetchFunction: inaccessible, - planCompilePush: async () => ({ - status: 200, - etag: '"opaque"', - outcome: "updated", - body: { - project: { graph_version: 11 }, - foundation_plan: { source_sha256: HEAD_SHA256 }, - }, - }), - }), - "invalid_configuration", - 2, - ); - - const changed = remoteDirectory(context, "https://api.example.test"); - writeFileSync( - planPath(changed), - Buffer.concat([PLAN_SOURCE, Buffer.from(" ")]), - ); - assertHandledFailure( - await invoke(["plan", "compile", "--github"], { - cwd: changed, - fetchFunction: inaccessible, - }), - "local_plan_changed", - ); - - const missingPlan = remoteDirectory(context, "https://api.example.test"); - rmSync(planPath(missingPlan)); - assertHandledFailure( - await invoke(["plan", "compile", "--github"], { - cwd: missingPlan, - fetchFunction: inaccessible, - }), - "local_input_unreadable", - ); -}); - -test("missing and rejected credentials use the stable authentication error", async (context) => { - const cwd = remoteDirectory(context, "https://api.example.test"); - const missing = await invoke(["plan", "compile", "--github"], { - cwd, - apiToken: undefined, - fetchFunction: inaccessibleFetch(), - }); - assertHandledFailure(missing, "authentication_required"); - - const rejected = await invoke(["plan", "compile", "--github"], { - cwd, - fetchFunction: sequenceFetch([ - problemResponse( - 401, - "authentication_required", - "An API token is required.", - ), - ]), - }); - assertHandledFailure(rejected, "authentication_required"); - assert.equal(errorEnvelope(rejected.stderr).status, 401); - - const reconciliation = await invoke(["plan", "compile", "--github"], { - cwd, - fetchFunction: sequenceFetch([ - async () => { - throw new TypeError("ambiguous publication request"); - }, - problemResponse( - 401, - "authentication_required", - "An API token is required.", - ), - ]), - }); - assertHandledFailure(reconciliation, "authentication_required"); - assert.equal(errorEnvelope(reconciliation.stderr).status, 401); -}); - -test("validated start rejections are distinct from unknown mutation outcomes", async (context) => { - const cwd = remoteDirectory(context, "https://api.example.test"); - const rejected = await invoke(["plan", "compile", "--github"], { - cwd, - fetchFunction: sequenceFetch([ - problemResponse(412, "precondition_failed", "The Plan changed."), - ]), - }); - - assert.deepEqual(errorEnvelope(rejected.stderr), { - error: "publication_start_rejected", - detail: "First Draft rejected the publication request.", - status: 412, - response: { - type: "about:blank", - title: "Precondition Failed", - status: 412, - code: "precondition_failed", - detail: "The Plan changed.", - }, - }); - - const malformed = await invoke(["plan", "compile", "--github"], { - cwd, - fetchFunction: sequenceFetch([ - new Response("canary-secret", { status: 500 }), - problemResponse(404, "publication_not_found", "Not found."), - ]), - }); - assertHandledFailure(malformed, "request_outcome_unknown"); - assert.doesNotMatch(malformed.stderr, /canary-secret/); -}); - -test("validated timeout and server errors reconcile without replaying the PUT", async (context) => { - for (const status of [408, 503]) { - const cwd = remoteDirectory(context, "https://api.example.test"); - /** @type {FetchCall[]} */ - const calls = []; - const result = await invoke(["plan", "compile", "--github"], { - cwd, - fetchFunction: sequenceFetch( - [ - problemResponse(status, "publication_unavailable", "Try later."), - jsonResponse(publicationBody("succeeded")), - ], - calls, - ), - }); - - assert.deepEqual(result, { - status: 0, - stdout: `${REPOSITORY_URL}\n`, - stderr: REPLAY_PROGRESS, - }); - assert.deepEqual( - calls.map(({ init }) => init?.method), - ["PUT", "GET"], - ); - } - - const cwd = remoteDirectory(context, "https://api.example.test"); - const unresolved = await invoke(["plan", "compile", "--github"], { - cwd, - fetchFunction: sequenceFetch([ - problemResponse(503, "publication_delayed", "Publication is delayed."), - new Response("canary-secret", { status: 500 }), - ]), - }); - - assertHandledFailure(unresolved, "request_outcome_unknown"); - assert.equal(errorEnvelope(unresolved.stderr).status, 503); - assert.deepEqual(errorEnvelope(unresolved.stderr).response, { - type: "about:blank", - title: "Service Unavailable", - status: 503, - code: "publication_delayed", - detail: "Publication is delayed.", - }); - assert.doesNotMatch(unresolved.stderr, /canary-secret/); -}); - -test("polling distinguishes unavailable and invalid status responses", async (context) => { - const unavailableCwd = remoteDirectory(context, "https://api.example.test"); - const unavailable = await invoke(["plan", "compile", "--github"], { - cwd: unavailableCwd, - fetchFunction: sequenceFetch([ - jsonResponse(publicationBody("compiling"), 201), - problemResponse(503, "publication_unavailable", "Try later."), - ]), - planPublishSleep: async () => {}, - }); - assertHandledFailure(unavailable, "publication_status_unavailable"); - assert.equal( - progressOutput(unavailable.stderr), - `First Draft: Analyzing Foundation Plan... -First Draft: Foundation Plan analysis valid. -First Draft: Compiling application... -`, - ); - assert.equal(errorEnvelope(unavailable.stderr).status, 503); - assert.equal( - errorEnvelope(unavailable.stderr).response.code, - "publication_unavailable", - ); - assert.match( - errorEnvelope(unavailable.stderr).detail, - /Do not run concurrent Compile commands.*unchanged Plan bytes.*retained singleton/, - ); - - const invalidCwd = remoteDirectory(context, "https://api.example.test"); - const invalidBody = { - ...publicationBody("provisioning_repository"), - canary: "canary-secret", - }; - const invalid = await invoke(["plan", "compile", "--github"], { - cwd: invalidCwd, - fetchFunction: sequenceFetch([ - jsonResponse(publicationBody("compiling"), 201), - jsonResponse(invalidBody), - ]), - planPublishSleep: async () => {}, - }); - assertHandledFailure(invalid, "invalid_publication_status"); - assert.doesNotMatch(invalid.stderr, /canary-secret/); -}); - -test("polling rejects replacement identities, regressions, and repository mutation", async (context) => { - const cases = [ - { - initial: publicationBody("compiling"), - changed: publicationBody("provisioning_repository", { - publication: { id: OTHER_PUBLICATION_ID }, - }), - }, - { - initial: publicationBody("compiling"), - changed: publicationBody("provisioning_repository", { - compilation: { id: OTHER_COMPILATION_ID }, - }), - }, - { - initial: publicationBody("publishing"), - changed: publicationBody("publishing", { - repository: { id: REPOSITORY.id + 1 }, - }), - }, - { - initial: publicationBody("publishing"), - changed: publicationBody("provisioning_repository", { - publication: { - repository: { ...REPOSITORY, tree_sha: null, commit_sha: null }, - }, - }), - }, - { - initial: publicationBody("repository_unknown"), - changed: publicationBody("provisioning_repository"), - }, - { - initial: publicationBody("publication_unknown"), - changed: publicationBody("publishing"), - }, - ]; - - for (const { initial, changed } of cases) { - const cwd = remoteDirectory(context, "https://api.example.test"); - const result = await invoke(["plan", "compile", "--github"], { - cwd, - fetchFunction: sequenceFetch([ - jsonResponse(initial, 201), - jsonResponse(changed), - ]), - planPublishSleep: async () => {}, - }); - - assertHandledFailure(result, "publication_changed"); - const envelope = errorEnvelope(result.stderr); - assert.deepEqual(envelope.current, initial); - assert.deepEqual(envelope.rejected, changed); - } -}); - -test("the bounded wait reports its last validated status", async (context) => { - const cwd = remoteDirectory(context, "https://api.example.test"); - let clock = 0; - const result = await invoke(["plan", "compile", "--github"], { - cwd, - fetchFunction: sequenceFetch([ - jsonResponse(publicationBody("compiling"), 201), - ]), - planPublishNow: () => clock, - planPublishSleep: async () => { - clock = 10 * 60_000; - }, - }); - - assertHandledFailure(result, "publication_wait_timed_out"); - assert.equal( - errorEnvelope(result.stderr).current.publication.status, - "compiling", - ); - assert.match( - errorEnvelope(result.stderr).detail, - /stopped waiting.*Do not run concurrent Compile commands.*unchanged Plan bytes.*retained singleton/, - ); -}); - -test("terminal progress distinguishes Compilation outcomes from later GitHub outcomes", async (context) => { - /** @type {[string, string, Parameters[1], string][]} */ - const cases = [ - [ - "failed", - "publication_failed", - { publication: { started_at: null } }, - "Application compilation failed.", - ], - [ - "cancelled", - "publication_cancelled", - { publication: { started_at: null } }, - "Application compilation cancelled.", - ], - [ - "failed", - "publication_failed", - { - compilation: { status: "succeeded", artifact: ARTIFACT }, - publication: { - failure: { phase: "publish", code: "publication_failed" }, - }, - }, - "GitHub publication failed.", - ], - [ - "cancelled", - "publication_cancelled", - { compilation: { status: "succeeded", artifact: ARTIFACT } }, - "GitHub publication cancelled.", - ], - [ - "repository_conflict", - "publication_failed", - { compilation: { status: "succeeded", artifact: ARTIFACT } }, - "GitHub publication failed.", - ], - ]; - - for (const [status, expectedError, changes, terminalProgress] of cases) { - const cwd = remoteDirectory(context, "https://api.example.test"); - const result = await invoke(["plan", "compile", "--github"], { - cwd, - fetchFunction: sequenceFetch([ - jsonResponse(publicationBody(status, changes), 201), - ]), - }); - - assertHandledFailure(result, expectedError); - const compiled = changes?.compilation?.status === "succeeded"; - assert.equal( - progressOutput(result.stderr), - `First Draft: Analyzing Foundation Plan... -First Draft: Foundation Plan analysis valid. -First Draft: Compiling application... -${compiled ? "First Draft: Application compiled.\n" : ""}First Draft: ${terminalProgress} -`, - ); - assert.equal( - errorEnvelope(result.stderr).current.publication.status, - status, - ); - } - - for (const status of ["failed", "cancelled"]) { - const cwd = remoteDirectory(context, "https://api.example.test"); - const result = await invoke(["plan", "compile", "--github"], { - cwd, - fetchFunction: sequenceFetch([ - jsonResponse( - publicationBody(status, { publication: { started_at: null } }), - 201, - ), - ]), - }); - - assertHandledFailure( - result, - status === "failed" ? "publication_failed" : "publication_cancelled", - ); - assert.equal( - errorEnvelope(result.stderr).current.publication.started_at, - null, - ); - } -}); - -test("exact response shapes and coherent terminal projections are required", async (context) => { - const invalidBodies = [ - { ...publicationBody("succeeded"), canary: "canary-secret" }, - withoutPublicationProgress(publicationBody("succeeded")), - publicationBody("succeeded", { - publication: { progress: null }, - }), - publicationBody("succeeded", { - publication: { - progress: { phase: "completed", retry_count: 0, reason_code: null }, - }, - }), - publicationBody("succeeded", { - publication: { - progress: { - ...defaultProgress("succeeded"), - additive: "canary-secret", - }, - }, - }), - publicationBody("succeeded", { - publication: { - progress: defaultProgress("succeeded", { - phase: "canary-secret", - }), - }, - }), - publicationBody("provisioning_repository", { - publication: { - progress: defaultProgress("provisioning_repository", { - phase: "canary-secret", - }), - }, - }), - publicationBody("succeeded", { - publication: { - progress: defaultProgress("succeeded", { - phase: "preparing_repository", - }), - }, - }), - publicationBody("provisioning_repository", { - publication: { - progress: defaultProgress("provisioning_repository", { - retry_count: 1, - }), - }, - }), - publicationBody("provisioning_repository", { - publication: { - progress: defaultProgress("provisioning_repository", { - retry_count: 1, - reason_code: "github.api_unavailable", - }), - }, - }), - publicationBody("provisioning_repository", { - publication: { - progress: { - phase: "github_preflight", - retry_at: null, - retry_count: 0, - reason_code: "github.api_unavailable", - }, - }, - }), - publicationBody("provisioning_repository", { - publication: { - progress: { - phase: "github_preflight", - retry_at: null, - retry_count: 1, - reason_code: null, - }, - }, - }), - publicationBody("provisioning_repository", { - publication: { - progress: { - phase: "github_preflight", - retry_at: RETRY_AT, - retry_count: 8, - reason_code: "github.api_unavailable", - }, - }, - }), - publicationBody("provisioning_repository", { - publication: { - progress: { - phase: "github_preflight", - retry_at: null, - retry_count: 8, - reason_code: "github.api_unavailable", - }, - }, - }), - publicationBody("provisioning_repository", { - publication: { - progress: { - phase: "github_preflight", - retry_at: "later", - retry_count: 1, - reason_code: "github.api_unavailable", - }, - }, - }), - publicationBody("provisioning_repository", { - publication: { - progress: { - phase: "github_preflight", - retry_at: RETRY_AT, - retry_count: 0, - reason_code: null, - }, - }, - }), - publicationBody("provisioning_repository", { - publication: { - progress: { - phase: "github_preflight", - retry_at: "2026-08-07T16:15:00Z", - retry_count: 1, - reason_code: "github.api_unavailable", - }, - }, - }), - publicationBody("provisioning_repository", { - publication: { - progress: { - phase: "github_preflight", - retry_at: "2026-08-07T16:15:00.000Z", - retry_count: 1, - reason_code: "github.api_unavailable", - }, - }, - }), - publicationBody("provisioning_repository", { - publication: { - progress: { - phase: "github_preflight", - retry_at: RETRY_AT, - retry_count: 1, - reason_code: "github.canary-secret", - }, - }, - }), - publicationBody("provisioning_repository", { - publication: { - progress: { - phase: "github_preflight", - retry_at: null, - retry_count: 1, - reason_code: "github.canary-secret", - }, - }, - }), - publicationBody("provisioning_repository", { - publication: { - progress: { - phase: "github_preflight", - retry_at: RETRY_AT, - retry_count: 1, - reason_code: "github.preflight_unavailable.canary-secret", - }, - }, - }), - publicationBody("succeeded", { - project: { head_source_sha256: "f".repeat(64) }, - }), - publicationBody("succeeded", { - project: { id: PUBLICATION_ID }, - }), - publicationBody("succeeded", { - project: { graph_version: 7, head_source_sha256: "a".repeat(64) }, - compilation: { - graph_version: 7, - head_source_sha256: "a".repeat(64), - }, - }), - publicationBody("succeeded", { - compilation: { artifact: null }, - }), - publicationBody("succeeded", { - compilation: { head_source_sha256: "f".repeat(64) }, - }), - publicationBody("succeeded", { - compilation: { graph_version: 2 }, - }), - publicationBody("succeeded", { - repository: { private: false }, - }), - publicationBody("succeeded", { - repository: { - owner: { id: 123456, login: "octocat", type: "Organization" }, - }, - }), - publicationBody("succeeded", { - repository: { - html_url: "https://github.com/octocat/a-different-repository", - }, - }), - publicationBody("succeeded", { - repository: { - full_name: "someone-else/oscar-party", - html_url: "https://github.com/someone-else/oscar-party", - }, - }), - publicationBody("succeeded", { - repository: { - full_name: "octocat/team/oscar-party", - html_url: "https://github.com/octocat/team/oscar-party", - }, - }), - publicationBody("succeeded", { - repository: { commit_sha: null, tree_sha: null }, - }), - publicationBody("succeeded", { - publication: { started_at: null }, - }), - publicationBody("failed", { - publication: { failure: null }, - }), - publicationBody("failed", { - compilation: { status: "running" }, - }), - publicationBody("cancelled", { - compilation: { status: "queued" }, - }), - publicationBody("publishing", { - publication: { completed_at: COMPLETED_AT }, - }), - ]; - - for (const phase of ["creation", "polling"]) { - await context.test(phase, async (context) => { - for (const [index, body] of invalidBodies.entries()) { - const cwd = remoteDirectory(context, "https://api.example.test"); - /** @type {FetchCall[]} */ - const calls = []; - const responses = - phase === "creation" - ? [ - jsonResponse(body, 201), - problemResponse( - 404, - "publication_not_found", - `Missing ${index}.`, - ), - ] - : [ - jsonResponse(publicationBody("compiling"), 201), - jsonResponse(body), - ]; - const result = await invoke(["plan", "compile", "--github"], { - cwd, - fetchFunction: sequenceFetch(responses, calls), - planPublishSleep: async () => {}, - }); - - assertHandledFailure( - result, - phase === "creation" - ? "request_outcome_unknown" - : "invalid_publication_status", - ); - if (phase === "polling") { - const envelope = errorEnvelope(result.stderr); - assert.deepEqual(Object.keys(envelope).sort(), [ - "detail", - "error", - "status", - ]); - assert.equal(envelope.status, 200); - } - assert.deepEqual( - calls.map(({ init }) => init?.method), - ["PUT", "GET"], - ); - assert.equal(calls[1]?.init?.body, undefined); - assert.doesNotMatch(result.stderr, /canary-secret/); - assert.equal(result.stderr.includes(cwd), false); - assert.equal(result.stderr.includes(API_TOKEN), false); - } - }); - } -}); - -/** @typedef {{input: string | URL | Request, init: RequestInit | undefined}} FetchCall */ - -/** - * @param {string} status - * @param {{project?: Record, compilation?: Record, publication?: Record, repository?: Record}} [changes] - */ -function publicationBody(status, changes = {}) { - const terminal = [ - "succeeded", - "repository_conflict", - "failed", - "cancelled", - ].includes(status); - const compilationStatus = - status === "compiling" - ? "queued" - : status === "cancelled" - ? "cancelled" - : status === "failed" - ? "failed" - : "succeeded"; - const repositoryRequired = [ - "publishing", - "publication_unknown", - "succeeded", - "repository_conflict", - ].includes(status); - const repository = repositoryRequired - ? { - ...REPOSITORY, - ...(status === "succeeded" ? {} : { tree_sha: null, commit_sha: null }), - ...changes.repository, - } - : null; - const failure = ["failed", "repository_conflict"].includes(status) - ? { phase: status === "failed" ? "compile" : "publish", code: status } - : null; - - return { - project: { - id: PROJECT_ID, - graph_version: 11, - head_source_sha256: HEAD_SHA256, - ...changes.project, - }, - compilation: { - id: COMPILATION_ID, - analysis_run_id: ANALYSIS_ID, - graph_version: 11, - head_source_sha256: HEAD_SHA256, - status: compilationStatus, - compiler_release: COMPILER_RELEASE, - target: TARGET, - artifact: compilationStatus === "succeeded" ? ARTIFACT : null, - ...changes.compilation, - }, - publication: { - id: PUBLICATION_ID, - status, - repository, - failure, - progress: defaultProgress(status), - created_at: CREATED_AT, - started_at: status === "compiling" ? null : STARTED_AT, - completed_at: terminal ? COMPLETED_AT : null, - ...changes.publication, - }, - }; -} - -/** @param {string} status @param {Record} [changes] */ -function defaultProgress(status, changes = {}) { - /** @type {Record} */ - const phases = { - compiling: "compiling", - provisioning_repository: "preparing_repository", - repository_unknown: "preparing_repository_reconciliation", - publishing: "preparing_artifact", - publication_unknown: "preparing_publication_reconciliation", - succeeded: "completed", - repository_conflict: "failed", - failed: "failed", - cancelled: "cancelled", - }; - return { - phase: phases[status], - retry_at: null, - retry_count: 0, - reason_code: null, - ...changes, - }; -} - -/** @param {ReturnType} body */ -function withoutPublicationProgress(body) { - const publication = /** @type {Record} */ ({ - ...body.publication, - }); - delete publication.progress; - return { ...body, publication }; -} - -function publicationPath() { - return `/v1/projects/${PROJECT_ID}/github-publication`; -} - -/** @param {Buffer} value */ -function sha256(value) { - return createHash("sha256").update(value).digest("hex"); -} - -/** @param {unknown} body @param {number} [status] */ -function jsonResponse(body, status = 200) { - return new Response(JSON.stringify(body), { - status, - headers: { "Content-Type": "application/json" }, - }); -} - -/** @param {number} status @param {string} code @param {string} detail */ -function problemResponse(status, code, detail) { - /** @type {Record} */ - const titles = { - 401: "Unauthorized", - 404: "Not Found", - 408: "Request Timeout", - 412: "Precondition Failed", - 503: "Service Unavailable", - }; - return new Response( - JSON.stringify({ - type: "about:blank", - title: titles[status] ?? "Error", - status, - code, - detail, - }), - { - status, - headers: { "Content-Type": "application/problem+json" }, - }, - ); -} - -/** - * @param {(Response | (() => Promise))[]} responses - * @param {FetchCall[]} [calls] - * @returns {typeof globalThis.fetch} - */ -function sequenceFetch(responses, calls = []) { - return async (input, init) => { - calls.push({ input, init }); - const response = responses.shift(); - assert(response, "unexpected request"); - return typeof response === "function" ? response() : response; - }; -} - -/** @param {import("node:http").ServerResponse} response @param {number} status @param {unknown} body */ -function respondJson(response, status, body) { - const source = Buffer.from(JSON.stringify(body)); - response.writeHead(status, { - "Content-Type": "application/json", - "Content-Length": source.byteLength, - }); - response.end(source); -} - -/** @param {import("node:http").IncomingMessage} request */ -async function readRequestBody(request) { - const chunks = []; - for await (const chunk of request) chunks.push(Buffer.from(chunk)); - return Buffer.concat(chunks); -} - -/** @param {import("node:test").TestContext} context @param {import("node:http").Server} server */ -async function listen(context, server) { - await new Promise((/** @type {(value?: void) => void} */ resolve) => { - server.listen(0, "127.0.0.1", resolve); - }); - context.after( - () => - new Promise( - ( - /** @type {(value?: void) => void} */ resolve, - /** @type {(error: Error) => void} */ reject, - ) => { - server.close((error) => { - if (error) reject(error); - else resolve(); - }); - }, - ), - ); - const address = server.address(); - assert(address && typeof address === "object"); - return `http://127.0.0.1:${address.port}`; -} - -/** @param {import("node:test").TestContext} context @param {string} apiUrl */ -function remoteDirectory(context, apiUrl) { - return localDirectory(context, { - format: "firstdraft.cli-state/1", - project_id: PROJECT_ID, - api_url: apiUrl, - foundation_plan_etag: ETAG, - }); -} - -/** @param {import("node:test").TestContext} context @param {Record} state */ -function localDirectory(context, state) { - const directory = mkdtempSync(path.join(tmpdir(), "firstdraft-publish-")); - context.after(() => rmSync(directory, { recursive: true, force: true })); - mkdirSync(path.join(directory, ".firstdraft")); - writeFileSync( - path.join(directory, ".firstdraft", "state.json"), - `${JSON.stringify(state, null, 2)}\n`, - { mode: 0o600 }, - ); - writeFileSync(planPath(directory), PLAN_SOURCE); - return directory; -} - -/** @param {string} directory */ -function planPath(directory) { - return path.join(directory, ".firstdraft", "foundation-plan.json"); -} - -/** @param {readonly string[]} argv @param {Record} [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) }, - apiToken: API_TOKEN, - planCompilePush: async () => ({ - status: 200, - etag: ETAG, - outcome: "updated", - body: { - project: { graph_version: 11 }, - foundation_plan: { source_sha256: HEAD_SHA256 }, - }, - }), - planCompileReadStatus: async () => ({ - status: 200, - body: validAnalysis(), - }), - ...options, - }); - return { status, stdout, stderr }; -} - -function validAnalysis() { - const gapSet = { - format: "firstdraft.foundation-gaps/2", - source: { sha256: HEAD_SHA256 }, - project: { id: PROJECT_ID, graph_version: 11 }, - analysis: { release: ANALYZER_RELEASE }, - compiler_release: COMPILER_RELEASE, - target: TARGET, - gaps: [], - }; - return { - project: { id: PROJECT_ID, graph_version: 11 }, - analysis: { - id: ANALYSIS_ID, - graph_version: 11, - head_source_sha256: HEAD_SHA256, - analyzer_release: ANALYZER_RELEASE, - compiler_release: COMPILER_RELEASE, - target: TARGET, - status: "valid", - diagnostics: [], - gap_set: gapSet, - gap_set_sha256: sha256( - Buffer.from(`${JSON.stringify(gapSet, null, 2)}\n`), - ), - started_at: STARTED_AT, - completed_at: COMPLETED_AT, - }, - }; -} - -/** - * @param {{status: number, stdout: string, stderr: string}} result - * @param {string} error - * @param {number} [status] - */ -function assertHandledFailure(result, error, status = 1) { - assert.equal(result.status, status); - assert.equal(result.stdout, ""); - assert.equal(errorEnvelope(result.stderr).error, error); - if (error === "request_outcome_unknown") { - assert.equal(errorEnvelope(result.stderr).phase, "publication"); - } -} - -/** @param {string} stderr */ -function errorEnvelope(stderr) { - const structured = stderr - .split("\n") - .filter((line) => !line.startsWith("First Draft: ")) - .join("\n"); - return JSON.parse(structured); -} - -/** @param {string} stderr */ -function progressOutput(stderr) { - const lines = stderr - .split("\n") - .filter((line) => line.startsWith("First Draft: ")); - return lines.length === 0 ? "" : `${lines.join("\n")}\n`; -} - -function inaccessibleFetch() { - return async () => { - throw new Error("network must remain inaccessible"); - }; -} - -function inaccessibleFileSystem() { - return { - lstatSync: () => { - throw new Error("filesystem must remain inaccessible"); - }, - readFileSync: () => { - throw new Error("filesystem must remain inaccessible"); - }, - renameSync: () => { - throw new Error("filesystem must remain inaccessible"); - }, - writeFileSync: () => { - throw new Error("filesystem must remain inaccessible"); - }, - }; -}