@firstdraft.com/cli 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/RELEASING.md CHANGED
@@ -39,7 +39,19 @@ declarations from exact, clean checkouts of `firstdraft/firstdraft` and `firstdr
39
39
  precedence. CLI `0.2.x` requires the service's `0.3.x` API contract because Analysis now returns the complete reviewed
40
40
  GapSet and digest. The released CLI `0.1.0` accepts only API `0.2.x`, uses a generic 2 MiB response bound for Analysis,
41
41
  and cannot safely consume every schema-valid API `0.3.x` result. CLI `0.2.x` retains that generic bound but gives
42
- Analysis and Compilation artifacts dedicated 128 MiB bounds. Comparator arrays form one conjunction, while
42
+ Analysis and Compilation artifacts dedicated 128 MiB bounds. CLI `0.3.x` retains those bounds and requires API
43
+ `0.4.x`, Plan `firstdraft.foundation-plan.sketch/0.20`, and target profile `rails-sketch/2026-09`. Its new minor line
44
+ combines that contract transition with the incompatible root archive-path change to `.firstdraft/design`; Skills
45
+ and other callers require the matching CLI line. Existing applications are not migrated.
46
+
47
+ The API `0.4.x` transition keeps `/v1` paths, authentication, statuses, and ETag behavior. Its breaking boundary is
48
+ the new Plan and target identity, including removal of record-wide Validation targets, normalization order,
49
+ optional Home selection, and target realization changes. The Service owns those semantics. The CLI initializes
50
+ the current identity, preserves authored bytes when pushing, and validates the current artifact identity; it does
51
+ not translate earlier Plans or artifacts. The proposed CLI `0.3.0` may retain that version while unpublished and
52
+ untagged under the policy above. This source declaration does not establish package availability or deployment.
53
+
54
+ Comparator arrays form one conjunction, while
43
55
  `foundation_plan_formats` lists alternatives. A prerelease satisfies a comparator set only when a comparator
44
56
  explicitly names a prerelease with the same major, minor, and patch numbers. Skills names the candidate CLI version
45
57
  explicitly, so a stale comparator makes the three-repository candidate ineligible.
package/docs/commands.md CHANGED
@@ -3,10 +3,10 @@
3
3
  This page owns the detailed public semantics of the current command surface. Run `firstdraft --help` or a command
4
4
  group's `--help` for concise executable syntax. See [Errors and recovery](errors.md) before retrying a failed mutation.
5
5
 
6
- The current `0.2.x` source line contains the auditable command shell, local Foundation Plan initialization, local
6
+ The current `0.3.x` source line contains the auditable command shell, local Foundation Plan initialization, local
7
7
  application-key and UUID generation, conditional whole-document push, whole-graph analysis status polling, direct
8
- Compile-and-materialize and private publish orchestration, and retained-Compilation inspection. CLI `0.2.x`
9
- requires the service's `0.3.x` API contract. See the [release policy](../RELEASING.md) for versioning and channel
8
+ Compile-and-materialize and private publish orchestration, and retained-Compilation inspection. CLI `0.3.x`
9
+ requires the service's `0.4.x` API contract. See the [release policy](../RELEASING.md) for versioning and channel
10
10
  semantics and [release history](release-history.md) for the transition from prereleases.
11
11
 
12
12
  ## Command map
@@ -44,9 +44,10 @@ From the project that the Plan describes:
44
44
  firstdraft plan init --name "Oscar Party"
45
45
  ```
46
46
 
47
- This creates an empty `sketch/0.19` Plan and client-generated Project ID under `.firstdraft/`. A nested ignore file
48
- keeps that local scratch area out of Git without changing the project's own `.gitignore`. Initialization makes no
49
- network request and refuses to replace an existing `.firstdraft` path.
47
+ This creates an empty `firstdraft.foundation-plan.sketch/0.20` Plan targeting `rails-sketch/2026-09` and a
48
+ client-generated Project ID under `.firstdraft/`. A nested ignore file keeps that local scratch area out of Git
49
+ without changing the project's own `.gitignore`. Initialization makes no network request and refuses to replace an
50
+ existing `.firstdraft` path.
50
51
 
51
52
  Provide either `--name`, `--application-key`, or both. Name-only initialization derives a lower-snake key. Key-only
52
53
  initialization derives a humanized display name. Supplying both preserves both values exactly after validating them
@@ -159,6 +160,10 @@ destination is checked again after analysis; root adoption instead holds its own
159
160
  pre-move identity recheck described below. Other existing destinations remain invalid, so
160
161
  `--output ./application` retains its absent-directory contract.
161
162
 
163
+ The nested archive layout below describes the unreleased `0.3.0` candidate.
164
+ [Published CLI `0.2.2`](release-history.md#022-publication-and-registry-observation) archives at top-level `design/`;
165
+ existing applications are not migrated automatically.
166
+
162
167
  `--output .` is the noninteractive root-adoption mode. `./`, an absolute spelling of the current directory, and
163
168
  another spelling that resolves to that same physical directory select the same mode. It works at any real current
164
169
  directory that meets the preconditions below and does not recognize Drawing Board or another repository layout
@@ -166,8 +171,8 @@ specially. This first root-adoption contract supports POSIX filesystems; Windows
166
171
  and refuses root adoption as `root_platform_unsupported`. Before starting Compilation, the CLI requires:
167
172
 
168
173
  - the current directory to be a real, writable, non-filesystem-root directory;
169
- - no existing top-level path whose portable, case-insensitive name is `design` or the reserved
170
- `.firstdraft-root-output` transaction path;
174
+ - no existing `.firstdraft/design` archive or top-level `.firstdraft-root-output` transaction path, including
175
+ portable, case-insensitive spellings;
171
176
  - every top-level entry other than `.git` to be a regular file or real directory on the current directory's
172
177
  filesystem. Interior symlinks, dependency trees, sockets, and nested repositories move opaquely with their
173
178
  top-level directory; the CLI neither follows nor repairs them; and
@@ -181,8 +186,8 @@ and refuses root adoption as `root_platform_unsupported`. Before starting Compil
181
186
  Git-backed root adoption invokes the installed Git executable explicitly. Read-only discovery uses
182
187
  `git --no-optional-locks` with stable NUL-delimited porcelain so it does not refresh the index. Before remote work,
183
188
  the CLI verifies in a temporary preview that every currently ignored entry remains ignored after its path and
184
- applicable worktree `.gitignore` files move beneath `design`; repository-local and configured global exclusions are
185
- both honored. A refusal is `invalid_output_path` with a machine-readable `reason` and happens before Plan push.
189
+ applicable worktree `.gitignore` files move beneath `.firstdraft/design`; repository-local and configured global
190
+ exclusions are both honored. A refusal is `invalid_output_path` with a machine-readable `reason` and happens before Plan push.
186
191
 
187
192
  The CLI creates `.firstdraft-root-output` with exclusive creation during the pre-push output check and holds it
188
193
  through analysis, Compilation, and materialization. That directory is both the single-writer lock and the owned
@@ -202,21 +207,25 @@ safe to remove; the manual reconciliation rule below applies only after `root_ro
202
207
 
203
208
  The complete generated artifact is written and verified inside that in-root transaction directory before any
204
209
  existing path moves. Staging inside the destination makes every later rename same-filesystem even when the current
205
- directory itself is a container mount point. The artifact may not own a top-level path whose portable,
206
- case-insensitive name is `design` or `.firstdraft-root-output`; artifact validation already excludes `.git` at any
207
- depth.
208
-
209
- The transaction creates `./design` with mode `0755` on POSIX, moves every preexisting non-Git top-level entry under
210
- it, keeps an existing top-level `.git` file or directory at the root, and installs the artifact's top-level entries
211
- at the root. Immediately before each artifact entry is installed, its root destination must still be absent; an
212
- unexpected entry stops the transaction and is never overwritten. If the root contains no entry other than `.git`,
213
- it does not retain an empty `design` directory. A
214
- nested mount that cannot travel with its top-level directory may make its rename fail; that is a transactional
215
- failure, not permission to copy or traverse the mount.
210
+ directory itself is a container mount point. The artifact may not own `.firstdraft/design`, its descendants, or
211
+ the top-level `.firstdraft-root-output` path, including portable, case-insensitive spellings. `.firstdraft` must be
212
+ a directory with that exact spelling when present; artifact validation already excludes `.git` at any depth.
213
+
214
+ The transaction creates `.firstdraft/design` inside the verified artifact stage with mode `0755` on POSIX and moves
215
+ every preexisting non-Git top-level entry beneath it. It keeps an existing top-level `.git` file or directory at the
216
+ root, then installs the artifact's top-level entries there. Installing the staged `.firstdraft` places the archive
217
+ directly at `.firstdraft/design`; there is no intermediate top-level `design` directory. The original planning
218
+ `.firstdraft` remains intact at `.firstdraft/design/.firstdraft`, separate from the generated submitted Plan and
219
+ gaps at `.firstdraft/`.
220
+
221
+ Immediately before each artifact entry is installed, its root destination must still be absent; an unexpected
222
+ entry stops the transaction and is never overwritten. If the root contains no entry other than `.git`, it does not
223
+ retain an empty archive. A nested mount that cannot travel with its top-level directory may make its rename fail;
224
+ that is a transactional failure, not permission to copy or traverse the mount.
216
225
 
217
226
  For a Git root, the CLI first prepares a replacement index that stages each formerly tracked path at
218
- `design/<old-path>` and stages every exact generated artifact path at the root. This handles overlapping names such
219
- as `README.md` and `.gitignore` without leaving the old design blob indexed at a generated path. Previously
227
+ `.firstdraft/design/<old-path>` and stages every exact generated artifact path at the root. This handles overlapping
228
+ names such as `README.md` and `.gitignore` without leaving the old design blob indexed at a generated path. Previously
220
229
  untracked and ignored paths are never added to the index. Preparing that index writes the generated blobs into the
221
230
  Git object database; a rollback may therefore leave unreachable blobs for ordinary Git garbage collection, while
222
231
  `HEAD`, refs, configuration, and history remain unchanged. After the worktree renames finish, the CLI installs the
@@ -230,14 +239,17 @@ The journal is a versioned private JSON record plus owned staging files. It reco
230
239
  top-level identity set, the transaction phase, completed design and artifact renames, and, for Git, the resolved
231
240
  index path and original and prepared index digests. Each irreversible phase is recorded before the next one starts.
232
241
  On any failure after a move, index installation, or post-install verification, the CLI first restores the exact
233
- prior index through the same Git lock boundary, then reverses artifact and design renames in journal order. A fully
242
+ prior index through the same Git lock boundary, then reverses artifact moves in reverse recorded order, followed
243
+ by design moves in reverse recorded order. Reversing the installed `.firstdraft` first returns the archive to
244
+ staging so the original planning `.firstdraft` can move back to its original root path. A fully
234
245
  successful rollback removes only the owned transaction. If rollback itself cannot finish,
235
246
  `materialization_failed` reports `reason: "root_rollback_incomplete"` and includes
236
247
  `recovery_path: ".firstdraft-root-output"`; it leaves the journal and owned copies in place rather than guessing.
237
- Do not delete that directory or run Git restoration commands. Inspect the versioned journal, restore the listed
238
- index and paths to its recorded original identities, verify that snapshot, and only then remove the transaction
239
- directory. Another root adoption reports `root_busy` until that state is reconciled; a foreign preexisting directory
240
- with the same reserved name reports `root_reserved_path`.
248
+ Do not delete that directory or run Git restoration commands. Follow the
249
+ [manual recovery order](errors.md#direct-compilation-recovery), reconcile the versioned journal with the current
250
+ path identities, and verify its original snapshot before removing the transaction directory. Another root adoption
251
+ reports `root_busy` until that state is reconciled; a foreign preexisting directory with the same reserved name
252
+ reports `root_reserved_path`.
241
253
 
242
254
  After valid analysis, the CLI requests one Compilation for that exact reviewed Head and never starts GitHub
243
255
  Publication. It validates that the `202` response identifies the same Project, graph version, Head, Analysis,
@@ -252,7 +264,9 @@ Root adoption additionally reports `root_adoption.design_path` (or `null` when n
252
264
  top-level moved-entry count, whether a Git repository was preserved, and whether its index was replaced.
253
265
  After final verification succeeds, the CLI removes its owned `.firstdraft-root-output` transaction directory.
254
266
  An absent output directory contains exactly the artifact files and modes. Root adoption additionally contains the
255
- preserved `design` directory and an existing root `.git`, when present; every artifact-owned path remains exact. The
267
+ preserved `.firstdraft/design` archive and an existing root `.git`, when present. Verification skips only the
268
+ archive and retained Git/transaction paths; it still checks every generated file, including
269
+ `.firstdraft/submitted-foundation-plan.json` and `.firstdraft/gaps.json`, and rejects unexpected generated paths. The
256
270
  CLI does not add a Git repository, run a formatter, or repair generated source. When an absent output is nested
257
271
  inside another Git worktree, initialize the application as its own repository before running generated checks that
258
272
  inspect Git; otherwise Git resolves to the parent worktree. Progress on stderr reports analysis and Compilation
@@ -275,7 +289,7 @@ local paths, or environment values. Success writes exactly the validated private
275
289
  newline to stdout. If the command fails after progress has begun, its structured JSON error envelope is the final
276
290
  stderr document after the progress lines.
277
291
 
278
- The closed API `0.3.x` progress-reason allowlist is `github.configuration_missing`, `github.oauth_unavailable`,
292
+ The closed API `0.4.x` progress-reason allowlist is `github.configuration_missing`, `github.oauth_unavailable`,
279
293
  `github.api_unavailable`, `github.reauthorization_required`, `github.account_mismatch`,
280
294
  `github.installation_unavailable`, `github.installation_not_ready`, `github.preflight_unavailable`, the legacy-only
281
295
  `github.preflight_unclassified`, and these stage-specific fallbacks: `github.preflight_unavailable.configuration`,
@@ -324,10 +338,16 @@ when a retained direct Compilation succeeded but an earlier root materialization
324
338
  never starts replacement work. An incomplete rollback leaves `.firstdraft-root-output` and requires journal
325
339
  reconciliation before this command can run again.
326
340
 
341
+ Artifact validation accepts only Plan format `firstdraft.foundation-plan.sketch/0.20` and target profile
342
+ `rails-sketch/2026-09`, in addition to matching the retained Compilation's provenance and verifying file integrity.
343
+ An earlier format or profile is rejected before materialization, even when the retained status names that profile.
344
+
327
345
  Successful root adoption is intentionally one-way. The original `.firstdraft` authoring state moves under
328
- `design/.firstdraft`; run later Plan commands from `design`, not from the generated application root. Compiling a
329
- later Plan revision does not overwrite an already adopted root: choose a new absent output and deliberately
330
- reconcile it with application work.
346
+ `.firstdraft/design/.firstdraft`; run later First Draft commands from `.firstdraft/design`. Run ordinary Rails
347
+ setup, preview, and tests from the generated application root. Retain the archive when further First Draft
348
+ authoring is useful. The CLI does not run or qualify the generated application's setup, preview, or test commands.
349
+ Compiling a later Plan revision does not overwrite an already adopted root: choose a new absent output and
350
+ deliberately reconcile it with application work.
331
351
 
332
352
  The command validates the UUID and output path before network access, makes one status `GET`, requires `succeeded`,
333
353
  and makes one artifact `GET`. It never starts work or polls. Historical artifact validation uses the retained
package/docs/errors.md CHANGED
@@ -70,11 +70,18 @@ materialization failure envelopes include that last validated projection as `cur
70
70
  - after `materialization_failed`, repair the destination condition, then use the same lower-level download command
71
71
  with a new absent path. A root-output attempt whose transaction fully rolled back may instead retry that retained
72
72
  download with `--output .`; `reason: "root_rollback_incomplete"` requires reconciliation of the retained
73
- `.firstdraft-root-output` journal before another root attempt. Only that reason requires manual reconciliation:
74
- do not delete its journal or run Git restoration commands; read its versioned record, restore the exact listed
75
- index and path identities, verify its original snapshot, and then remove the transaction directory. A journal
76
- whose phase records no irreversible operation is safe to remove. After `.firstdraft` has moved successfully under
77
- `design`, run retained status and later Plan commands from `design`, not from the generated application root.
73
+ `.firstdraft-root-output` journal before another root attempt. Only that reason requires manual reconciliation.
74
+
75
+ For an incomplete root rollback, preserve the journal and avoid Git restoration commands. Reconcile its recorded
76
+ identities with the current tree: some moves may already have been reversed. Restore the exact original index
77
+ through Git's index lock when applicable. Reverse the remaining `artifact_moves` in reverse recorded order, moving
78
+ each destination back to its source; only then reverse the remaining `design_moves` in reverse recorded order.
79
+ The recorded design destinations are inside transaction staging. While the generated `.firstdraft` remains at the
80
+ root, its archive is at `.firstdraft/design`; reversing that artifact move returns the archive to staging before the
81
+ original planning `.firstdraft` can return to the root. Do not merge or overwrite either directory. Verify the
82
+ original snapshot before removing the transaction directory. A journal whose phase records no irreversible
83
+ operation is safe to remove. After successful adoption, run retained status and later Plan commands from
84
+ `.firstdraft/design`, and ordinary Rails commands from the generated application root.
78
85
 
79
86
  After `compilation_wait_timed_out`, retained work may still continue. Use
80
87
  `firstdraft compilation status <current.compilation.id>` for one read-only status check; do not rerun
@@ -46,3 +46,16 @@ source or documentation does not mutate either dist-tag.
46
46
  - Package version `0.2.1` and protected tag `v0.2.1` are consumed and immutable. As observed on August 29, 2026,
47
47
  current-directory root-output had integrated to `main` at `4352f64baf673ad93457e8bc84273e9d1d9a9501` (tree
48
48
  `b43ba6de98e27328e548cc3410ba9f39dfa9fcee`) but was not part of those registry bytes.
49
+
50
+ ## 0.2.2 publication and registry observation
51
+
52
+ - The [npm registry](https://registry.npmjs.org/@firstdraft.com%2fcli) records version `0.2.2` published at
53
+ `2026-08-30T04:40:13.459Z`.
54
+ [Tag `v0.2.2`](https://github.com/firstdraft/cli/releases/tag/v0.2.2) resolves to
55
+ `799a184cb2453ceadf5575f7b46ba975e084f192`. That source implements current-root adoption with the archive at
56
+ top-level `design/`.
57
+ - On September 18, 2026, a read-only registry check found both `next` and `latest` selecting `0.2.2`. This is an
58
+ observation of their selection, not evidence of the time or approval of the earlier promotion. The check ran no
59
+ fresh package parity, service, authenticated user-journey, or Codespaces qualification.
60
+ - Package version `0.2.2` and protected tag `v0.2.2` are consumed and immutable. The nested `.firstdraft/design`
61
+ archive belongs to the unpublished `0.3.0` source candidate; preparing it does not change installed `0.2.2` bytes.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@firstdraft.com/cli",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "Command-line interface for First Draft",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/cli.js CHANGED
@@ -196,7 +196,7 @@ and proceeds only when that analysis is valid. Without --output, it conditionall
196
196
  creates or replays the internal GitHub Publication lifecycle and prints the
197
197
  private repository URL. With --output, it starts one direct Compilation and
198
198
  atomically materializes the verified artifact into an absent directory, or
199
- preserves existing root material under ./design when the output is ., without
199
+ preserves existing root material under .firstdraft/design when the output is ., without
200
200
  starting GitHub Publication. Progress is written to stderr.
201
201
  `;
202
202
 
@@ -245,7 +245,7 @@ Environment:
245
245
  The command reads the retained Compilation once, requires it to have
246
246
  succeeded, downloads and verifies its exact artifact once, and atomically
247
247
  materializes it into an absent output path or adopts the current directory
248
- while preserving existing material under ./design. It never starts work.
248
+ while preserving existing material under .firstdraft/design. It never starts work.
249
249
  `;
250
250
 
251
251
  const PLAN_INIT_HELP = `First Draft CLI
@@ -1,7 +1,10 @@
1
1
  import { mkdirSync, writeFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
 
4
- import { FOUNDATION_PLAN_FORMAT } from "../compilation-artifact.js";
4
+ import {
5
+ FOUNDATION_PLAN_FORMAT,
6
+ RAILS_TARGET_PROFILE,
7
+ } from "../compilation-artifact.js";
5
8
 
6
9
  /**
7
10
  * @typedef {object} FileSystem
@@ -58,7 +61,7 @@ function emptyPlan(applicationKey, name) {
58
61
  format: FOUNDATION_PLAN_FORMAT,
59
62
  target: {
60
63
  id: "rails",
61
- profile: "rails-sketch/2026-08",
64
+ profile: RAILS_TARGET_PROFILE,
62
65
  },
63
66
  application: {
64
67
  key: applicationKey,
@@ -26,7 +26,8 @@ import {
26
26
  export const ARTIFACT_MEDIA_TYPE =
27
27
  "application/vnd.firstdraft.compilation-artifact+json";
28
28
  export const ARTIFACT_FORMAT = "firstdraft.compilation-artifact/1";
29
- export const FOUNDATION_PLAN_FORMAT = "firstdraft.foundation-plan.sketch/0.19";
29
+ export const FOUNDATION_PLAN_FORMAT = "firstdraft.foundation-plan.sketch/0.20";
30
+ export const RAILS_TARGET_PROFILE = "rails-sketch/2026-09";
30
31
  export const MAX_ARTIFACT_BYTES = 128 * 1024 * 1024;
31
32
 
32
33
  const ARTIFACT_KEYS = ["format", "provenance", "manifest_sha256", "files"];
@@ -283,9 +284,9 @@ export function materializeCompilationArtifact(artifact, target) {
283
284
  writeArtifactTree(artifact.files, root);
284
285
  applyMode(root, DIRECTORY_MODE);
285
286
  },
286
- verifyArtifact: (root, ignoredRootEntries) =>
287
- verifyArtifactTree(artifact.files, root, ignoredRootEntries, {
288
- verifyRootMode: ignoredRootEntries === undefined,
287
+ verifyArtifact: (root, ignoredPaths) =>
288
+ verifyArtifactTree(artifact.files, root, ignoredPaths, {
289
+ verifyRootMode: ignoredPaths === undefined,
289
290
  }),
290
291
  });
291
292
  } catch (error) {
@@ -361,6 +362,7 @@ function parseProvenance(value, expected) {
361
362
  !hasExactKeys(value.target, TARGET_KEYS) ||
362
363
  value.target.id !== expected.target.id ||
363
364
  value.target.profile !== expected.target.profile ||
365
+ value.target.profile !== RAILS_TARGET_PROFILE ||
364
366
  !hasExactKeys(value.core, CORE_KEYS) ||
365
367
  !isRepository(value.core.repository) ||
366
368
  typeof value.core.revision !== "string" ||
@@ -595,19 +597,19 @@ function writeArtifactTree(files, root) {
595
597
  /**
596
598
  * @param {ValidatedArtifactFile[]} files
597
599
  * @param {string} root
598
- * @param {Set<string>} [ignoredRootEntries]
600
+ * @param {Set<string>} [ignoredPaths]
599
601
  * @param {{verifyRootMode?: boolean}} [options]
600
602
  */
601
603
  function verifyArtifactTree(
602
604
  files,
603
605
  root,
604
- ignoredRootEntries = new Set(),
606
+ ignoredPaths = new Set(),
605
607
  { verifyRootMode = true } = {},
606
608
  ) {
607
609
  const expectedFiles = new Map(files.map((file) => [file.path, file]));
608
610
  const expectedDirectories = new Set();
609
- for (const file of files) {
610
- const components = file.path.split("/");
611
+ for (const relativePath of [...expectedFiles.keys(), ...ignoredPaths]) {
612
+ const components = relativePath.split("/");
611
613
  for (let index = 1; index < components.length; index += 1) {
612
614
  expectedDirectories.add(components.slice(0, index).join("/"));
613
615
  }
@@ -625,7 +627,7 @@ function verifyArtifactTree(
625
627
  "The materialized compilation root is invalid.",
626
628
  );
627
629
  }
628
- walkTree(root, "", actualFiles, actualDirectories, ignoredRootEntries);
630
+ walkTree(root, "", actualFiles, actualDirectories, ignoredPaths);
629
631
  if (
630
632
  !setsEqual(actualFiles, new Set(expectedFiles.keys())) ||
631
633
  !setsEqual(actualDirectories, expectedDirectories)
@@ -681,18 +683,18 @@ function hasExpectedMode(actual, expected) {
681
683
  * @param {string} relative
682
684
  * @param {Set<string>} files
683
685
  * @param {Set<string>} directories
684
- * @param {Set<string>} ignoredRootEntries
686
+ * @param {Set<string>} ignoredPaths
685
687
  */
686
- function walkTree(root, relative, files, directories, ignoredRootEntries) {
688
+ function walkTree(root, relative, files, directories, ignoredPaths) {
687
689
  const directory = relative ? path.join(root, ...relative.split("/")) : root;
688
690
  const entries = readdirSync(directory, { withFileTypes: true });
689
691
 
690
692
  for (const entry of entries) {
691
- if (relative === "" && ignoredRootEntries.has(entry.name)) continue;
692
693
  const entryRelative = relative ? `${relative}/${entry.name}` : entry.name;
694
+ if (ignoredPaths.has(entryRelative)) continue;
693
695
  if (entry.isDirectory()) {
694
696
  directories.add(entryRelative);
695
- walkTree(root, entryRelative, files, directories, ignoredRootEntries);
697
+ walkTree(root, entryRelative, files, directories, ignoredPaths);
696
698
  } else if (entry.isFile()) {
697
699
  files.add(entryRelative);
698
700
  } else {
@@ -23,7 +23,7 @@ import path from "node:path";
23
23
  import { isFileSystemError } from "./file-system.js";
24
24
 
25
25
  export const ROOT_TRANSACTION_NAME = ".firstdraft-root-output";
26
- export const ROOT_DESIGN_NAME = "design";
26
+ export const ROOT_DESIGN_PATH = ".firstdraft/design";
27
27
 
28
28
  const JOURNAL_FORMAT = "firstdraft.root-output-transaction/1";
29
29
  const JOURNAL_NAME = "journal.json";
@@ -37,10 +37,7 @@ const PRIVATE_DIRECTORY_MODE = 0o700;
37
37
  const PRIVATE_FILE_MODE = 0o600;
38
38
  const MAX_GIT_OUTPUT_BYTES = 128 * 1024 * 1024;
39
39
  const GIT_HASH_PATTERN = /^[0-9a-f]{40,64}$/;
40
- const RESERVED_NAMES = new Set([
41
- ROOT_DESIGN_NAME.toLowerCase(),
42
- ROOT_TRANSACTION_NAME.toLowerCase(),
43
- ]);
40
+ const RESERVED_NAMES = new Set([ROOT_TRANSACTION_NAME.toLowerCase()]);
44
41
 
45
42
  export class RootOutputPathError extends Error {
46
43
  /** @param {string} message @param {string} reason @param {{cause?: unknown}} [options] */
@@ -270,7 +267,7 @@ export function releaseRootOutput(target) {
270
267
  * @param {string} artifact.manifest_sha256
271
268
  * @param {object} callbacks
272
269
  * @param {(root: string) => void} callbacks.writeArtifact
273
- * @param {(root: string, ignoredRootEntries?: Set<string>) => void} callbacks.verifyArtifact
270
+ * @param {(root: string, ignoredPaths?: Set<string>) => void} callbacks.verifyArtifact
274
271
  * @param {(from: string, to: string) => void} [callbacks.rename]
275
272
  */
276
273
  export function materializeRootOutput(
@@ -310,7 +307,7 @@ export function materializeRootOutput(
310
307
  design_path:
311
308
  movedEntries.length === 0
312
309
  ? null
313
- : path.join(target.path, ROOT_DESIGN_NAME),
310
+ : path.join(target.path, ROOT_DESIGN_PATH),
314
311
  moved_entry_count: movedEntries.length,
315
312
  git_repository_preserved: target.git !== null,
316
313
  git_index_replaced: target.git !== null,
@@ -344,12 +341,6 @@ function assertReservedPathsAvailable(root) {
344
341
  const names = readdirSync(root);
345
342
  for (const name of names) {
346
343
  const folded = name.toLowerCase();
347
- if (folded === ROOT_DESIGN_NAME.toLowerCase()) {
348
- throw new RootOutputPathError(
349
- "The root output design path is reserved.",
350
- "root_reserved_path",
351
- );
352
- }
353
344
  if (folded !== ROOT_TRANSACTION_NAME.toLowerCase()) continue;
354
345
  if (name === ROOT_TRANSACTION_NAME) throw existingTransactionError(root);
355
346
  throw new RootOutputPathError(
@@ -357,6 +348,20 @@ function assertReservedPathsAvailable(root) {
357
348
  "root_reserved_path",
358
349
  );
359
350
  }
351
+ for (const name of names) assertDesignPathAvailable(root, name);
352
+ }
353
+
354
+ /** @param {string} root @param {string} name */
355
+ function assertDesignPathAvailable(root, name) {
356
+ if (name.toLowerCase() !== ".firstdraft") return;
357
+ const entry = path.join(root, name);
358
+ if (!lstatSync(entry).isDirectory()) return;
359
+ if (readdirSync(entry).some((child) => child.toLowerCase() === "design")) {
360
+ throw new RootOutputPathError(
361
+ "The root output design path is reserved.",
362
+ "root_reserved_path",
363
+ );
364
+ }
360
365
  }
361
366
 
362
367
  /** @param {string} root */
@@ -388,6 +393,7 @@ function captureRootSnapshot(root, rootDevice) {
388
393
  const names = readdirSync(root).sort(compareStrings);
389
394
  for (const name of names) {
390
395
  if (name === ROOT_TRANSACTION_NAME) continue;
396
+ assertDesignPathAvailable(root, name);
391
397
  if (RESERVED_NAMES.has(name.toLowerCase())) {
392
398
  throw new RootOutputPathError(
393
399
  "A reserved root output path appeared during preflight.",
@@ -549,7 +555,14 @@ function removeCompletedTransaction(target) {
549
555
  function assertArtifactRootNames(files) {
550
556
  for (const file of files) {
551
557
  const top = file.path.split("/", 1)[0] ?? "";
552
- if (RESERVED_NAMES.has(top.toLowerCase())) {
558
+ const folded = file.path.toLowerCase();
559
+ if (
560
+ RESERVED_NAMES.has(top.toLowerCase()) ||
561
+ folded === ".firstdraft" ||
562
+ (top.toLowerCase() === ".firstdraft" && top !== ".firstdraft") ||
563
+ folded === ROOT_DESIGN_PATH ||
564
+ folded.startsWith(`${ROOT_DESIGN_PATH}/`)
565
+ ) {
553
566
  throw new RootOutputMaterializationError(
554
567
  "The compilation artifact owns a reserved root path.",
555
568
  "root_artifact_collision",
@@ -567,10 +580,15 @@ function performRootTransaction(target, files, rename) {
567
580
  const designEntries = target.snapshot.filter(
568
581
  (entry) => entry.name !== ".git",
569
582
  );
570
- const designPath = path.join(target.path, ROOT_DESIGN_NAME);
571
583
  const artifactStage = path.join(target.transactionPath, ARTIFACT_STAGE_NAME);
584
+ // Keep the old .firstdraft inside the staged archive until the generated
585
+ // .firstdraft and its archive can be installed together at the root.
586
+ const designPath = path.join(artifactStage, ROOT_DESIGN_PATH);
572
587
  const artifactTopNames = [
573
- ...new Set(files.map((file) => file.path.split("/", 1)[0] ?? "")),
588
+ ...new Set([
589
+ ...files.map((file) => file.path.split("/", 1)[0] ?? ""),
590
+ ...(designEntries.length > 0 ? [".firstdraft"] : []),
591
+ ]),
574
592
  ].sort(compareStrings);
575
593
 
576
594
  if (designEntries.length > 0) {
@@ -578,6 +596,11 @@ function performRootTransaction(target, files, rename) {
578
596
  kind: "create_design",
579
597
  path: designPath,
580
598
  });
599
+ mkdirSync(path.dirname(designPath), {
600
+ recursive: true,
601
+ mode: DIRECTORY_MODE,
602
+ });
603
+ chmodSync(path.dirname(designPath), DIRECTORY_MODE);
581
604
  mkdirSync(designPath, { mode: DIRECTORY_MODE });
582
605
  target.journal.design_created = true;
583
606
  chmodSync(designPath, DIRECTORY_MODE);
@@ -644,7 +667,7 @@ function finishIrreversibleStep(target, phase) {
644
667
  /**
645
668
  * @param {RootOutputTarget} target
646
669
  * @param {Array<{path: string}>} files
647
- * @param {(root: string, ignoredRootEntries?: Set<string>) => void} verifyArtifact
670
+ * @param {(root: string, ignoredPaths?: Set<string>) => void} verifyArtifact
648
671
  */
649
672
  function verifyRootResult(target, files, verifyArtifact) {
650
673
  const ignored = new Set([ROOT_TRANSACTION_NAME]);
@@ -652,11 +675,11 @@ function verifyRootResult(target, files, verifyArtifact) {
652
675
  ignored.add(".git");
653
676
  }
654
677
  if (target.snapshot.some((entry) => entry.name !== ".git")) {
655
- ignored.add(ROOT_DESIGN_NAME);
678
+ ignored.add(ROOT_DESIGN_PATH);
656
679
  }
657
680
  verifyArtifact(target.path, ignored);
658
681
 
659
- const designPath = path.join(target.path, ROOT_DESIGN_NAME);
682
+ const designPath = path.join(target.path, ROOT_DESIGN_PATH);
660
683
  for (const identity of target.snapshot) {
661
684
  const currentPath =
662
685
  identity.name === ".git"
@@ -698,7 +721,7 @@ function verifyRootResult(target, files, verifyArtifact) {
698
721
  const expectedTopNames = new Set(
699
722
  files.map((file) => file.path.split("/", 1)[0] ?? ""),
700
723
  );
701
- for (const name of ignored) expectedTopNames.add(name);
724
+ for (const name of ignored) expectedTopNames.add(name.split("/", 1)[0] ?? "");
702
725
  const actualTopNames = new Set(readdirSync(target.path));
703
726
  if (!setsEqual(expectedTopNames, actualTopNames)) {
704
727
  throw new RootOutputMaterializationError(
@@ -750,7 +773,11 @@ function rollbackRootTransaction(target, rename) {
750
773
 
751
774
  if (target.journal.design_created) {
752
775
  try {
753
- const designPath = path.join(target.path, ROOT_DESIGN_NAME);
776
+ const designPath = path.join(
777
+ target.transactionPath,
778
+ ARTIFACT_STAGE_NAME,
779
+ ROOT_DESIGN_PATH,
780
+ );
754
781
  if (readdirSync(designPath).length === 0) {
755
782
  rmdirSync(designPath);
756
783
  } else {
@@ -1019,7 +1046,7 @@ function assertIgnoreProtection(target) {
1019
1046
  }
1020
1047
 
1021
1048
  const expected = target.git.ignoredPaths.map(
1022
- (candidate) => `${ROOT_DESIGN_NAME}/${candidate}`,
1049
+ (candidate) => `${ROOT_DESIGN_PATH}/${candidate}`,
1023
1050
  );
1024
1051
  const result = invokeGit(
1025
1052
  target.path,
@@ -1066,7 +1093,7 @@ function copyApplicableIgnoreFiles(root, previewWorktree, ignoredPath) {
1066
1093
 
1067
1094
  const destination = path.join(
1068
1095
  previewWorktree,
1069
- ROOT_DESIGN_NAME,
1096
+ ROOT_DESIGN_PATH,
1070
1097
  ...ancestor,
1071
1098
  ".gitignore",
1072
1099
  );
@@ -1084,7 +1111,7 @@ function createPreviewEntry(root, previewWorktree, ignoredPath) {
1084
1111
  const source = path.join(root, ...ignoredPath.split("/"));
1085
1112
  const destination = path.join(
1086
1113
  previewWorktree,
1087
- ROOT_DESIGN_NAME,
1114
+ ROOT_DESIGN_PATH,
1088
1115
  ...ignoredPath.split("/"),
1089
1116
  );
1090
1117
  let stat;
@@ -1123,7 +1150,7 @@ function prepareGitIndex(target, files) {
1123
1150
  for (const entry of git.indexEntries) {
1124
1151
  indexRecords.push(
1125
1152
  Buffer.from(
1126
- `${entry.mode} ${entry.object} 0\t${ROOT_DESIGN_NAME}/${entry.path}\0`,
1153
+ `${entry.mode} ${entry.object} 0\t${ROOT_DESIGN_PATH}/${entry.path}\0`,
1127
1154
  ),
1128
1155
  );
1129
1156
  }
@@ -1317,7 +1344,7 @@ function rollbackIndex(target) {
1317
1344
  function assertMovedIgnoreProtection(target) {
1318
1345
  if (target.git === null || target.git.ignoredPaths.length === 0) return;
1319
1346
  const expected = target.git.ignoredPaths.map(
1320
- (candidate) => `${ROOT_DESIGN_NAME}/${candidate}`,
1347
+ (candidate) => `${ROOT_DESIGN_PATH}/${candidate}`,
1321
1348
  );
1322
1349
  const result = invokeGit(
1323
1350
  target.path,