@f5-sales-demo/xcsh 23.2.2 → 23.3.4

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 (32) hide show
  1. package/package.json +8 -8
  2. package/src/commands/blindfold-args.ts +16 -3
  3. package/src/commands/blindfold-help.ts +2 -2
  4. package/src/commands/blindfold.ts +2 -2
  5. package/src/internal-urls/api-catalog-index.generated.ts +25301 -25301
  6. package/src/internal-urls/api-catalog-qmd-index.generated.ts +2 -2
  7. package/src/internal-urls/api-catalog-resolve.ts +4 -0
  8. package/src/internal-urls/api-spec-index.generated.ts +1 -1
  9. package/src/internal-urls/api-spec-resolve.ts +7 -1
  10. package/src/internal-urls/build-info.generated.ts +9 -9
  11. package/src/internal-urls/docs-index.generated.ts +2 -1
  12. package/src/internal-urls/immutable-selection.ts +178 -0
  13. package/src/internal-urls/public-citation-destinations.generated.ts +2 -2
  14. package/src/internal-urls/terraform-documentation-assets.generated.ts +28 -28
  15. package/src/internal-urls/terraform-documentation.ts +1 -1
  16. package/src/internal-urls/terraform-index.generated.ts +1 -1
  17. package/src/internal-urls/terraform-property-index.ts +14 -1
  18. package/src/internal-urls/terraform-property-ranking.ts +10 -3
  19. package/src/internal-urls/terraform-provider-pin.generated.ts +1 -1
  20. package/src/prompts/tools/xcsh-api.md +2 -0
  21. package/src/prompts/tools/xcsh-blindfold.md +1 -1
  22. package/src/services/blindfold-contract/blindfold-contract-v1.txt +1 -0
  23. package/src/services/blindfold-contract/lock.json +6 -0
  24. package/src/services/blindfold-documents.ts +1 -12
  25. package/src/services/blindfold-ensure.ts +428 -0
  26. package/src/services/blindfold.ts +16 -6
  27. package/src/terraform-documentation-smoke.ts +2 -2
  28. package/src/terraform-port-smoke.ts +15 -0
  29. package/src/tools/xcsh-api-renderer.ts +16 -0
  30. package/src/tools/xcsh-api-replacement.ts +524 -0
  31. package/src/tools/xcsh-api.ts +61 -0
  32. package/src/tools/xcsh-blindfold.ts +6 -1
@@ -7,7 +7,6 @@ import {
7
7
  blindfoldPrepare,
8
8
  } from "@f5-sales-demo/pi-natives";
9
9
  import type { HttpTransport, ResourceManifest } from "@f5-sales-demo/pi-resource-management";
10
-
11
10
  import {
12
11
  canonicalBlindfoldDocument,
13
12
  normalizeBlindfoldDocument,
@@ -15,11 +14,21 @@ import {
15
14
  readBlindfoldResponse,
16
15
  serializeBlindfoldDocument,
17
16
  } from "./blindfold-documents";
17
+ import { ensureBlindfold } from "./blindfold-ensure";
18
18
 
19
- export const BLINDFOLD_OPERATIONS = ["public-key", "policy", "encrypt", "certificate", "create", "replace"] as const;
19
+ export const BLINDFOLD_OPERATIONS = [
20
+ "public-key",
21
+ "policy",
22
+ "encrypt",
23
+ "certificate",
24
+ "create",
25
+ "replace",
26
+ "ensure",
27
+ ] as const;
20
28
  export type BlindfoldOperation = (typeof BLINDFOLD_OPERATIONS)[number];
21
29
  export interface BlindfoldArgs {
22
30
  operation: BlindfoldOperation;
31
+ file?: string;
23
32
  compatibility?: boolean;
24
33
  encoding?: "base64" | "location";
25
34
  outfile?: string;
@@ -41,7 +50,7 @@ export interface BlindfoldArgs {
41
50
  dryRun?: "client";
42
51
  }
43
52
  export interface BlindfoldReport {
44
- status: "material-retrieved" | "prepared" | "dry-run" | "accepted";
53
+ status: "material-retrieved" | "prepared" | "dry-run" | "accepted" | "unchanged";
45
54
  operation: BlindfoldOperation;
46
55
  materialSource?: "retrieved" | "supplied";
47
56
  target: { apiUrl?: string; tenant: string; namespace?: string; name?: string; contextName?: string };
@@ -57,7 +66,7 @@ export interface BlindfoldRuntime {
57
66
  planMode?: boolean;
58
67
  guard?: () => void;
59
68
  }
60
- interface Options {
69
+ export interface BlindfoldOptions {
61
70
  emit?: (content: string) => void;
62
71
  env: Readonly<Record<string, string | undefined>>;
63
72
  cwd?: string;
@@ -109,11 +118,12 @@ export async function writeBlindfoldArtifact(
109
118
  }
110
119
  /** Holds encrypted material locally; callers receive only the public report. */
111
120
  export class BlindfoldService {
112
- readonly #options: Options;
113
- constructor(options: Options) {
121
+ readonly #options: BlindfoldOptions;
122
+ constructor(options: BlindfoldOptions) {
114
123
  this.#options = options;
115
124
  }
116
125
  async run(args: BlindfoldArgs, runtime: BlindfoldRuntime = {}): Promise<BlindfoldReport> {
126
+ if (args.operation === "ensure") return ensureBlindfold(this.#options, args, runtime);
117
127
  const guard = () => {
118
128
  if (runtime.signal?.aborted) throw new Error("Blindfold operation cancelled");
119
129
  runtime.guard?.();
@@ -3,6 +3,7 @@ import path from "node:path";
3
3
  import { TerraformDocumentationRepository } from "./internal-urls/terraform-documentation";
4
4
  import { EMBEDDED_TERRAFORM_DOCUMENTATION } from "./internal-urls/terraform-documentation-assets.generated";
5
5
  import type { InternalUrl } from "./internal-urls/types";
6
+ import { assertTerraformPortSection } from "./terraform-port-smoke";
6
7
 
7
8
  export async function runTerraformDocumentationSmoke(): Promise<string> {
8
9
  if (!EMBEDDED_TERRAFORM_DOCUMENTATION) throw new Error("Terraform smoke requires embedded assets");
@@ -41,8 +42,7 @@ export async function runTerraformDocumentationSmoke(): Promise<string> {
41
42
  const section = await read(
42
43
  "xcsh://terraform-documentation/documentation/resources/http_loadbalancer/properties/https/index.md#schema-https--port",
43
44
  );
44
- if (!section.includes("### port") || !section.includes("Validators"))
45
- throw new Error("Terraform explicit-anchor smoke failed");
45
+ assertTerraformPortSection(section);
46
46
  trace.push({ event: "terraform-explicit-anchor", outcome: "complete-property" });
47
47
  const database = await repository.database();
48
48
  const leaf =
@@ -0,0 +1,15 @@
1
+ /** Require the exact published port property and receipt-pinned constraint. */
2
+ export function assertTerraformPortSection(section: string): void {
3
+ if (!section.includes('<a id="schema-https--port"></a>') || !/^### port(?: property)?\s*$/m.test(section))
4
+ throw new Error("Terraform explicit-anchor smoke failed");
5
+ const fences = [...section.matchAll(/^```json\s*\n([\s\S]*?)^```\s*$/gm)];
6
+ const constrained = fences.some(match => {
7
+ try {
8
+ const rules = JSON.parse(match[1]!) as Record<string, Record<string, unknown>>;
9
+ return rules["x-validation-rules"]?.["ves.io.schema.rules.uint32.lte"] === "65535";
10
+ } catch {
11
+ return false;
12
+ }
13
+ });
14
+ if (!constrained) throw new Error("Terraform port constraint smoke failed");
15
+ }
@@ -358,11 +358,27 @@ export const xcshApiToolRenderer = {
358
358
  const errorIcon = uiTheme.styledSymbol("status.error", "error");
359
359
 
360
360
  if (isError) {
361
+ if (details?.replacementId)
362
+ resultLines.push(
363
+ uiTheme.fg(
364
+ "warning",
365
+ `Replacement ${details.replacementId}: ${details.replacementStage ?? "pending"}. Resume this ID; do not DELETE again.`,
366
+ ),
367
+ );
361
368
  const apiMessage =
362
369
  parsed && typeof parsed.message === "string" ? stripProtobufPrefix(parsed.message) : undefined;
363
370
  const errorLabel = apiMessage ?? (status > 0 ? `Request failed (${status})` : "Request failed");
364
371
  resultLines.push(`${errorIcon} ${uiTheme.fg("warning", errorLabel)}`);
365
372
  if (guidance) resultLines.push(` ${uiTheme.fg("dim", `Try: ${guidance}`)}`);
373
+ } else if (details?.replacementStage === "complete" && parsed) {
374
+ resultLines.push(`${infoIcon} Recreated ${details.resourceLabel ?? resourceName}`);
375
+ resultLines.push(
376
+ uiTheme.fg(
377
+ "dim",
378
+ `Verified type ${String(parsed.targetSelections)} and new UID ${String(parsed.newUid)}`,
379
+ ),
380
+ );
381
+ resultLines.push(uiTheme.fg("warning", "Cutover caused downtime; the VIP may have changed."));
366
382
  } else if (details?.mutationVerb && details?.resourceLabel) {
367
383
  resultLines.push(`${infoIcon} ${details.mutationVerb} ${details.resourceLabel}`);
368
384
  } else if (method === "GET" && parsed) {
@@ -0,0 +1,524 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import * as fs from "node:fs/promises";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
5
+ import { isDeepStrictEqual } from "node:util";
6
+ import type { AgentToolResult } from "@f5-sales-demo/pi-agent-core";
7
+ import {
8
+ createBody,
9
+ type MutationContract,
10
+ objectValue,
11
+ selectedMember,
12
+ validateBody,
13
+ valueAt,
14
+ } from "../internal-urls/immutable-selection";
15
+ import type { XcshApiToolDetails } from "./xcsh-api";
16
+
17
+ type ObjectValue = Record<string, unknown>;
18
+ interface Stage {
19
+ version: 1;
20
+ id: string;
21
+ scope: string;
22
+ resourcePath: string;
23
+ name: string;
24
+ namespace: string;
25
+ originalUid: string;
26
+ originalVersion: string;
27
+ originalSelections: string[];
28
+ targetSelections: string[];
29
+ stage: "prepared" | "deleting" | "absent" | "creating" | "verifying" | "complete";
30
+ newUid?: string;
31
+ serviceState?: string;
32
+ certificateState?: string;
33
+ }
34
+ interface Options {
35
+ contract: MutationContract;
36
+ apiBase: string;
37
+ contextName?: string;
38
+ resourcePath: string;
39
+ payload: ObjectValue;
40
+ recreate: boolean;
41
+ replacementId?: string;
42
+ headers: Record<string, string>;
43
+ signal?: AbortSignal;
44
+ contextMatches: () => boolean;
45
+ stateDir?: string;
46
+ }
47
+ class ReplacementError extends Error {
48
+ constructor(
49
+ readonly code: string,
50
+ message: string,
51
+ readonly status = 409,
52
+ ) {
53
+ super(message);
54
+ }
55
+ }
56
+ function identity(object: ObjectValue, name: string, namespace: string) {
57
+ const meta = objectValue(object.metadata);
58
+ const system = objectValue(object.system_metadata);
59
+ if (meta.name !== name || meta.namespace !== namespace)
60
+ throw new ReplacementError("identity_mismatch", "Readback name or namespace does not match the requested object");
61
+ const uid = system.uid;
62
+ const version = object.resource_version ?? system.resource_version;
63
+ if (typeof uid !== "string" || !uid || typeof version !== "string" || !version)
64
+ throw new ReplacementError("identity_unavailable", "The existing object must have a UID and resource version");
65
+ return { uid, version };
66
+ }
67
+ function mergeObject(current: ObjectValue, update: ObjectValue): ObjectValue {
68
+ const result = { ...current };
69
+ for (const [key, value] of Object.entries(update)) {
70
+ result[key] =
71
+ value &&
72
+ typeof value === "object" &&
73
+ !Array.isArray(value) &&
74
+ current[key] &&
75
+ typeof current[key] === "object" &&
76
+ !Array.isArray(current[key])
77
+ ? mergeObject(objectValue(current[key]), objectValue(value))
78
+ : value;
79
+ }
80
+ return result;
81
+ }
82
+ function maskSensitiveDiagnostic(raw: string, payload: unknown): string {
83
+ const secrets: string[] = [];
84
+ const visit = (value: unknown, sensitive = false) => {
85
+ if (typeof value === "string") {
86
+ if (sensitive && value.length) secrets.push(value);
87
+ return;
88
+ }
89
+ if (Array.isArray(value)) {
90
+ value.forEach(v => {
91
+ visit(v, sensitive);
92
+ });
93
+ return;
94
+ }
95
+ if (value && typeof value === "object")
96
+ for (const [key, child] of Object.entries(value))
97
+ visit(child, sensitive || /(?:token|password|private_key|secret|credential)/i.test(key));
98
+ };
99
+ visit(payload);
100
+ let text = raw;
101
+ for (const secret of secrets.sort((a, b) => b.length - a.length)) {
102
+ text = text.split(secret).join("[MASKED]");
103
+ const escaped = JSON.stringify(secret).slice(1, -1);
104
+ text = text.split(escaped).join("[MASKED]");
105
+ }
106
+ return text.replace(
107
+ /-----BEGIN (?:RSA |EC |ENCRYPTED )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |ENCRYPTED )?PRIVATE KEY-----/g,
108
+ "[MASKED PRIVATE KEY]",
109
+ );
110
+ }
111
+ function containsConfig(actual: unknown, expected: unknown): boolean {
112
+ if (expected === null || typeof expected !== "object") return isDeepStrictEqual(actual, expected);
113
+ if (Array.isArray(expected))
114
+ return (
115
+ Array.isArray(actual) &&
116
+ actual.length === expected.length &&
117
+ expected.every((value, index) => containsConfig(actual[index], value))
118
+ );
119
+ if (!actual || typeof actual !== "object" || Array.isArray(actual)) return false;
120
+ return Object.entries(expected).every(([key, value]) => containsConfig((actual as ObjectValue)[key], value));
121
+ }
122
+ async function writePrivate(file: string, value: unknown) {
123
+ const temporary = `${file}.${randomUUID()}.tmp`;
124
+ const handle = await fs.open(temporary, "wx", 0o600);
125
+ try {
126
+ await handle.writeFile(JSON.stringify(value));
127
+ await handle.sync();
128
+ } finally {
129
+ await handle.close();
130
+ }
131
+ await fs.rename(temporary, file);
132
+ }
133
+ export async function checkImmutableMutation(
134
+ options: Options,
135
+ ): Promise<(AgentToolResult<XcshApiToolDetails> & { isError?: boolean }) | undefined> {
136
+ const { contract, payload, resourcePath } = options;
137
+ const namespace = decodeURIComponent(resourcePath.split("/").at(-3)!);
138
+ const name = decodeURIComponent(resourcePath.split("/").at(-1)!);
139
+ const scope = createHash("sha256")
140
+ .update(JSON.stringify([options.apiBase, options.contextName ?? "", resourcePath]))
141
+ .digest("hex");
142
+ const root = options.stateDir ?? path.join(os.homedir(), ".xcsh", "state", "replacements");
143
+ let stage: Stage | undefined;
144
+ let locked = false;
145
+ const requestId = randomUUID();
146
+ const detail: XcshApiToolDetails = {
147
+ status: 409,
148
+ url: `${options.apiBase}${resourcePath}`,
149
+ method: "PUT",
150
+ requestId,
151
+ contextName: options.contextName,
152
+ };
153
+ const result = (code: string, message: string, status = 409, extra: ObjectValue = {}) => ({
154
+ content: [
155
+ {
156
+ type: "text" as const,
157
+ text: JSON.stringify({
158
+ code,
159
+ message,
160
+ replacementId: stage?.id,
161
+ stage: stage?.stage,
162
+ serviceState: stage?.serviceState,
163
+ certificateState: stage?.certificateState,
164
+ ...extra,
165
+ }),
166
+ },
167
+ ],
168
+ details: { ...detail, status, replacementId: stage?.id, replacementStage: stage?.stage },
169
+ isError: true,
170
+ });
171
+ const save = async () => {
172
+ if (stage) await writePrivate(path.join(root, `${stage.id}.json`), stage);
173
+ };
174
+ const read = async (method = "GET", body?: ObjectValue) => {
175
+ if (!options.contextMatches())
176
+ throw new ReplacementError(
177
+ "context_mismatch",
178
+ "The active API context changed; resume in the original context",
179
+ );
180
+ const timeout = AbortSignal.timeout(30_000);
181
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
182
+ const response = await fetch(`${options.apiBase}${method === "POST" ? contract.collection : resourcePath}`, {
183
+ method,
184
+ headers: {
185
+ ...options.headers,
186
+ "X-Request-ID": randomUUID(),
187
+ ...(body ? { "Content-Type": "application/json" } : {}),
188
+ },
189
+ signal,
190
+ body: body ? JSON.stringify(body) : undefined,
191
+ });
192
+ const raw = await response.text();
193
+ const safeRaw = maskSensitiveDiagnostic(raw, payload);
194
+ let object: ObjectValue | undefined;
195
+ try {
196
+ object = objectValue(JSON.parse(raw));
197
+ } catch {}
198
+ return { status: response.status, ok: response.ok, object, raw: safeRaw };
199
+ };
200
+ const pause = async (attempt: number) => {
201
+ options.signal?.throwIfAborted();
202
+ await Bun.sleep(Math.min(250 * 2 ** attempt, 2000));
203
+ options.signal?.throwIfAborted();
204
+ };
205
+ try {
206
+ const meta = objectValue(payload.metadata);
207
+ if (meta.name !== name || meta.namespace !== namespace)
208
+ throw new ReplacementError("identity_mismatch", "Payload name and namespace must match the API path");
209
+ const target = contract.groups.map(g => selectedMember(payload, g));
210
+ if (options.replacementId && !/^[0-9a-f-]{36}$/.test(options.replacementId))
211
+ throw new ReplacementError("invalid_replacement_id", "Invalid replacement ID");
212
+ await fs.mkdir(root, { recursive: true, mode: 0o700 });
213
+ try {
214
+ await fs.mkdir(path.join(root, `${scope}.lock`), { mode: 0o700 });
215
+ locked = true;
216
+ } catch (err) {
217
+ if ((err as NodeJS.ErrnoException).code === "EEXIST")
218
+ return result("replacement_busy", "Another operation holds this object's replacement lock");
219
+ throw err;
220
+ }
221
+ if (!options.replacementId) {
222
+ for (const file of await fs.readdir(root)) {
223
+ if (!file.endsWith(".json")) continue;
224
+ const pending = JSON.parse(await fs.readFile(path.join(root, file), "utf8")) as Stage;
225
+ if (pending.scope === scope && pending.stage !== "complete") {
226
+ stage = pending;
227
+ return result(
228
+ "replacement_pending",
229
+ "This object already has a pending cutover. Resume the replacement ID instead of starting another deletion.",
230
+ );
231
+ }
232
+ }
233
+ }
234
+ if (options.replacementId) {
235
+ stage = JSON.parse(await fs.readFile(path.join(root, `${options.replacementId}.json`), "utf8")) as Stage;
236
+ if (
237
+ stage.version !== 1 ||
238
+ stage.id !== options.replacementId ||
239
+ stage.scope !== scope ||
240
+ stage.resourcePath !== resourcePath ||
241
+ stage.name !== name ||
242
+ stage.namespace !== namespace
243
+ )
244
+ throw new ReplacementError(
245
+ "replacement_scope_mismatch",
246
+ "Replacement ID does not match this context and object",
247
+ );
248
+ if (!isDeepStrictEqual(stage.targetSelections, target))
249
+ throw new ReplacementError(
250
+ "replacement_target_mismatch",
251
+ "A resumed replacement must keep its original target type",
252
+ );
253
+ }
254
+ const current = await read();
255
+ if (!stage) {
256
+ if (!current.ok || !current.object)
257
+ throw new ReplacementError(
258
+ "preflight_failed",
259
+ `Cannot read the current object (${current.status}): ${current.raw}`,
260
+ current.status,
261
+ );
262
+ const source = contract.groups.map(g => selectedMember(current.object!, g));
263
+ if (isDeepStrictEqual(source, target)) return undefined;
264
+ if (!options.recreate)
265
+ return result(
266
+ "replacement_required",
267
+ "The immutable type selection changed. Explicit conversion requests use onImmutableSelectionChange: recreate. DELETE then POST causes downtime and may change UID or VIP.",
268
+ 409,
269
+ { currentSelections: source, targetSelections: target },
270
+ );
271
+ const old = identity(current.object, name, namespace);
272
+ stage = {
273
+ version: 1,
274
+ id: randomUUID(),
275
+ scope,
276
+ resourcePath,
277
+ name,
278
+ namespace,
279
+ originalUid: old.uid,
280
+ originalVersion: old.version,
281
+ originalSelections: source,
282
+ targetSelections: target,
283
+ stage: "prepared",
284
+ };
285
+ } else if (!options.recreate)
286
+ return result("replacement_pending", "Resume requires onImmutableSelectionChange: recreate");
287
+ // The body snapshot is private configuration, separate from the payload-free stage journal.
288
+ // It never contains transport credentials and is never written to tool logs or details.
289
+ if (stage.stage === "complete")
290
+ return result("replacement_complete", "This replacement is already complete; use GET for its current state.");
291
+ let base: ObjectValue;
292
+ const bodyPath = path.join(root, `${stage.id}.body`);
293
+ if (stage.stage === "prepared" && !options.replacementId) {
294
+ const writable = current.object!.create_form ?? current.object!;
295
+ base = objectValue(createBody(writable, contract.createSchema, contract.spec));
296
+ } else {
297
+ base = objectValue(JSON.parse(await fs.readFile(bodyPath, "utf8")));
298
+ }
299
+
300
+ await writePrivate(bodyPath, base);
301
+ await save();
302
+ const body = mergeObject(base, payload);
303
+ for (const [i, g] of contract.groups.entries()) {
304
+ const owner = valueAt(body, g.path);
305
+ for (const member of g.members) delete owner[member];
306
+ owner[target[i]!] = valueAt(payload, g.path)[target[i]!];
307
+ }
308
+ const projected = objectValue(createBody(body, contract.createSchema, contract.spec));
309
+ const errors = validateBody(projected, contract.createSchema, contract.spec);
310
+ const minimum = contract.createSchema["x-f5xc-minimum-configuration"] as
311
+ | { required_fields?: string[] }
312
+ | undefined;
313
+ for (const field of minimum?.required_fields ?? []) {
314
+ let value: unknown = projected;
315
+ for (const part of field.split(".")) value = (value as ObjectValue)?.[part];
316
+ if (value === undefined || value === null) errors.push(`${field}: required`);
317
+ }
318
+ if (errors.length)
319
+ return result(
320
+ "replacement_validation_failed",
321
+ "Correct the create payload and resume the replacement. No DELETE was issued by this attempt.",
322
+ 422,
323
+ { errors },
324
+ );
325
+ contract.groups.forEach(g => {
326
+ selectedMember(projected, g);
327
+ });
328
+ await writePrivate(bodyPath, projected);
329
+ await save();
330
+ if (stage.stage === "prepared" || stage.stage === "deleting") {
331
+ if (current.status === 404 && stage.stage === "deleting") {
332
+ stage.stage = "absent";
333
+ await save();
334
+ } else {
335
+ if (!current.ok || !current.object)
336
+ throw new ReplacementError("preflight_failed", "Existing object cannot be verified");
337
+ const original = identity(current.object, name, namespace);
338
+ if (
339
+ original.uid !== stage.originalUid ||
340
+ original.version !== stage.originalVersion ||
341
+ !isDeepStrictEqual(
342
+ contract.groups.map(g => selectedMember(current.object!, g)),
343
+ stage.originalSelections,
344
+ )
345
+ )
346
+ throw new ReplacementError("concurrent_change", "The original object changed; no DELETE was issued");
347
+ // Save deletion intent before the final read. No asynchronous operation intervenes
348
+ // between comparing this read and sending DELETE; the API still has no conditional DELETE.
349
+ stage.stage = "deleting";
350
+ await save();
351
+ const latest = await read();
352
+ if (
353
+ !latest.ok ||
354
+ !latest.object ||
355
+ !isDeepStrictEqual(identity(latest.object, name, namespace), original) ||
356
+ !isDeepStrictEqual(latest.object.spec, current.object.spec) ||
357
+ !isDeepStrictEqual(latest.object.metadata, current.object.metadata)
358
+ )
359
+ throw new ReplacementError(
360
+ "concurrent_change",
361
+ "Object changed immediately before deletion; no DELETE was issued",
362
+ );
363
+ const deleted = await read("DELETE");
364
+ if (!deleted.ok && deleted.status !== 404)
365
+ throw new ReplacementError(
366
+ "delete_failed",
367
+ `DELETE failed (${deleted.status}): ${deleted.raw}`,
368
+ deleted.status,
369
+ );
370
+ let absent = false;
371
+ for (let attempt = 0; attempt < 6; attempt++) {
372
+ const observed = await read();
373
+ if (observed.status === 404) {
374
+ absent = true;
375
+ break;
376
+ }
377
+ if (!observed.ok)
378
+ throw new ReplacementError(
379
+ "absence_unverified",
380
+ `Cannot verify deletion (${observed.status})`,
381
+ observed.status,
382
+ );
383
+ if (observed.object && identity(observed.object, name, namespace).uid !== stage.originalUid)
384
+ throw new ReplacementError("identity_mismatch", "Another object appeared while waiting for deletion");
385
+ await pause(attempt);
386
+ }
387
+ if (!absent)
388
+ return result(
389
+ "replacement_pending",
390
+ "Deletion has not reached absence. Keep diagnosing and resume this replacement ID.",
391
+ );
392
+ stage.stage = "absent";
393
+ await save();
394
+ }
395
+ }
396
+
397
+ for (let attempt = 0; attempt < 5; attempt++) {
398
+ // Every uncertain create is followed by GET before any retry. Never delete a new object.
399
+ const observed =
400
+ stage.stage === "absent" && attempt === 0 && !options.replacementId
401
+ ? { status: 404, ok: false, object: undefined }
402
+ : await read();
403
+ if (observed.ok && observed.object) {
404
+ const newIdentity = identity(observed.object, name, namespace);
405
+ if (
406
+ newIdentity.uid === stage.originalUid ||
407
+ (stage.newUid && stage.newUid !== newIdentity.uid) ||
408
+ !isDeepStrictEqual(
409
+ contract.groups.map(g => selectedMember(observed.object!, g)),
410
+ target,
411
+ )
412
+ )
413
+ throw new ReplacementError(
414
+ "replacement_identity_mismatch",
415
+ "Readback is not the expected new object; no deletion or POST will be attempted",
416
+ );
417
+ const writable = objectValue(
418
+ createBody(observed.object.create_form ?? observed.object, contract.createSchema, contract.spec),
419
+ );
420
+ if (!containsConfig(writable, projected))
421
+ throw new ReplacementError(
422
+ "replacement_configuration_mismatch",
423
+ "The new object's configuration does not match the requested create body; continue diagnosis without deleting it",
424
+ );
425
+ stage.newUid = newIdentity.uid;
426
+ stage.stage = "verifying";
427
+ await save();
428
+ const service = objectValue(observed.object.spec).state;
429
+ stage.serviceState = typeof service === "string" ? service : undefined;
430
+ const automatic = target.includes("https_auto_cert");
431
+ const certificateState = (objectValue(observed.object.spec).auto_cert_info as ObjectValue | undefined)
432
+ ?.auto_cert_state;
433
+ stage.certificateState = typeof certificateState === "string" ? certificateState : undefined;
434
+ await save();
435
+ if (
436
+ typeof service !== "string" ||
437
+ !/^(?:VIRTUAL_HOST_READY|READY|ACTIVE|RUNNING)$/i.test(service) ||
438
+ (automatic &&
439
+ certificateState !== undefined &&
440
+ !/^(?:CertificateIssued|AutoCertIssued|CertificateValid)$/i.test(String(certificateState)))
441
+ ) {
442
+ await pause(attempt);
443
+ continue;
444
+ }
445
+ stage.stage = "complete";
446
+ await save();
447
+ await fs.rm(bodyPath, { force: true });
448
+ return {
449
+ content: [
450
+ {
451
+ type: "text",
452
+ text: JSON.stringify({
453
+ code: "replacement_complete",
454
+ message: `Recreated ${name} in ${namespace}. Verified target type, new UID, and service state. The cutover caused downtime and may have changed the VIP.`,
455
+ replacementId: stage.id,
456
+ originalUid: stage.originalUid,
457
+ newUid: stage.newUid,
458
+ targetSelections: target,
459
+ serviceState: service,
460
+ }),
461
+ },
462
+ ],
463
+ details: {
464
+ ...detail,
465
+ status: 200,
466
+ method: "POST",
467
+ replacementId: stage.id,
468
+ replacementStage: stage.stage,
469
+ mutationVerb: "Created",
470
+ resourceLabel: `load balancer ${name}`,
471
+ },
472
+ };
473
+ }
474
+ if (observed.status !== 404) {
475
+ await pause(attempt);
476
+ continue;
477
+ }
478
+ if (stage.stage === "verifying")
479
+ return result(
480
+ "replacement_pending",
481
+ "The new object disappeared during verification. Diagnose before retrying.",
482
+ );
483
+ stage.stage = "creating";
484
+ await save();
485
+ let created: Awaited<ReturnType<typeof read>>;
486
+ try {
487
+ created = await read("POST", projected);
488
+ } catch {
489
+ await pause(attempt);
490
+ continue;
491
+ }
492
+ if (created.ok && typeof (created.object?.system_metadata as ObjectValue)?.uid === "string") {
493
+ stage.newUid = (created.object!.system_metadata as ObjectValue).uid as string;
494
+ await save();
495
+ }
496
+ const validationFailure =
497
+ /(?:should be valid|should (?:be|have)|must be|required|invalid|does not exist|validation)/i.test(
498
+ created.raw,
499
+ );
500
+ if (!created.ok && (validationFailure || ![408, 409, 429, 500, 502, 503, 504].includes(created.status)))
501
+ return result(
502
+ "replacement_create_failed",
503
+ `POST failed (${created.status}): ${created.raw}. The original LB remains deleted. Correct the payload and resume this replacement ID; do not DELETE again.`,
504
+ created.status,
505
+ );
506
+ await pause(attempt);
507
+ }
508
+ return result(
509
+ "replacement_pending",
510
+ "The cutover is incomplete. Continue diagnosis and resume this replacement ID; the original LB is not restored.",
511
+ );
512
+ } catch (err) {
513
+ if (err instanceof ReplacementError) return result(err.code, err.message, err.status);
514
+ // Transport exceptions may contain private request data. Stage/HTTP diagnostics carry
515
+ // the actionable context without echoing arbitrary exception strings.
516
+ return result(
517
+ "replacement_pending",
518
+ "The immutable mutation could not finish. Inspect the object state and resume the private replacement stage. No success is claimed.",
519
+ 503,
520
+ );
521
+ } finally {
522
+ if (locked) await fs.rmdir(path.join(root, `${scope}.lock`));
523
+ }
524
+ }