From 3227d7bbc81927dfcd2a13f47ca11068c8825975 Mon Sep 17 00:00:00 2001 From: Raghu Betina Date: Tue, 24 Nov 2026 02:33:57 -0600 Subject: [PATCH 1/2] Find a maintained app's Project from its own files `firstdraft maintain` read the Project only from planning state, which an app compiled with --output, or any fresh clone of an app, does not have. With publication removed, that is where someone fixing a production error works, so the commands could not run where they are most needed. Every Compilation writes its GapSet into the app as .firstdraft/gaps.json, and its project.id is the Project's ID, which no recompile changes. Without Project state, the maintain commands and a deployed_error report now read that ID. The file holds no origin, so they use the one `login` would select (--staging, FIRSTDRAFT_API_URL, or firstdraft.com) and need a login for it, and maintain says so on standard error. It also records no Compilation, so a deployed_error report from such a copy ends with compilation_not_recorded unless one is named. Planning state, where it exists, still wins. The maintain commands now read the Project once per command and pass it to each request. Checked against a fresh clone of raghubetina/dunbar150-compiled and a local service holding its Project: maintain, maintain show, and maintain resolve each succeeded and printed the note. --- CHANGELOG.md | 5 +- docs/commands.md | 29 ++++++++-- docs/errors.md | 88 ++++++++++++++-------------- src/agent-sentences.js | 13 +++++ src/cli.js | 121 ++++++++++++++++++++++++++++----------- src/commands/maintain.js | 62 +++++++++----------- src/plan-state.js | 72 +++++++++++++++++++++++ test/maintain.test.js | 110 ++++++++++++++++++++++++++++++++++- test/report.test.js | 55 ++++++++++++++++++ 9 files changed, 435 insertions(+), 120 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 29816a9..c9fa40c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -94,8 +94,9 @@ target to profile `rails-sketch/2026-11` and the accepted API contract to `0.9.x `untrusted` list names the fields that can hold end users' text, and what done means. `maintain resolve ` resolves it with a `--reason`, a `--cause` that says what caused the error (`unknown` when the agent could not tell), and an optional `--detail`, such as the pull request. Each takes `--environment`, `production` by default, - runs from the generated application's root or the Project's directory, uses the Project's pinned origin, and changes - no local state. + and changes no local state. They run from the application's folder or the Project's directory: without the + Project's state there, as in a fresh clone of the application, they read the Project ID from the application's + `.firstdraft/gaps.json`, use the origin `login` would select, and say so on standard error. - `report failure --kind deployed_error --item ` reports an error in a deployed application that `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, diff --git a/docs/commands.md b/docs/commands.md index c7fcc92..28e74f3 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -779,7 +779,10 @@ A failure report needs only `--kind` (`spec_failure`, `setup_failure`, `boot_err [`firstdraft maintain`](#maintain-a-deployed-application) resolved with `--cause generated_code`: it also needs `--item `, sent as `maintenance_item_id`, and takes no `--message`, because the item's evidence can hold end users' text. Another kind with `--item`, or a `deployed_error` without a lowercase item ID or with `--message`, is -`invalid_arguments`, and nothing is read or sent. Each other field is sent only in its shape, and left out otherwise: +`invalid_arguments`, and nothing is read or sent. A `deployed_error` finds its Project as +[`firstdraft maintain`](#maintain-a-deployed-application) does, from the application's `.firstdraft/gaps.json` too. +Those files record no Compilation, so without one given right after `report failure` it ends with +`compilation_not_recorded` and sends nothing. Each other field is sent only in its shape, and left out otherwise: | Option | Field | What it may contain | | ----------------------------------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -929,10 +932,26 @@ only while the item stays resolved, so after an unconfirmed resolution run `main resolving again. Each command takes `--environment`, which defaults to `production`: a lowercase name of letters, digits, and hyphens -that starts with a letter. Item IDs are lowercase UUIDs. The commands use the Project ID and API origin in -`.firstdraft/state.json`. Run them from the generated application's root, where the CLI finds that state archived at -`.firstdraft/design` after root adoption, as the report commands do, or from the Project's directory. `show` and -`resolve` make one request, and the index two. Each request has a +that starts with a letter. Item IDs are lowercase UUIDs. Run the commands in the application's folder or in the +Project's directory. They find the Project in this order: + +1. The Project's `.firstdraft/state.json` in the current directory, or its archive at `.firstdraft/design` after root + adoption, as the report commands do. It pins both the Project ID and the API origin. +2. Without that state, as in a fresh clone of the application or one compiled with `--output`, the Project ID in the + application's own `.firstdraft/gaps.json`, which every Compilation writes and which keeps the same Project ID + across recompiles. That file holds no origin, so the commands use the one `login` would select: `--staging`, + `FIRSTDRAFT_API_URL`, or `https://firstdraft.com`. They need a login for that origin on this computer, and after a + successful response they write this line on standard error, before any other: + + ```text + No First Draft planning folder is here, so the CLI read the Project from .firstdraft/gaps.json and used : if the Project is on another First Draft origin, add --staging or set FIRSTDRAFT_API_URL. This copy records no Compilation, so a failure report from here needs the Compilation's ID right after 'report failure'. + ``` + + It is `applicationProjectLine` in `src/agent-sentences.js`. A Project on another origin answers + `environment_not_found`. + +Without either, or with a `gaps.json` that names no Project, the command ends with `local_input_unreadable`. `show` +and `resolve` make one request, and the index two. Each request has a bounded timeout and refuses redirects; the commands change no local state, and print only a response that matches the contract exactly, including its Project ID, Environment name, and item ID. See [maintenance recovery](errors.md#maintenance-recovery). diff --git a/docs/errors.md b/docs/errors.md index c046c76..7b174f8 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -281,50 +281,50 @@ resolve an item that is still resolved, with `maintain_rejected` and `409 item_a ## Error index -| Commands | `error` | Exit | Meaning | -| ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | ---: | --------------------------------------------------------------------------------------------------------------- | -| Any leaf command | `invalid_arguments` | 2 | Syntax was invalid; no request was made. | -| Network commands except `logout` | `update_required`, `api_contract_unsupported` | 1 | First Draft needs a newer plugin or CLI, or serves another API contract ([recovery](#update-and-limit-errors)). | -| Network commands except `logout` | `rate_limited` | 1 | First Draft refused a request at a limit; `retry_at` says when to try again. | -| `plan init` | `local_initialization_failed` | 1 | Initialization failed without overwriting an existing path. | -| Network commands | `invalid_configuration` | 2 | API origin or saved Head state is incompatible. | -| `login` | `authorization_denied`, `authorization_expired` | 1 | The approval was denied, or the callback wait or device code ended before the CLI received a token. | -| `login --finish` | `authorization_pending`, `login_not_started` | 1 | First Draft has not confirmed an approval yet, or no device login is waiting for the origin. | -| `login` | `login_failed` | 1 | Nothing was saved; `phase: "write"` means a token was issued ([recovery](#login-and-logout-errors)). | -| `logout` | `logout_failed` | 1 | Check `phase` and `revoked`; revocation may have happened ([recovery](#login-and-logout-errors)). | -| Network commands | `authentication_required` | 1 | No environment or saved token exists for the origin, or First Draft rejected it. | -| Plan, `compilation *`, `report`, `note`, `maintain` | `local_input_unreadable` | 1 | Required local Plan or private state, or the Compilation record, could not be read. | -| Status, Compile, Compilation, `report`, `note`, `maintain` | `project_not_pushed` | 1 | No API origin is pinned for the local Project. | -| `plan push`, `plan compile` | `request_outcome_unknown` | 1 | A mutation or its response could not be verified; `plan compile` identifies its mutation phase. | -| `plan push`, `plan compile` | `local_state_not_saved` | 1 | The Plan was accepted but the private ETag state could not be replaced; includes `recovery_state`. | -| `plan push`, `plan compile` | `server_rejected` | 1 | First Draft returned validated Plan diagnostics or rejected the request with a validated problem. | -| `plan status` | `server_rejected` | 1 | First Draft rejected the analysis status request with a validated non-authentication problem. | -| `plan status` | `status_unavailable`, `invalid_server_response` | 1 | The analysis read failed or violated its protocol. | -| `plan compile` | `analysis_status_unavailable`, `invalid_analysis_status`, `analysis_status_rejected` | 1 | The bounded analysis read failed, was invalid, or was rejected. | -| Analysis waits | `analysis_changed`, `wait_timed_out`, `analysis_wait_timed_out` | 1 | The pinned analysis changed or remained processing at the deadline. | -| `plan compile` | `plan_not_valid` | 1 | Analysis completed without `valid`; `current` contains diagnostics and status. | -| `plan compile` | `local_plan_changed` | 1 | Local bytes or saved state changed after acceptance, before the selected mutation. | -| `plan compile` | `compilation_start_rejected`, `compilation_status_unavailable`, `invalid_compilation_status` | 1 | Direct start was rejected or retained status failed; post-start errors include `current`. | -| `plan compile` | `compilation_changed`, `compilation_wait_timed_out`, `compilation_failed`, `compilation_cancelled` | 1 | The pinned direct Compilation changed, timed out, failed, or was cancelled. | -| `plan compile --github` | `publication_start_rejected`, `publication_status_unavailable`, `invalid_publication_status` | 1 | Publication start or status failed its validated transport contract. | -| `plan compile --github` | `publication_changed`, `publication_wait_timed_out`, `publication_failed`, `publication_cancelled` | 1 | The pinned Publication changed, timed out, or reached a non-success terminal state. | -| `compilation status`, `compilation download` | `compilation_status_unavailable`, `invalid_compilation_status` | 1 | The retained status could not be read or violated its exact contract. | -| `compilation status --wait` | `compilation_changed`, `compilation_wait_timed_out` | 1 | Retained identity/provenance changed or the wait ended. | -| `compilation download` | `compilation_not_succeeded` | 1 | Status was not `succeeded`; no artifact request was made. | -| `compilation cancel` | `compilation_cancel_rejected` | 1 | Nothing was cancelled; `response.code` says why ([recovery](#stuck-compilation-recovery)). | -| `compilation cancel` | `compilation_cancel_unavailable` | 1 | The cancellation could not be confirmed; repeating it is safe. | -| `compilation cancel` | `invalid_compilation_status` | 1 | The response violated the Compilation contract; check status before repeating. | -| Download commands | `artifact_unavailable`, `invalid_artifact` | 1 | Artifact transport or integrity validation failed; direct Compile post-start errors include `current`. | -| Download commands | `invalid_output_path` | 2 | The absent destination or root-adoption preconditions failed; `reason` identifies the stable refusal. | -| Download commands | `materialization_failed` | 1 | The output changed or its transaction failed; `reason` identifies incomplete rollback when applicable. | -| `account`, `start`, `maintain` | `account_unavailable`, `invalid_server_response` | 1 | The account read failed or violated its contract. | -| `report progress`, `report failure` | `report_rejected`, `report_unavailable`, `account_unavailable`, `invalid_server_response` | 1 | The report was refused or its outcome is unconfirmed, or the account read failed; continue without it. | -| `note ` | `note_rejected`, `note_unavailable`, `account_unavailable`, `invalid_server_response` | 1 | The note was refused or its outcome is unconfirmed, or the account read failed; continue without it. | -| `report`, `note wrong_output` | `compilation_not_recorded` | 1 | No Compilation was given or recorded; nothing was sent ([recovery](#report-and-note-errors)). | -| `note ` | `note_incomplete` | 2 | A field the note needs had nothing left after shaping; nothing was sent. | -| `maintain` commands | `maintain_rejected` | 1 | Refused with a validated problem; `response.code` says why ([recovery](#maintenance-recovery)). | -| `maintain` commands | `maintain_unavailable` | 1 | The request failed or its result is unconfirmed; retry a read, or check a resolution with `maintain show`. | -| `maintain` commands | `invalid_maintain_response` | 1 | A success response violated the contract; retrying unchanged will not repair it. | +| Commands | `error` | Exit | Meaning | +| ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | ---: | ---------------------------------------------------------------------------------------------------------------------------- | +| Any leaf command | `invalid_arguments` | 2 | Syntax was invalid; no request was made. | +| Network commands except `logout` | `update_required`, `api_contract_unsupported` | 1 | First Draft needs a newer plugin or CLI, or serves another API contract ([recovery](#update-and-limit-errors)). | +| Network commands except `logout` | `rate_limited` | 1 | First Draft refused a request at a limit; `retry_at` says when to try again. | +| `plan init` | `local_initialization_failed` | 1 | Initialization failed without overwriting an existing path. | +| Network commands | `invalid_configuration` | 2 | API origin or saved Head state is incompatible. | +| `login` | `authorization_denied`, `authorization_expired` | 1 | The approval was denied, or the callback wait or device code ended before the CLI received a token. | +| `login --finish` | `authorization_pending`, `login_not_started` | 1 | First Draft has not confirmed an approval yet, or no device login is waiting for the origin. | +| `login` | `login_failed` | 1 | Nothing was saved; `phase: "write"` means a token was issued ([recovery](#login-and-logout-errors)). | +| `logout` | `logout_failed` | 1 | Check `phase` and `revoked`; revocation may have happened ([recovery](#login-and-logout-errors)). | +| Network commands | `authentication_required` | 1 | No environment or saved token exists for the origin, or First Draft rejected it. | +| Plan, `compilation *`, `report`, `note`, `maintain` | `local_input_unreadable` | 1 | Required local Plan or private state, the Compilation record, or an application's `.firstdraft/gaps.json` could not be read. | +| Status, Compile, Compilation, `report`, `note`, `maintain` | `project_not_pushed` | 1 | No API origin is pinned for the local Project. | +| `plan push`, `plan compile` | `request_outcome_unknown` | 1 | A mutation or its response could not be verified; `plan compile` identifies its mutation phase. | +| `plan push`, `plan compile` | `local_state_not_saved` | 1 | The Plan was accepted but the private ETag state could not be replaced; includes `recovery_state`. | +| `plan push`, `plan compile` | `server_rejected` | 1 | First Draft returned validated Plan diagnostics or rejected the request with a validated problem. | +| `plan status` | `server_rejected` | 1 | First Draft rejected the analysis status request with a validated non-authentication problem. | +| `plan status` | `status_unavailable`, `invalid_server_response` | 1 | The analysis read failed or violated its protocol. | +| `plan compile` | `analysis_status_unavailable`, `invalid_analysis_status`, `analysis_status_rejected` | 1 | The bounded analysis read failed, was invalid, or was rejected. | +| Analysis waits | `analysis_changed`, `wait_timed_out`, `analysis_wait_timed_out` | 1 | The pinned analysis changed or remained processing at the deadline. | +| `plan compile` | `plan_not_valid` | 1 | Analysis completed without `valid`; `current` contains diagnostics and status. | +| `plan compile` | `local_plan_changed` | 1 | Local bytes or saved state changed after acceptance, before the selected mutation. | +| `plan compile` | `compilation_start_rejected`, `compilation_status_unavailable`, `invalid_compilation_status` | 1 | Direct start was rejected or retained status failed; post-start errors include `current`. | +| `plan compile` | `compilation_changed`, `compilation_wait_timed_out`, `compilation_failed`, `compilation_cancelled` | 1 | The pinned direct Compilation changed, timed out, failed, or was cancelled. | +| `plan compile --github` | `publication_start_rejected`, `publication_status_unavailable`, `invalid_publication_status` | 1 | Publication start or status failed its validated transport contract. | +| `plan compile --github` | `publication_changed`, `publication_wait_timed_out`, `publication_failed`, `publication_cancelled` | 1 | The pinned Publication changed, timed out, or reached a non-success terminal state. | +| `compilation status`, `compilation download` | `compilation_status_unavailable`, `invalid_compilation_status` | 1 | The retained status could not be read or violated its exact contract. | +| `compilation status --wait` | `compilation_changed`, `compilation_wait_timed_out` | 1 | Retained identity/provenance changed or the wait ended. | +| `compilation download` | `compilation_not_succeeded` | 1 | Status was not `succeeded`; no artifact request was made. | +| `compilation cancel` | `compilation_cancel_rejected` | 1 | Nothing was cancelled; `response.code` says why ([recovery](#stuck-compilation-recovery)). | +| `compilation cancel` | `compilation_cancel_unavailable` | 1 | The cancellation could not be confirmed; repeating it is safe. | +| `compilation cancel` | `invalid_compilation_status` | 1 | The response violated the Compilation contract; check status before repeating. | +| Download commands | `artifact_unavailable`, `invalid_artifact` | 1 | Artifact transport or integrity validation failed; direct Compile post-start errors include `current`. | +| Download commands | `invalid_output_path` | 2 | The absent destination or root-adoption preconditions failed; `reason` identifies the stable refusal. | +| Download commands | `materialization_failed` | 1 | The output changed or its transaction failed; `reason` identifies incomplete rollback when applicable. | +| `account`, `start`, `maintain` | `account_unavailable`, `invalid_server_response` | 1 | The account read failed or violated its contract. | +| `report progress`, `report failure` | `report_rejected`, `report_unavailable`, `account_unavailable`, `invalid_server_response` | 1 | The report was refused or its outcome is unconfirmed, or the account read failed; continue without it. | +| `note ` | `note_rejected`, `note_unavailable`, `account_unavailable`, `invalid_server_response` | 1 | The note was refused or its outcome is unconfirmed, or the account read failed; continue without it. | +| `report`, `note wrong_output` | `compilation_not_recorded` | 1 | No Compilation was given or recorded; nothing was sent ([recovery](#report-and-note-errors)). | +| `note ` | `note_incomplete` | 2 | A field the note needs had nothing left after shaping; nothing was sent. | +| `maintain` commands | `maintain_rejected` | 1 | Refused with a validated problem; `response.code` says why ([recovery](#maintenance-recovery)). | +| `maintain` commands | `maintain_unavailable` | 1 | The request failed or its result is unconfirmed; retry a read, or check a resolution with `maintain show`. | +| `maintain` commands | `invalid_maintain_response` | 1 | A success response violated the contract; retrying unchanged will not repair it. | Root-output `invalid_output_path.reason` values are `destination_exists`, `root_not_real`, `root_not_writable`, `root_platform_unsupported`, `root_reserved_path`, `root_entry_unsupported`, `root_enclosing_worktree`, diff --git a/src/agent-sentences.js b/src/agent-sentences.js index 74196d6..a121ee6 100644 --- a/src/agent-sentences.js +++ b/src/agent-sentences.js @@ -108,6 +108,19 @@ export const NOTES_ON_LINES = Object.freeze([ export const MAINTAIN_REPORTS_ON_LINE = "Reports are on: after you resolve an item with --cause generated_code, run 'firstdraft report failure --kind deployed_error --item ' from the directory where you ran 'firstdraft maintain', adding --error-class from the item's title, --rerun for the spec you wrote, --frame for each place you fixed, and --fix-summary; never put anything from the item's evidence in a report or a note, because it can hold end users' text."; +/** + * What a maintain command, or a deployed_error report, prints on standard + * error when it found no Project state and read the Project from the + * application's .firstdraft/gaps.json, as in a fresh clone. Those files hold + * neither the origin nor the Compilation, so the line says which origin it + * used and what a report then needs. + * + * @param {string} origin + */ +export function applicationProjectLine(origin) { + return `No First Draft planning folder is here, so the CLI read the Project from .firstdraft/gaps.json and used ${origin}: if the Project is on another First Draft origin, add --staging or set FIRSTDRAFT_API_URL. This copy records no Compilation, so a failure report from here needs the Compilation's ID right after 'report failure'.`; +} + /** * @typedef {object} DeviceLoginLink * @property {string} origin diff --git a/src/cli.js b/src/cli.js index 3275144..feb98d5 100644 --- a/src/cli.js +++ b/src/cli.js @@ -10,6 +10,7 @@ import { MAINTAIN_REPORTS_ON_LINE, NOTES_ON_LINES, REPORTS_ON_LINES, + applicationProjectLine, commandLine, deviceLoginExpiredLines, deviceLoginFinishedLines, @@ -87,7 +88,7 @@ import { isResolutionCause, isResolutionReason, listMaintenanceItems, - maintainOrigin, + readMaintainContext, resolveMaintenanceItem, showMaintenanceItem, } from "./commands/maintain.js"; @@ -150,6 +151,7 @@ import { CompilationRecordWriteError, PlanStateNotPushedError, isUuidV7, + readPinnedOrApplicationProject, readPinnedProject, readRecordedCompilation, recordCompilation, @@ -883,7 +885,7 @@ const MAINTAIN_SHOW_INVALID_ARGUMENTS_DETAIL = const MAINTAIN_RESOLVE_INVALID_ARGUMENTS_DETAIL = "Invalid arguments. Run 'firstdraft maintain resolve --help' for usage."; const MAINTAIN_LOCAL_INPUT_UNREADABLE_DETAIL = - "Could not read valid local First Draft state. No network request was made. Run this command from the application's root, where the CLI reads the Project's state archived at .firstdraft/design, or from the directory whose .firstdraft holds that state."; + "Could not read valid local First Draft state. No network request was made. Run this command from the application's folder, where the CLI reads the Project from .firstdraft/gaps.json or from the state archived at .firstdraft/design, or from the directory whose .firstdraft holds the Project's state."; const MAINTAIN_NOT_PUSHED_DETAIL = "The local Project has no pinned API origin. Run 'firstdraft plan push' first."; const MAINTAIN_REJECTED_DETAIL = @@ -920,6 +922,8 @@ const REPORT_ACCOUNT_INVALID_RESPONSE_DETAIL = "First Draft returned an invalid account response, so no report was sent. Continue without it."; const REPORT_NOT_RECORDED_DETAIL = "No Compilation is recorded for this Project, so nothing was sent. 'firstdraft plan compile' and 'firstdraft compilation download' record the one whose code they write; to name one yourself, put its compilation.id right after 'report progress' or 'report failure'."; +const REPORT_FROM_APPLICATION_NOT_RECORDED_DETAIL = + "No First Draft planning folder is here, so the CLI read the Project from .firstdraft/gaps.json, which records no Compilation, and nothing was sent. To name the Compilation the deployed code came from, put its compilation.id right after 'report failure'; otherwise continue without the report."; const NOTE_NOT_RECORDED_DETAIL = "No Compilation is recorded for this Project, so nothing was sent. 'firstdraft plan compile' and 'firstdraft compilation download' record the one whose code they write; to name one yourself, pass its compilation.id with --compilation-id."; const NOTE_REJECTED_DETAIL = @@ -2012,19 +2016,18 @@ async function runMaintainIndex(options) { return runMaintainRequest( options, parsed.values.staging, - async (fetchFunction) => { + async (fetchFunction, context) => { const account = await readAccount({ - origin: maintainOrigin(options.cwd, options.planPushFileSystem), + origin: context.apiUrl, fetchFunction, createRequestSignal: options.createRequestSignal, }); return { output: await listMaintenanceItems({ - cwd: options.cwd, + context, environment, page, fetchFunction, - fileSystem: options.planPushFileSystem, createRequestSignal: options.createRequestSignal, }), notes: account.reports === "on" ? [MAINTAIN_REPORTS_ON_LINE] : [], @@ -2074,13 +2077,12 @@ async function runMaintainShow(options) { return runMaintainRequest( options, parsed.values.staging, - async (fetchFunction) => ({ + async (fetchFunction, context) => ({ output: await showMaintenanceItem({ - cwd: options.cwd, + context, environment, itemId, fetchFunction, - fileSystem: options.planPushFileSystem, createRequestSignal: options.createRequestSignal, }), }), @@ -2135,16 +2137,15 @@ async function runMaintainResolve(options) { return runMaintainRequest( options, parsed.values.staging, - async (fetchFunction) => ({ + async (fetchFunction, context) => ({ output: await resolveMaintenanceItem({ - cwd: options.cwd, + context, environment, itemId, reason, cause, detail, fetchFunction, - fileSystem: options.planPushFileSystem, createRequestSignal: options.createRequestSignal, }), }), @@ -2152,12 +2153,13 @@ async function runMaintainResolve(options) { } /** - * Prints `output` as JSON on standard output, then any `notes` for the agent - * on standard error. + * Reads the Project once, sends, then prints `output` as JSON on standard + * output and any notes for the agent on standard error, first the one that + * says the Project came from the application's files. * * @param {MaintainCommandOptions} options * @param {boolean | undefined} stagingOption - * @param {(fetchFunction: typeof globalThis.fetch) => Promise<{output: unknown, notes?: readonly string[]}>} send + * @param {(fetchFunction: typeof globalThis.fetch, context: import("./commands/maintain.js").MaintainContext) => Promise<{output: unknown, notes?: readonly string[]}>} send */ async function runMaintainRequest(options, stagingOption, send) { const { stdout, stderr } = options; @@ -2174,11 +2176,26 @@ async function runMaintainRequest(options, stagingOption, send) { writeAuthenticationRequired(stderr); return 1; } + const context = readMaintainContext({ + cwd: options.cwd, + fileSystem: options.planPushFileSystem, + selectOrigin: () => + resolveLoginOrigin({ + apiUrl: options.apiUrl, + staging: options.staging || stagingOption, + }), + }); const { output, notes = [] } = await options.service.settle( - send(authentication.fetchFunction), + send(authentication.fetchFunction, context), ); writeJson(stdout, output); - if (notes.length > 0) writeLines(stderr, notes); + const lines = [ + ...(context.fromApplication + ? [applicationProjectLine(context.apiUrl)] + : []), + ...notes, + ]; + if (lines.length > 0) writeLines(stderr, lines); return 0; } catch (error) { const stopStatus = writeServiceStop(stderr, error); @@ -4258,6 +4275,7 @@ async function runReportFailure(options) { wrapper: "failure_report", route: SERVICE_ROUTES.sendFailureReport, compilationId, + fromApplication: deployedError, body: (cwd) => ({ ...failureReportBody( { @@ -4398,6 +4416,9 @@ const MAX_REPORT_COUNT = 1_000_000; * given one, or else the one the CLI recorded * @property {boolean} compilationInPath whether the route's path names it * @property {string | undefined} compilationId the one the caller gave + * @property {boolean} [fromApplication] whether, without Project state, it + * may read the Project from the application's .firstdraft/gaps.json, as a + * deployed_error does in a fresh clone of the application * @property {(cwd: string, compilationId: string | null) => {body: unknown, omitted: string[], missing: string[]}} body * `missing` names the left-out fields it needs, so nothing is sent * @property {string} help the command that describes each field @@ -4447,7 +4468,9 @@ async function sendReportCommand(options, outgoing) { const { stdout, stderr, createRequestSignal, service } = options; const { noun, wrapper, route, namesCompilation, body } = outgoing; try { - const pinned = authenticatePinnedProject(options); + const pinned = authenticatePinnedProject(options, { + fromApplication: outgoing.fromApplication === true, + }); if (pinned === null) { writeAuthenticationRequired(stderr); return 1; @@ -4467,7 +4490,7 @@ async function sendReportCommand(options, outgoing) { service.throwIfStopped(); const compilationId = namesCompilation ? (outgoing.compilationId ?? - readRecordedCompilation({ stateDirectory: pinned.stateDirectory })) + recordedCompilation(pinned.stateDirectory)) : null; const shaped = body(pinned.cwd, compilationId); if (shaped.missing.length > 0) { @@ -4514,7 +4537,10 @@ async function sendReportCommand(options, outgoing) { if (error instanceof CompilationNotRecordedError) { writeJson(stderr, { error: "compilation_not_recorded", - detail: outgoing.notRecordedDetail, + detail: + error instanceof ApplicationRecordsNoCompilationError + ? REPORT_FROM_APPLICATION_NOT_RECORDED_DETAIL + : outgoing.notRecordedDetail, }); return 1; } @@ -4576,24 +4602,48 @@ function recordWrittenCompilation(stderr, cwd, compilationId) { } } +class ApplicationRecordsNoCompilationError extends CompilationNotRecordedError {} + +/** + * The Compilation the CLI recorded beside the Project's state. A Project read + * from the application's files has no state directory, so none is recorded. + * + * @param {string | null} stateDirectory + */ +function recordedCompilation(stateDirectory) { + if (stateDirectory === null) { + throw new ApplicationRecordsNoCompilationError( + "The application's files record no Compilation.", + ); + } + + return readRecordedCompilation({ stateDirectory }); +} + /** * Reads the Project that a successful push pinned and authenticates its * origin, before a command prints what it will send there. Returns null when - * no token is available for that origin. + * no token is available for that origin. With `fromApplication`, a directory + * with no Project state may name the Project in its .firstdraft/gaps.json, at + * the origin `login` would select. * * @param {ServiceCommandOptions} options + * @param {{fromApplication?: boolean}} [lookup] */ -function authenticatePinnedProject({ - cwd, - getCwd, - fetchFunction, - credentials, - apiUrl, - apiToken, - stagingApiToken, - staging, - service, -}) { +function authenticatePinnedProject( + { + cwd, + getCwd, + fetchFunction, + credentials, + apiUrl, + apiToken, + stagingApiToken, + staging, + service, + }, + { fromApplication = false } = {}, +) { const authentication = authenticateApiCommand({ fetchFunction: service.fetch(fetchFunction), apiUrl, @@ -4605,7 +4655,12 @@ function authenticatePinnedProject({ if (authentication === null) return null; const directory = cwd ?? getCwd(); - const project = readPinnedProject({ cwd: directory }); + const project = fromApplication + ? readPinnedOrApplicationProject({ + cwd: directory, + selectOrigin: () => resolveLoginOrigin({ apiUrl, staging }), + }) + : { ...readPinnedProject({ cwd: directory }), fromApplication: false }; if (staging && project.apiUrl !== STAGING_API_URL) { throw new PlanPushConfigurationError( "The requested API environment does not match the Project origin. No request was made.", diff --git a/src/commands/maintain.js b/src/commands/maintain.js index 0442658..95a66f7 100644 --- a/src/commands/maintain.js +++ b/src/commands/maintain.js @@ -1,5 +1,3 @@ -import { lstatSync, readFileSync } from "node:fs"; - import { FirstDraftNetworkError, FirstDraftProtocolError, @@ -10,7 +8,7 @@ import { sendRequest, serviceEndpoint, } from "../api-response.js"; -import { readPinnedProject } from "../plan-state.js"; +import { readPinnedOrApplicationProject } from "../plan-state.js"; const REQUEST_TIMEOUT_MS = 30_000; export const DEFAULT_ENVIRONMENT = "production"; @@ -76,9 +74,6 @@ const REQUEST_KEYS = ["method", "host", "path"]; const TIMESTAMP_PATTERN = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|[+-](\d{2}):(\d{2}))$/; -/** @type {import("../plan-state.js").PlanStateFileSystem} */ -const DEFAULT_FILE_SYSTEM = { lstatSync, readFileSync }; - export class MaintainRejectedError extends Error { /** * @param {number} status @@ -138,22 +133,34 @@ export function isResolutionCause(value) { } /** - * The origin pinned by the Project's first push, which every maintain request - * and its account read use. + * The Project and origin every maintain request uses, read once per command: + * the Project's state, in `cwd` or in an adopted application's archive at + * .firstdraft/design, or else the Project the application's own + * .firstdraft/gaps.json names, at the origin `login` would select. * - * @param {string} cwd - * @param {import("../plan-state.js").PlanStateFileSystem} [fileSystem] + * @param {{cwd: string, fileSystem?: import("../plan-state.js").PlanStateFileSystem, selectOrigin: () => string}} options + * @returns {MaintainContext} */ -export function maintainOrigin(cwd, fileSystem = DEFAULT_FILE_SYSTEM) { - return readContext(cwd, fileSystem).apiUrl; +export function readMaintainContext({ cwd, fileSystem, selectOrigin }) { + const { apiUrl, projectId, fromApplication } = readPinnedOrApplicationProject( + { cwd, fileSystem, selectOrigin }, + ); + return { apiUrl, projectId, fromApplication }; } +/** + * @typedef {object} MaintainContext + * @property {string} apiUrl + * @property {string} projectId + * @property {boolean} fromApplication true when the Project came from the + * application's files, so the origin is not pinned + */ + /** * @typedef {object} MaintainRequestOptions - * @property {string} cwd + * @property {MaintainContext} context * @property {string} environment * @property {typeof globalThis.fetch} [fetchFunction] - * @property {import("../plan-state.js").PlanStateFileSystem} [fileSystem] * @property {(timeoutMs: number) => AbortSignal} [createRequestSignal] */ @@ -163,14 +170,13 @@ export function maintainOrigin(cwd, fileSystem = DEFAULT_FILE_SYSTEM) { * @param {MaintainRequestOptions & {page: number}} options */ export async function listMaintenanceItems({ - cwd, + context, environment, page, fetchFunction = globalThis.fetch, - fileSystem = DEFAULT_FILE_SYSTEM, createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs), }) { - const { apiUrl, projectId } = readContext(cwd, fileSystem); + const { apiUrl, projectId } = context; const endpoint = serviceEndpoint( SERVICE_ROUTES.listMaintenanceItems, apiUrl, @@ -210,14 +216,13 @@ export async function listMaintenanceItems({ * @param {MaintainRequestOptions & {itemId: string}} options */ export async function showMaintenanceItem({ - cwd, + context, environment, itemId, fetchFunction = globalThis.fetch, - fileSystem = DEFAULT_FILE_SYSTEM, createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs), }) { - const { apiUrl, projectId } = readContext(cwd, fileSystem); + const { apiUrl, projectId } = context; const endpoint = serviceEndpoint(SERVICE_ROUTES.readMaintenanceItem, apiUrl, { project_id: projectId, environment_name: environment, @@ -258,17 +263,16 @@ export async function showMaintenanceItem({ * @param {MaintainRequestOptions & {itemId: string, reason: string, cause: string, detail?: string}} options */ export async function resolveMaintenanceItem({ - cwd, + context, environment, itemId, reason, cause, detail, fetchFunction = globalThis.fetch, - fileSystem = DEFAULT_FILE_SYSTEM, createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs), }) { - const { apiUrl, projectId } = readContext(cwd, fileSystem); + const { apiUrl, projectId } = context; const endpoint = serviceEndpoint( SERVICE_ROUTES.resolveMaintenanceItem, apiUrl, @@ -302,18 +306,6 @@ export async function resolveMaintenanceItem({ }; } -/** - * The pinned Project, read from `cwd` or, at an adopted application's root, - * from its archive at .firstdraft/design, as the report commands read it. - * - * @param {string} cwd - * @param {import("../plan-state.js").PlanStateFileSystem} fileSystem - */ -function readContext(cwd, fileSystem) { - const { apiUrl, projectId } = readPinnedProject({ cwd, fileSystem }); - return { apiUrl, projectId }; -} - /** * @param {typeof globalThis.fetch} fetchFunction * @param {import("../api-response.js").ServiceEndpoint} endpoint diff --git a/src/plan-state.js b/src/plan-state.js index f21a756..4d82496 100644 --- a/src/plan-state.js +++ b/src/plan-state.js @@ -66,6 +66,78 @@ export function readPinnedProject({ cwd, fileSystem }) { }; } +// Every Compilation writes its GapSet into the application as +// .firstdraft/gaps.json, and the GapSet's project.id is the Project's ID, +// which no recompile changes. The service caps a GapSet at 32 MiB. +const APPLICATION_GAP_SET = path.join(".firstdraft", "gaps.json"); +const MAX_GAP_SET_BYTES = 32 * 1024 * 1024; +const GAP_SET_FORMAT_PREFIX = "firstdraft.foundation-gaps/"; + +/** + * The Project as readPinnedProject reads it, or, where there is no Project + * state but the application's own .firstdraft/gaps.json names a Project, as + * in a fresh clone of the application, that Project at `selectOrigin()`. The + * application's files hold no origin and no Compilation record, so such a + * Project has neither a pinned origin nor a state directory. + * + * @param {object} options + * @param {string} options.cwd + * @param {PlanStateFileSystem} [options.fileSystem] + * @param {() => string} options.selectOrigin the origin `login` would use + * @returns {{apiUrl: string, projectId: string, stateDirectory: string | null, fromApplication: boolean}} + */ +export function readPinnedOrApplicationProject({ + cwd, + fileSystem = DEFAULT_FILE_SYSTEM, + selectOrigin, +}) { + const stateFile = path.join( + pinnedProjectDirectory(cwd, fileSystem), + ".firstdraft", + "state.json", + ); + const gapSetFile = path.join(cwd, APPLICATION_GAP_SET); + if (isAbsent(stateFile, fileSystem) && !isAbsent(gapSetFile, fileSystem)) { + return { + apiUrl: selectOrigin(), + projectId: readGapSetProjectId(gapSetFile, fileSystem), + stateDirectory: null, + fromApplication: true, + }; + } + + return { ...readPinnedProject({ cwd, fileSystem }), fromApplication: false }; +} + +/** + * @param {string} filePath + * @param {PlanStateFileSystem} fileSystem + */ +function readGapSetProjectId(filePath, fileSystem) { + const source = readLocalFile(filePath, MAX_GAP_SET_BYTES, fileSystem); + /** @type {unknown} */ + let document; + try { + document = JSON.parse(source.toString("utf8")); + } catch { + throw new PlanStateLocalError("The application's GapSet is not JSON."); + } + const projectId = + isRecord(document) && + typeof document.format === "string" && + document.format.startsWith(GAP_SET_FORMAT_PREFIX) && + isRecord(document.project) + ? document.project.id + : undefined; + if (typeof projectId !== "string" || !PROJECT_ID_PATTERN.test(projectId)) { + throw new PlanStateLocalError( + "The application's GapSet names no First Draft Project.", + ); + } + + return projectId; +} + /** * The directory whose .firstdraft holds the Project's state: `cwd`, or the * archive at .firstdraft/design when `cwd` is an adopted application root. diff --git a/test/maintain.test.js b/test/maintain.test.js index 2a4cae0..e8c9423 100644 --- a/test/maintain.test.js +++ b/test/maintain.test.js @@ -4,7 +4,10 @@ import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; -import { MAINTAIN_REPORTS_ON_LINE } from "../src/agent-sentences.js"; +import { + MAINTAIN_REPORTS_ON_LINE, + applicationProjectLine, +} from "../src/agent-sentences.js"; import { run } from "../src/cli.js"; const PROJECT_ID = "01900000-0000-7000-8000-000000006001"; @@ -679,9 +682,84 @@ test("maintain run from an adopted application root reads the archived Project", assert.equal(result.status, 0, result.stderr); assert.equal(result.stdout, `${JSON.stringify(body, null, 2)}\n`); + assert.equal(result.stderr, ""); assert.equal(String(calls[0]?.input), `${API_URL}${ITEM_PATH}`); }); +test("maintain run in a fresh clone of the application reads the Project from its gaps.json", async (context) => { + for (const { argv, options, origin } of [ + { argv: ["maintain"], options: {}, origin: "https://firstdraft.com" }, + { + argv: ["maintain", "--staging"], + options: {}, + origin: "https://staging.firstdraft.com", + }, + { argv: ["maintain"], options: { apiUrl: API_URL }, origin: API_URL }, + ]) { + /** @type {FetchCall[]} */ + const calls = []; + const body = indexBody(); + const result = await invoke(argv, { + cwd: applicationClone(context), + reports: null, + stagingApiToken: API_TOKEN, + ...options, + fetchFunction: sequenceFetch( + [jsonResponse({ reports: "off" }), jsonResponse(body)], + calls, + ), + }); + + assert.equal(result.status, 0, result.stderr); + assert.equal(result.stdout, `${JSON.stringify(body, null, 2)}\n`); + assert.equal(result.stderr, `${applicationProjectLine(origin)}\n`); + assert.deepEqual( + calls.map((call) => String(call.input)), + [`${origin}/v1/account`, `${origin}${ITEMS_PATH}?page=1`], + ); + } + + /** @type {FetchCall[]} */ + const calls = []; + const resolved = resolvedBody("duplicate", "later_code"); + const result = await invoke([...RESOLVE_DUPLICATE], { + cwd: applicationClone(context), + fetchFunction: sequenceFetch([jsonResponse(resolved)], calls), + }); + assert.equal(result.status, 0, result.stderr); + assert.equal( + result.stderr, + `${applicationProjectLine("https://firstdraft.com")}\n`, + ); + assert.equal( + String(calls[0]?.input), + `https://firstdraft.com${RESOLUTION_PATH}`, + ); +}); + +test("an application gaps.json that names no Project is unreadable local state", async (context) => { + for (const contents of [ + "not json", + JSON.stringify({ format: "firstdraft.foundation-gaps/2", project: {} }), + JSON.stringify({ + format: "other", + project: { id: PROJECT_ID, graph_version: 1 }, + }), + JSON.stringify({ + format: "firstdraft.foundation-gaps/2", + project: { id: "canary", graph_version: 1 }, + }), + ]) { + const result = await invoke(["maintain", "show", ITEM_ID], { + cwd: applicationClone(context, contents), + fetchFunction: async () => assert.fail("No request was expected"), + }); + assertHandledFailure(result, "local_input_unreadable"); + assert.match(JSON.parse(result.stderr).detail, /\.firstdraft\/gaps\.json/); + assertNoSecrets(result); + } +}); + test("maintain authentication problems are stable", async (context) => { const missing = await invoke(["maintain"], { cwd: projectDirectory(context), @@ -888,6 +966,36 @@ function problemResponse({ status, code, detail }) { ); } +/** + * A clone of a compiled application: its .firstdraft holds what the Compiler + * wrote, the GapSet and the submitted Plan, and no planning state. + * + * @param {import("node:test").TestContext} context + * @param {string} [gapSet] + */ +function applicationClone( + context, + gapSet = JSON.stringify({ + format: "firstdraft.foundation-gaps/2", + source: { sha256: "a".repeat(64) }, + project: { id: PROJECT_ID, graph_version: 3 }, + analysis: { release: "analysis" }, + compiler_release: "compiler", + target: { id: "rails", profile: "rails-sketch/2026-11" }, + gaps: [], + }), +) { + const cwd = mkdtempSync(path.join(tmpdir(), "firstdraft-maint-clone-")); + context.after(() => rmSync(cwd, { recursive: true, force: true })); + mkdirSync(path.join(cwd, ".firstdraft")); + writeFileSync(path.join(cwd, ".firstdraft", "gaps.json"), `${gapSet}\n`); + writeFileSync( + path.join(cwd, ".firstdraft", "submitted-foundation-plan.json"), + "{}\n", + ); + return cwd; +} + /** * @param {import("node:test").TestContext} context * @param {{pushed?: boolean}} [options] diff --git a/test/report.test.js b/test/report.test.js index 7b38e1b..83960e1 100644 --- a/test/report.test.js +++ b/test/report.test.js @@ -634,6 +634,61 @@ test("a deployed error names its maintain item and carries no message", async (c assert.match(result.stdout, /\nSent\.\n$/); }); +test("a deployed error from a fresh clone of the application finds its Project but needs its Compilation", async (context) => { + const clone = temporaryDirectory(context); + mkdirSync(path.join(clone, ".firstdraft")); + writeFileSync( + path.join(clone, ".firstdraft", "gaps.json"), + `${JSON.stringify({ + format: "firstdraft.foundation-gaps/2", + project: { id: PROJECT_ID, graph_version: 2 }, + })}\n`, + ); + const deployed = ["--kind", "deployed_error", "--item", ITEM_ID]; + + const unnamed = await invoke(["report", "failure", ...deployed], { + cwd: clone, + fetchFunction: reportsOn(async () => + assert.fail("No report should be sent without a Compilation"), + ), + }); + assert.equal(unnamed.status, 1); + assert.equal(unnamed.stdout, ""); + const error = JSON.parse(unnamed.stderr); + assert.equal(error.error, "compilation_not_recorded"); + assert.match( + error.detail, + /\.firstdraft\/gaps\.json, which records no Compilation/, + ); + + /** @type {string | undefined} */ + let url; + const named = await invoke( + ["report", "failure", COMPILATION_ID, ...deployed], + { + cwd: clone, + fetchFunction: reportsOn(async (input) => { + url = String(input); + return acknowledgment("failure_report"); + }), + }, + ); + assert.equal(named.status, 0, named.stderr); + assert.equal( + url, + `${PRODUCTION}/v1/projects/${PROJECT_ID}/compilations/${COMPILATION_ID}/failure-reports`, + ); + + const otherKind = await invoke( + [...FAILURE.slice(0, 3), "--kind", "boot_error"], + { + cwd: clone, + }, + ); + assert.equal(otherKind.status, 1); + assert.equal(JSON.parse(otherKind.stderr).error, "local_input_unreadable"); +}); + test("a failure report carries only the fields that fit their shapes", async (context) => { /** @type {unknown} */ let sent; From 921e29cb9e7d4881267be01845c7a4491a7a700e Mon Sep 17 00:00:00 2001 From: Raghu Betina Date: Tue, 24 Nov 2026 02:43:24 -0600 Subject: [PATCH 2/2] Keep the app-files fallback inside the app and quiet Review found that the fallback read gaps.json through a symlinked .firstdraft, which the planning-state reader refuses, so a link into another checkout could act on that checkout's Project; it now requires a real .firstdraft directory. It also decoded malformed UTF-8 leniently; it now refuses it, as the state reader does. The note maintain prints from a fresh clone told every agent where a failure report's Compilation goes, including the agent of a person who said no to reports, who is to hear nothing about them. The note now names only the file and the origin; the report's own compilation_not_recorded detail, reached only with reports on, says the rest. The help texts and the command reference now say which origin a clone uses, that a deployed_error from a clone reads the account first, and that it reads the app's gaps.json for its Project ID. --- docs/commands.md | 23 ++++++++++++++--------- src/agent-sentences.js | 12 ++++++------ src/cli.js | 6 ++++-- src/plan-state.js | 9 +++++++-- test/maintain.test.js | 40 ++++++++++++++++++++++++++++++++++++++-- 5 files changed, 69 insertions(+), 21 deletions(-) diff --git a/docs/commands.md b/docs/commands.md index 28e74f3..0b7ae86 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -781,8 +781,9 @@ A failure report needs only `--kind` (`spec_failure`, `setup_failure`, `boot_err users' text. Another kind with `--item`, or a `deployed_error` without a lowercase item ID or with `--message`, is `invalid_arguments`, and nothing is read or sent. A `deployed_error` finds its Project as [`firstdraft maintain`](#maintain-a-deployed-application) does, from the application's `.firstdraft/gaps.json` too. -Those files record no Compilation, so without one given right after `report failure` it ends with -`compilation_not_recorded` and sends nothing. Each other field is sent only in its shape, and left out otherwise: +Those files record no Compilation. The command reads the account first: with reports off it exits 0 as usual, and +with reports on, without a Compilation given right after `report failure`, it ends with `compilation_not_recorded` and +sends nothing. Each other field is sent only in its shape, and left out otherwise: | Option | Field | What it may contain | | ----------------------------------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -797,11 +798,13 @@ Free text keeps plain words only: the CLI takes the first line, replaces everyth quote character (`'`, `"`, or a backtick, including an apostrophe inside a word) to the end of the line with one `[…]`, replaces each earlier word that contains `=`, `/`, `\`, or `@` or is longer than 24 characters with `[…]`, and keeps the words that fit the length limit. A `lint_failure` therefore sends no rule name, and a rerun command that is not an -RSpec run is left out. Besides the Project's state and the Compilation record, the CLI reads no file for a failure -report and attaches no diff or environment variable, but +RSpec run is left out. Besides the Project's state and the Compilation record, or, for a `deployed_error` without +planning state, the application's `.firstdraft/gaps.json`, of which it uses only the Project ID, the CLI reads no file +for a failure report and attaches no diff or environment variable, but the plain words of a message or fix summary it is given can still quote code, so pass only text that may be sent. -Each command first reads the account with a `GET` of `/v1/account` at the origin pinned by a successful push. Unless +Each command first reads the account with a `GET` of `/v1/account` at the origin pinned by a successful push, or, +for a `deployed_error` without planning state, the origin `login` selects. Unless First Draft answers `{"reports": "on"}`, no report is sent. With reports off, the command writes a line that says so and exits 0, so the agent's work continues; it reads no Compilation record first. When the account read fails, no report is sent either. The command then ends with `account_unavailable`, with `invalid_server_response` when the answer breaks the account's contract, or with @@ -895,7 +898,7 @@ firstdraft maintain resolve 3f2c9a4e-8d1b-4c7a-9e5f-0a1b2c3d4e5f --reason pull_r --cause generated_code --detail https://github.com/acme/app/pull/7 ``` -`firstdraft maintain` first reads the account with a `GET` of `/v1/account` at the pinned origin, as a report +`firstdraft maintain` first reads the account with a `GET` of `/v1/account` at the Project's origin, as a report command does, then prints one page of the Environment's open items, most severe first, 200 per page. Each item has `id`, `kind`, `severity`, `title`, `occurrences`, `first_seen_at`, `last_seen_at`, `last_release`, `status`, `resolution_reason`, `resolution_cause`, and `issue_url`, the GitHub issue First Draft filed and keeps current for @@ -941,10 +944,11 @@ Project's directory. They find the Project in this order: application's own `.firstdraft/gaps.json`, which every Compilation writes and which keeps the same Project ID across recompiles. That file holds no origin, so the commands use the one `login` would select: `--staging`, `FIRSTDRAFT_API_URL`, or `https://firstdraft.com`. They need a login for that origin on this computer, and after a - successful response they write this line on standard error, before any other: + successful response they write this line on standard error, after any update line and before the reports + sentence: ```text - No First Draft planning folder is here, so the CLI read the Project from .firstdraft/gaps.json and used : if the Project is on another First Draft origin, add --staging or set FIRSTDRAFT_API_URL. This copy records no Compilation, so a failure report from here needs the Compilation's ID right after 'report failure'. + No First Draft planning folder is here, so the CLI read the Project from .firstdraft/gaps.json and used : if the Project is on another First Draft origin, add --staging or set FIRSTDRAFT_API_URL. ``` It is `applicationProjectLine` in `src/agent-sentences.js`. A Project on another origin answers @@ -960,7 +964,8 @@ contract exactly, including its Project ID, Environment name, and item ID. See The CLI calls these Service API routes. The `/v1` routes send the selected token as a Bearer credential; `account` and `start` read `/v1/account` at the origin selected as for `login`; the report and note commands and the `maintain` index read it, and every other -`/v1` request goes, to the origin pinned for the Project. The `/oauth` routes go to the origin selected for `login` or `logout` and send form-encoded OAuth parameters +`/v1` request goes, to the origin pinned for the Project, or, for a maintain command or a `deployed_error` without +planning state, the origin selected as for `login`. The `/oauth` routes go to the origin selected for `login` or `logout` and send form-encoded OAuth parameters without a Bearer credential. Every request refuses redirects and has a bounded timeout. Each request takes its method and path from one `SERVICE_ROUTES` entry in `src/api-response.js`. `test/service-endpoints.test.js` fails when this table and diff --git a/src/agent-sentences.js b/src/agent-sentences.js index a121ee6..94851f5 100644 --- a/src/agent-sentences.js +++ b/src/agent-sentences.js @@ -109,16 +109,16 @@ export const MAINTAIN_REPORTS_ON_LINE = "Reports are on: after you resolve an item with --cause generated_code, run 'firstdraft report failure --kind deployed_error --item ' from the directory where you ran 'firstdraft maintain', adding --error-class from the item's title, --rerun for the spec you wrote, --frame for each place you fixed, and --fix-summary; never put anything from the item's evidence in a report or a note, because it can hold end users' text."; /** - * What a maintain command, or a deployed_error report, prints on standard - * error when it found no Project state and read the Project from the - * application's .firstdraft/gaps.json, as in a fresh clone. Those files hold - * neither the origin nor the Compilation, so the line says which origin it - * used and what a report then needs. + * What a maintain command prints on standard error when it found no Project + * state and read the Project from the + * application's .firstdraft/gaps.json, as in a fresh clone. That file holds + * no origin, so the line says which origin it used. It says nothing about + * reports, which the agent of a person who said no never hears about. * * @param {string} origin */ export function applicationProjectLine(origin) { - return `No First Draft planning folder is here, so the CLI read the Project from .firstdraft/gaps.json and used ${origin}: if the Project is on another First Draft origin, add --staging or set FIRSTDRAFT_API_URL. This copy records no Compilation, so a failure report from here needs the Compilation's ID right after 'report failure'.`; + return `No First Draft planning folder is here, so the CLI read the Project from .firstdraft/gaps.json and used ${origin}: if the Project is on another First Draft origin, add --staging or set FIRSTDRAFT_API_URL.`; } /** diff --git a/src/cli.js b/src/cli.js index feb98d5..6405e67 100644 --- a/src/cli.js +++ b/src/cli.js @@ -300,7 +300,8 @@ Environment: The command keeps each field only in its shape: an RSpec run of the application's specs, a Ruby constant, frames in the application's files, version numbers, and the plain words of free text. It first reads the account -at the origin pinned by a successful plan push. With reports on, it prints the +at the origin pinned by a successful plan push; a deployed_error without +planning state uses the origin login selects. With reports on, it prints the exact report and what it left out, then sends it once there. With reports off, it sends no report and still exits 0. Run it from the generated application's root. Without , the report names the Compilation the CLI last @@ -611,7 +612,8 @@ Without a command, it first reads the account, then prints the Environment's open items, most severe first, 200 per page; next_page names the next page or is null. When reports are on, it also says on standard error when to send a failure report about an item. Maintain commands use the API origin pinned by a -successful plan push. +successful plan push. Without planning state here, they read the Project from +.firstdraft/gaps.json and use --staging, FIRSTDRAFT_API_URL, or production. `; const MAINTAIN_SHOW_HELP = `First Draft CLI diff --git a/src/plan-state.js b/src/plan-state.js index 4d82496..761458a 100644 --- a/src/plan-state.js +++ b/src/plan-state.js @@ -98,6 +98,7 @@ export function readPinnedOrApplicationProject({ ); const gapSetFile = path.join(cwd, APPLICATION_GAP_SET); if (isAbsent(stateFile, fileSystem) && !isAbsent(gapSetFile, fileSystem)) { + assertLocalDirectory(path.join(cwd, ".firstdraft"), fileSystem); return { apiUrl: selectOrigin(), projectId: readGapSetProjectId(gapSetFile, fileSystem), @@ -118,9 +119,13 @@ function readGapSetProjectId(filePath, fileSystem) { /** @type {unknown} */ let document; try { - document = JSON.parse(source.toString("utf8")); + document = JSON.parse( + new TextDecoder("utf-8", { fatal: true }).decode(source), + ); } catch { - throw new PlanStateLocalError("The application's GapSet is not JSON."); + throw new PlanStateLocalError( + "The application's GapSet is not UTF-8 JSON.", + ); } const projectId = isRecord(document) && diff --git a/test/maintain.test.js b/test/maintain.test.js index e8c9423..f1118b4 100644 --- a/test/maintain.test.js +++ b/test/maintain.test.js @@ -1,5 +1,11 @@ import assert from "node:assert/strict"; -import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { + mkdtempSync, + mkdirSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; @@ -55,7 +61,8 @@ Without a command, it first reads the account, then prints the Environment's open items, most severe first, 200 per page; next_page names the next page or is null. When reports are on, it also says on standard error when to send a failure report about an item. Maintain commands use the API origin pinned by a -successful plan push. +successful plan push. Without planning state here, they read the Project from +.firstdraft/gaps.json and use --staging, FIRSTDRAFT_API_URL, or production. `; const MAINTAIN_SHOW_HELP = `First Draft CLI @@ -760,6 +767,35 @@ test("an application gaps.json that names no Project is unreadable local state", } }); +test("a linked .firstdraft or a GapSet that is not UTF-8 is read before no request", async (context) => { + const linked = mkdtempSync(path.join(tmpdir(), "firstdraft-maint-linked-")); + context.after(() => rmSync(linked, { recursive: true, force: true })); + symlinkSync( + path.join(applicationClone(context), ".firstdraft"), + path.join(linked, ".firstdraft"), + ); + + const malformed = applicationClone(context); + writeFileSync( + path.join(malformed, ".firstdraft", "gaps.json"), + Buffer.concat([ + Buffer.from( + `{"format":"firstdraft.foundation-gaps/2","project":{"id":"${PROJECT_ID}","graph_version":1},"gaps":["`, + ), + Buffer.from([0xff]), + Buffer.from(`"]}\n`), + ]), + ); + + for (const cwd of [linked, malformed]) { + const result = await invoke(["maintain", "show", ITEM_ID], { + cwd, + fetchFunction: async () => assert.fail("No request was expected"), + }); + assertHandledFailure(result, "local_input_unreadable"); + } +}); + test("maintain authentication problems are stable", async (context) => { const missing = await invoke(["maintain"], { cwd: projectDirectory(context),