@firstdraft.com/cli 0.9.0 → 0.11.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.
@@ -0,0 +1,204 @@
1
+ import { isUuidV7 } from "../plan-state.js";
2
+ import { PARENT_SEGMENT, plainWords } from "./report.js";
3
+
4
+ // A note carries only fields of a known shape, as a failure report does: the
5
+ // plain words of free text, and identifiers that fit their patterns. The
6
+ // Service refuses the same shapes.
7
+
8
+ export const NOTE_KINDS = Object.freeze([
9
+ "unstated_request",
10
+ "unclear_guidance",
11
+ "wrong_output",
12
+ ]);
13
+ /**
14
+ * Each kind's fields, in the order a note carries them. A field the kind does
15
+ * not list is no option of its command.
16
+ */
17
+ export const NOTE_FIELDS = Object.freeze({
18
+ unstated_request: Object.freeze(["request", "workaround"]),
19
+ unclear_guidance: Object.freeze(["page", "code", "unclear", "workaround"]),
20
+ wrong_output: Object.freeze([
21
+ "source",
22
+ "code",
23
+ "compilation_id",
24
+ "file",
25
+ "expected",
26
+ "actual",
27
+ "workaround",
28
+ ]),
29
+ });
30
+
31
+ const PLAIN_WORD_FIELDS = new Set([
32
+ "request",
33
+ "unclear",
34
+ "expected",
35
+ "actual",
36
+ "workaround",
37
+ ]);
38
+ const REQUIRED_PLAIN_WORDS = Object.freeze({
39
+ unstated_request: ["request"],
40
+ unclear_guidance: ["unclear"],
41
+ wrong_output: ["expected", "actual"],
42
+ });
43
+ const MAX_PLAIN_WORDS = 300;
44
+ const MAX_PAGE = 200;
45
+ const MAX_CODE = 120;
46
+ const MAX_FILE = 300;
47
+ // SKILL.md, references/plan/policies.md, references/interview.md#scope
48
+ const SKILL_PAGE =
49
+ /^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*\.md(?:#[A-Za-z0-9_-]+)?$/;
50
+ // foundation_plan.identity.reserved_constant_collision, invalid_output_path
51
+ const CODE = /^[a-z0-9_]+(?:\.[a-z0-9_]+)*$/;
52
+ // app/models/movie.rb, app/models/movie.rb:12
53
+ const APPLICATION_FILE = /^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*(?::\d{1,7})?$/;
54
+
55
+ export class NoteIncompleteError extends Error {
56
+ /** @param {readonly string[]} missing what noteBody said the note needs */
57
+ constructor(missing) {
58
+ super("A field the note needs did not fit its shape.");
59
+ this.missing = missing;
60
+ }
61
+ }
62
+
63
+ /** @typedef {"unstated_request" | "unclear_guidance" | "wrong_output"} NoteKind */
64
+ /** @typedef {Partial<Record<string, string>>} NoteFields */
65
+
66
+ /**
67
+ * Whether these fields, as given, can make a note of `kind`: each required
68
+ * field is given, `wrong_output` names a source and only the fields that
69
+ * source takes, and a Compilation is a lowercase UUIDv7. A note about
70
+ * generated code may still lack its Compilation, which the command reads
71
+ * from its record.
72
+ *
73
+ * @param {NoteKind} kind
74
+ * @param {NoteFields} fields
75
+ */
76
+ export function noteArgumentsValid(kind, fields) {
77
+ const allowed = /** @type {readonly string[]} */ (NOTE_FIELDS[kind]);
78
+ if (Object.keys(fields).some((field) => !allowed.includes(field))) {
79
+ return false;
80
+ }
81
+ if (REQUIRED_PLAIN_WORDS[kind].some((field) => fields[field] === undefined)) {
82
+ return false;
83
+ }
84
+ if (kind === "unclear_guidance") {
85
+ return fields.page !== undefined || fields.code !== undefined;
86
+ }
87
+ if (kind === "wrong_output") {
88
+ if (fields.source === "analysis") {
89
+ return fields.compilation_id === undefined && fields.file === undefined;
90
+ }
91
+ return (
92
+ fields.source === "generated_code" &&
93
+ fields.code === undefined &&
94
+ (fields.compilation_id === undefined || isUuidV7(fields.compilation_id))
95
+ );
96
+ }
97
+ return true;
98
+ }
99
+
100
+ /**
101
+ * Shapes the note that is printed and sent. Each field keeps only what fits
102
+ * its shape; `omitted` says, for the preview, what was left out, and
103
+ * `missing` says which left-out fields the note needs, so it cannot be sent.
104
+ *
105
+ * @param {NoteKind} kind
106
+ * @param {NoteFields} fields valid for noteArgumentsValid
107
+ */
108
+ export function noteBody(kind, fields) {
109
+ /** @type {Record<string, string>} */
110
+ const note = { kind };
111
+ /** @type {[string, string][]} */
112
+ const leftOut = [];
113
+ for (const field of NOTE_FIELDS[kind]) {
114
+ const value = fields[field];
115
+ if (value === undefined) continue;
116
+
117
+ const shaped = shapeField(field, value);
118
+ if (shaped) {
119
+ note[field] = shaped;
120
+ } else {
121
+ leftOut.push([field, `${field}, which ${SHAPE_REASONS[field]}`]);
122
+ }
123
+ }
124
+
125
+ /** @type {Set<string>} */
126
+ const needed = new Set(REQUIRED_PLAIN_WORDS[kind]);
127
+ // Guidance that was unclear needs a page or a code to say which.
128
+ if (
129
+ kind === "unclear_guidance" &&
130
+ note.page === undefined &&
131
+ note.code === undefined
132
+ ) {
133
+ needed.add("page").add("code");
134
+ }
135
+ return {
136
+ body: { note },
137
+ omitted: leftOut
138
+ .filter(([field]) => !needed.has(field))
139
+ .map(([, reason]) => reason),
140
+ missing: leftOut
141
+ .filter(([field]) => needed.has(field))
142
+ .map(([, reason]) => reason),
143
+ };
144
+ }
145
+
146
+ const NO_PLAIN_WORDS = "has no plain words on its first line";
147
+ /** @type {Readonly<Record<string, string>>} */
148
+ const SHAPE_REASONS = {
149
+ request: NO_PLAIN_WORDS,
150
+ unclear: NO_PLAIN_WORDS,
151
+ expected: NO_PLAIN_WORDS,
152
+ actual: NO_PLAIN_WORDS,
153
+ workaround: NO_PLAIN_WORDS,
154
+ page: "is not SKILL.md or another path ending in .md",
155
+ code: "is not a diagnostic code or CLI error value",
156
+ file: "is not a relative path in the application",
157
+ };
158
+
159
+ /**
160
+ * One field in its shape, or an empty string when nothing of it fits.
161
+ *
162
+ * @param {string} field
163
+ * @param {string} value
164
+ */
165
+ function shapeField(field, value) {
166
+ if (PLAIN_WORD_FIELDS.has(field)) return plainWords(value, MAX_PLAIN_WORDS);
167
+ if (field === "page") return skillPage(value) ?? "";
168
+ if (field === "code") return diagnosticCode(value) ?? "";
169
+ if (field === "file") return applicationFile(value) ?? "";
170
+ // source and compilation_id were checked as arguments.
171
+ return value;
172
+ }
173
+
174
+ /**
175
+ * @param {string} value
176
+ * @returns {string | undefined}
177
+ */
178
+ export function skillPage(value) {
179
+ return value.length <= MAX_PAGE &&
180
+ SKILL_PAGE.test(value) &&
181
+ !PARENT_SEGMENT.test(value.replace(/#.*$/, ""))
182
+ ? value
183
+ : undefined;
184
+ }
185
+
186
+ /**
187
+ * @param {string} value
188
+ * @returns {string | undefined}
189
+ */
190
+ export function diagnosticCode(value) {
191
+ return value.length <= MAX_CODE && CODE.test(value) ? value : undefined;
192
+ }
193
+
194
+ /**
195
+ * @param {string} value
196
+ * @returns {string | undefined}
197
+ */
198
+ export function applicationFile(value) {
199
+ return value.length <= MAX_FILE &&
200
+ APPLICATION_FILE.test(value) &&
201
+ !PARENT_SEGMENT.test(value)
202
+ ? value
203
+ : undefined;
204
+ }
@@ -1,4 +1,5 @@
1
- import { publishPlan } from "./plan-publish.js";
1
+ import { readPlanState } from "../plan-state.js";
2
+ import { reviewedSources } from "./sketches.js";
2
3
  import { compileAndDownload } from "./compilation.js";
3
4
  import {
4
5
  prepareCompilationOutputTarget,
@@ -8,6 +9,7 @@ import {
8
9
  PlanPushNetworkError,
9
10
  PlanPushProtocolError,
10
11
  pushPlan,
12
+ resolveApiUrl,
11
13
  } from "./plan-push.js";
12
14
  import { PlanStatusChangedError, readPlanStatus } from "./plan-status.js";
13
15
 
@@ -58,6 +60,7 @@ export class PlanCompileAnalysisInvalidError extends Error {
58
60
  /**
59
61
  * @typedef {object} CompilePlanOptions
60
62
  * @property {string} cwd
63
+ * @property {string} [reviewedDigest]
61
64
  * @property {string} [apiUrl]
62
65
  * @property {typeof globalThis.fetch} [fetchFunction]
63
66
  * @property {import("./plan-push.js").PlanPushFileSystem} [fileSystem]
@@ -65,66 +68,15 @@ export class PlanCompileAnalysisInvalidError extends Error {
65
68
  * @property {(timeoutMs?: number) => AbortSignal} [createRequestSignal]
66
69
  * @property {(delayMs: number) => Promise<void>} [analysisSleep]
67
70
  * @property {() => number} [analysisNow]
68
- * @property {(delayMs: number) => Promise<void>} [publicationSleep]
69
- * @property {() => number} [publicationNow]
70
71
  * @property {(progress: import("../plan-compile-progress.js").PlanCompileProgress) => void} [onProgress]
71
72
  * @property {typeof pushPlan} [push]
72
73
  * @property {typeof readPlanStatus} [readStatus]
73
- * @property {typeof publishPlan} [publish]
74
74
  */
75
75
 
76
- /**
77
- * Submit and analyze the exact current local Plan before invoking the internal
78
- * GitHub Publication lifecycle. The Publication function performs the final
79
- * local-byte check immediately before its conditional mutation.
80
- *
81
- * @param {CompilePlanOptions} options
82
- */
83
- export async function compilePlanToGitHub({
84
- cwd,
85
- apiUrl,
86
- fetchFunction,
87
- fileSystem,
88
- createTemporaryId,
89
- createRequestSignal,
90
- analysisSleep,
91
- analysisNow,
92
- publicationSleep,
93
- publicationNow,
94
- onProgress = () => {},
95
- push = pushPlan,
96
- readStatus = readPlanStatus,
97
- publish = publishPlan,
98
- }) {
99
- const prepared = await preparePlan({
100
- cwd,
101
- apiUrl,
102
- fetchFunction,
103
- fileSystem,
104
- createTemporaryId,
105
- createRequestSignal,
106
- analysisSleep,
107
- analysisNow,
108
- onProgress,
109
- push,
110
- readStatus,
111
- });
112
-
113
- return publish({
114
- cwd,
115
- fetchFunction,
116
- fileSystem,
117
- createRequestSignal,
118
- sleep: publicationSleep,
119
- now: publicationNow,
120
- expectedEtag: prepared.pushed.etag,
121
- onProgress,
122
- });
123
- }
124
-
125
76
  /**
126
77
  * @typedef {CompilePlanOptions & {
127
78
  * output: string,
79
+ * revision?: string,
128
80
  * compilationSleep?: (delayMs: number) => Promise<void>,
129
81
  * compilationNow?: () => number,
130
82
  * compile?: typeof compileAndDownload
@@ -134,14 +86,14 @@ export async function compilePlanToGitHub({
134
86
  /**
135
87
  * Submit and analyze the exact current local Plan, then start one direct
136
88
  * Compilation and materialize its verified artifact into an absent directory
137
- * or the eligible current directory. GitHub Publication is the explicit
138
- * --github mode owned by compilePlanToGitHub.
89
+ * or the eligible current directory.
139
90
  *
140
91
  * @param {CompilePlanToDirectoryOptions} options
141
92
  */
142
93
  export async function compilePlanToDirectory({
143
94
  cwd,
144
95
  output,
96
+ revision,
145
97
  apiUrl,
146
98
  fetchFunction,
147
99
  fileSystem,
@@ -156,10 +108,14 @@ export async function compilePlanToDirectory({
156
108
  readStatus = readPlanStatus,
157
109
  compile = compileAndDownload,
158
110
  }) {
111
+ const reviewed = reviewedSources(cwd, revision);
112
+ if (reviewed)
113
+ resolveApiUrl(apiUrl, readPlanState({ cwd, fileSystem }).api_url);
159
114
  const outputTarget = prepareCompilationOutputTarget({ cwd, output });
160
115
  try {
161
116
  const prepared = await preparePlan({
162
117
  cwd,
118
+ reviewedDigest: reviewed?.planSha256,
163
119
  apiUrl,
164
120
  fetchFunction,
165
121
  fileSystem,
@@ -175,7 +131,8 @@ export async function compilePlanToDirectory({
175
131
 
176
132
  return await compile({
177
133
  cwd,
178
- expectedEtag: prepared.pushed.etag,
134
+ ...(reviewed ? { revision, sketchFiles: reviewed.files } : {}),
135
+ expectedEtag: prepared.etag,
179
136
  expected: {
180
137
  projectId: body.project.id,
181
138
  graphVersion: body.project.graph_version,
@@ -199,10 +156,11 @@ export async function compilePlanToDirectory({
199
156
  }
200
157
 
201
158
  /**
202
- * @param {Omit<CompilePlanOptions, "publicationSleep" | "publicationNow" | "publish">} options
159
+ * @param {CompilePlanOptions} options
203
160
  */
204
161
  async function preparePlan({
205
162
  cwd,
163
+ reviewedDigest,
206
164
  apiUrl,
207
165
  fetchFunction,
208
166
  fileSystem,
@@ -214,24 +172,32 @@ async function preparePlan({
214
172
  push = pushPlan,
215
173
  readStatus = readPlanStatus,
216
174
  }) {
217
- const pushed = await push({
218
- cwd,
219
- apiUrl,
220
- fetchFunction,
221
- fileSystem,
222
- createTemporaryId,
223
- createRequestSignal,
224
- });
225
- if (!("outcome" in pushed)) {
226
- throw new PlanCompilePushRejectedError(pushed);
227
- }
228
- const acceptedGraphVersion = /** @type {{graph_version: number}} */ (
229
- pushed.body.project
230
- ).graph_version;
231
- const acceptedHeadSourceSha256 = /** @type {{source_sha256: string}} */ (
232
- pushed.body.foundation_plan
233
- ).source_sha256;
175
+ let acceptedGraphVersion;
176
+ let acceptedHeadSourceSha256 = reviewedDigest;
177
+ let etag;
178
+ if (reviewedDigest) {
179
+ etag = '"sha256:' + reviewedDigest + '"';
180
+ } else {
181
+ const pushed = await push({
182
+ cwd,
183
+ apiUrl,
184
+ fetchFunction,
185
+ fileSystem,
186
+ createTemporaryId,
187
+ createRequestSignal,
188
+ });
189
+ if (!("outcome" in pushed)) {
190
+ throw new PlanCompilePushRejectedError(pushed);
191
+ }
192
+ acceptedGraphVersion = /** @type {{graph_version: number}} */ (
193
+ pushed.body.project
194
+ ).graph_version;
195
+ acceptedHeadSourceSha256 = /** @type {{source_sha256: string}} */ (
196
+ pushed.body.foundation_plan
197
+ ).source_sha256;
234
198
 
199
+ etag = pushed.etag;
200
+ }
235
201
  let status;
236
202
  onProgress({ phase: "analysis", status: "waiting" });
237
203
  try {
@@ -258,8 +224,9 @@ async function preparePlan({
258
224
  throw new PlanCompileAnalysisRejectedError(status);
259
225
  }
260
226
  if (
261
- status.body.project.graph_version !== acceptedGraphVersion ||
262
- status.body.analysis.graph_version !== acceptedGraphVersion ||
227
+ (acceptedGraphVersion !== undefined &&
228
+ (status.body.project.graph_version !== acceptedGraphVersion ||
229
+ status.body.analysis.graph_version !== acceptedGraphVersion)) ||
263
230
  status.body.analysis.head_source_sha256 !== acceptedHeadSourceSha256
264
231
  ) {
265
232
  throw new PlanStatusChangedError(status.body);
@@ -269,5 +236,5 @@ async function preparePlan({
269
236
  }
270
237
  onProgress({ phase: "analysis", status: "valid" });
271
238
 
272
- return { pushed, status };
239
+ return { etag, status };
273
240
  }
@@ -1,4 +1,5 @@
1
- import { mkdirSync, writeFileSync } from "node:fs";
1
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { readPlanState } from "../plan-state.js";
2
3
  import path from "node:path";
3
4
 
4
5
  import {
@@ -37,6 +38,18 @@ export function initializePlan({
37
38
  const directory = path.join(cwd, ".firstdraft");
38
39
  const writeOptions = { flag: "wx", mode: 0o600, flush: true };
39
40
 
41
+ if (
42
+ fileSystem === DEFAULT_FILE_SYSTEM &&
43
+ existsSync(path.join(directory, "state.json")) &&
44
+ readPlanState({ cwd }).reserved
45
+ ) {
46
+ fileSystem.writeFileSync(
47
+ path.join(directory, "foundation-plan.json"),
48
+ plan,
49
+ writeOptions,
50
+ );
51
+ return;
52
+ }
40
53
  fileSystem.mkdirSync(directory, { recursive: false, mode: 0o700 });
41
54
  fileSystem.writeFileSync(
42
55
  path.join(directory, ".gitignore"),
@@ -20,6 +20,7 @@ import {
20
20
  normalizeApiUrl,
21
21
  readLocalFile,
22
22
  readPlanState,
23
+ withPlanStateLock,
23
24
  } from "../plan-state.js";
24
25
 
25
26
  export {
@@ -97,15 +98,28 @@ export class PlanPushStateWriteError extends Error {
97
98
  * @param {PushPlanOptions} options
98
99
  * @returns {Promise<PushPlanResult | RejectedPushResult>}
99
100
  */
100
- export async function pushPlan({
101
- cwd,
102
- apiUrl,
103
- fetchFunction = globalThis.fetch,
104
- fileSystem = DEFAULT_FILE_SYSTEM,
105
- createTemporaryId = randomUUID,
106
- createRequestSignal = () => AbortSignal.timeout(REQUEST_TIMEOUT_MS),
107
- }) {
108
- const state = readPlanState({ cwd, fileSystem });
101
+ export async function pushPlan(options) {
102
+ const state = readPlanState(options);
103
+ if (state.reserved)
104
+ return withPlanStateLock(path.join(options.cwd, ".firstdraft"), () =>
105
+ pushCurrentPlan(options),
106
+ );
107
+ return pushCurrentPlan(options, state);
108
+ }
109
+
110
+ /** @param {PushPlanOptions} options @param {ReturnType<typeof readPlanState>} [initialState] @returns {Promise<PushPlanResult | RejectedPushResult>} */
111
+ async function pushCurrentPlan(
112
+ {
113
+ cwd,
114
+ apiUrl,
115
+ fetchFunction = globalThis.fetch,
116
+ fileSystem = DEFAULT_FILE_SYSTEM,
117
+ createTemporaryId = randomUUID,
118
+ createRequestSignal = () => AbortSignal.timeout(REQUEST_TIMEOUT_MS),
119
+ },
120
+ initialState,
121
+ ) {
122
+ const state = initialState ?? readPlanState({ cwd, fileSystem });
109
123
  const directory = path.join(cwd, ".firstdraft");
110
124
  const planPath = path.join(directory, "foundation-plan.json");
111
125
  const statePath = path.join(directory, "state.json");
@@ -115,6 +129,7 @@ export async function pushPlan({
115
129
  project_id: state.project_id,
116
130
  });
117
131
  const headers = {
132
+ ...(state.reserved ? { "FirstDraft-Require-Project": "true" } : {}),
118
133
  Accept: "application/json, application/problem+json",
119
134
  "Content-Type": FOUNDATION_PLAN_MEDIA_TYPE,
120
135
  ...(state.foundation_plan_etag
@@ -192,7 +207,7 @@ export async function pushPlan({
192
207
  }
193
208
 
194
209
  /** @param {string | undefined} configured @param {string | undefined} stored */
195
- function resolveApiUrl(configured, stored) {
210
+ export function resolveApiUrl(configured, stored) {
196
211
  const configuredOrigin =
197
212
  configured === undefined ? undefined : normalizeApiUrl(configured);
198
213
  if (
@@ -226,8 +241,7 @@ function saveState({
226
241
  temporaryId,
227
242
  }) {
228
243
  const recoveryState = {
229
- format: state.format,
230
- project_id: state.project_id,
244
+ ...state,
231
245
  api_url: apiUrl,
232
246
  foundation_plan_etag: etag,
233
247
  };
@@ -162,7 +162,7 @@ export async function readPlanStatus({
162
162
  now = Date.now,
163
163
  }) {
164
164
  const state = readPlanState({ cwd, fileSystem });
165
- if (state.api_url === undefined) {
165
+ if (state.api_url === undefined || state.foundation_plan_etag === undefined) {
166
166
  throw new PlanStatusNotPushedError(
167
167
  "The local Foundation Plan has not been pushed.",
168
168
  );