farseer-cli 1.16.0 → 1.18.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.
Files changed (61) hide show
  1. package/README.md +329 -1
  2. package/dist/commands/code.js +104 -0
  3. package/dist/commands/code.js.map +7 -0
  4. package/dist/commands/formula.js +16 -7
  5. package/dist/commands/formula.js.map +2 -2
  6. package/dist/commands/tool.js +120 -0
  7. package/dist/commands/tool.js.map +7 -0
  8. package/dist/index.js +21 -2
  9. package/dist/index.js.map +2 -2
  10. package/dist/mcp/tools/modelTools.js +65 -23
  11. package/dist/mcp/tools/modelTools.js.map +3 -3
  12. package/dist/mcp/tools/runTools.js +6 -2
  13. package/dist/mcp/tools/runTools.js.map +2 -2
  14. package/dist/mcp/utils/launchPin.js +1 -1
  15. package/dist/mcp/utils/launchPin.js.map +2 -2
  16. package/dist/pipeline/service.js +1 -1
  17. package/dist/pipeline/service.js.map +2 -2
  18. package/dist/services/codefirst/api.js +269 -0
  19. package/dist/services/codefirst/api.js.map +7 -0
  20. package/dist/services/codefirst/binaryDisk.js +67 -0
  21. package/dist/services/codefirst/binaryDisk.js.map +7 -0
  22. package/dist/services/codefirst/byteHashes.js +129 -0
  23. package/dist/services/codefirst/byteHashes.js.map +7 -0
  24. package/dist/services/codefirst/documents.js +563 -0
  25. package/dist/services/codefirst/documents.js.map +7 -0
  26. package/dist/services/codefirst/layoutBinaryProjection.js +974 -0
  27. package/dist/services/codefirst/layoutBinaryProjection.js.map +7 -0
  28. package/dist/services/codefirst/layoutCompose.js +593 -0
  29. package/dist/services/codefirst/layoutCompose.js.map +7 -0
  30. package/dist/services/codefirst/layoutCore.js +260 -0
  31. package/dist/services/codefirst/layoutCore.js.map +7 -0
  32. package/dist/services/codefirst/layoutPaths.js +492 -0
  33. package/dist/services/codefirst/layoutPaths.js.map +7 -0
  34. package/dist/services/codefirst/layoutProjection.js +995 -0
  35. package/dist/services/codefirst/layoutProjection.js.map +7 -0
  36. package/dist/services/codefirst/layoutReadback.js +2552 -0
  37. package/dist/services/codefirst/layoutReadback.js.map +7 -0
  38. package/dist/services/codefirst/layoutReadbackPlacement.js +1517 -0
  39. package/dist/services/codefirst/layoutReadbackPlacement.js.map +7 -0
  40. package/dist/services/codefirst/layoutReceipt.js +1592 -0
  41. package/dist/services/codefirst/layoutReceipt.js.map +7 -0
  42. package/dist/services/codefirst/layoutScan.js +882 -0
  43. package/dist/services/codefirst/layoutScan.js.map +7 -0
  44. package/dist/services/codefirst/output.js +179 -0
  45. package/dist/services/codefirst/output.js.map +7 -0
  46. package/dist/services/codefirst/types.js +17 -0
  47. package/dist/services/codefirst/types.js.map +7 -0
  48. package/dist/services/codefirst/workflow.js +581 -0
  49. package/dist/services/codefirst/workflow.js.map +7 -0
  50. package/dist/services/codefirst/workspace.js +310 -0
  51. package/dist/services/codefirst/workspace.js.map +7 -0
  52. package/dist/services/codefirst/workspaceLock.js +148 -0
  53. package/dist/services/codefirst/workspaceLock.js.map +7 -0
  54. package/dist/services/codefirst/workspaceRoot.js +147 -0
  55. package/dist/services/codefirst/workspaceRoot.js.map +7 -0
  56. package/dist/utils/formulaFilters.js +48 -0
  57. package/dist/utils/formulaFilters.js.map +7 -0
  58. package/dist/utils/logger.js +9 -3
  59. package/dist/utils/logger.js.map +2 -2
  60. package/docs/cli-guide.md +13 -0
  61. package/package.json +3 -2
@@ -0,0 +1,581 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var workflow_exports = {};
30
+ __export(workflow_exports, {
31
+ KEPT_UNAPPLIED_DRAFTS: () => KEPT_UNAPPLIED_DRAFTS,
32
+ applyModel: () => applyModel,
33
+ checkoutModel: () => checkoutModel,
34
+ planModel: () => planModel,
35
+ pruneDrafts: () => pruneDrafts,
36
+ pullModel: () => pullModel,
37
+ waitSeconds: () => waitSeconds
38
+ });
39
+ module.exports = __toCommonJS(workflow_exports);
40
+ var fs = __toESM(require("fs"));
41
+ var import_api = require("./api");
42
+ var import_binaryDisk = require("./binaryDisk");
43
+ var import_documents = require("./documents");
44
+ var import_layoutCompose = require("./layoutCompose");
45
+ var import_layoutCore = require("./layoutCore");
46
+ var import_layoutPaths = require("./layoutPaths");
47
+ var import_layoutReadback = require("./layoutReadback");
48
+ var import_layoutReceipt = require("./layoutReceipt");
49
+ var import_layoutScan = require("./layoutScan");
50
+ var import_output = require("./output");
51
+ var import_workspace = require("./workspace");
52
+ var import_workspaceLock = require("./workspaceLock");
53
+ var import_workspaceRoot = require("./workspaceRoot");
54
+ const pause = () => new Promise((resolve) => setTimeout(resolve, 2e3));
55
+ function waitSeconds(value) {
56
+ const seconds = Number(value);
57
+ if (!Number.isFinite(seconds) || seconds < 0 || seconds > 3600)
58
+ throw new Error("--wait-seconds must be between 0 and 3600");
59
+ return seconds;
60
+ }
61
+ function loadState(root) {
62
+ if (!fs.existsSync((0, import_workspace.workspacePath)(root, import_workspace.STATE_FILE)))
63
+ throw new Error("No model workspace; run farseer code checkout <tenant> first");
64
+ return (0, import_documents.parseState)((0, import_layoutScan.stateText)(root));
65
+ }
66
+ function updateDraft(root, planId, change) {
67
+ const current = loadState(root);
68
+ const draft = current.layout.receipts[planId];
69
+ if (!draft) return false;
70
+ change(draft);
71
+ (0, import_workspace.saveState)(root, current);
72
+ return true;
73
+ }
74
+ function unansweredApply(planId) {
75
+ return `the apply request for plan p${planId} got no answer from the server, so it may still be running there; run farseer code apply p${planId} again, which resumes that apply and writes its receipt`;
76
+ }
77
+ function workspaceApi(workspace) {
78
+ const api = new import_api.CodeFirstApi(workspace.target);
79
+ const resolved = api.baseUrl();
80
+ if (resolved !== workspace.state.baseUrl)
81
+ throw new Error(
82
+ `This workspace was checked out from ${workspace.state.baseUrl}, but this command would use ${resolved}; run it with the credential and FARSEER_API_URL the workspace was checked out with`
83
+ );
84
+ return api;
85
+ }
86
+ function sameStoredPlan(stored, draft) {
87
+ const operations = (items) => items.map(
88
+ (op) => (0, import_documents.canonicalText)({
89
+ action: op.action,
90
+ kind: op.kind,
91
+ key: op.key ?? null,
92
+ handle: op.handle ?? null,
93
+ name: op.name,
94
+ paths: op.fieldDiff.map((diff) => diff.path)
95
+ })
96
+ ).sort();
97
+ return (0, import_documents.canonicalText)(stored.documentKeys ?? []) === (0, import_documents.canonicalText)([...draft.documentKeys]) && (0, import_documents.canonicalText)(stored.handles ?? {}) === (0, import_documents.canonicalText)(draft.handles) && (0, import_documents.canonicalText)(operations(stored.operations ?? [])) === (0, import_documents.canonicalText)(operations(draft.operations));
98
+ }
99
+ function composeWorkspace(root, state) {
100
+ const evidence = {
101
+ ...state.layout.evidence,
102
+ groupedSubmissionProofs: [],
103
+ binarySubmissionProofs: [],
104
+ canonicalBaseline: state.baseline
105
+ };
106
+ const scan = (0, import_layoutScan.scanLayout)({ root, tracked: state.layout.tracked });
107
+ const composed = (0, import_layoutCompose.composeLayoutSubmission)({
108
+ scan,
109
+ byteEvidence: (0, import_layoutScan.loadLayoutByteEvidence)({ root, scan, evidence }),
110
+ evidence
111
+ });
112
+ if (composed.status !== "complete")
113
+ throw new Error(
114
+ `Workspace cannot be composed: ${composed.diagnostics.map((item) => `${item.code} ${item.path}: ${item.message}`).join("; ")}`
115
+ );
116
+ return composed;
117
+ }
118
+ async function readHead(api, deadline, print) {
119
+ for (; ; ) {
120
+ const response = await api.head();
121
+ if (response.status === 200) return response.data;
122
+ if (response.status !== 409) throw new Error(`Unable to read model head (HTTP ${response.status})`);
123
+ const revision = response.data.revisionId;
124
+ if (Date.now() >= deadline) throw new Error(`Apply r${revision} is in progress; retry pull shortly`);
125
+ print(`Apply r${revision} in progress; retry shortly.`);
126
+ await pause();
127
+ }
128
+ }
129
+ const PRESERVE_NOTICE = {
130
+ unmaterialized: "unmaterialized",
131
+ "kept-local": "kept local",
132
+ "kept-local-edits": "kept local edits",
133
+ conflict: "conflict",
134
+ "local-deletion-pending": "kept local",
135
+ "pull-needed": "pull needed",
136
+ "protected-descendant": "conflict",
137
+ // The one `kept-in-place` notice names the folder and everything that holds it; this is silent.
138
+ "folder-held": void 0,
139
+ "unsupported-evidence": "conflict",
140
+ "post-submission-change": "kept local edits",
141
+ // A receipt says nothing about a resource it never carried; that is not news for the author.
142
+ "deferred-receipt": void 0,
143
+ "shared-container-relocation": "kept local",
144
+ "shared-container-sibling": "kept local",
145
+ "unsuccessful-outcome": void 0,
146
+ "missing-outcome": void 0
147
+ };
148
+ function materializationPath(item) {
149
+ return item.codec === "grouped" ? item.destination.file : item.bytes;
150
+ }
151
+ function preservePath(item) {
152
+ for (const contributor of item.contributors) {
153
+ if (contributor.kind === "grouped" || contributor.kind === "grouped-navigation")
154
+ return contributor.selector.file;
155
+ if (contributor.kind === "raw") return contributor.bytes ?? (0, import_layoutPaths.rawBytesPath)(contributor.selector.sidecar);
156
+ }
157
+ return item.documentKey ?? "workspace";
158
+ }
159
+ function planNotices(result) {
160
+ const notices = [];
161
+ for (const item of result.materializations) {
162
+ if (item.mode === "set")
163
+ notices.push({
164
+ status: item.placement === "insert-authoritative" ? "new" : "updated",
165
+ key: item.documentKey,
166
+ path: materializationPath(item)
167
+ });
168
+ else if (item.mode === "preserve") {
169
+ const status = PRESERVE_NOTICE[item.reason];
170
+ if (status)
171
+ notices.push({
172
+ status,
173
+ ...item.documentKey ? { key: item.documentKey } : {},
174
+ path: preservePath(item)
175
+ });
176
+ }
177
+ }
178
+ for (const removal of result.deletes.json)
179
+ notices.push({ status: "deleted", key: removal.documentKeys[0], path: removal.path });
180
+ for (const notice of result.notices) notices.push({ ...notice });
181
+ return notices;
182
+ }
183
+ function reportUnverified(result, print) {
184
+ if (!result.unverifiedDocumentKeys.length) return;
185
+ print(
186
+ `warning: unverified-readback: ${result.unverifiedDocumentKeys.length} resources kept their previous baseline (${result.unverifiedDocumentKeys.slice(0, 5).join(", ")}${result.unverifiedDocumentKeys.length > 5 ? ", \u2026" : ""})`
187
+ );
188
+ for (const item of result.verificationDiagnostics.slice(0, 5))
189
+ print(`warning: ${item.code}: ${item.path}: ${item.message}`);
190
+ }
191
+ function reportCompositionWarnings(warnings, print) {
192
+ for (const item of warnings) print(`warning: ${item.code}: ${item.path}: ${item.message}`);
193
+ }
194
+ function reportCleanup(result, print) {
195
+ for (const warning of result.cleanupWarnings ?? []) print(`warning: cleanup: ${warning}`);
196
+ }
197
+ function reportUnreadableReceipts(state, print) {
198
+ for (const planId of Object.keys(state.layout.unreadableReceipts ?? {}).sort())
199
+ print(
200
+ `warning: the saved receipt for plan p${planId} could not be read and was set aside; read the next plan before applying it, in case it creates a resource that apply already made`
201
+ );
202
+ }
203
+ function reportBehindHead(behind, print) {
204
+ if (behind > 0)
205
+ print(`warning: workspace is behind head: ${behind} resources not materialized locally; run farseer code pull`);
206
+ }
207
+ function requireComplete(result) {
208
+ if (result.status === "blocked")
209
+ throw new Error(
210
+ `Workspace cannot be updated: ${result.diagnostics.map((item) => `${item.code} ${item.path}: ${item.message}`).join("; ")}`
211
+ );
212
+ return result;
213
+ }
214
+ async function materializeHead(api, root, head, force, print, verbose = false) {
215
+ const result = requireComplete(
216
+ await (0, import_layoutReceipt.materializeLayoutPlan)({ root, head, source: { kind: "checkout", force }, api })
217
+ );
218
+ const notices = planNotices(result);
219
+ (0, import_output.renderNotices)(notices).forEach((line) => print(line));
220
+ reportCompositionWarnings(result.compositionWarnings, print);
221
+ reportUnverified(result, print);
222
+ reportCleanup(result, print);
223
+ if (verbose) head.diagnostics.forEach((d) => print(`warning: ${d.code}: ${d.message}`));
224
+ const saved = loadState(root);
225
+ reportUnreadableReceipts(saved, print);
226
+ reportBehindHead(Object.entries(head.manifest).filter(([key, hash]) => saved.baseline[key] !== hash).length, print);
227
+ print(`Model pulled at r${head.revisionId}: ${Object.keys(head.manifest).length} resources.`);
228
+ if ((0, import_output.layoutExitCode)(notices)) process.exitCode = 1;
229
+ return notices.filter((notice) => ["new", "updated", "deleted"].includes(notice.status)).length;
230
+ }
231
+ async function checkoutModel(target, typedTenant, directory, seconds, print = console.log, options = {}) {
232
+ if (typedTenant !== void 0 && target.tenant !== typedTenant)
233
+ throw new Error(
234
+ `Refusing to check out: the command named the tenant ${typedTenant} but the resolved target is ${target.tenant}`
235
+ );
236
+ const api = new import_api.CodeFirstApi(target);
237
+ const head = await readHead(api, Date.now() + seconds * 1e3, print);
238
+ const root = (0, import_workspaceRoot.createCodeWorkspace)(directory, target.tenant, {
239
+ organisation: target.organisation,
240
+ baseUrl: api.baseUrl()
241
+ });
242
+ return (0, import_workspaceLock.withWorkspaceLock)(root, "code checkout", async () => {
243
+ print(`Checked out ${target.tenant} into ${root}`);
244
+ return materializeHead(api, root, head, false, print, options.verbose);
245
+ });
246
+ }
247
+ const KEPT_UNAPPLIED_DRAFTS = 3;
248
+ function pruneDrafts(state) {
249
+ const before = Object.keys(state.layout.receipts).length;
250
+ for (const [planId, draft] of Object.entries(state.layout.receipts))
251
+ if (draft.receipt && !draft.applying) delete state.layout.receipts[planId];
252
+ const unapplied = Object.entries(state.layout.receipts).filter(([, draft]) => !draft.applying && !draft.receipt).map(([planId]) => planId).sort((left, right) => Number(right) - Number(left));
253
+ const dropped = unapplied.slice(KEPT_UNAPPLIED_DRAFTS).reverse();
254
+ for (const planId of dropped) delete state.layout.receipts[planId];
255
+ return { changed: Object.keys(state.layout.receipts).length !== before, unapplied: dropped };
256
+ }
257
+ function reportDroppedDrafts(unapplied, print) {
258
+ if (!unapplied.length) return;
259
+ const plans = unapplied.map((planId) => `p${planId}`).join(", ");
260
+ print(
261
+ `Dropped the saved plan${unapplied.length > 1 ? "s" : ""} ${plans}: only the newest ${KEPT_UNAPPLIED_DRAFTS} unapplied plans stay applicable.`
262
+ );
263
+ }
264
+ function pruneSavedDrafts(root, print) {
265
+ const current = loadState(root);
266
+ const pruned = pruneDrafts(current);
267
+ if (pruned.changed) (0, import_workspace.saveState)(root, current);
268
+ reportDroppedDrafts(pruned.unapplied, print);
269
+ }
270
+ function storeReceipt(root, planId, receipt) {
271
+ const stored = loadState(root);
272
+ const draft = { ...stored.layout.receipts[planId], receipt, revisionId: receipt.revisionId, applying: true };
273
+ delete draft.unanswered;
274
+ stored.layout.receipts[planId] = draft;
275
+ (0, import_workspace.saveState)(root, stored);
276
+ }
277
+ async function materializeReceipt(api, root, planId, head, print) {
278
+ const result = requireComplete(
279
+ await (0, import_layoutReceipt.materializeLayoutPlan)({ root, head, source: { kind: "receipt", planId }, api })
280
+ );
281
+ const written = loadState(root);
282
+ delete written.layout.receipts[planId];
283
+ (0, import_workspace.saveState)(root, written);
284
+ const notices = planNotices(result);
285
+ (0, import_output.renderNotices)(notices).forEach((line) => print(line));
286
+ reportCompositionWarnings(result.compositionWarnings, print);
287
+ reportUnverified(result, print);
288
+ reportCleanup(result, print);
289
+ return notices;
290
+ }
291
+ async function writeUnwrittenReceipts(api, root, head, print) {
292
+ let attention = false;
293
+ for (const [planId, draft] of Object.entries(loadState(root).layout.receipts).sort()) {
294
+ if (!draft.applying) continue;
295
+ let receipt = draft.receipt;
296
+ if (!receipt) {
297
+ const observed = await api.attempt(planId);
298
+ if (observed.status === 404 && draft.unanswered)
299
+ throw new Error(`Cannot pull yet: ${unansweredApply(planId)}`);
300
+ if (observed.status === 404) {
301
+ updateDraft(root, planId, (current) => {
302
+ current.applying = false;
303
+ });
304
+ print(`Plan p${planId} was never applied; it stays applicable with farseer code apply p${planId}`);
305
+ continue;
306
+ }
307
+ if (observed.status !== 200)
308
+ throw new Error(`Apply p${planId} is still in progress; resume it with farseer code apply p${planId}`);
309
+ receipt = observed.data;
310
+ storeReceipt(root, planId, receipt);
311
+ }
312
+ print(`Writing the receipt of plan p${planId}: r${receipt.revisionId} (${receipt.status}).`);
313
+ (0, import_output.renderReceipt)(receipt, [...draft.submission.operations]).forEach((line) => print(line));
314
+ const notices = await materializeReceipt(api, root, planId, head, print);
315
+ if ((0, import_output.layoutExitCode)(notices, receipt.status)) attention = true;
316
+ }
317
+ return attention;
318
+ }
319
+ async function pullModel(workspace, force, seconds, print = console.log, options = {}) {
320
+ return (0, import_workspaceLock.withWorkspaceLock)(
321
+ workspace.root,
322
+ "code pull",
323
+ () => pullWorkspace(workspace, force, seconds, print, options)
324
+ );
325
+ }
326
+ async function pullWorkspace(workspace, force, seconds, print, options) {
327
+ const api = workspaceApi(workspace);
328
+ pruneSavedDrafts(workspace.root, print);
329
+ const head = await readHead(api, Date.now() + seconds * 1e3, print);
330
+ const attention = await writeUnwrittenReceipts(api, workspace.root, head, print);
331
+ const written = await materializeHead(api, workspace.root, head, force, print, options.verbose);
332
+ if (attention) process.exitCode = 1;
333
+ return written;
334
+ }
335
+ async function uploadChangedBytes(api, root, state, current) {
336
+ const known = new Set(
337
+ state.layout.evidence.binaryRoutes.flatMap((route) => route.byteHash ? [route.byteHash] : [])
338
+ );
339
+ const referenced = new Set(
340
+ [...current.binary.rawObservations, ...current.binary.attachmentObservations].flatMap(
341
+ (observation) => observation.bytes ? [observation.bytes] : []
342
+ )
343
+ );
344
+ const sent = /* @__PURE__ */ new Set();
345
+ for (const fact of current.byteFacts) {
346
+ if (!referenced.has(fact.path) || fact.state !== "present") continue;
347
+ if (known.has((0, import_layoutCore.canonicalFragmentHash)(fact.content)) || sent.has(fact.content.sha256))
348
+ continue;
349
+ if (fact.content.size > import_binaryDisk.BLOB_UPLOAD_LIMIT)
350
+ throw new Error(`Changed file ${fact.path} exceeds the 64 MiB upload limit`);
351
+ const source = (0, import_layoutScan.resolveLayoutPath)(root, fact.path);
352
+ if (!(0, import_binaryDisk.sameBytes)((0, import_binaryDisk.hashFile)(source), fact.content))
353
+ throw new Error(`Local bytes changed before upload: ${fact.path}`);
354
+ await api.uploadBlob(fact.content.sha256, fs.createReadStream(source));
355
+ sent.add(fact.content.sha256);
356
+ }
357
+ }
358
+ async function planModel(workspace, seconds, print = console.log, options = {}) {
359
+ return (0, import_workspaceLock.withWorkspaceLock)(workspace.root, "code plan", () => planWorkspace(workspace, seconds, print, options));
360
+ }
361
+ async function planWorkspace(workspace, seconds, print, options) {
362
+ const api = workspaceApi(workspace);
363
+ const note = options.json ? options.note ?? console.error : print;
364
+ pruneSavedDrafts(workspace.root, note);
365
+ const root = workspace.root, readText = (0, import_layoutScan.stateText)(root), state = (0, import_documents.parseState)(readText);
366
+ const current = composeWorkspace(root, state);
367
+ reportUnreadableReceipts(state, note);
368
+ reportCompositionWarnings(current.warnings, note);
369
+ if (!current.documents.length && !Object.keys(state.baseline).length)
370
+ throw new Error("The workspace holds no model; run farseer code pull first");
371
+ if (!current.documents.length)
372
+ throw new Error(
373
+ `The workspace holds no model files, but its baseline has ${Object.keys(state.baseline).length} resources, so a plan would delete them all; restore the files with farseer code pull --force`
374
+ );
375
+ await uploadChangedBytes(api, root, state, current);
376
+ (0, import_layoutReceipt.refuseUnwrittenReceipts)(state);
377
+ const deadline = Date.now() + seconds * 1e3;
378
+ let response = await api.plan(current.documents, state.baseline);
379
+ while (response.status === 409 && Date.now() < deadline) {
380
+ note(`Apply r${response.data.revisionId} in progress; retry shortly.`);
381
+ await pause();
382
+ response = await api.plan(current.documents, state.baseline);
383
+ }
384
+ if (response.status === 409) throw new Error("Apply in progress; retry farseer code plan shortly");
385
+ const planned = planOf(response.data);
386
+ if (planned && planned.documentKeys?.length === current.documents.length)
387
+ (0, import_documents.validateDocumentKeys)(current.documents, planned.documentKeys, true);
388
+ let dropped = [];
389
+ if (planned?.planId) {
390
+ const submission = (0, import_layoutReadback.bindLayoutReceiptSubmission)({
391
+ planId: planned.planId,
392
+ plan: planned,
393
+ captured: (0, import_layoutReadback.captureLayoutSubmissionComposition)(current)
394
+ });
395
+ const saved = (0, import_documents.parseState)((0, import_layoutScan.stateText)(root));
396
+ saved.layout.receipts[planned.planId] = { submission };
397
+ dropped = pruneDrafts(saved).unapplied;
398
+ (0, import_workspace.saveState)(root, saved);
399
+ } else (0, import_workspace.saveLearnedByteHashes)(root, readText);
400
+ if (options.json) print(JSON.stringify(response.body, null, 2));
401
+ if (!planned) throw new Error(planRefusal(response.status, response.data));
402
+ if (!options.json)
403
+ (0, import_output.renderPlan)(planned, { verbose: options.verbose, files: (0, import_layoutCompose.submittedDocumentFiles)(current.sources) }).forEach(
404
+ (line) => print(line)
405
+ );
406
+ reportBehindHead(planned.behindHead ?? 0, note);
407
+ if (planned.planId)
408
+ note(`Plan p${planned.planId} created against r${planned.observedRevisionId ?? state.revisionId}.`);
409
+ reportDroppedDrafts(dropped, note);
410
+ if (!planned.applicable || response.status === 400) process.exitCode = 1;
411
+ }
412
+ const expiryText = (date) => Number.isNaN(date.getTime()) ? void 0 : date.toISOString();
413
+ function planOf(body) {
414
+ return body !== null && typeof body === "object" && "operations" in body ? body : void 0;
415
+ }
416
+ function planRefusal(status, body) {
417
+ const { code, message } = body !== null && typeof body === "object" ? body : {};
418
+ if (typeof code !== "string") return `Invalid plan response (HTTP ${status})`;
419
+ return `The server refused the plan (HTTP ${status}, ${code})${typeof message === "string" ? `: ${message}` : ""}`;
420
+ }
421
+ async function applyModel(workspace, rawId, seconds, print = console.log) {
422
+ return (0, import_workspaceLock.withWorkspaceLock)(
423
+ workspace.root,
424
+ `code apply ${rawId}`,
425
+ () => applyWorkspace(workspace, rawId, seconds, print)
426
+ );
427
+ }
428
+ async function applyWorkspace(workspace, rawId, seconds, print) {
429
+ const planId = rawId.replace(/^p/, "");
430
+ if (!/^[1-9][0-9]*$/.test(planId)) throw new Error("Expected a plan id such as p123");
431
+ const api = workspaceApi(workspace);
432
+ pruneSavedDrafts(workspace.root, print);
433
+ const root = workspace.root;
434
+ const initial = loadState(root), draft = initial.layout.receipts[planId];
435
+ reportUnreadableReceipts(initial, print);
436
+ if (!draft) {
437
+ const unreadable = (0, import_layoutReceipt.layoutReceiptDrafts)(initial).find(([id, saved]) => id === planId && saved.quarantined);
438
+ throw new Error(
439
+ !unreadable ? `This plan was not created in this workspace, its receipt is already written, or it was dropped as older than the newest ${KEPT_UNAPPLIED_DRAFTS} unapplied plans; create a new plan here` : unreadable[1].applying ? (0, import_layoutReceipt.quarantinedApplyAdvice)(planId) : `The saved receipt for plan p${planId} could not be read; run farseer code plan and apply the new plan`
440
+ );
441
+ }
442
+ const reportExpired = (expiresAt) => {
443
+ const on = expiresAt && expiryText(expiresAt);
444
+ print(`Plan p${planId} expired${on ? ` on ${on}` : ""}; run farseer code plan again.`);
445
+ process.exitCode = 1;
446
+ };
447
+ let absentAttempt = false;
448
+ if (draft.applying) {
449
+ const observed = await api.attempt(planId);
450
+ if (observed.status === 404) {
451
+ absentAttempt = true;
452
+ } else if (observed.status !== 200 && observed.status !== 202) {
453
+ throw new Error(
454
+ `Unable to inspect saved attempt (HTTP ${observed.status}); retry farseer code apply p${planId}`
455
+ );
456
+ }
457
+ }
458
+ let storedPlan;
459
+ try {
460
+ storedPlan = (await api.getPlan(planId)).data;
461
+ } catch (error) {
462
+ if (absentAttempt && !draft.unanswered)
463
+ updateDraft(root, planId, (current) => {
464
+ current.applying = false;
465
+ });
466
+ throw error;
467
+ }
468
+ if (!sameStoredPlan(storedPlan, draft.submission))
469
+ throw new Error(
470
+ `Plan p${planId} on ${workspace.state.baseUrl} is not the plan this workspace created (its documents, operations or handles differ); run farseer code plan and apply the new plan`
471
+ );
472
+ if (storedPlan.expired) {
473
+ if (absentAttempt)
474
+ updateDraft(root, planId, (current) => {
475
+ current.applying = false;
476
+ delete current.unanswered;
477
+ });
478
+ reportExpired(storedPlan.expiresAt);
479
+ return;
480
+ }
481
+ if (!updateDraft(root, planId, (current) => {
482
+ current.applying = true;
483
+ current.unanswered = true;
484
+ }))
485
+ throw new Error(`The saved draft of plan p${planId} was removed by another command; run farseer code pull`);
486
+ const deadline = Date.now() + seconds * 1e3;
487
+ const releaseIfAbsent = async () => {
488
+ let observed;
489
+ try {
490
+ observed = await api.attempt(planId);
491
+ } catch {
492
+ observed = void 0;
493
+ }
494
+ updateDraft(root, planId, (current) => {
495
+ delete current.unanswered;
496
+ if (observed?.status === 404) current.applying = false;
497
+ });
498
+ };
499
+ const post = () => api.apply(planId).catch(async (error) => {
500
+ if (!(0, import_api.requestSettled)(error))
501
+ throw new Error(
502
+ `${error instanceof Error ? error.message : String(error)}: ${unansweredApply(planId)}`,
503
+ { cause: error }
504
+ );
505
+ await releaseIfAbsent();
506
+ throw error;
507
+ });
508
+ let response = await post();
509
+ while (response.status === 409 && "code" in response.data && (response.data.code === "apply-in-progress" || response.data.code === "admission-conflict") && Date.now() < deadline) {
510
+ print(
511
+ response.data.code === "apply-in-progress" ? `Apply r${response.data.revisionId} in progress; retry shortly.` : `The head changed while plan p${planId} was being admitted; retry shortly.`
512
+ );
513
+ await pause();
514
+ response = await post();
515
+ }
516
+ if ("code" in response.data && response.data.code === "admission-conflict") {
517
+ await releaseIfAbsent();
518
+ print(`The head kept changing while plan p${planId} was being admitted. Retry: farseer code apply p${planId}`);
519
+ process.exitCode = 1;
520
+ return;
521
+ }
522
+ while (response.status === 202 && Date.now() < deadline) {
523
+ const pending = response.data;
524
+ updateDraft(root, planId, (current) => {
525
+ current.revisionId = pending.revisionId;
526
+ delete current.unanswered;
527
+ });
528
+ print(`Pending r${pending.revisionId}; waiting for attempt receipt.`);
529
+ await pause();
530
+ response = await post();
531
+ }
532
+ if ("code" in response.data && response.data.code === "plan-expired") {
533
+ updateDraft(root, planId, (current) => {
534
+ current.applying = false;
535
+ delete current.unanswered;
536
+ });
537
+ reportExpired(response.data.expiresAt);
538
+ return;
539
+ }
540
+ if (response.status === 202 || response.status === 409) {
541
+ const answered = response.data;
542
+ updateDraft(root, planId, (current) => {
543
+ if (response.status === 202) current.revisionId = answered.revisionId;
544
+ delete current.unanswered;
545
+ });
546
+ print(
547
+ `Revision r${answered.revisionId} is ${response.status === 202 ? "pending" : "applying"}. Resume: farseer code apply p${planId}`
548
+ );
549
+ process.exitCode = 1;
550
+ return;
551
+ }
552
+ if (response.status !== 200) {
553
+ await releaseIfAbsent();
554
+ throw new Error(`Apply failed (HTTP ${response.status})`);
555
+ }
556
+ const receipt = response.data;
557
+ storeReceipt(root, planId, receipt);
558
+ let head;
559
+ try {
560
+ head = await readHead(api, deadline, print);
561
+ } catch (error) {
562
+ print(
563
+ `Post-apply readback unavailable: ${error.message}; the next farseer code pull writes the receipt`
564
+ );
565
+ }
566
+ (0, import_output.renderReceipt)(receipt, storedPlan.operations).forEach((line) => print(line));
567
+ const notices = head ? await materializeReceipt(api, root, planId, head, print) : [];
568
+ print(`Tenant '${workspace.target.tenant}' now at r${receipt.revisionId} (${receipt.status})`);
569
+ if (!head || (0, import_output.layoutExitCode)(notices, receipt.status)) process.exitCode = 1;
570
+ }
571
+ // Annotate the CommonJS export names for ESM import in node:
572
+ 0 && (module.exports = {
573
+ KEPT_UNAPPLIED_DRAFTS,
574
+ applyModel,
575
+ checkoutModel,
576
+ planModel,
577
+ pruneDrafts,
578
+ pullModel,
579
+ waitSeconds
580
+ });
581
+ //# sourceMappingURL=workflow.js.map