@firstdraft.com/cli 0.1.0-alpha.2 → 0.1.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/README.md CHANGED
@@ -3,11 +3,13 @@
3
3
  `firstdraft` is the command-line client for [First Draft](https://github.com/firstdraft/firstdraft). It is being
4
4
  built for agents that author and review Foundation Plans with their users.
5
5
 
6
- Public alpha releases use npm's `next` tag. This release line contains the auditable command shell, local Foundation
7
- Plan initialization, local application-key and UUID generation, conditional whole-document push, whole-graph
8
- analysis status polling, compile-and-publish orchestration, and read-only retained-Compilation download.
9
- Interfaces may change between prereleases, and publishing the CLI does not make the wider First Draft service
10
- generally available.
6
+ The current `0.1.x` line contains the auditable command shell, local Foundation Plan initialization, local
7
+ application-key and UUID generation, conditional whole-document push, whole-graph analysis status polling,
8
+ compile-and-publish orchestration, and read-only retained-Compilation download. Before `1.0.0`, increasing the minor
9
+ version starts a breaking compatibility line; increasing the patch version is otherwise backward-compatible within
10
+ that line. This policy applies to ordinary versions; historical prereleases are outside those compatibility
11
+ guarantees. `0.1.0` intentionally supersedes `0.1.0-alpha.2` and requires the service's `0.2.x` API contract.
12
+ Publishing the CLI does not make the wider First Draft service generally available.
11
13
 
12
14
  ## Requirements
13
15
 
@@ -16,18 +18,29 @@ generally available.
16
18
 
17
19
  ## Installation
18
20
 
19
- Once npm reports a public alpha, install the current prerelease explicitly:
21
+ Once npm reports an approved coordinated release, install it from the approval-gated `next` channel:
20
22
 
21
23
  ```sh
22
24
  npm install --global @firstdraft.com/cli@next
23
25
  firstdraft --version
24
26
  ```
25
27
 
26
- The npm package is `@firstdraft.com/cli`; it installs the `firstdraft` executable.
28
+ The npm package is `@firstdraft.com/cli`; it installs the `firstdraft` executable. `next` is a distribution channel,
29
+ not a claim that the selected version has SemVer prerelease syntax.
27
30
 
28
- There is intentionally no stable `latest` release yet. Pin an exact prerelease version instead of `next` when a
29
- repeatable installation matters. Remote Plan and Compilation commands require a
30
- compatible First Draft service and are currently intended for coordinated trials.
31
+ Pin an exact compatible version, such as `@firstdraft.com/cli@0.1.0` after the registry reports it, instead of
32
+ `next` when a repeatable installation matters. Moving npm's `latest` tag is a separate approval-gated promotion
33
+ after qualification; the initial release workflow does not move it. As observed on August 7, 2026, `latest` still
34
+ identifies `0.1.0-alpha.2`. After `0.1.0` is published under `next`, an untagged npm install will continue to select
35
+ that historical alpha rather than `0.1.0` until the separate promotion occurs. Remote Plan and Compilation commands
36
+ require a compatible First Draft service and are currently intended for coordinated trials.
37
+
38
+ Before the first ordinary `v0.1.0` release tag is created, an operator must inspect npm's exact listed
39
+ [GitHub Actions trusted-publisher](https://docs.npmjs.com/trusted-publishers/) relationship for
40
+ `@firstdraft.com/cli`, type `github`, the `firstdraft/cli` repository, `publish.yml`, the protected `npm` environment,
41
+ and permission `createPackage` (npm's trust-list vocabulary for the allowed publish operation). The release workflow
42
+ authenticates only with a short-lived GitHub OIDC credential. A persistent npm token, `NODE_AUTH_TOKEN`, or GitHub
43
+ Actions secret is not permitted as a publication fallback.
31
44
 
32
45
  ## Authenticate API commands
33
46
 
@@ -165,22 +178,41 @@ authorization to request that lifecycle. Immediately before its conditional muta
165
178
  Plan and requires its exact bytes to match the accepted Head, so bytes changed after analysis cannot be published.
166
179
  It extracts the accepted source SHA-256 from the saved ETag, hashes the current local bytes, and then sends that
167
180
  complete ETag in `If-Match`.
168
- The command writes no progress output to stdout. Success is exactly one validated JSON object containing the
169
- retained `project`, `compilation`, and `publication`, including the private GitHub repository URL.
181
+ The command writes stable human-readable progress to stderr, with every line prefixed by `First Draft:`. It reports
182
+ analysis, compilation completion or terminal failure or cancellation, the current GitHub phase, and an allowlisted
183
+ reason, retry count, and exact UTC retry time when a GitHub preflight check is delayed. A retained retry with no next
184
+ time is reported as paused and requiring operator recovery. Progress never includes IDs, hashes, repository names or
185
+ URLs, raw server projections, local paths, or environment values. Success writes exactly the validated private
186
+ GitHub repository URL plus a newline to stdout. If the command fails after progress has begun, its existing
187
+ structured JSON error envelope is the final stderr document after the progress lines.
188
+
189
+ The closed API `0.2.x` progress-reason allowlist is `github.configuration_missing`, `github.oauth_unavailable`,
190
+ `github.api_unavailable`, `github.reauthorization_required`, `github.account_mismatch`,
191
+ `github.installation_unavailable`, `github.installation_not_ready`, `github.preflight_unavailable`, the legacy-only
192
+ `github.preflight_unclassified`, and these stage-specific fallbacks: `github.preflight_unavailable.configuration`,
193
+ `github.preflight_unavailable.authorization`, `github.preflight_unavailable.repository_client`,
194
+ `github.preflight_unavailable.artifact_preparation`, `github.preflight_unavailable.installation_token`,
195
+ `github.preflight_unavailable.publication_preparation`, and `github.preflight_unavailable.repository_ref_client`.
196
+ Other values make the response invalid rather than becoming terminal output.
170
197
 
171
198
  The internal Publication is a Project singleton in this release. A repeat safely receives the same Publication
172
199
  instead of creating another. If the first conditional `PUT` has an ambiguous result, the CLI reconciles it with
173
- one read-only singleton `GET` and never automatically repeats the mutation. Rerunning `plan compile` safely
174
- replays the singleton request. Publication polling is sequential, bounded to ten minutes, and pinned to the
175
- retained Project Head, Compilation input, Publication identity, and repository identity.
200
+ one read-only singleton `GET` and never automatically repeats the mutation within that invocation. Do not run
201
+ concurrent Compile commands. After an invocation exits because the initial outcome or a later status read is
202
+ unavailable, wait and rerun `plan compile` with unchanged Plan bytes; its conditional request safely reconciles or
203
+ resumes the same retained singleton without creating another Compilation, repository, or push. Publication polling
204
+ is sequential, bounded to ten minutes, and pinned to the retained Project Head, Compilation input, Publication
205
+ identity, and repository identity.
176
206
 
177
207
  This release cannot repoint a Project's Publication to a later accepted Head. The public CLI therefore has no
178
- `plan publish` command and no local-start `plan compile --output` mode. Use the standalone retained-Compilation
179
- commands below when local generated source is useful.
208
+ `plan publish` command and no local-start `plan compile --output` mode. It retains lower-level Compilation commands
209
+ for operational callers that acquire an ID separately, but they are intentionally not a continuation of the
210
+ URL-only `plan compile` journey.
180
211
 
181
212
  ## Inspect a retained Compilation
182
213
 
183
- Read one Compilation ID returned by `plan compile`:
214
+ These lower-level commands are for callers that already hold a retained Compilation ID from authenticated API
215
+ metadata or operational tooling; `plan compile` prints only the final repository URL:
184
216
 
185
217
  ```sh
186
218
  firstdraft compilation status 01900000-0000-7000-8000-000000000001
@@ -216,13 +248,16 @@ structure, contents, and digests without claiming POSIX mode bits.
216
248
 
217
249
  ## Handled failures
218
250
 
219
- Every handled subcommand failure writes exactly one JSON object to standard error. Branch on its stable `error`
220
- value rather than the human-readable `detail`; `plan compile` also supplies `phase: "push" | "publication"` when
221
- `request_outcome_unknown` requires phase-specific recovery:
251
+ Every handled subcommand failure ends with exactly one JSON object on standard error. `plan compile` may first write
252
+ progress lines; machine consumers can remove only lines beginning with the exact `First Draft: ` prefix and parse
253
+ the remaining JSON document. Branch on its stable `error` value rather than the human-readable `detail`; `plan
254
+ compile` also supplies `phase: "push" | "publication"` when `request_outcome_unknown` requires phase-specific
255
+ recovery:
222
256
 
223
257
  - `phase: "push"` means the Plan mutation may have been accepted; stop and reconcile local Head state.
224
- - `phase: "publication"` means the singleton Publication mutation was not resolved; rerunning `plan compile` is a
225
- safe replay.
258
+ - `phase: "publication"` means the singleton Publication mutation was not resolved. Do not run concurrent Compile
259
+ commands. After the prior invocation exits, wait and rerun `plan compile` with unchanged Plan bytes to safely
260
+ reconcile or resume the retained singleton.
226
261
 
227
262
  | Commands | `error` | Exit | Meaning |
228
263
  | -------------------------------------------- | -------------------------------------------------------------------------------------------------- | ---: | -------------------------------------------------------------------------------------------------------------- |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@firstdraft.com/cli",
3
- "version": "0.1.0-alpha.2",
3
+ "version": "0.1.0",
4
4
  "description": "Command-line interface for First Draft",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/cli.js CHANGED
@@ -62,6 +62,7 @@ import {
62
62
  readPlanStatus,
63
63
  } from "./commands/plan-status.js";
64
64
  import { isFileSystemError } from "./file-system.js";
65
+ import { createPlanCompileProgressReporter } from "./plan-compile-progress.js";
65
66
  import { isUuidV7 } from "./plan-state.js";
66
67
  import { generateUuidV7 } from "./uuid-v7.js";
67
68
  import { VERSION } from "./version.js";
@@ -181,9 +182,9 @@ Environment:
181
182
  FIRSTDRAFT_API_URL Override the initial API origin
182
183
 
183
184
  The command submits the exact current whole-file Plan, waits for its analysis,
184
- and proceeds only when that analysis is valid. It then conditionally creates
185
- or replays the internal GitHub Publication lifecycle and prints its complete
186
- validated Project, Compilation, and Publication projection.
185
+ and proceeds only when that analysis is valid. It then conditionally creates or
186
+ replays the internal GitHub Publication lifecycle. Progress is written to
187
+ stderr. Success prints only the validated private GitHub repository URL.
187
188
  `;
188
189
 
189
190
  const COMPILATION_HELP = `First Draft CLI
@@ -318,17 +319,17 @@ const PLAN_PUBLISH_NOT_PUSHED_DETAIL =
318
319
  const PLAN_PUBLISH_LOCAL_PLAN_CHANGED_DETAIL =
319
320
  "The local Foundation Plan changed after validation. Run 'firstdraft plan compile' again to submit the current bytes.";
320
321
  const PLAN_PUBLISH_REQUEST_OUTCOME_UNKNOWN_DETAIL =
321
- "The Publication may have started, but its singleton status could not be verified. No mutation was retried. Running 'firstdraft plan compile' again is safe.";
322
+ "The Publication may have started, but its retained singleton status could not be verified. No mutation was retried. Do not run concurrent Compile commands. Wait, then rerun 'firstdraft plan compile' with unchanged Plan bytes to safely reconcile or resume the retained singleton.";
322
323
  const PLAN_PUBLISH_START_REJECTED_DETAIL =
323
324
  "First Draft rejected the publication request.";
324
325
  const PLAN_PUBLISH_STATUS_UNAVAILABLE_DETAIL =
325
- "Could not read the pinned publication status. The command stopped without starting another Publication.";
326
+ "Could not read the retained Publication status. The command stopped without starting another Publication. Do not run concurrent Compile commands. Wait, then rerun 'firstdraft plan compile' with unchanged Plan bytes to safely resume the retained singleton.";
326
327
  const PLAN_PUBLISH_STATUS_INVALID_DETAIL =
327
328
  "First Draft returned an invalid publication status response. Retrying unchanged will not repair this protocol mismatch.";
328
329
  const PLAN_PUBLISH_CHANGED_DETAIL =
329
330
  "The pinned Publication changed while being polled. The command stopped without following a replacement.";
330
331
  const PLAN_PUBLISH_TIMEOUT_DETAIL =
331
- "The pinned Publication is still processing after the bounded ten-minute wait.";
332
+ "The retained Publication is still processing after the bounded ten-minute wait. This invocation stopped waiting, but retained work may continue. Do not run concurrent Compile commands. Wait, then rerun 'firstdraft plan compile' with unchanged Plan bytes to safely resume the retained singleton.";
332
333
  const PLAN_PUBLISH_FAILED_DETAIL =
333
334
  "The pinned Publication failed. Its validated status identifies the failed phase.";
334
335
  const PLAN_PUBLISH_CANCELLED_DETAIL = "The pinned Publication was cancelled.";
@@ -1495,6 +1496,7 @@ async function runPlanCompile({
1495
1496
  }
1496
1497
 
1497
1498
  let result;
1499
+ const reportProgress = createPlanCompileProgressReporter(stderr);
1498
1500
  try {
1499
1501
  result = await compilePlan({
1500
1502
  cwd,
@@ -1510,12 +1512,17 @@ async function runPlanCompile({
1510
1512
  push: planCompilePush,
1511
1513
  readStatus: planCompileReadStatus,
1512
1514
  publish: planCompilePublish,
1515
+ onProgress: reportProgress,
1513
1516
  });
1514
1517
  } catch (error) {
1515
1518
  return writePlanCompileError(stderr, error);
1516
1519
  }
1517
1520
 
1518
- writeJson(stdout, result);
1521
+ const repository =
1522
+ /** @type {NonNullable<typeof result.publication.repository>} */ (
1523
+ result.publication.repository
1524
+ );
1525
+ stdout.write(`${repository.html_url}\n`);
1519
1526
  return 0;
1520
1527
  }
1521
1528
 
@@ -62,6 +62,7 @@ export class PlanCompileAnalysisInvalidError extends Error {
62
62
  * @property {() => number} [analysisNow]
63
63
  * @property {(delayMs: number) => Promise<void>} [publicationSleep]
64
64
  * @property {() => number} [publicationNow]
65
+ * @property {(progress: import("../plan-compile-progress.js").PlanCompileProgress) => void} [onProgress]
65
66
  * @property {typeof pushPlan} [push]
66
67
  * @property {typeof readPlanStatus} [readStatus]
67
68
  * @property {typeof publishPlan} [publish]
@@ -85,6 +86,7 @@ export async function compilePlan({
85
86
  analysisNow,
86
87
  publicationSleep,
87
88
  publicationNow,
89
+ onProgress = () => {},
88
90
  push = pushPlan,
89
91
  readStatus = readPlanStatus,
90
92
  publish = publishPlan,
@@ -105,6 +107,7 @@ export async function compilePlan({
105
107
  ).graph_version;
106
108
 
107
109
  let status;
110
+ onProgress({ phase: "analysis", status: "waiting" });
108
111
  try {
109
112
  status = await readStatus({
110
113
  cwd,
@@ -137,6 +140,7 @@ export async function compilePlan({
137
140
  if (status.body.analysis.status !== "valid") {
138
141
  throw new PlanCompileAnalysisNotValidError(status.body);
139
142
  }
143
+ onProgress({ phase: "analysis", status: "valid" });
140
144
 
141
145
  return publish({
142
146
  cwd,
@@ -146,5 +150,6 @@ export async function compilePlan({
146
150
  sleep: publicationSleep,
147
151
  now: publicationNow,
148
152
  expectedEtag: pushed.etag,
153
+ onProgress,
149
154
  });
150
155
  }
@@ -69,11 +69,13 @@ const PUBLICATION_KEYS = [
69
69
  "created_at",
70
70
  "failure",
71
71
  "id",
72
+ "progress",
72
73
  "repository",
73
74
  "started_at",
74
75
  "status",
75
76
  ];
76
77
  const FAILURE_KEYS = ["code", "phase"];
78
+ const PROGRESS_KEYS = ["phase", "reason_code", "retry_at", "retry_count"];
77
79
  const REPOSITORY_KEYS = [
78
80
  "commit_sha",
79
81
  "default_branch",
@@ -85,6 +87,41 @@ const REPOSITORY_KEYS = [
85
87
  "tree_sha",
86
88
  ];
87
89
  const OWNER_KEYS = ["id", "login", "type"];
90
+ const PROGRESS_PHASES = new Set([
91
+ "compiling",
92
+ "preparing_repository",
93
+ "github_preflight",
94
+ "creating_repository",
95
+ "preparing_repository_reconciliation",
96
+ "reconciling_repository",
97
+ "preparing_artifact",
98
+ "publishing_artifact",
99
+ "preparing_publication_reconciliation",
100
+ "reconciling_publication",
101
+ "completed",
102
+ "failed",
103
+ "cancelled",
104
+ ]);
105
+ const PROGRESS_REASON_CODES = new Set([
106
+ "github.configuration_missing",
107
+ "github.oauth_unavailable",
108
+ "github.api_unavailable",
109
+ "github.reauthorization_required",
110
+ "github.account_mismatch",
111
+ "github.installation_unavailable",
112
+ "github.installation_not_ready",
113
+ "github.preflight_unavailable",
114
+ "github.preflight_unclassified",
115
+ "github.preflight_unavailable.configuration",
116
+ "github.preflight_unavailable.authorization",
117
+ "github.preflight_unavailable.repository_client",
118
+ "github.preflight_unavailable.artifact_preparation",
119
+ "github.preflight_unavailable.installation_token",
120
+ "github.preflight_unavailable.publication_preparation",
121
+ "github.preflight_unavailable.repository_ref_client",
122
+ ]);
123
+ const MAX_PROGRESS_RETRY_COUNT = 7;
124
+ const RETRY_TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/;
88
125
 
89
126
  /**
90
127
  * @typedef {object} PlanPublishFileSystem
@@ -183,7 +220,7 @@ export class PublicationCancelledError extends Error {
183
220
  * @typedef {object} PublicationResponse
184
221
  * @property {{id: string, graph_version: number, head_source_sha256: string}} project
185
222
  * @property {{id: string, analysis_run_id: string, graph_version: number, head_source_sha256: string, status: string, compiler_release: string, target: {id: string, profile: string}, artifact: null | {sha256: string, manifest_sha256: string, file_count: number}}} compilation
186
- * @property {{id: string, status: string, repository: null | {id: number, private: true, owner: {id: number, login: string, type: "User"}, full_name: string, default_branch: string, html_url: string, tree_sha: string | null, commit_sha: string | null}, failure: null | {phase: string, code: string}, created_at: string, started_at: string | null, completed_at: string | null}} publication
223
+ * @property {{id: string, status: string, repository: null | {id: number, private: true, owner: {id: number, login: string, type: "User"}, full_name: string, default_branch: string, html_url: string, tree_sha: string | null, commit_sha: string | null}, failure: null | {phase: string, code: string}, progress: {phase: string, retry_at: string | null, retry_count: number, reason_code: string | null}, created_at: string, started_at: string | null, completed_at: string | null}} publication
187
224
  */
188
225
 
189
226
  /**
@@ -195,6 +232,7 @@ export class PublicationCancelledError extends Error {
195
232
  * @property {(timeoutMs: number) => AbortSignal} [createRequestSignal]
196
233
  * @property {(delayMs: number) => Promise<void>} [sleep]
197
234
  * @property {() => number} [now]
235
+ * @property {(progress: import("../plan-compile-progress.js").PlanCompileProgress) => void} [onProgress]
198
236
  */
199
237
 
200
238
  /**
@@ -209,6 +247,7 @@ export async function publishPlan({
209
247
  createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs),
210
248
  sleep = sleepFor,
211
249
  now = Date.now,
250
+ onProgress = () => {},
212
251
  }) {
213
252
  const state = readPlanState({ cwd, fileSystem });
214
253
  if (state.api_url === undefined || state.foundation_plan_etag === undefined) {
@@ -252,6 +291,8 @@ export async function publishPlan({
252
291
  const deadline = now() + WAIT_TIMEOUT_MS;
253
292
  let initial;
254
293
 
294
+ onProgress({ phase: "compilation", status: "waiting" });
295
+
255
296
  try {
256
297
  initial = await startPublication({
257
298
  endpoint,
@@ -309,6 +350,7 @@ export async function publishPlan({
309
350
  }
310
351
 
311
352
  let current = initial;
353
+ reportProgress(onProgress, current);
312
354
  while (!TERMINAL_PUBLICATION_STATUSES.has(current.publication.status)) {
313
355
  const remaining = deadline - now();
314
356
  if (remaining <= 0) throw new PublicationTimeoutError(current);
@@ -331,6 +373,7 @@ export async function publishPlan({
331
373
  throw new PublicationChangedError(current, next);
332
374
  }
333
375
  current = next;
376
+ reportProgress(onProgress, current);
334
377
  }
335
378
 
336
379
  if (
@@ -502,6 +545,7 @@ function parsePublicationResponse(value, projectId, headSourceSha256) {
502
545
  !PUBLICATION_STATUSES.has(publication.status) ||
503
546
  !isNullableRepository(publication.repository) ||
504
547
  !isNullableFailure(publication.failure) ||
548
+ !isProgress(publication.progress, publication.status) ||
505
549
  !isTimestamp(publication.created_at) ||
506
550
  !isNullableTimestamp(publication.started_at) ||
507
551
  !isNullableTimestamp(publication.completed_at) ||
@@ -525,6 +569,10 @@ function parsePublicationResponse(value, projectId, headSourceSha256) {
525
569
  const failure = /** @type {null | {phase: string, code: string}} */ (
526
570
  publication.failure
527
571
  );
572
+ const progress =
573
+ /** @type {{phase: string, retry_at: string | null, retry_count: number, reason_code: string | null}} */ (
574
+ publication.progress
575
+ );
528
576
 
529
577
  return {
530
578
  project: {
@@ -571,6 +619,12 @@ function parsePublicationResponse(value, projectId, headSourceSha256) {
571
619
  },
572
620
  failure:
573
621
  failure === null ? null : { phase: failure.phase, code: failure.code },
622
+ progress: {
623
+ phase: progress.phase,
624
+ retry_at: progress.retry_at,
625
+ retry_count: progress.retry_count,
626
+ reason_code: progress.reason_code,
627
+ },
574
628
  created_at: /** @type {string} */ (publication.created_at),
575
629
  started_at: /** @type {string | null} */ (publication.started_at),
576
630
  completed_at: /** @type {string | null} */ (publication.completed_at),
@@ -670,6 +724,82 @@ function isNullableFailure(value) {
670
724
  );
671
725
  }
672
726
 
727
+ /** @param {unknown} value @param {unknown} publicationStatus */
728
+ function isProgress(value, publicationStatus) {
729
+ if (
730
+ !hasExactKeySet(value, PROGRESS_KEYS) ||
731
+ typeof value.phase !== "string" ||
732
+ !PROGRESS_PHASES.has(value.phase) ||
733
+ !Number.isSafeInteger(value.retry_count) ||
734
+ Number(value.retry_count) < 0 ||
735
+ Number(value.retry_count) > MAX_PROGRESS_RETRY_COUNT ||
736
+ !isNullableRetryTimestamp(value.retry_at) ||
737
+ !(
738
+ value.reason_code === null ||
739
+ (typeof value.reason_code === "string" &&
740
+ PROGRESS_REASON_CODES.has(value.reason_code))
741
+ ) ||
742
+ !progressMatchesPublicationStatus(value.phase, publicationStatus)
743
+ ) {
744
+ return false;
745
+ }
746
+
747
+ if (value.phase !== "github_preflight") {
748
+ return (
749
+ value.retry_at === null &&
750
+ value.retry_count === 0 &&
751
+ value.reason_code === null
752
+ );
753
+ }
754
+
755
+ return value.retry_count === 0
756
+ ? value.retry_at === null && value.reason_code === null
757
+ : value.reason_code !== null;
758
+ }
759
+
760
+ /** @param {string} progressPhase @param {unknown} publicationStatus */
761
+ function progressMatchesPublicationStatus(progressPhase, publicationStatus) {
762
+ if (progressPhase === "compiling") return publicationStatus === "compiling";
763
+ if (progressPhase === "completed") return publicationStatus === "succeeded";
764
+ if (progressPhase === "failed") {
765
+ return (
766
+ publicationStatus === "failed" ||
767
+ publicationStatus === "repository_conflict"
768
+ );
769
+ }
770
+ if (progressPhase === "cancelled") return publicationStatus === "cancelled";
771
+ if (progressPhase === "github_preflight") {
772
+ return [
773
+ "provisioning_repository",
774
+ "repository_unknown",
775
+ "publishing",
776
+ "publication_unknown",
777
+ ].includes(String(publicationStatus));
778
+ }
779
+
780
+ const expectedStatus = new Map([
781
+ ["preparing_repository", "provisioning_repository"],
782
+ ["creating_repository", "provisioning_repository"],
783
+ ["preparing_repository_reconciliation", "repository_unknown"],
784
+ ["reconciling_repository", "repository_unknown"],
785
+ ["preparing_artifact", "publishing"],
786
+ ["publishing_artifact", "publishing"],
787
+ ["preparing_publication_reconciliation", "publication_unknown"],
788
+ ["reconciling_publication", "publication_unknown"],
789
+ ]).get(progressPhase);
790
+ return publicationStatus === expectedStatus;
791
+ }
792
+
793
+ /** @param {unknown} value */
794
+ function isNullableRetryTimestamp(value) {
795
+ return (
796
+ value === null ||
797
+ (typeof value === "string" &&
798
+ RETRY_TIMESTAMP_PATTERN.test(value) &&
799
+ isTimestamp(value))
800
+ );
801
+ }
802
+
673
803
  /** @param {unknown} value */
674
804
  function isNullableRepository(value) {
675
805
  if (value === null) return true;
@@ -817,6 +947,25 @@ function validRepositoryTransition(previous, current) {
817
947
  );
818
948
  }
819
949
 
950
+ /**
951
+ * @param {(progress: import("../plan-compile-progress.js").PlanCompileProgress) => void} onProgress
952
+ * @param {PublicationResponse} current
953
+ */
954
+ function reportProgress(onProgress, current) {
955
+ const progress = current.publication.progress;
956
+ onProgress({
957
+ phase: "publication",
958
+ compilationStatus:
959
+ /** @type {"queued" | "running" | "succeeded" | "failed" | "cancelled"} */ (
960
+ current.compilation.status
961
+ ),
962
+ publicationPhase: progress.phase,
963
+ retryAt: progress.retry_at,
964
+ retryCount: progress.retry_count,
965
+ reasonCode: progress.reason_code,
966
+ });
967
+ }
968
+
820
969
  /** @param {Response} response @param {unknown} body */
821
970
  function safeProblem(response, body) {
822
971
  if (!isProblemBody(response, body)) return null;
@@ -0,0 +1,125 @@
1
+ const PREFIX = "First Draft: ";
2
+
3
+ const PUBLICATION_MESSAGES = new Map([
4
+ ["preparing_repository", "Preparing private GitHub repository..."],
5
+ ["creating_repository", "Creating private GitHub repository..."],
6
+ [
7
+ "preparing_repository_reconciliation",
8
+ "Preparing to verify GitHub repository creation...",
9
+ ],
10
+ ["reconciling_repository", "Verifying GitHub repository creation..."],
11
+ ["preparing_artifact", "Preparing compiled application..."],
12
+ ["publishing_artifact", "Publishing compiled application to GitHub..."],
13
+ [
14
+ "preparing_publication_reconciliation",
15
+ "Preparing to verify GitHub publication...",
16
+ ],
17
+ ["reconciling_publication", "Verifying GitHub publication..."],
18
+ ["completed", "GitHub publication complete."],
19
+ ]);
20
+
21
+ /**
22
+ * @typedef {object} AnalysisProgress
23
+ * @property {"analysis"} phase
24
+ * @property {"waiting" | "valid"} status
25
+ */
26
+
27
+ /**
28
+ * @typedef {object} CompilationProgress
29
+ * @property {"compilation"} phase
30
+ * @property {"waiting"} status
31
+ */
32
+
33
+ /**
34
+ * @typedef {object} PublicationProgress
35
+ * @property {"publication"} phase
36
+ * @property {"queued" | "running" | "succeeded" | "failed" | "cancelled"} compilationStatus
37
+ * @property {string} publicationPhase
38
+ * @property {string | null} retryAt
39
+ * @property {number} retryCount
40
+ * @property {string | null} reasonCode
41
+ */
42
+
43
+ /**
44
+ * @typedef {AnalysisProgress | CompilationProgress | PublicationProgress} PlanCompileProgress
45
+ */
46
+
47
+ /**
48
+ * Convert deliberately narrow lifecycle observations into stable progress.
49
+ * This boundary never receives response projections, identifiers, hashes,
50
+ * repository names, URLs, or local state.
51
+ *
52
+ * @param {{write: (text: string) => unknown}} writer
53
+ * @returns {(progress: PlanCompileProgress) => void}
54
+ */
55
+ export function createPlanCompileProgressReporter(writer) {
56
+ let compilationSucceeded = false;
57
+ /** @type {string | null} */
58
+ let previousProgress = null;
59
+
60
+ /** @param {string} message */
61
+ function write(message) {
62
+ writer.write(`${PREFIX}${message}\n`);
63
+ }
64
+
65
+ return (progress) => {
66
+ const serialized = JSON.stringify(progress);
67
+ if (serialized === previousProgress) return;
68
+ previousProgress = serialized;
69
+
70
+ if (progress.phase === "analysis") {
71
+ write(
72
+ progress.status === "waiting"
73
+ ? "Analyzing Foundation Plan..."
74
+ : "Foundation Plan analysis valid.",
75
+ );
76
+ return;
77
+ }
78
+
79
+ if (progress.phase === "compilation") {
80
+ write("Compiling application...");
81
+ return;
82
+ }
83
+
84
+ if (progress.compilationStatus === "succeeded" && !compilationSucceeded) {
85
+ write("Application compiled.");
86
+ compilationSucceeded = true;
87
+ }
88
+
89
+ if (progress.publicationPhase === "compiling") return;
90
+ if (progress.publicationPhase === "failed") {
91
+ write(
92
+ progress.compilationStatus === "failed"
93
+ ? "Application compilation failed."
94
+ : "GitHub publication failed.",
95
+ );
96
+ return;
97
+ }
98
+ if (progress.publicationPhase === "cancelled") {
99
+ write(
100
+ progress.compilationStatus === "cancelled"
101
+ ? "Application compilation cancelled."
102
+ : "GitHub publication cancelled.",
103
+ );
104
+ return;
105
+ }
106
+ if (progress.publicationPhase === "github_preflight") {
107
+ write(githubPreflightMessage(progress));
108
+ return;
109
+ }
110
+
111
+ const message = PUBLICATION_MESSAGES.get(progress.publicationPhase);
112
+ if (message !== undefined) write(message);
113
+ };
114
+ }
115
+
116
+ /** @param {PublicationProgress} progress */
117
+ function githubPreflightMessage(progress) {
118
+ if (progress.retryCount === 0) return "Checking GitHub access...";
119
+
120
+ const retry =
121
+ progress.retryAt === null
122
+ ? "automatic retries paused; operator recovery required"
123
+ : `next retry: ${progress.retryAt}`;
124
+ return `Checking GitHub access (reason: ${progress.reasonCode}; retry count: ${progress.retryCount}; ${retry}).`;
125
+ }