@airctrl/cli 0.0.0-stage → 0.4.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,1485 @@
1
+ /**
2
+ * U9b-3c/3d · `sa *` commands (§10.c#16.B/F + §10.c#17). Importable + side-effect-free — the thin bin executes.
3
+ *
4
+ * FOUR ADMIN commands (U9b-3c), human PAT + `--account <id>` ONLY (no `--profile`, no MACHINE material): `authorize`
5
+ * (durable crash-safe successor authorize with a first-run/resume state machine), `cancel`, `tokens`,
6
+ * `revoke-token`. Every command vetoes ANY service-account principal via `resolveHumanClient` BEFORE any
7
+ * filesystem / HTTP / stdout, and sends `x-account-id`. All persistence evidence is judged by the SSOT
8
+ * `evidenceSecure`; the post-commit error matrices (D4 bootstrap-finalize, D5 rotation-artifact) never roll
9
+ * back a committed remote op, never delete a handoff on failure, and never leak a bearer/claimTicket/path.
10
+ * Output is EXACTLY one JSON line per success. For any path that ACQUIRES the lease, it is emitted ONLY after a
11
+ * successful lease `release()`. A confirmed artifact-only reconcile (handoff durably absent) takes the ratified
12
+ * no-lease fast path (§10.c#16.D) and emits without acquiring a lease — so "after release" applies to the
13
+ * lease-holding paths, not to that fast path.
14
+ */
15
+ import { homedir } from 'node:os';
16
+ import { generateSaClaimTicketPlaintext, BootstrapContext, createBootstrapClaimClient, createClient, prepareCapability, runCredentialLifecycle, isSaCoordinatorError, SaCoordinatorError, } from '@airctrl/sdk';
17
+ import { join } from 'node:path';
18
+ import { acquireHandoffLease, createProvisionalHandoff, createRotationArtifact, loadRotationArtifact, deleteRotationArtifact, createReceipt, loadReceipt, createProfile, loadProfile, replaceProfile, deleteProfileUnderLock, canonicalJson, acquireProfileLock, evidenceSecure, deleteEvidenceSecure, confirmDurableAbsence, assertBaseUrlMatch, assertRegularFile, assertHandoffChain, assertHandoffId, normalizeBaseUrl, handoffDir, handoffFile, StoreError, REAL_FS, } from './store/index.js';
19
+ import { resolveHumanClient, resolveClient, resolveHolderProfile } from './resolve-client.js';
20
+ import { preflightMigratePrincipal, acquireMigrationLeaseContext, withMigrationLease, } from './migrate.js';
21
+ import { resolveStatusPrincipal } from './resolve-status-principal.js';
22
+ import { withPatExpired } from './pat-expired.js';
23
+ import { CliError, ReconcileError } from './cli-error.js';
24
+ import { saDeadlineExpired } from './deadline.js';
25
+ import { parseArgv, ParseError } from './parser.js';
26
+ import { saRotateIdentity } from './identity-rotation.js';
27
+ /** Per-subcommand grammars (exported so tests exercise the REAL specs). `--account` is required in the FOUR
28
+ * ADMIN commands (`authorize`/`cancel`/`tokens`/`revoke-token`), whose flag sets exclude `--profile` (a
29
+ * `--profile` there is `cli_unknown_flag` — no MACHINE authority). The MACHINE `bootstrap`, `verify`, `status`,
30
+ * and `reconcile` commands DO accept `--profile` (and never `--account`); `reconcile` also takes `--receipt`
31
+ * (required) and `--handoff` (optional). */
32
+ export const SA_SPECS = {
33
+ authorize: { positionals: ['serviceAccountId'], flags: ['account', 'handoff'], requiredFlags: ['account'] },
34
+ cancel: { positionals: ['serviceAccountId', 'credentialId'], flags: ['account'], requiredFlags: ['account'] },
35
+ tokens: { positionals: ['serviceAccountId'], flags: ['account'], requiredFlags: ['account'] },
36
+ 'revoke-token': { positionals: ['serviceAccountId', 'patId'], flags: ['account'], requiredFlags: ['account'] },
37
+ // U9b-3d MACHINE bootstrap (§10.c#17): no positional (the handoff carries the SA); `--handoff` + `--profile`
38
+ // both required; no `--account` (no ADMIN authority). The handoff is the authority for SA/baseUrl/credential.
39
+ bootstrap: { positionals: [], flags: ['handoff', 'profile'], requiredFlags: ['handoff', 'profile'] },
40
+ // U9b-3e-1 MACHINE/HOLDER verify (§10.c#18.8): unlock-only; no positional; optional `--profile` selector; no `--account`.
41
+ verify: { positionals: [], flags: ['profile'], requiredFlags: [] },
42
+ // U9b-3e-2 MACHINE/HOLDER status (§10.c#18.7): remote status read; no positional; optional `--profile`; no `--account`, no SA-id flag.
43
+ status: { positionals: [], flags: ['profile'], requiredFlags: [] },
44
+ // U9b-3e-3 MACHINE/local-only reconcile (§10.c#18.9): no positional; `--profile`+`--receipt` required; `--handoff` optional; no `--account`.
45
+ reconcile: { positionals: [], flags: ['profile', 'receipt', 'handoff'], requiredFlags: ['profile', 'receipt'] },
46
+ // U9b-3e-4 MACHINE/HOLDER rotate (§10.c#18.6): no positional; `--operation`+`--profile` required; `--holder-profile`
47
+ // allowed by the parser but stage-required at runtime (`sa_holder_profile_required`); no `--account`.
48
+ rotate: { positionals: [], flags: ['operation', 'profile', 'holder-profile'], requiredFlags: ['operation', 'profile'] },
49
+ // U4 Capa 3 MACHINE/HOLDER identity rotation (C3 · T6): the THREE flags are obligatory; no positional, no `--account`.
50
+ 'rotate-identity': { positionals: [], flags: ['operation', 'profile', 'holder-profile'], requiredFlags: ['operation', 'profile', 'holder-profile'] },
51
+ // U9b-4-1 MACHINE/HOLDER legacy migration (§10.c#20.1): positional `<serviceAccountId>` (the SOLE source of the SA
52
+ // id) + `--profile` both required; no `--account` (no ADMIN authority). Authority = `preflightMigratePrincipal`.
53
+ migrate: { positionals: ['serviceAccountId'], flags: ['profile'], requiredFlags: ['profile'] },
54
+ };
55
+ /** Historical command grammar retained for regression tests; it is not part of public CLI help. */
56
+ export const SA_INTERNAL_USAGE = 'airctrl sa rotate-identity --operation <uuid> --profile <successor> --holder-profile <holder>';
57
+ /** Build `SaDeps` from the loosely-typed CLI seams, defaulting the store root to the real HOME. */
58
+ export function buildSaDeps(deps) {
59
+ return {
60
+ resolve: deps.resolve,
61
+ env: deps.resolve.env ?? process.env,
62
+ stdout: deps.stdout ?? ((s) => process.stdout.write(s)),
63
+ root: deps.profileRoot ?? homedir(),
64
+ fs: deps.fsOps ?? REAL_FS,
65
+ now: deps.now ?? Date.now,
66
+ newOperationId: deps.newOperationId ?? (() => crypto.randomUUID()),
67
+ newIdempotencyKey: deps.newIdempotencyKey ?? (() => crypto.randomUUID()),
68
+ newReceiptId: deps.newReceiptId ?? (() => crypto.randomUUID()),
69
+ newClaimTicket: deps.newClaimTicket ?? generateSaClaimTicketPlaintext,
70
+ newBootstrap: deps.newBootstrap ?? (() => BootstrapContext.prepare()),
71
+ makeBootstrapClaimClient: deps.makeBootstrapClaimClient ?? ((opts) => createBootstrapClaimClient(opts)),
72
+ makeClient: deps.makeClient ?? createClient,
73
+ newCapability: deps.newCapability ?? (() => prepareCapability()),
74
+ };
75
+ }
76
+ // ── Store-error code classes (D4/D5) ────────────────────────────────────────────────────────────────────
77
+ const codeOf = (e) => (e instanceof StoreError ? e.code : undefined);
78
+ // Operational = the write could not be proven durable; the remote op is already committed.
79
+ const FINALIZE_OPERATIONAL = new Set(['sa_store_io_error', 'sa_store_access_denied', 'sa_store_no_space', 'sa_store_reconcile_failed']);
80
+ const ROTATION_OPERATIONAL = new Set(['sa_store_io_error', 'sa_store_access_denied', 'sa_store_no_space']);
81
+ // Path/integrity codes are PRESERVED verbatim (never reclassified as a conflict/state).
82
+ const FINALIZE_PATH = new Set(['sa_store_symlink_rejected', 'sa_store_lstat_failed', 'sa_store_not_regular_file', 'sa_handoff_corrupt']);
83
+ const ROTATION_PATH = new Set(['sa_store_symlink_rejected', 'sa_store_lstat_failed', 'sa_store_not_regular_file', 'sa_rotation_artifact_corrupt']);
84
+ // ── Expiry (transversal to finalized bootstrap AND rotation artifact) ────────────────────────────────────
85
+ // Boundary per contract: `expiresAt <= now()` is EXPIRED (a deadline reached exactly is elapsed). FINDING 4.
86
+ function assertNotExpired(expiresAt, now) {
87
+ if (saDeadlineExpired(expiresAt, now()))
88
+ throw new ReconcileError('authorization_expired'); // SSOT boundary (§10.c#20.I)
89
+ }
90
+ /**
91
+ * Bind a persisted handoff/artifact to the CURRENT invocation BEFORE any HTTP/stdout/cleanup/return (FINDING 2 +
92
+ * R2·FINDING 1): the stores validate the selector + the doc's `operationId` are each a UUID, but NOT that the
93
+ * doc's CONTENT `operationId` equals the `--handoff` selector (the file name). So the FULL binding is: the
94
+ * persisted `operationId` MUST equal the selected `operationId`, the persisted `serviceAccountId` MUST equal the
95
+ * requested one, and its authoritative `baseUrl` MUST normalize-equal the current one. Any mismatch of
96
+ * operationId/serviceAccountId → `sa_handoff_binding_mismatch`; baseUrl → `sa_baseurl_conflict`. `accountId` is
97
+ * deliberately NOT a persisted binding — the schema never stores it, and we do not invent one.
98
+ */
99
+ function assertBoundToInvocation(persisted, base, operationId) {
100
+ if (persisted.operationId !== operationId)
101
+ throw new CliError('sa_handoff_binding_mismatch');
102
+ if (persisted.serviceAccountId !== base.serviceAccountId)
103
+ throw new CliError('sa_handoff_binding_mismatch');
104
+ assertBaseUrlMatch(persisted.baseUrl, base.baseUrl); // persisted is authoritative; mismatch → sa_baseurl_conflict
105
+ }
106
+ /**
107
+ * Fail-closed, non-follow existence check of the managed handoff leaf WITHOUT a lease (R2·FINDING 2). The managed
108
+ * chain (`.airctrl` → `sa` → `handoffs`) is validated FIRST via the SAME FsOps instance — a symlinked/junctioned
109
+ * component fails closed (`sa_store_symlink_rejected`) and a non-ENOENT lstat → `sa_store_lstat_failed` — so the
110
+ * leaf lookup never traverses a redirected component. Only then the leaf regular-file gate runs; a not-yet-created
111
+ * chain tolerates absent → false.
112
+ */
113
+ function handoffPresent(root, id, fs) {
114
+ assertHandoffChain(root, fs); // managed-chain fail-closed BEFORE touching the leaf (same FsOps instance)
115
+ const p = join(handoffDir(root), handoffFile(id));
116
+ return assertRegularFile(p, { notRegular: 'sa_handoff_corrupt' }, fs) === 'present';
117
+ }
118
+ // ── Conflict classification (binding vs state) ──────────────────────────────────────────────────────────
119
+ /** Classify a bootstrap-finalize `sa_handoff_conflict` (D4.D). Reads back the persisted doc; a corrupt/path
120
+ * read PRESERVES its own stable code. Binding fields differ → binding mismatch; else → state inconsistent. */
121
+ function classifyFinalizeConflict(lease, expected) {
122
+ const st = lease.readState(); // corrupt/symlink/lstat/non-regular throw → preserved by the caller's rethrow
123
+ if (st.phase === 'finalized') {
124
+ const h = st.handoff;
125
+ const bindingDiff = h.operationId !== expected.operationId ||
126
+ h.serviceAccountId !== expected.serviceAccountId ||
127
+ h.baseUrl !== expected.baseUrl ||
128
+ h.claimTicket !== expected.claimTicket;
129
+ throw new CliError(bindingDiff ? 'sa_handoff_binding_mismatch' : 'sa_handoff_state_inconsistent');
130
+ }
131
+ // A provisional-on-disk during a finalize conflict is an internal contradiction → state inconsistent.
132
+ throw new CliError('sa_handoff_state_inconsistent');
133
+ }
134
+ /** Classify a rotation-artifact `sa_rotation_artifact_conflict` (D5.D). `loadRotationArtifact` corrupt/path
135
+ * PRESERVES its code (precedence 1). Binding (operationId/serviceAccountId/baseUrl) differs → binding
136
+ * mismatch (precedence 2); else → state inconsistent (precedence 3–4, incl. all-equal-but-conflict). */
137
+ function classifyRotationConflict(root, operationId, fs, expected) {
138
+ const art = loadRotationArtifact(root, operationId, fs); // corrupt/symlink/lstat/non-regular throw → preserved
139
+ const bindingDiff = art.operationId !== operationId || art.serviceAccountId !== expected.serviceAccountId || art.baseUrl !== expected.baseUrl;
140
+ throw new CliError(bindingDiff ? 'sa_handoff_binding_mismatch' : 'sa_handoff_state_inconsistent');
141
+ }
142
+ /** D4 — bootstrap: finalize the handoff, then judge the evidence. Any throw is classified; NEVER a rollback. */
143
+ function finalizeBootstrap(lease, ctx, meta, deps) {
144
+ let ev;
145
+ try {
146
+ ev = lease.finalize({ credentialId: meta.credentialId, expiresAt: meta.expiresAt });
147
+ }
148
+ catch (e) {
149
+ const c = codeOf(e);
150
+ if (c && FINALIZE_OPERATIONAL.has(c))
151
+ throw new CliError('sa_handoff_insecure'); // C: not demonstrably durable
152
+ if (c === 'sa_handoff_conflict') {
153
+ classifyFinalizeConflict(lease, {
154
+ operationId: ctx.operationId,
155
+ serviceAccountId: ctx.serviceAccountId,
156
+ baseUrl: ctx.baseUrl,
157
+ claimTicket: ctx.claimTicket,
158
+ });
159
+ }
160
+ if (c && FINALIZE_PATH.has(c))
161
+ throw e; // E: preserve the stable path/integrity code
162
+ throw e; // F: unknown → rethrow → cli_internal_error
163
+ }
164
+ if (!evidenceSecure(ev, deps.fs, { requireCleanTemp: false }))
165
+ throw new CliError('sa_handoff_insecure'); // B
166
+ }
167
+ /** D5 — rotation: write the artifact (secure), THEN delete the handoff. Degraded/operational/delete-fail →
168
+ * cleanup-pending (handoff preserved); conflict → binding/state; path/integrity preserved; unknown rethrown. */
169
+ function commitRotation(lease, ctx, meta, deps) {
170
+ const artifact = {
171
+ schemaVersion: 1,
172
+ operationId: ctx.operationId,
173
+ credentialId: meta.credentialId,
174
+ expiresAt: meta.expiresAt,
175
+ serviceAccountId: ctx.serviceAccountId,
176
+ baseUrl: ctx.baseUrl,
177
+ };
178
+ let ev;
179
+ try {
180
+ ev = createRotationArtifact(deps.root, artifact, deps.fs);
181
+ }
182
+ catch (e) {
183
+ const c = codeOf(e);
184
+ if (c && ROTATION_OPERATIONAL.has(c))
185
+ throw new CliError('sa_handoff_cleanup_pending'); // C
186
+ if (c === 'sa_rotation_artifact_conflict') {
187
+ classifyRotationConflict(deps.root, ctx.operationId, deps.fs, { serviceAccountId: ctx.serviceAccountId, baseUrl: ctx.baseUrl });
188
+ }
189
+ if (c && ROTATION_PATH.has(c))
190
+ throw e; // E: preserve
191
+ throw e; // F: unknown
192
+ }
193
+ if (!evidenceSecure(ev, deps.fs, { requireCleanTemp: false }))
194
+ throw new CliError('sa_handoff_cleanup_pending'); // B
195
+ // A: artifact secure → remove the (still-sensitive) provisional handoff DURABLY. A delete failure / insecure
196
+ // durability never removes both → sa_handoff_cleanup_pending (residual handoff, artifact usable).
197
+ assertHandoffDeleted(lease, deps);
198
+ }
199
+ /** Run the durable authorize HTTP under the lease, persist by mode, gate expiry, and return the output. */
200
+ async function authorizeAndPersist(lease, human, ctx, deps) {
201
+ const meta = await human.client.saAuthorizeCredential(ctx.serviceAccountId, {
202
+ accountId: ctx.accountId,
203
+ operationId: ctx.operationId,
204
+ bootstrapClaimTicketCandidate: ctx.claimTicket,
205
+ idempotencyKey: ctx.operationId, // stable per logical op → server dedup consistent across retries
206
+ });
207
+ if (meta.mode === 'bootstrap')
208
+ finalizeBootstrap(lease, ctx, meta, deps);
209
+ else
210
+ commitRotation(lease, ctx, meta, deps);
211
+ assertNotExpired(meta.expiresAt, deps.now); // replay/skew: an already-past deadline → authorization_expired, not success
212
+ return { operationId: ctx.operationId, credentialId: meta.credentialId, expiresAt: meta.expiresAt, mode: meta.mode };
213
+ }
214
+ /**
215
+ * Run `fn` under the held lease with the ratified error precedence (§10.c#16.A): a primary error wins and a
216
+ * `release()` failure is swallowed; a functional success whose `release()` fails becomes
217
+ * `sa_handoff_lease_release_failed` (no success output). Never a naive `finally { release() }`.
218
+ */
219
+ async function withLease(lease, fn) {
220
+ let result;
221
+ let primary = null;
222
+ try {
223
+ result = await fn();
224
+ }
225
+ catch (e) {
226
+ primary = e;
227
+ }
228
+ let releaseErr = null;
229
+ try {
230
+ lease.release();
231
+ }
232
+ catch (e) {
233
+ releaseErr = e;
234
+ }
235
+ if (primary)
236
+ throw primary;
237
+ if (releaseErr)
238
+ throw new CliError('sa_handoff_lease_release_failed');
239
+ return result;
240
+ }
241
+ // ── State-machine readers ───────────────────────────────────────────────────────────────────────────────
242
+ /** Load the rotation artifact for the selector; `not_found` → null; corrupt/path preserved. */
243
+ function tryLoadArtifact(root, operationId, fs) {
244
+ try {
245
+ return loadRotationArtifact(root, operationId, fs);
246
+ }
247
+ catch (e) {
248
+ if (codeOf(e) === 'sa_rotation_artifact_not_found')
249
+ return null;
250
+ throw e;
251
+ }
252
+ }
253
+ /** Read the handoff state under the lease; `not_found` → null (handoff absent); corrupt/path preserved. */
254
+ function tryReadState(lease) {
255
+ try {
256
+ return lease.readState();
257
+ }
258
+ catch (e) {
259
+ if (codeOf(e) === 'sa_handoff_not_found')
260
+ return null;
261
+ throw e;
262
+ }
263
+ }
264
+ function finalizedOutput(h) {
265
+ return { operationId: h.operationId, credentialId: h.credentialId, expiresAt: h.expiresAt, mode: 'bootstrap' };
266
+ }
267
+ function artifactOutput(a) {
268
+ return { operationId: a.operationId, credentialId: a.credentialId, expiresAt: a.expiresAt, mode: 'rotation' };
269
+ }
270
+ /**
271
+ * Consume the handoff DURABLY (U9b-3e-P0 §10.c#18.5): `lease.delete()` unlinks + `fsyncDir(parent)`. Errors are
272
+ * CLASSIFIED, never a catch-all (F3): ONLY an operational `sa_store_io_error` (unlink) OR insecure durability
273
+ * (`deleteEvidenceSecure === false`) becomes `sa_handoff_cleanup_pending`; a path/integrity code
274
+ * (`sa_store_symlink_rejected`/`sa_store_not_regular_file`/`sa_store_lstat_failed`) and any ownership/lease
275
+ * `StoreError` PROPAGATE their stable code; an unknown throw is RETHROWN so the boundary yields
276
+ * `cli_internal_error` (never a faked cleanup-pending, never a raw message/path). A retry with the leaf already
277
+ * gone re-runs `fsyncDir` and completes iff the new evidence is secure.
278
+ */
279
+ function assertHandoffDeleted(lease, deps) {
280
+ let result;
281
+ try {
282
+ result = lease.delete();
283
+ }
284
+ catch (e) {
285
+ if (codeOf(e) === 'sa_store_io_error')
286
+ throw new CliError('sa_handoff_cleanup_pending'); // operational unlink failure only
287
+ throw e; // path/integrity + ownership/lease → preserve stable code; unknown → boundary cli_internal_error
288
+ }
289
+ if (!deleteEvidenceSecure(result, deps.fs))
290
+ throw new CliError('sa_handoff_cleanup_pending'); // insecure durability
291
+ }
292
+ /** FIRST RUN: mint operationId+ticket, persist the provisional handoff (gated) BEFORE the lease/HTTP, run. */
293
+ async function saAuthorizeFirstRun(base, deps) {
294
+ const operationId = deps.newOperationId();
295
+ const claimTicket = deps.newClaimTicket();
296
+ const provisional = { schemaVersion: 1, operationId, claimTicket, serviceAccountId: base.serviceAccountId, baseUrl: base.baseUrl };
297
+ const created = createProvisionalHandoff(deps.root, operationId, provisional, deps.fs);
298
+ // Insecure handoff → NO HTTP; preserve the handoff; not resumable until corrected.
299
+ if (!evidenceSecure(created, deps.fs, { requireCleanTemp: false }))
300
+ throw new CliError('sa_handoff_insecure');
301
+ const lease = acquireHandoffLease(deps.root, operationId, deps.fs);
302
+ return withLease(lease, () => authorizeAndPersist(lease, base.human, { serviceAccountId: base.serviceAccountId, accountId: base.accountId, operationId, claimTicket, baseUrl: base.baseUrl }, deps));
303
+ }
304
+ /**
305
+ * RESUME (`--handoff <operationId>`): strict state machine (§10.c#16.B/D). Never mints a new operation. Every
306
+ * persisted document is bound to the CURRENT invocation (FINDING 2) BEFORE any HTTP/cleanup/output. Artifact
307
+ * reads that decide a lease-protected branch are RE-READ under the lease so no pre-lease snapshot can produce a
308
+ * false `not_found` when a concurrent holder published the artifact and deleted the handoff (FINDING 3).
309
+ */
310
+ async function saAuthorizeResume(operationId, base, deps) {
311
+ assertHandoffId(operationId); // validate the user-supplied selector BEFORE building any managed path
312
+ const root = deps.root;
313
+ // FINDING 3 · race-safe fast path: ONLY when the handoff is confirmed absent (fail-closed, non-follow) AND an
314
+ // artifact exists. A handoff cannot reappear for this operationId (resume never creates one), so an absent
315
+ // handoff + present artifact is a settled rotation — reconcile WITHOUT a lease (a stale/busy lease must not
316
+ // block a confirmed artifact-only).
317
+ if (!handoffPresent(root, operationId, deps.fs)) {
318
+ const artifact = tryLoadArtifact(root, operationId, deps.fs);
319
+ if (artifact) {
320
+ assertBoundToInvocation(artifact, base, operationId); // FINDING 2 + R2·F1
321
+ // U9b-3e-P0 F4/R2·F2: an artifact-only success may print stdout ONLY after the handoff's ABSENCE is proven
322
+ // DURABLE (re-lstat fail-closed + one `fsyncDir`), and that cleanup is evaluated BEFORE expiry (an expired
323
+ // artifact must NOT skip an unreconciled sensitive cleanup). We never adopt a busy/stale operation lease for
324
+ // the fast path, and NEVER unlink a leaf that reappeared without ownership: a reappearance → fall through to
325
+ // the lease-protected branch below (which re-reads under serialization). Insecure durability → cleanup-pending.
326
+ const proof = confirmDurableAbsence(join(handoffDir(root), handoffFile(operationId)), (f) => assertHandoffChain(root, f), deps.fs);
327
+ if (proof.outcome === 'absent') {
328
+ if (!deleteEvidenceSecure(proof, deps.fs))
329
+ throw new CliError('sa_handoff_cleanup_pending'); // R2·F2: cleanup BEFORE expiry
330
+ assertNotExpired(artifact.expiresAt, deps.now); // expired → authorization_expired (only after durable cleanup)
331
+ return artifactOutput(artifact);
332
+ }
333
+ // leaf reappeared between pre-check and confirmation → do NOT unlink without a lease; classify under the lease.
334
+ }
335
+ // Both absent pre-lease (or a raced reappearance) → fall through and RE-READ under the lease.
336
+ }
337
+ // Handoff present OR pre-lease artifact absent → classify under the lease, RE-READING BOTH under serialization.
338
+ const lease = acquireHandoffLease(root, operationId, deps.fs);
339
+ return withLease(lease, async () => {
340
+ const state = tryReadState(lease); // re-read the handoff under ownership
341
+ const artifact = tryLoadArtifact(root, operationId, deps.fs); // RE-READ the artifact under the lease (FINDING 3)
342
+ // 1) finalized bootstrap + rotation artifact → ALWAYS inconsistent (mutually exclusive), before any compare.
343
+ if (state?.phase === 'finalized') {
344
+ if (artifact)
345
+ throw new CliError('sa_handoff_state_inconsistent');
346
+ assertBoundToInvocation(state.handoff, base, operationId); // FINDING 2 + R2·F1
347
+ // 4) finalized bootstrap, no artifact → vigente output / expired → authorization_expired (no re-authorize).
348
+ assertNotExpired(state.handoff.expiresAt, deps.now);
349
+ return finalizedOutput(state.handoff);
350
+ }
351
+ if (state?.phase === 'provisional') {
352
+ assertBoundToInvocation(state.handoff, base, operationId); // FINDING 2 + R2·F1 — handoff ↔ invocation
353
+ if (artifact) {
354
+ assertBoundToInvocation(artifact, base, operationId); // FINDING 2 + R2·F1 — artifact ↔ invocation
355
+ // 2) handoff ↔ artifact bindings must also agree; different → binding mismatch.
356
+ const bindingDiff = artifact.operationId !== state.handoff.operationId || artifact.serviceAccountId !== state.handoff.serviceAccountId;
357
+ if (bindingDiff)
358
+ throw new CliError('sa_handoff_binding_mismatch');
359
+ assertHandoffDeleted(lease, deps); // durably remove the residual sensitive provisional (both vigente + expired)
360
+ assertNotExpired(artifact.expiresAt, deps.now); // expired → authorization_expired (after cleanup)
361
+ return artifactOutput(artifact);
362
+ }
363
+ // 3) provisional, no artifact → replay HTTP with the PERSISTED (already invocation-bound) values.
364
+ return authorizeAndPersist(lease, base.human, {
365
+ serviceAccountId: state.handoff.serviceAccountId,
366
+ accountId: base.accountId,
367
+ operationId,
368
+ claimTicket: state.handoff.claimTicket,
369
+ baseUrl: state.handoff.baseUrl,
370
+ }, deps);
371
+ }
372
+ // handoff absent (re-read under lease). Artifact present (race caught) → artifact-only; else genuine not-found.
373
+ if (artifact) {
374
+ assertBoundToInvocation(artifact, base, operationId); // FINDING 2 + R2·F1
375
+ // R2·F1: even under the lease with the leaf already absent, PROVE the absence is durable — `lease.delete()`
376
+ // returns outcome:'absent' + `fsyncDir(parent)` and `assertHandoffDeleted` gates `deleteEvidenceSecure`
377
+ // (path/integrity codes propagate). R2·F2: cleanup BEFORE expiry. Consistent with the provisional+artifact branch.
378
+ assertHandoffDeleted(lease, deps);
379
+ assertNotExpired(artifact.expiresAt, deps.now);
380
+ return artifactOutput(artifact);
381
+ }
382
+ // 6) neither handoff nor artifact under the lease → not-found; NEVER mint a new operation on resume.
383
+ throw new CliError('sa_handoff_not_found');
384
+ });
385
+ }
386
+ async function saAuthorize(argv, deps) {
387
+ const parsed = parseArgv(argv, SA_SPECS.authorize);
388
+ const human = resolveHumanClient(deps.resolve); // VETO any SA principal BEFORE any fs/HTTP
389
+ const base = {
390
+ human,
391
+ serviceAccountId: parsed.positionals[0],
392
+ accountId: parsed.flags.account,
393
+ baseUrl: human.baseUrl,
394
+ };
395
+ const output = parsed.flags.handoff !== undefined
396
+ ? await saAuthorizeResume(parsed.flags.handoff, base, deps)
397
+ : await saAuthorizeFirstRun(base, deps);
398
+ deps.stdout(`${JSON.stringify(output)}\n`); // ONE JSON line, only after a successful release
399
+ return 0;
400
+ }
401
+ // ── `sa cancel` / `sa revoke-token` (remote op → receipt, gated) ────────────────────────────────────────
402
+ /** D2 — write the receipt EXCLUSIVELY, then judge the returned evidence. Collision preserved; else failure. */
403
+ function writeReceipt(receipt, deps) {
404
+ const receiptId = deps.newReceiptId();
405
+ let ev;
406
+ try {
407
+ ev = createReceipt(deps.root, receiptId, receipt, deps.fs);
408
+ }
409
+ catch (e) {
410
+ if (codeOf(e) === 'sa_store_dest_exists')
411
+ throw e; // genuine collision (new id next retry)
412
+ throw new CliError('sa_receipt_write_failed'); // any non-collision throw
413
+ }
414
+ if (!evidenceSecure(ev, deps.fs, { requireCleanTemp: true }))
415
+ throw new CliError('sa_receipt_write_failed');
416
+ return receiptId;
417
+ }
418
+ async function saCancel(argv, deps) {
419
+ const parsed = parseArgv(argv, SA_SPECS.cancel);
420
+ const human = resolveHumanClient(deps.resolve);
421
+ const serviceAccountId = parsed.positionals[0];
422
+ const credentialId = parsed.positionals[1];
423
+ const accountId = parsed.flags.account;
424
+ await human.client.saCancelCredential(serviceAccountId, credentialId, { accountId, idempotencyKey: deps.newIdempotencyKey() });
425
+ const receiptId = writeReceipt({
426
+ schemaVersion: 1,
427
+ serviceAccountId,
428
+ terminalStatus: 'cancelled',
429
+ credentialId,
430
+ terminalReason: 'admin_cancelled',
431
+ baseUrl: human.baseUrl,
432
+ createdAt: new Date(deps.now()).toISOString(),
433
+ }, deps);
434
+ deps.stdout(`${JSON.stringify({ cancelled: true, receiptId })}\n`);
435
+ return 0;
436
+ }
437
+ async function saRevokeToken(argv, deps) {
438
+ const parsed = parseArgv(argv, SA_SPECS['revoke-token']);
439
+ const human = resolveHumanClient(deps.resolve);
440
+ const serviceAccountId = parsed.positionals[0];
441
+ const patId = parsed.positionals[1];
442
+ const accountId = parsed.flags.account;
443
+ const { cryptoLocked } = await human.client.saRevokeToken(serviceAccountId, patId, { accountId, idempotencyKey: deps.newIdempotencyKey() });
444
+ const receiptId = writeReceipt({
445
+ schemaVersion: 1,
446
+ serviceAccountId,
447
+ terminalStatus: 'revoked',
448
+ patId,
449
+ cryptoLocked,
450
+ terminalReason: 'token_revoked',
451
+ baseUrl: human.baseUrl,
452
+ createdAt: new Date(deps.now()).toISOString(),
453
+ }, deps);
454
+ deps.stdout(`${JSON.stringify({ revoked: true, cryptoLocked, receiptId })}\n`);
455
+ return 0;
456
+ }
457
+ // ── `sa tokens` (read-only, no receipt, no idempotency) ─────────────────────────────────────────────────
458
+ async function saTokens(argv, deps) {
459
+ const parsed = parseArgv(argv, SA_SPECS.tokens);
460
+ const human = resolveHumanClient(deps.resolve);
461
+ const tokens = await human.client.saListTokens(parsed.positionals[0], { accountId: parsed.flags.account });
462
+ deps.stdout(`${JSON.stringify(tokens)}\n`);
463
+ return 0;
464
+ }
465
+ // Authority control env vars whose PRESENCE forbids a MACHINE bootstrap (D7). Their VALUES are never read.
466
+ // `AC_SA_SERVICE_ACCOUNT_ID` (U9b-3e-2 §10.b#7.bis) is an SA-identity signal, so its presence is forbidden too.
467
+ const MACHINE_FORBIDDEN_ENV = ['AC_TOKEN', 'AC_SA_CREDENTIAL_ID', 'AC_SA_CAP_PRIVATE_KEY_B64', 'AC_SA_SERVICE_ACCOUNT_ID', 'AC_SA_PRINCIPAL', 'AC_SA_PROFILE'];
468
+ /**
469
+ * Reject a MACHINE bootstrap if any authority control var is PRESENT (R2·FINDING 2A). Presence = an OWN property
470
+ * (`Object.hasOwn`, prototype-safe) — the VALUE is NEVER read (a getter sentinel is never triggered; an inherited
471
+ * property does not count; an own empty-string counts as present). The name/value are never printed.
472
+ */
473
+ function assertMachineIsolation(env, code = 'sa_bootstrap_env_authority_forbidden') {
474
+ for (const k of MACHINE_FORBIDDEN_ENV) {
475
+ if (Object.hasOwn(env, k))
476
+ throw new CliError(code);
477
+ }
478
+ }
479
+ /**
480
+ * Resolve the effective baseUrl (R2·FINDING 2B). The handoff baseUrl is authoritative. `AC_API_BASE_URL` is a
481
+ * non-secret config (read allowed): undefined → use the handoff; PRESENT (any defined value, incl. empty/whitespace)
482
+ * → run the SSOT `assertBaseUrlMatch` — empty/whitespace → `sa_baseurl_invalid`, different → `sa_baseurl_conflict`,
483
+ * normalize-equal → allowed. No trim/preprocess that would turn a supplied-invalid value into "absent".
484
+ */
485
+ function resolveBootstrapBaseUrl(handoffBaseUrl, env) {
486
+ const raw = env['AC_API_BASE_URL'];
487
+ if (raw === undefined)
488
+ return normalizeBaseUrl(handoffBaseUrl);
489
+ return assertBaseUrlMatch(handoffBaseUrl, raw);
490
+ }
491
+ /**
492
+ * Falsy-safe RELEASE PRECEDENCE core (U9b-4-1 · §10.c#20.1.a — post-gate R2). Runs `run()`, then attempts `release()`
493
+ * EXACTLY once, tracking presence with EXPLICIT flags (never truthiness): a functional PRIMARY throw WINS by identity
494
+ * EVEN when it is a falsy value (`undefined`/`null`/`false`/`0`/`''`); a functional SUCCESS whose `release()` fails
495
+ * collapses to `onReleaseFailure()`. `withProfileLock` is its ONLY production consumer; it is exported ONLY so the
496
+ * falsy-primary matrix can be exercised directly — a REAL profile-lock callback can never throw a falsy primary
497
+ * (`tryLoadProfile`/`createProfile`/`loadProfile`/`reclassifyAppeared` all normalize to a truthy `StoreError`/`CliError`
498
+ * — see the store `errors.ts`/`atomic-write.ts` boundaries), so that matrix is unreachable via any real command path.
499
+ */
500
+ export function withReleasePrecedence(run, release, onReleaseFailure) {
501
+ let result;
502
+ let primary;
503
+ let hasPrimary = false;
504
+ try {
505
+ result = run();
506
+ }
507
+ catch (e) {
508
+ primary = e;
509
+ hasPrimary = true;
510
+ }
511
+ let hasReleaseError = false;
512
+ try {
513
+ release(); // exactly once
514
+ }
515
+ catch {
516
+ hasReleaseError = true;
517
+ }
518
+ if (hasPrimary)
519
+ throw primary; // functional primary WINS by identity (even a falsy throw)
520
+ if (hasReleaseError)
521
+ throw onReleaseFailure(); // success + release failure → stable code
522
+ return result;
523
+ }
524
+ /**
525
+ * SSOT brief-profile-lock (U9b-4-1 · §10.c#20.1.a — consolidación falsy-safe). Acquires the per-profile lock and runs
526
+ * `fn` through {@link withReleasePrecedence} — REPLACES the former `withProfileLock` (naive `finally` that let a release
527
+ * throw MASK the primary) AND `withProfileLockChecked` (truthiness that LOST a falsy primary). Used by bootstrap, rotate
528
+ * and migrate for CREATE / re-read / classification. NEVER wrap `replaceProfile` in this lock — it takes its OWN
529
+ * internal per-profile lock (nested → `sa_profile_busy`).
530
+ */
531
+ function withProfileLock(root, name, fs, fn) {
532
+ const lock = acquireProfileLock(root, name, fs);
533
+ return withReleasePrecedence(fn, () => lock.release(), () => new StoreError('sa_profile_lock_release_failed'));
534
+ }
535
+ /** Gate a profile write's structured evidence; a non-secure result → `sa_profile_insecure` (dest never deleted). */
536
+ function assertProfileSecure(ev, fs) {
537
+ if (!evidenceSecure(ev, fs, { requireCleanTemp: true }))
538
+ throw new CliError('sa_profile_insecure');
539
+ }
540
+ /** Load the destination profile; `sa_profile_not_found` → null; corrupt/path/other → preserve the stable code. */
541
+ function tryLoadProfile(root, name, fs) {
542
+ try {
543
+ return loadProfile(root, name, fs);
544
+ }
545
+ catch (e) {
546
+ if (codeOf(e) === 'sa_profile_not_found')
547
+ return null;
548
+ throw e;
549
+ }
550
+ }
551
+ /** Common STANDARD-bootstrap envelope shared by every persisted stage. */
552
+ function bootstrapEnvelope(handoff, baseUrl) {
553
+ return {
554
+ schemaVersion: 1,
555
+ flow: 'standard',
556
+ mode: 'bootstrap',
557
+ serviceAccountId: handoff.serviceAccountId,
558
+ baseUrl,
559
+ principalType: 'service_account',
560
+ credentialId: handoff.credentialId,
561
+ };
562
+ }
563
+ /** Bind an EXISTING destination profile to this handoff (§10.c#17.5); any mismatch → `sa_bootstrap_profile_conflict`. */
564
+ function assertProfileBoundToHandoff(profile, handoff, operationId) {
565
+ const p = profile;
566
+ const baseUrlMatches = (() => {
567
+ try {
568
+ return normalizeBaseUrl(String(p.baseUrl)) === normalizeBaseUrl(handoff.baseUrl);
569
+ }
570
+ catch {
571
+ return false;
572
+ }
573
+ })();
574
+ if (p.flow !== 'standard' ||
575
+ p.mode !== 'bootstrap' ||
576
+ p.serviceAccountId !== handoff.serviceAccountId ||
577
+ !baseUrlMatches ||
578
+ p.credentialId !== handoff.credentialId ||
579
+ (p.handoffId !== undefined && p.handoffId !== operationId) // handoffId only present at capability_prepared
580
+ ) {
581
+ throw new CliError('sa_bootstrap_profile_conflict');
582
+ }
583
+ }
584
+ // ── U5 slice-3 · bootstrap adapter over the @airctrl/sdk credential-lifecycle coordinator ─────────────────
585
+ // (freshBootstrap/resumeFromProfile/activateAndFinish/finishActive were removed — the coordinator now owns the FSM.)
586
+ // The coordinator drives the logic; these adapters translate its environment-neutral `LogicalState` ↔ the frozen
587
+ // durable `Profile` (byte-for-byte), keep the existing locks/atomic-write/evidenceSecure/handoff, and map the
588
+ // domain error codes back to the CLI's. No `store/schema.ts` change: create/replaceProfile still apply the strict
589
+ // schema; the coordinator's `validateCheckpoint` is the wire (loose) layer on read.
590
+ /** Map a domain `SaCoordinatorError` to the CLI surface; deadline → ReconcileError; everything else preserved. */
591
+ async function mapCoordinatorErrors(fn) {
592
+ try {
593
+ return await fn();
594
+ }
595
+ catch (e) {
596
+ if (isSaCoordinatorError(e)) {
597
+ if (e.code === 'sa_legacy_deadline_elapsed')
598
+ throw new ReconcileError('deadline_elapsed');
599
+ throw new CliError(e.code);
600
+ }
601
+ throw e; // AirctrlError / TypeError / ReconcileError / CliError / StoreError → unchanged
602
+ }
603
+ }
604
+ /** Custody is auto-satisfied on the CLI: the coordinator persists (+ evidenceSecure) `activation_prepared` via
605
+ * `confirm` BEFORE calling this, so durability IS custody. Resolves immediately; stdout still comes post-finalize. */
606
+ const PASSIVE_CUSTODY = { confirmCustody: async () => { } };
607
+ function bsGet(p, key) {
608
+ const v = p[key];
609
+ if (typeof v !== 'string' || v.length === 0)
610
+ throw new StoreError('sa_profile_corrupt');
611
+ return v;
612
+ }
613
+ /** LogicalState → the EXACT persisted bootstrap Profile per stage (byte-for-byte with the pre-U5 CLI). */
614
+ function bootstrapLogicalToProfile(handoff, ctx, s) {
615
+ const env = bootstrapEnvelope(handoff, ctx.baseUrl);
616
+ switch (s.stage) {
617
+ case 'capability_prepared':
618
+ return { ...env, stage: 'capability_prepared', expiresAt: handoff.expiresAt, capPublicKeyB64: s.capPublicKeyB64, capPrivateKeyB64: s.capPrivateKeyB64, claimIdempotencyKey: s.claimIdempotencyKey, handoffId: ctx.operationId };
619
+ case 'claimed':
620
+ return { ...env, stage: 'claimed', expiresAt: handoff.expiresAt, capPublicKeyB64: s.capPublicKeyB64, capPrivateKeyB64: s.capPrivateKeyB64, bearer: s.bearer, patId: s.patId, popChallengeSealedB64: s.popChallengeSealedB64 };
621
+ case 'activation_prepared':
622
+ return { ...env, stage: 'activation_prepared', expiresAt: handoff.expiresAt, capPublicKeyB64: s.capPublicKeyB64, capPrivateKeyB64: s.capPrivateKeyB64, bearer: s.bearer, patId: s.patId, activationBody: s.activationBody, activateIdempotencyKey: s.activateIdempotencyKey };
623
+ case 'active':
624
+ return { ...env, stage: 'active', patId: s.patId, bearer: s.bearer, capPublicKeyB64: s.capPublicKeyB64, capPrivateKeyB64: s.capPrivateKeyB64 };
625
+ default:
626
+ throw new CliError('sa_bootstrap_not_resumable');
627
+ }
628
+ }
629
+ /** Persisted bootstrap Profile → the EXACT LogicalState (exact-own key set the coordinator's validateCheckpoint expects). */
630
+ function bootstrapProfileToLogical(p) {
631
+ const base = { flow: 'bootstrap', serviceAccountId: p.serviceAccountId, baseUrl: bsGet(p, 'baseUrl'), credentialId: bsGet(p, 'credentialId') };
632
+ switch (p.stage) {
633
+ case 'capability_prepared':
634
+ return { ...base, stage: 'capability_prepared', capPublicKeyB64: bsGet(p, 'capPublicKeyB64'), capPrivateKeyB64: bsGet(p, 'capPrivateKeyB64'), claimIdempotencyKey: bsGet(p, 'claimIdempotencyKey') };
635
+ case 'claimed':
636
+ return { ...base, stage: 'claimed', capPublicKeyB64: bsGet(p, 'capPublicKeyB64'), capPrivateKeyB64: bsGet(p, 'capPrivateKeyB64'), bearer: bsGet(p, 'bearer'), patId: bsGet(p, 'patId'), popChallengeSealedB64: bsGet(p, 'popChallengeSealedB64') };
637
+ case 'activation_prepared':
638
+ return { ...base, stage: 'activation_prepared', capPublicKeyB64: bsGet(p, 'capPublicKeyB64'), capPrivateKeyB64: bsGet(p, 'capPrivateKeyB64'), bearer: bsGet(p, 'bearer'), patId: bsGet(p, 'patId'), activationBody: p.activationBody, activateIdempotencyKey: bsGet(p, 'activateIdempotencyKey') };
639
+ case 'active':
640
+ return { ...base, stage: 'active', capPublicKeyB64: bsGet(p, 'capPublicKeyB64'), capPrivateKeyB64: bsGet(p, 'capPrivateKeyB64'), bearer: bsGet(p, 'bearer'), patId: bsGet(p, 'patId') };
641
+ default:
642
+ throw new CliError('sa_bootstrap_not_resumable'); // terminal / unexpected own-stage
643
+ }
644
+ }
645
+ /** The bootstrap CheckpointPort: read = classify (under brief lock + binding + expiry); confirm = create/replace
646
+ * via the frozen store primitives; finalizeActive keeps the active profile; discardTransient deletes the handoff. */
647
+ function makeBootstrapCheckpoint(deps, ctx, handoff, lease) {
648
+ let created = false;
649
+ return {
650
+ async read() {
651
+ const existing = withProfileLock(deps.root, ctx.profileName, deps.fs, () => tryLoadProfile(deps.root, ctx.profileName, deps.fs));
652
+ if (!existing) {
653
+ assertNotExpired(handoff.expiresAt, deps.now); // fresh: expiry gate BEFORE create/claim (§17.3)
654
+ return null;
655
+ }
656
+ assertProfileBoundToHandoff(existing, handoff, ctx.operationId); // binding gate BEFORE ignoring expiry on active
657
+ if (existing.stage === 'activation_prepared')
658
+ assertNotExpired(bsGet(existing, 'expiresAt'), deps.now); // resume expiry (not for active)
659
+ return bootstrapProfileToLogical(existing);
660
+ },
661
+ async confirm(s) {
662
+ const profile = bootstrapLogicalToProfile(handoff, ctx, s);
663
+ if (s.stage === 'capability_prepared' && !created) {
664
+ // CREATE under a BRIEF lock with a re-read (§17.3): a destination that APPEARED between `read()` (absent) and
665
+ // now — while `newBootstrap` ran — cannot be this handoff (the handoff lease is held). It is a profile
666
+ // CONFLICT (F1): fail closed with `sa_bootstrap_profile_conflict`, NEVER overwrite (no createProfile), never
667
+ // leak `sa_store_dest_exists`. The appeared profile + handoff stay intact; claim/activate/stdout do not run.
668
+ const ev = withProfileLock(deps.root, ctx.profileName, deps.fs, () => {
669
+ if (tryLoadProfile(deps.root, ctx.profileName, deps.fs))
670
+ throw new CliError('sa_bootstrap_profile_conflict');
671
+ return createProfile(deps.root, ctx.profileName, profile, deps.fs);
672
+ });
673
+ assertProfileSecure(ev, deps.fs); // gate AFTER releasing the lock; insecure → sa_profile_insecure
674
+ created = true;
675
+ }
676
+ else {
677
+ const from = s.stage === 'claimed' ? 'capability_prepared' : 'claimed'; // activation_prepared ← claimed
678
+ assertProfileSecure(replaceProfile(deps.root, ctx.profileName, from, profile, deps.fs), deps.fs);
679
+ }
680
+ },
681
+ async finalizeActive(s) {
682
+ const profile = bootstrapLogicalToProfile(handoff, ctx, s);
683
+ assertProfileSecure(replaceProfile(deps.root, ctx.profileName, 'activation_prepared', profile, deps.fs), deps.fs);
684
+ },
685
+ async discardTransient() {
686
+ assertHandoffDeleted(lease, deps); // consume the handoff durably (unlink + fsyncDir); residual/insecure → cleanup-pending
687
+ },
688
+ };
689
+ }
690
+ /** The bootstrap CoordinatorRuntime — SDK/crypto/HTTP seams from `SaDeps`; confirm-active by durability (no status HTTP). */
691
+ function makeBootstrapRuntime(ctx, deps) {
692
+ return {
693
+ prepareBootstrap: deps.newBootstrap,
694
+ prepareCapability: deps.newCapability,
695
+ bootstrapClaimClient: deps.makeBootstrapClaimClient({ baseUrl: ctx.baseUrl }),
696
+ resolveHolder: () => {
697
+ throw new CliError('sa_bootstrap_not_resumable');
698
+ },
699
+ makeClient: deps.makeClient,
700
+ newIdempotencyKey: deps.newIdempotencyKey,
701
+ now: deps.now,
702
+ confirmActivation: async () => true, // durable host: activate success + durable checkpoint IS the confirmation
703
+ };
704
+ }
705
+ async function saBootstrap(argv, deps) {
706
+ const parsed = parseArgv(argv, SA_SPECS.bootstrap); // parse FIRST (before env), then required flags
707
+ assertMachineIsolation(deps.env); // reject authority env presence BEFORE any fs/HTTP (never reads values)
708
+ const operationId = parsed.flags.handoff;
709
+ const profileName = parsed.flags.profile;
710
+ assertHandoffId(operationId); // validate the selector before building any managed path
711
+ const lease = acquireHandoffLease(deps.root, operationId, deps.fs); // handoff lease FIRST (fail-fast, no wait)
712
+ const output = await withLease(lease, async () => {
713
+ const state = tryReadState(lease);
714
+ if (!state)
715
+ throw new CliError('sa_handoff_not_found'); // absent (rotation artifact of same selector NOT consumed)
716
+ if (state.phase !== 'finalized')
717
+ throw new CliError('sa_handoff_not_finalized'); // provisional → authorize incompleto
718
+ const handoff = state.handoff;
719
+ if (handoff.operationId !== operationId)
720
+ throw new CliError('sa_handoff_binding_mismatch');
721
+ const baseUrl = resolveBootstrapBaseUrl(handoff.baseUrl, deps.env); // handoff authoritative; AC_API_BASE_URL match (before write/HTTP)
722
+ const ctx = { baseUrl, profileName, operationId };
723
+ const binding = { flow: 'bootstrap', serviceAccountId: handoff.serviceAccountId, baseUrl, credentialId: handoff.credentialId, bootstrapClaimTicket: handoff.claimTicket };
724
+ const result = await mapCoordinatorErrors(() => runCredentialLifecycle(binding, makeBootstrapRuntime(ctx, deps), { checkpoint: makeBootstrapCheckpoint(deps, ctx, handoff, lease), custody: PASSIVE_CUSTODY }));
725
+ return { profile: profileName, serviceAccountId: result.serviceAccountId, credentialId: result.credentialId, patId: result.patId, stage: 'active' };
726
+ });
727
+ deps.stdout(`${JSON.stringify(output)}\n`); // ONE JSON line, only after a successful lease release
728
+ return 0;
729
+ }
730
+ // ── `sa verify` — MACHINE/HOLDER unlock-only (§10.c#18.8) ───────────────────────────────────────────────
731
+ /**
732
+ * Prove a service account's ACTIVE credential can cryptographically open its sealed activation payload — nothing
733
+ * else. Parse strict FIRST; resolve the principal EXACTLY once; admit ONLY an SA with a live sealed capability
734
+ * (`principalKind==='sa' && saCredentialMode==='sealed'` — `sa_env_active` / STANDARD active / LEGACY active). Any
735
+ * other resolved principal (human, `sa_env_legacy`, LEGACY pre-migration) → `sa_verify_requires_active_credential`;
736
+ * `none`/pending/prepared/terminal/invalid keep the code `resolveClient` already throws (never remapped). Runs
737
+ * `unlock()` exactly once (service mode, no vault password), discards the Session, and never reads records / writes
738
+ * the store / takes a lock / prompts. Success prints EXACTLY one JSON line `{"ok":true}`; any failure → zero stdout +
739
+ * the stable boundary. `pat_expired` (401) during `/me/crypto-material` → `sa_reconciliation_required reason=pat_expired`.
740
+ */
741
+ async function saVerify(argv, deps) {
742
+ const parsed = parseArgv(argv, SA_SPECS.verify); // strict parse BEFORE any resolution; `--profile` is the only accepted flag
743
+ const rc = resolveClient({ ...deps.resolve, profileFlag: parsed.flags.profile }); // resolve principal EXACTLY once
744
+ if (rc.principalKind !== 'sa' || rc.saCredentialMode !== 'sealed') {
745
+ throw new CliError('sa_verify_requires_active_credential'); // human / sa_env_legacy / LEGACY pre-migration
746
+ }
747
+ await withPatExpired(rc, () => rc.client.unlock()); // service-mode unlock ONCE; Session discarded (no persist/read/write)
748
+ deps.stdout(`${JSON.stringify({ ok: true })}\n`); // ONE JSON line, only after a successful unlock
749
+ return 0;
750
+ }
751
+ // ── `sa status` — MACHINE/HOLDER remote status read (§10.c#18.7) ─────────────────────────────────────────
752
+ /**
753
+ * Read a credential's OWN remote status. Parse strict FIRST; resolve the status principal EXACTLY once
754
+ * (`resolveStatusPrincipal`, NOT `resolveClient` — which rejects the pending stages status admits). The resolved
755
+ * client is typed as the minimal `StatusClient` surface (only `saGetCredentialStatus`), built with `baseUrl + auth`
756
+ * and no capability → it cannot unlock/read records by type. Runs exactly one
757
+ * `saGetCredentialStatus(serviceAccountId, credentialId)` wrapped by the `pat_expired` SSOT, then prints the SDK
758
+ * result VERBATIM (`{status, credentialFlow, expiresAt, activatedAt?}`) — one JSON line — ONLY after success. No
759
+ * `expiresAt` prevalidation (the remote status is authoritative), no unlock, no record reads, no store
760
+ * writes/locks/leases/prompt. `pat_expired` (401) → `sa_reconciliation_required reason=pat_expired`; any other
761
+ * failure → zero stdout + the stable boundary.
762
+ */
763
+ async function saStatus(argv, deps) {
764
+ const parsed = parseArgv(argv, SA_SPECS.status); // strict parse BEFORE any resolution; `--profile` is the only accepted flag
765
+ const rc = resolveStatusPrincipal({ ...deps.resolve, profileFlag: parsed.flags.profile }); // resolve status principal EXACTLY once
766
+ const result = await withPatExpired(rc, () => rc.client.saGetCredentialStatus(rc.serviceAccountId, rc.credentialId)); // ONE call
767
+ deps.stdout(`${JSON.stringify(result)}\n`); // verbatim SDK shape; ONE JSON line, only after success
768
+ return 0;
769
+ }
770
+ /** Bind a receipt to a profile (D2). Any mismatch → `sa_receipt_mismatch`; values never echoed. */
771
+ function bindReceiptToProfile(receipt, profile) {
772
+ const p = profile;
773
+ const baseEqual = (a, b) => {
774
+ try {
775
+ return normalizeBaseUrl(a) === normalizeBaseUrl(b);
776
+ }
777
+ catch {
778
+ return false;
779
+ }
780
+ };
781
+ if (receipt.serviceAccountId !== profile.serviceAccountId)
782
+ throw new CliError('sa_receipt_mismatch');
783
+ if (!baseEqual(receipt.baseUrl, profile.baseUrl))
784
+ throw new CliError('sa_receipt_mismatch');
785
+ if (receipt.terminalStatus === 'cancelled') {
786
+ if (receipt.credentialId !== p.credentialId)
787
+ throw new CliError('sa_receipt_mismatch');
788
+ }
789
+ else {
790
+ // revoke: the profile MUST carry a patId, and it MUST equal the receipt's (§D2).
791
+ if (typeof p.patId !== 'string' || p.patId.length === 0 || receipt.patId !== p.patId)
792
+ throw new CliError('sa_receipt_mismatch');
793
+ }
794
+ }
795
+ /** Build the EXPECTED terminal document from the CURRENT profile + receipt (D2); compared by canonical equality. */
796
+ function buildExpectedTerminal(profile, receipt) {
797
+ const p = profile;
798
+ const terminal = {
799
+ schemaVersion: p.schemaVersion,
800
+ flow: profile.flow,
801
+ stage: 'terminal',
802
+ serviceAccountId: profile.serviceAccountId,
803
+ baseUrl: profile.baseUrl,
804
+ principalType: p.principalType,
805
+ credentialId: p.credentialId,
806
+ terminalStatus: receipt.terminalStatus,
807
+ terminalReason: receipt.terminalReason,
808
+ };
809
+ if (profile.flow === 'standard')
810
+ terminal.mode = p.mode; // STANDARD envelope carries `mode`
811
+ if (receipt.terminalStatus === 'revoked')
812
+ terminal.patId = receipt.patId; // cancel terminal carries NO patId
813
+ return terminal;
814
+ }
815
+ /** Gate a durable profile delete's evidence (§18.9); insecure durability → `sa_profile_cleanup_pending`. */
816
+ function gateProfileDelete(result, deps) {
817
+ if (!deleteEvidenceSecure(result, deps.fs))
818
+ throw new CliError('sa_profile_cleanup_pending');
819
+ }
820
+ /** Bind a finalized handoff to a receipt up front (operationId/SA/baseUrl; cancel also credentialId) — §D5. */
821
+ function bindHandoffToReceipt(handoff, receipt, operationId) {
822
+ const baseEqual = (a, b) => {
823
+ try {
824
+ return normalizeBaseUrl(a) === normalizeBaseUrl(b);
825
+ }
826
+ catch {
827
+ return false;
828
+ }
829
+ };
830
+ if (handoff.operationId !== operationId)
831
+ throw new CliError('sa_handoff_binding_mismatch');
832
+ if (handoff.serviceAccountId !== receipt.serviceAccountId)
833
+ throw new CliError('sa_handoff_binding_mismatch');
834
+ if (!baseEqual(handoff.baseUrl, receipt.baseUrl))
835
+ throw new CliError('sa_handoff_binding_mismatch');
836
+ // cancel: the handoff's credentialId must equal the receipt's; revoke has NO receipt.credentialId to compare.
837
+ if (receipt.terminalStatus === 'cancelled' && handoff.credentialId !== receipt.credentialId) {
838
+ throw new CliError('sa_handoff_binding_mismatch');
839
+ }
840
+ }
841
+ /** Bind a finalized handoff to the (re-read) profile: SA/baseUrl/credentialId — §D5. */
842
+ function bindHandoffToProfile(handoff, profile) {
843
+ const p = profile;
844
+ const baseEqual = (() => {
845
+ try {
846
+ return normalizeBaseUrl(handoff.baseUrl) === normalizeBaseUrl(profile.baseUrl);
847
+ }
848
+ catch {
849
+ return false;
850
+ }
851
+ })();
852
+ if (handoff.serviceAccountId !== profile.serviceAccountId)
853
+ throw new CliError('sa_handoff_binding_mismatch');
854
+ if (!baseEqual)
855
+ throw new CliError('sa_handoff_binding_mismatch');
856
+ if (handoff.credentialId !== p.credentialId)
857
+ throw new CliError('sa_handoff_binding_mismatch');
858
+ }
859
+ /**
860
+ * Classify a LOCKED profile against the receipt (+ optional handoff): `'delete'` iff it is the canonical exact
861
+ * terminal, `'not_terminal'` if still non-terminal (the caller re-drives), or THROW `sa_receipt_mismatch` for a
862
+ * substituted/contrary terminal. Runs UNDER `deleteProfileUnderLock`'s lock, so the decision and the unlink are
863
+ * atomic (F1 TOCTOU-safe). `expectedTerminal` is rebuilt from the fresh locked read.
864
+ */
865
+ function makeClassify(receipt, bindHandoff) {
866
+ return (profile) => {
867
+ bindReceiptToProfile(receipt, profile);
868
+ bindHandoff(profile);
869
+ if (profile.stage !== 'terminal')
870
+ return 'not_terminal';
871
+ if (canonicalJson(profile) === canonicalJson(buildExpectedTerminal(profile, receipt)))
872
+ return 'delete';
873
+ throw new CliError('sa_receipt_mismatch');
874
+ };
875
+ }
876
+ /**
877
+ * Drive the profile to `terminal` (bounded reclassification via a `Set` of observed non-terminal stages — no ordinal
878
+ * map, no magic retry count; `assertTransition` inside `replaceProfile` is the SSOT of legality) then atomically
879
+ * validate-exact + delete it under a SINGLE profile lock (§18.9, F1). `deleteProfileUnderLock` owns the lock across the
880
+ * exact re-read, the handoff durable-delete (`beforeDelete`, handoff mode) and the profile durable-delete — so no
881
+ * process can substitute the terminal between the check and the unlink. Lock order: handoff lease → profile lock →
882
+ * handoff delete → profile delete → profile unlock (finally) → handoff lease release (`withLease`) → stdout. Crash
883
+ * window: after the handoff delete, if the profile delete is not durable/crashes, the retry is reconcilable — handoff
884
+ * absent + terminal exact completes the profile delete; an already-unlinked profile yields `profile_absent`. Receipt
885
+ * always retained.
886
+ */
887
+ function terminalizeThenDelete(name, receipt, deps, mode, bindHandoff, beforeDelete) {
888
+ const classify = makeClassify(receipt, bindHandoff);
889
+ const seen = new Set();
890
+ for (;;) {
891
+ const res = deleteProfileUnderLock(deps.root, name, classify, beforeDelete, deps.fs);
892
+ if (res.outcome === 'absent')
893
+ return { reconciled: false, reason: 'profile_absent' };
894
+ if (res.outcome === 'deleted') {
895
+ gateProfileDelete(res.result, deps);
896
+ return { reconciled: true, mode, receiptRetained: true };
897
+ }
898
+ // 'not_terminal' → drive the profile toward terminal (bounded), then re-run the atomic validate-exact + delete.
899
+ let profile;
900
+ try {
901
+ profile = loadProfile(deps.root, name, deps.fs);
902
+ }
903
+ catch (e) {
904
+ if (codeOf(e) === 'sa_profile_not_found')
905
+ return { reconciled: false, reason: 'profile_absent' };
906
+ throw e; // corrupt/path preserved
907
+ }
908
+ if (profile.stage === 'terminal')
909
+ continue; // raced back to terminal → re-run the atomic delete
910
+ bindReceiptToProfile(receipt, profile); // validate before mutating (re-checked under the lock in classify)
911
+ bindHandoff(profile);
912
+ if (seen.has(profile.stage))
913
+ throw new StoreError('sa_profile_unexpected_state'); // repeated/non-monotonic → fail-closed
914
+ seen.add(profile.stage);
915
+ try {
916
+ assertProfileSecure(replaceProfile(deps.root, name, profile.stage, buildExpectedTerminal(profile, receipt), deps.fs), deps.fs);
917
+ }
918
+ catch (e) {
919
+ if (codeOf(e) === 'sa_profile_unexpected_state' || codeOf(e) === 'sa_profile_not_found')
920
+ continue; // raced → re-classify
921
+ throw e; // transition_invalid / path / corrupt / evidence propagate
922
+ }
923
+ // profile now terminal → loop → deleteProfileUnderLock validates-exact + deletes atomically
924
+ }
925
+ }
926
+ /** LOCAL reconcile: no lease, receipt loaded first. */
927
+ function reconcileLocal(name, receiptId, deps) {
928
+ const receipt = loadReceipt(deps.root, receiptId, deps.fs); // missing → sa_receipt_not_found; corrupt → sa_receipt_corrupt
929
+ return terminalizeThenDelete(name, receipt, deps, 'local', () => undefined, () => undefined);
930
+ }
931
+ /** HANDOFF reconcile: handoff lease FIRST; receipt loaded AFTER the lease; handoff durable-deleted before the profile. */
932
+ async function reconcileHandoff(name, receiptId, operationId, deps) {
933
+ const lease = acquireHandoffLease(deps.root, operationId, deps.fs); // validates the selector; O_EXCL fail-fast
934
+ return withLease(lease, async () => {
935
+ const receipt = loadReceipt(deps.root, receiptId, deps.fs); // after the lease → sa_receipt_not_found is the primary
936
+ const state = tryReadState(lease);
937
+ if (state === null) {
938
+ // Handoff ABSENT → validate-exact + delete the profile atomically under its lock (no handoff to delete).
939
+ const res = deleteProfileUnderLock(deps.root, name, makeClassify(receipt, () => undefined), () => undefined, deps.fs);
940
+ if (res.outcome === 'absent')
941
+ return { reconciled: false, reason: 'profile_absent' };
942
+ if (res.outcome === 'not_terminal')
943
+ return { reconciled: false, reason: 'handoff_absent' }; // non-terminal + handoff required absent
944
+ gateProfileDelete(res.result, deps);
945
+ return { reconciled: true, mode: 'handoff', receiptRetained: true };
946
+ }
947
+ if (state.phase === 'provisional')
948
+ throw new CliError('sa_handoff_state_inconsistent'); // no credentialId → cannot reconcile a remote receipt
949
+ const handoff = state.handoff; // finalized; `expired:true` does NOT block reconciliation
950
+ bindHandoffToReceipt(handoff, receipt, operationId);
951
+ return terminalizeThenDelete(name, receipt, deps, 'handoff', (p) => bindHandoffToProfile(handoff, p), () => assertHandoffDeleted(lease, deps));
952
+ });
953
+ }
954
+ async function saReconcile(argv, deps) {
955
+ const parsed = parseArgv(argv, SA_SPECS.reconcile); // strict parse BEFORE any store access; no principal resolution
956
+ const name = parsed.flags.profile;
957
+ const receiptId = parsed.flags.receipt;
958
+ const operationId = parsed.flags.handoff;
959
+ const output = operationId !== undefined
960
+ ? await reconcileHandoff(name, receiptId, operationId, deps)
961
+ : reconcileLocal(name, receiptId, deps);
962
+ deps.stdout(`${JSON.stringify(output)}\n`); // ONE JSON line; reconciled:false is a valid exit-0 outcome
963
+ return 0;
964
+ }
965
+ /** Normalize-equal two baseUrls; any parse failure → not equal (fail-closed). */
966
+ function baseUrlEq(a, b) {
967
+ try {
968
+ return normalizeBaseUrl(a) === normalizeBaseUrl(b);
969
+ }
970
+ catch {
971
+ return false;
972
+ }
973
+ }
974
+ /** Resolve the effective baseUrl for rotate. The artifact baseUrl is authoritative; `AC_API_BASE_URL` (non-secret)
975
+ * is accepted ONLY if it normalize-matches (empty/whitespace → `sa_baseurl_invalid`, different → `sa_baseurl_conflict`). */
976
+ function resolveRotationBaseUrl(artifactBaseUrl, env) {
977
+ const raw = env['AC_API_BASE_URL'];
978
+ if (raw === undefined)
979
+ return normalizeBaseUrl(artifactBaseUrl);
980
+ return assertBaseUrlMatch(artifactBaseUrl, raw);
981
+ }
982
+ /**
983
+ * §18.4 · resolve the residual handoff × rotation artifact UNDER the operation lease → the bound artifact that drives
984
+ * the rotation, or a stable code. A COMPATIBLE residual provisional handoff is durably consumed BEFORE any HTTP; an
985
+ * incompatible/finalized handoff, or a missing/settled-inconsistent artifact, is fail-closed. `commitRotation` writes
986
+ * the artifact then deletes the provisional handoff, so a residual provisional + valid artifact is a normal replay.
987
+ */
988
+ function resolveRotationArtifact(state, artifact, operationId, lease, deps) {
989
+ if (!artifact)
990
+ throw new CliError('sa_rotation_artifact_not_found'); // present handoff never authorizes deleting it
991
+ if (artifact.operationId !== operationId)
992
+ throw new CliError('sa_handoff_binding_mismatch'); // selector ↔ content
993
+ if (!state)
994
+ return artifact; // handoff absent (settled) → drive rotation from the artifact
995
+ if (state.phase === 'finalized')
996
+ throw new CliError('sa_handoff_state_inconsistent'); // bootstrap-finalized ⊥ rotation
997
+ const h = state.handoff; // provisional residual: must be compatible with the artifact+invocation
998
+ const compatible = h.operationId === artifact.operationId && h.serviceAccountId === artifact.serviceAccountId && baseUrlEq(h.baseUrl, artifact.baseUrl);
999
+ if (!compatible)
1000
+ throw new CliError('sa_handoff_binding_mismatch');
1001
+ assertHandoffDeleted(lease, deps); // durable cleanup of the residual sensitive provisional BEFORE any unlock/claim/activate
1002
+ return artifact;
1003
+ }
1004
+ /** Classify an EXISTING profile B against the artifact (fail-closed). A profile occupying B's name that is not a
1005
+ * rotation for THIS artifact → `sa_rotation_profile_conflict`; a pending B binds serviceAccountId+baseUrl+credentialId+expiresAt. */
1006
+ function classifyB(profile, artifact) {
1007
+ const p = profile;
1008
+ if (p.flow !== 'standard' || p.mode !== 'rotation')
1009
+ throw new CliError('sa_rotation_profile_conflict');
1010
+ if (profile.serviceAccountId !== artifact.serviceAccountId)
1011
+ throw new CliError('sa_rotation_profile_conflict');
1012
+ if (p.credentialId !== artifact.credentialId)
1013
+ throw new CliError('sa_rotation_profile_conflict');
1014
+ if (!baseUrlEq(profile.baseUrl, artifact.baseUrl))
1015
+ throw new CliError('sa_baseurl_conflict');
1016
+ const stage = profile.stage;
1017
+ if (stage === 'active') {
1018
+ if (p.operationId !== artifact.operationId)
1019
+ throw new CliError('sa_rotation_profile_conflict'); // D6 completion binding
1020
+ return { kind: 'active' }; // active drops expiresAt/holder refs; carries operationId
1021
+ }
1022
+ if (stage === 'capability_prepared' || stage === 'claimed' || stage === 'activation_prepared') {
1023
+ if (p.expiresAt !== artifact.expiresAt)
1024
+ throw new CliError('sa_rotation_profile_conflict'); // pending deadline is bound + immutable
1025
+ return { kind: 'pending', stage };
1026
+ }
1027
+ throw new CliError('sa_rotation_profile_conflict'); // terminal / unexpected
1028
+ }
1029
+ /** A pending B that already persists holder refs must match the resolved holder A exactly (values never echoed). */
1030
+ function assertHolderRefsMatch(profile, holder) {
1031
+ const p = profile;
1032
+ if (p.holderProfileName !== holder.profileName)
1033
+ throw new CliError('sa_holder_binding_mismatch');
1034
+ if (p.holderCredentialId !== holder.credentialId)
1035
+ throw new CliError('sa_holder_binding_mismatch');
1036
+ }
1037
+ /** The rotation envelope shared by every persisted B stage (holder refs / expiresAt / stage material added per stage). */
1038
+ function rotationEnvelope(ctx) {
1039
+ return {
1040
+ schemaVersion: 1,
1041
+ flow: 'standard',
1042
+ mode: 'rotation',
1043
+ serviceAccountId: ctx.artifact.serviceAccountId,
1044
+ baseUrl: ctx.baseUrl,
1045
+ principalType: 'service_account',
1046
+ credentialId: ctx.artifact.credentialId,
1047
+ };
1048
+ }
1049
+ function rotateOutput(ctx, patId) {
1050
+ return { profile: ctx.profileName, serviceAccountId: ctx.artifact.serviceAccountId, credentialId: ctx.artifact.credentialId, patId, stage: 'active' };
1051
+ }
1052
+ /** Durable-delete the rotation artifact by operationId (§18.5). Operational unlink OR insecure durability →
1053
+ * `sa_rotation_cleanup_pending`; path/integrity preserved. IDEMPOTENT: an already-absent leaf still flushes the
1054
+ * parent EXACTLY once (`durableDelete` outcome:'absent' + one `fsyncDir(dirname)`) and completes iff secure — so a
1055
+ * crash after the unlink but before stdout/release is recoverable (F1). */
1056
+ function durableAbsenceOrCleanup(root, operationId, deps) {
1057
+ let result;
1058
+ try {
1059
+ result = deleteRotationArtifact(root, operationId, deps.fs);
1060
+ }
1061
+ catch (e) {
1062
+ if (codeOf(e) === 'sa_store_io_error')
1063
+ throw new CliError('sa_rotation_cleanup_pending');
1064
+ throw e; // path/integrity preserved; unknown → boundary cli_internal_error
1065
+ }
1066
+ if (!deleteEvidenceSecure(result, deps.fs))
1067
+ throw new CliError('sa_rotation_cleanup_pending');
1068
+ }
1069
+ function cleanupRotationArtifact(ctx, deps) {
1070
+ durableAbsenceOrCleanup(deps.root, ctx.operationId, deps);
1071
+ }
1072
+ /**
1073
+ * F1 · completion recovery. When the artifact is ABSENT, a rotation `active` B carrying THIS `operationId` (D6) proves
1074
+ * the rotation finished (the artifact was durably unlinked) but stdout/lease-release was interrupted → recover. A
1075
+ * DIFFERENT operationId → `sa_rotation_profile_conflict` (NEVER adopt another operation's B). Any non-rotation /
1076
+ * non-active profile → null (the caller yields `sa_rotation_artifact_not_found`, fail-closed).
1077
+ */
1078
+ function classifyCompletion(profile, operationId) {
1079
+ const p = profile;
1080
+ if (p.flow !== 'standard' || p.mode !== 'rotation' || profile.stage !== 'active')
1081
+ return null;
1082
+ if (p.operationId !== operationId)
1083
+ throw new CliError('sa_rotation_profile_conflict');
1084
+ return { profile };
1085
+ }
1086
+ function completionOutput(profile, profileName) {
1087
+ const p = profile;
1088
+ return { profile: profileName, serviceAccountId: profile.serviceAccountId, credentialId: String(p.credentialId), patId: String(p.patId), stage: 'active' };
1089
+ }
1090
+ /** Resolve holder A EXACTLY once and validate its binding to the artifact/B BEFORE any unlock/HTTP (§18.3.7 · F2/F3):
1091
+ * `--holder-profile` required; A STANDARD-active; same SA; same baseUrl (normalize). NO unlock here. */
1092
+ function resolveAndBindHolder(holderFlag, ctx, deps) {
1093
+ if (holderFlag === undefined)
1094
+ throw new CliError('sa_holder_profile_required');
1095
+ const holder = resolveHolderProfile({ ...deps.resolve, profileFlag: holderFlag });
1096
+ if (holder.serviceAccountId !== ctx.artifact.serviceAccountId)
1097
+ throw new CliError('sa_holder_binding_mismatch');
1098
+ if (!baseUrlEq(holder.baseUrl, ctx.baseUrl))
1099
+ throw new CliError('sa_baseurl_conflict'); // holder ↔ artifact env binding
1100
+ return holder;
1101
+ }
1102
+ /** Unlock holder A's service Session EXACTLY once (pat_expired → reconciliation). Called ONLY after every binding
1103
+ * check passed — no profile lock is ever held during the unlock. */
1104
+ async function unlockHolder(holder) {
1105
+ return (await withPatExpired({ principalKind: 'sa' }, () => holder.client.unlock()));
1106
+ }
1107
+ function rotationHolderRefs(hst) {
1108
+ if (!hst.resolved)
1109
+ throw new CliError('sa_rotation_not_resumable'); // holder resolved before its refs are persisted
1110
+ return { holderProfileName: hst.resolved.profileName, holderCredentialId: hst.resolved.credentialId };
1111
+ }
1112
+ /** LogicalState → the EXACT persisted rotation Profile per stage (byte-for-byte with the pre-U5 CLI). */
1113
+ function rotationLogicalToProfile(ctx, hst, s) {
1114
+ const env = rotationEnvelope(ctx);
1115
+ switch (s.stage) {
1116
+ case 'capability_prepared':
1117
+ return { ...env, stage: 'capability_prepared', expiresAt: ctx.artifact.expiresAt, capPublicKeyB64: s.capPublicKeyB64, capPrivateKeyB64: s.capPrivateKeyB64, claimIdempotencyKey: s.claimIdempotencyKey, ...rotationHolderRefs(hst) };
1118
+ case 'claimed':
1119
+ return { ...env, stage: 'claimed', expiresAt: ctx.artifact.expiresAt, capPublicKeyB64: s.capPublicKeyB64, capPrivateKeyB64: s.capPrivateKeyB64, bearer: s.bearer, patId: s.patId, popChallengeSealedB64: s.popChallengeSealedB64, saIdentityPublicKeyB64: s.saIdentityPublicKeyB64, ...rotationHolderRefs(hst) };
1120
+ case 'activation_prepared':
1121
+ return { ...env, stage: 'activation_prepared', expiresAt: ctx.artifact.expiresAt, capPublicKeyB64: s.capPublicKeyB64, capPrivateKeyB64: s.capPrivateKeyB64, bearer: s.bearer, patId: s.patId, activationBody: s.activationBody, activateIdempotencyKey: s.activateIdempotencyKey, ...rotationHolderRefs(hst) };
1122
+ case 'active':
1123
+ return { ...env, stage: 'active', patId: s.patId, bearer: s.bearer, capPublicKeyB64: s.capPublicKeyB64, capPrivateKeyB64: s.capPrivateKeyB64, operationId: ctx.operationId };
1124
+ default:
1125
+ throw new CliError('sa_rotation_not_resumable');
1126
+ }
1127
+ }
1128
+ /** Persisted rotation Profile → the EXACT LogicalState (exact-own key set the coordinator's validateCheckpoint expects). */
1129
+ function rotationProfileToLogical(p) {
1130
+ const base = { flow: 'rotation', serviceAccountId: p.serviceAccountId, baseUrl: bsGet(p, 'baseUrl'), credentialId: bsGet(p, 'credentialId') };
1131
+ switch (p.stage) {
1132
+ case 'capability_prepared':
1133
+ return { ...base, stage: 'capability_prepared', capPublicKeyB64: bsGet(p, 'capPublicKeyB64'), capPrivateKeyB64: bsGet(p, 'capPrivateKeyB64'), claimIdempotencyKey: bsGet(p, 'claimIdempotencyKey') };
1134
+ case 'claimed':
1135
+ return { ...base, stage: 'claimed', capPublicKeyB64: bsGet(p, 'capPublicKeyB64'), capPrivateKeyB64: bsGet(p, 'capPrivateKeyB64'), bearer: bsGet(p, 'bearer'), patId: bsGet(p, 'patId'), popChallengeSealedB64: bsGet(p, 'popChallengeSealedB64'), saIdentityPublicKeyB64: bsGet(p, 'saIdentityPublicKeyB64') };
1136
+ case 'activation_prepared':
1137
+ return { ...base, stage: 'activation_prepared', capPublicKeyB64: bsGet(p, 'capPublicKeyB64'), capPrivateKeyB64: bsGet(p, 'capPrivateKeyB64'), bearer: bsGet(p, 'bearer'), patId: bsGet(p, 'patId'), activationBody: p.activationBody, activateIdempotencyKey: bsGet(p, 'activateIdempotencyKey') };
1138
+ case 'active':
1139
+ return { ...base, stage: 'active', capPublicKeyB64: bsGet(p, 'capPublicKeyB64'), capPrivateKeyB64: bsGet(p, 'capPrivateKeyB64'), bearer: bsGet(p, 'bearer'), patId: bsGet(p, 'patId') };
1140
+ default:
1141
+ throw new CliError('sa_rotation_profile_conflict'); // terminal / unexpected
1142
+ }
1143
+ }
1144
+ function makeRotateCheckpoint(deps, ctx, hst) {
1145
+ let created = false;
1146
+ return {
1147
+ async read() {
1148
+ // Read + classifyB INSIDE the brief lock (§18 · F4 precedence): a binding-conflict primary must win by identity
1149
+ // over a lock-release failure (withProfileLock gives the fn's error priority).
1150
+ const found = withProfileLock(deps.root, ctx.profileName, deps.fs, () => {
1151
+ const p = tryLoadProfile(deps.root, ctx.profileName, deps.fs);
1152
+ return p ? { profile: p, cls: classifyB(p, ctx.artifact) } : null;
1153
+ });
1154
+ if (!found) {
1155
+ assertNotExpired(ctx.artifact.expiresAt, deps.now); // fresh: EARLY expiry gate (before holder resolve + keygen)
1156
+ return null;
1157
+ }
1158
+ if (found.cls.kind === 'pending')
1159
+ assertNotExpired(ctx.artifact.expiresAt, deps.now); // resume expiry BEFORE holder/unlock
1160
+ hst.loadedProfile = found.profile; // for the resume holder-ref check at unlock time
1161
+ return rotationProfileToLogical(found.profile);
1162
+ },
1163
+ async confirm(s) {
1164
+ if (s.stage === 'capability_prepared' && !created) {
1165
+ // TOCTOU-safe CREATE (§18): re-read under the lock. An appeared VALID rotation (for this artifact) → signal
1166
+ // `sa_credential_appeared` so the coordinator recovers by class (never overwrite); an invalid/non-rotation B →
1167
+ // classifyB throws conflict; else re-check expiry immediately before CREATE, then create + gate evidence.
1168
+ withProfileLock(deps.root, ctx.profileName, deps.fs, () => {
1169
+ const existing = tryLoadProfile(deps.root, ctx.profileName, deps.fs);
1170
+ if (existing) {
1171
+ classifyB(existing, ctx.artifact); // throws sa_rotation_profile_conflict / sa_baseurl_conflict if invalid
1172
+ throw new SaCoordinatorError('sa_credential_appeared');
1173
+ }
1174
+ assertNotExpired(ctx.artifact.expiresAt, deps.now); // immediately before CREATE (expired-during-keygen creates nothing)
1175
+ assertProfileSecure(createProfile(deps.root, ctx.profileName, rotationLogicalToProfile(ctx, hst, s), deps.fs), deps.fs);
1176
+ });
1177
+ created = true;
1178
+ }
1179
+ else {
1180
+ const from = s.stage === 'claimed' ? 'capability_prepared' : 'claimed'; // activation_prepared ← claimed
1181
+ assertProfileSecure(replaceProfile(deps.root, ctx.profileName, from, rotationLogicalToProfile(ctx, hst, s), deps.fs), deps.fs);
1182
+ }
1183
+ },
1184
+ async finalizeActive(s) {
1185
+ assertProfileSecure(replaceProfile(deps.root, ctx.profileName, 'activation_prepared', rotationLogicalToProfile(ctx, hst, s), deps.fs), deps.fs);
1186
+ },
1187
+ async discardTransient() {
1188
+ cleanupRotationArtifact(ctx, deps); // delete ONLY the artifact (never the active profile)
1189
+ },
1190
+ };
1191
+ }
1192
+ function makeRotateRuntime(ctx, deps, hst, holderFlag) {
1193
+ return {
1194
+ prepareBootstrap: () => Promise.reject(new CliError('sa_rotation_not_resumable')),
1195
+ prepareCapability: deps.newCapability,
1196
+ bootstrapClaimClient: { claim: () => Promise.reject(new CliError('sa_rotation_not_resumable')) },
1197
+ validateHolder: async () => { hst.resolved = resolveAndBindHolder(holderFlag, ctx, deps); }, // resolve+bind BEFORE keygen, NO unlock
1198
+ resolveHolder: async () => {
1199
+ hst.resolved ??= resolveAndBindHolder(holderFlag, ctx, deps); // resume path (no validateHolder) — resolve exactly once
1200
+ if (hst.loadedProfile)
1201
+ assertHolderRefsMatch(hst.loadedProfile, hst.resolved); // resume: persisted refs must equal A (BEFORE unlock)
1202
+ return (await unlockHolder(hst.resolved));
1203
+ },
1204
+ makeClient: deps.makeClient,
1205
+ newIdempotencyKey: deps.newIdempotencyKey,
1206
+ now: deps.now,
1207
+ confirmActivation: async () => true, // durable host: activate success + durable checkpoint IS the confirmation
1208
+ };
1209
+ }
1210
+ async function saRotate(argv, deps) {
1211
+ const parsed = parseArgv(argv, SA_SPECS.rotate); // parse FIRST
1212
+ assertMachineIsolation(deps.env, 'sa_holder_requires_profile'); // D5: reject env authority BEFORE the lease (value never read)
1213
+ const operationId = parsed.flags.operation;
1214
+ const profileName = parsed.flags.profile;
1215
+ const holderFlag = parsed.flags['holder-profile']; // stage-required at runtime (§18.6)
1216
+ assertHandoffId(operationId); // validate the selector before building any managed path
1217
+ const lease = acquireHandoffLease(deps.root, operationId, deps.fs); // operation lease FIRST (fail-fast, O_EXCL)
1218
+ const output = await withLease(lease, async () => {
1219
+ const state = tryReadState(lease); // residual handoff under the lease (not_found → null; corrupt/path preserved)
1220
+ const artifactMaybe = tryLoadArtifact(deps.root, operationId, deps.fs); // artifact under the lease
1221
+ if (!artifactMaybe) {
1222
+ // Artifact ABSENT (§18.4). A residual handoff + missing artifact is NEVER a settled rotation → not_found, handoff
1223
+ // intact. D6 completion recovery applies ONLY when BOTH are absent (crash after the durable unlink, before stdout).
1224
+ if (state)
1225
+ throw new CliError('sa_rotation_artifact_not_found');
1226
+ const completed = withProfileLock(deps.root, profileName, deps.fs, () => {
1227
+ const p = tryLoadProfile(deps.root, profileName, deps.fs);
1228
+ return p ? classifyCompletion(p, operationId) : null;
1229
+ });
1230
+ if (completed) {
1231
+ resolveRotationBaseUrl(completed.profile.baseUrl, deps.env); // F2: AC_API_BASE_URL normalize-match BEFORE cleanup/stdout
1232
+ durableAbsenceOrCleanup(deps.root, operationId, deps); // re-prove durable absence; insecure → cleanup-pending
1233
+ return completionOutput(completed.profile, profileName);
1234
+ }
1235
+ throw new CliError('sa_rotation_artifact_not_found');
1236
+ }
1237
+ const artifact = resolveRotationArtifact(state, artifactMaybe, operationId, lease, deps); // §18.4 matrix (consumes a compatible residual provisional)
1238
+ const baseUrl = resolveRotationBaseUrl(artifact.baseUrl, deps.env); // AC_API_BASE_URL normalize-match (before any HTTP)
1239
+ const ctx = { baseUrl, profileName, operationId, artifact };
1240
+ const hst = {};
1241
+ const binding = { flow: 'rotation', serviceAccountId: artifact.serviceAccountId, baseUrl, credentialId: artifact.credentialId };
1242
+ const result = await mapCoordinatorErrors(() => runCredentialLifecycle(binding, makeRotateRuntime(ctx, deps, hst, holderFlag), { checkpoint: makeRotateCheckpoint(deps, ctx, hst), custody: PASSIVE_CUSTODY }));
1243
+ return rotateOutput(ctx, result.patId);
1244
+ });
1245
+ deps.stdout(`${JSON.stringify(output)}\n`); // ONE JSON line, only after a successful lease release
1246
+ return 0;
1247
+ }
1248
+ // ── U9b-4-1 · `sa migrate` — LEGACY MIGRATION HOLDER-SIDE DRIVER (§10.c#20 + §10.c#20.1) ────────────────────
1249
+ /** Read a REQUIRED non-empty string field of a schema-validated profile; a violation is a corrupt profile (fail-closed). */
1250
+ function pstr(p, key) {
1251
+ const v = p[key];
1252
+ if (typeof v !== 'string' || v.length === 0)
1253
+ throw new StoreError('sa_profile_corrupt');
1254
+ return v;
1255
+ }
1256
+ /** Pure SSOT envelope for every LEGACY-migration checkpoint (§10.c#20.1.e). Per-stage fields are added by the caller. */
1257
+ function legacyMigrationEnvelope(serviceAccountId, baseUrl) {
1258
+ return {
1259
+ schemaVersion: 1,
1260
+ flow: 'legacy_migration',
1261
+ serviceAccountId,
1262
+ baseUrl,
1263
+ principalType: 'service_account_legacy',
1264
+ };
1265
+ }
1266
+ function migrateOutput(profileName, active) {
1267
+ return { profile: profileName, serviceAccountId: active.serviceAccountId, credentialId: pstr(active, 'credentialId'), patId: pstr(active, 'patId'), stage: 'active' };
1268
+ }
1269
+ /**
1270
+ * Reclassify a profile that APPEARED at fresh-CREATE time (§10.c#20.1.f · post-gate F2). Bound to the ENTIRE fresh
1271
+ * preflight authority — NOT just flow+SA: `legacy_migration` flow, SAME `serviceAccountId`, `baseUrl` normalize-equal
1272
+ * to the captured `pre.baseUrl`, `bearer` EXACTLY the captured `pre.bearer`, non-terminal stage. ANY mismatch →
1273
+ * `sa_migration_profile_conflict` (before unlock/HTTP/output; never echoes the bearer/baseUrl). Returned profile:
1274
+ * `active` → the driver does local recovery; an in-progress stage → resume from it (never adopts a foreign authority).
1275
+ */
1276
+ function reclassifyAppeared(p, pre) {
1277
+ if (p.flow !== 'legacy_migration' || p.serviceAccountId !== pre.serviceAccountId)
1278
+ throw new CliError('sa_migration_profile_conflict');
1279
+ if (p.stage === 'terminal')
1280
+ throw new CliError('sa_migration_profile_conflict');
1281
+ try {
1282
+ if (normalizeBaseUrl(p.baseUrl) !== normalizeBaseUrl(pre.baseUrl))
1283
+ throw new CliError('sa_migration_profile_conflict');
1284
+ }
1285
+ catch {
1286
+ throw new CliError('sa_migration_profile_conflict'); // an unparseable/foreign baseUrl → conflict (no echo)
1287
+ }
1288
+ if (p.bearer !== pre.bearer)
1289
+ throw new CliError('sa_migration_profile_conflict'); // exact bearer bind (no echo)
1290
+ return p;
1291
+ }
1292
+ /** The replaceProfile expected-current-stage for a legacy forward edge (byte-for-byte with the CLI step functions). */
1293
+ function migratePrevStage(stage) {
1294
+ switch (stage) {
1295
+ case 'capability_prepared':
1296
+ return 'legacy_source';
1297
+ case 'migration_prepared':
1298
+ return 'capability_prepared';
1299
+ case 'activation_prepared':
1300
+ return 'migration_prepared';
1301
+ default:
1302
+ throw new CliError('sa_migration_profile_conflict');
1303
+ }
1304
+ }
1305
+ /** LogicalState → the EXACT persisted legacy Profile per stage (byte-for-byte with the pre-U5 CLI step functions). */
1306
+ function migrateLogicalToProfile(ctx, s) {
1307
+ const env = legacyMigrationEnvelope(ctx.serviceAccountId, ctx.baseUrl);
1308
+ switch (s.stage) {
1309
+ case 'legacy_source':
1310
+ return { ...env, stage: 'legacy_source', bearer: s.bearer };
1311
+ case 'capability_prepared':
1312
+ return { ...env, stage: 'capability_prepared', bearer: s.bearer, capPublicKeyB64: s.capPublicKeyB64, capPrivateKeyB64: s.capPrivateKeyB64, prepareIdempotencyKey: s.prepareIdempotencyKey };
1313
+ case 'migration_prepared':
1314
+ return { ...env, stage: 'migration_prepared', expiresAt: s.expiresAt, credentialId: s.credentialId, bearer: s.bearer, capPublicKeyB64: s.capPublicKeyB64, capPrivateKeyB64: s.capPrivateKeyB64, identityChallengeSealedB64: s.identityChallengeSealedB64, capChallengeSealedB64: s.capChallengeSealedB64 };
1315
+ case 'activation_prepared':
1316
+ return { ...env, stage: 'activation_prepared', expiresAt: s.expiresAt, credentialId: s.credentialId, bearer: s.bearer, capPublicKeyB64: s.capPublicKeyB64, capPrivateKeyB64: s.capPrivateKeyB64, activationBody: s.activationBody, completeIdempotencyKey: s.completeIdempotencyKey };
1317
+ case 'active':
1318
+ // LEGACY `active` inlines its envelope (stage BEFORE serviceAccountId) and PROMOTES principalType (§10.c#20.1.e).
1319
+ return { schemaVersion: 1, flow: 'legacy_migration', stage: 'active', serviceAccountId: ctx.serviceAccountId, baseUrl: ctx.baseUrl, principalType: 'service_account', credentialId: s.credentialId, patId: s.patId, bearer: s.bearer, capPublicKeyB64: s.capPublicKeyB64, capPrivateKeyB64: s.capPrivateKeyB64 };
1320
+ default:
1321
+ throw new CliError('sa_migration_profile_conflict');
1322
+ }
1323
+ }
1324
+ /** Persisted legacy Profile → the EXACT LogicalState (flow 'legacy_migration' → 'legacy'; exact-own key set). */
1325
+ function migrateProfileToLogical(p) {
1326
+ const base = { flow: 'legacy', serviceAccountId: p.serviceAccountId, baseUrl: bsGet(p, 'baseUrl') };
1327
+ switch (p.stage) {
1328
+ case 'legacy_source':
1329
+ return { ...base, stage: 'legacy_source', bearer: bsGet(p, 'bearer') };
1330
+ case 'capability_prepared':
1331
+ return { ...base, stage: 'capability_prepared', bearer: bsGet(p, 'bearer'), capPublicKeyB64: bsGet(p, 'capPublicKeyB64'), capPrivateKeyB64: bsGet(p, 'capPrivateKeyB64'), prepareIdempotencyKey: bsGet(p, 'prepareIdempotencyKey') };
1332
+ case 'migration_prepared':
1333
+ return { ...base, stage: 'migration_prepared', bearer: bsGet(p, 'bearer'), capPublicKeyB64: bsGet(p, 'capPublicKeyB64'), capPrivateKeyB64: bsGet(p, 'capPrivateKeyB64'), credentialId: bsGet(p, 'credentialId'), expiresAt: bsGet(p, 'expiresAt'), identityChallengeSealedB64: bsGet(p, 'identityChallengeSealedB64'), capChallengeSealedB64: bsGet(p, 'capChallengeSealedB64') };
1334
+ case 'activation_prepared':
1335
+ return { ...base, stage: 'activation_prepared', bearer: bsGet(p, 'bearer'), capPublicKeyB64: bsGet(p, 'capPublicKeyB64'), capPrivateKeyB64: bsGet(p, 'capPrivateKeyB64'), credentialId: bsGet(p, 'credentialId'), expiresAt: bsGet(p, 'expiresAt'), activationBody: p.activationBody, completeIdempotencyKey: bsGet(p, 'completeIdempotencyKey') };
1336
+ case 'active':
1337
+ return { ...base, stage: 'active', bearer: bsGet(p, 'bearer'), capPublicKeyB64: bsGet(p, 'capPublicKeyB64'), capPrivateKeyB64: bsGet(p, 'capPrivateKeyB64'), credentialId: bsGet(p, 'credentialId'), patId: bsGet(p, 'patId') };
1338
+ default:
1339
+ throw new CliError('sa_migration_profile_conflict'); // terminal / unexpected own-stage
1340
+ }
1341
+ }
1342
+ /** reclassifyAppeared bound to the fresh authority (flow/SA/baseUrl/bearer/non-terminal); valid → the coordinator resumes. */
1343
+ function reclassifyAppearedForCoordinator(existing, ctx) {
1344
+ reclassifyAppeared(existing, { mode: 'fresh', serviceAccountId: ctx.serviceAccountId, profileName: ctx.profileName, bearer: ctx.bearer, baseUrl: ctx.baseUrl }); // throws sa_migration_profile_conflict on any mismatch
1345
+ }
1346
+ /**
1347
+ * The legacy CheckpointPort. `read` REFLECTS the `withMigrationLease` classification (the SSOT under the migration
1348
+ * lease): fresh → null (the appeared/TOCTOU is caught by `confirm(legacy_source)`'s LOCKED re-read, never by an
1349
+ * unlocked read — byte-for-byte with `ensureFreshLegacySource`); resume → the lease-classified profile. The ONLY
1350
+ * subsequent read is the coordinator's post-`sa_credential_appeared` re-read; it consumes EXACTLY the snapshot
1351
+ * captured under the SAME profile-lock that authorized the appeared profile (`authorizedAppeared`) — it NEVER re-reads
1352
+ * disk, because between the locked reclassify and this read the file could be substituted (same flow/SA/baseUrl,
1353
+ * different bearer) and `classifyResume` does NOT bind the legacy bearer when `credentialId` is null. Fail closed if
1354
+ * no authorized snapshot was captured. `confirm(legacy_source)` = the fresh CREATE with `reclassifyAppeared`; later
1355
+ * stages = `replaceProfile(prevStage)`. `finalizeActive` = replaceProfile(activation_prepared → active);
1356
+ * `discardTransient` = NO-OP (no artifact; the active profile is retained and the migration lease is released by
1357
+ * `withMigrationLease`).
1358
+ */
1359
+ function makeMigrateCheckpoint(deps, ctx, resolved) {
1360
+ let firstRead = true;
1361
+ let created = false;
1362
+ let authorizedAppeared = null; // the appeared snapshot captured UNDER the profile-lock (post-reclassify)
1363
+ return {
1364
+ async read() {
1365
+ if (firstRead) {
1366
+ firstRead = false;
1367
+ if (resolved.mode === 'fresh')
1368
+ return null; // withMigrationLease authority; appeared caught at confirm(legacy_source)
1369
+ return migrateProfileToLogical(resolved.profile); // resume: the lease-classified profile (§10.c#20.A)
1370
+ }
1371
+ return authorizedAppeared; // post-appeared re-read: consume ONLY the lock-authorized snapshot; NEVER re-read disk (TOCTOU); null → fail closed
1372
+ },
1373
+ async confirm(s) {
1374
+ if (s.stage === 'legacy_source' && !created) {
1375
+ // FRESH CREATE under a BRIEF profile lock with a re-read (§10.c#20.1.f · ensureFreshLegacySource). An APPEARED
1376
+ // profile → reclassifyAppeared (bound to flow/SA/baseUrl/bearer/non-terminal): a VALID appeared → CAPTURE its
1377
+ // exact LogicalState under THIS lock + signal `sa_credential_appeared` so the coordinator re-reads (that snapshot)
1378
+ // + resumes; a conflict → sa_migration_profile_conflict. NEVER overwrite. createProfile is exclusive; a
1379
+ // sa_store_dest_exists after an absent re-read → re-read + reclassify + capture under the SAME lock.
1380
+ withProfileLock(deps.root, ctx.profileName, deps.fs, () => {
1381
+ const existing = tryLoadProfile(deps.root, ctx.profileName, deps.fs);
1382
+ if (existing) {
1383
+ reclassifyAppearedForCoordinator(existing, ctx);
1384
+ authorizedAppeared = migrateProfileToLogical(existing); // capture the AUTHORIZED snapshot before releasing the lock
1385
+ throw new SaCoordinatorError('sa_credential_appeared');
1386
+ }
1387
+ try {
1388
+ assertProfileSecure(createProfile(deps.root, ctx.profileName, migrateLogicalToProfile(ctx, s), deps.fs), deps.fs);
1389
+ }
1390
+ catch (e) {
1391
+ if (e instanceof StoreError && e.code === 'sa_store_dest_exists') {
1392
+ const appeared = tryLoadProfile(deps.root, ctx.profileName, deps.fs); // re-read under the SAME lock
1393
+ if (appeared) {
1394
+ reclassifyAppearedForCoordinator(appeared, ctx);
1395
+ authorizedAppeared = migrateProfileToLogical(appeared); // capture the AUTHORIZED snapshot before releasing the lock
1396
+ throw new SaCoordinatorError('sa_credential_appeared');
1397
+ }
1398
+ throw e; // still absent → propagate the exclusive-create failure
1399
+ }
1400
+ throw e; // corrupt/path/insecure preserved by identity
1401
+ }
1402
+ });
1403
+ created = true;
1404
+ }
1405
+ else {
1406
+ assertProfileSecure(replaceProfile(deps.root, ctx.profileName, migratePrevStage(s.stage), migrateLogicalToProfile(ctx, s), deps.fs), deps.fs);
1407
+ }
1408
+ },
1409
+ async finalizeActive(s) {
1410
+ assertProfileSecure(replaceProfile(deps.root, ctx.profileName, 'activation_prepared', migrateLogicalToProfile(ctx, s), deps.fs), deps.fs);
1411
+ },
1412
+ async discardTransient() {
1413
+ // Legacy has NO artifact/handoff: the migration lease is the transient and `withMigrationLease` releases it.
1414
+ // The active profile is retained (§10.c#20.1 · rule 9). No-op.
1415
+ },
1416
+ };
1417
+ }
1418
+ /** The legacy CoordinatorRuntime — capability keygen + client/clock seams from `SaDeps`; no holder/bootstrap/confirm seam. */
1419
+ function makeMigrateRuntime(deps) {
1420
+ return {
1421
+ prepareBootstrap: () => Promise.reject(new CliError('sa_legacy_not_resumable')), // never for legacy
1422
+ prepareCapability: deps.newCapability,
1423
+ bootstrapClaimClient: { claim: () => Promise.reject(new CliError('sa_legacy_not_resumable')) }, // never for legacy
1424
+ resolveHolder: () => {
1425
+ throw new CliError('sa_legacy_not_resumable'); // legacy unlocks via the shared UnlockController (makeClient), never resolveHolder
1426
+ },
1427
+ makeClient: deps.makeClient,
1428
+ newIdempotencyKey: deps.newIdempotencyKey,
1429
+ now: deps.now,
1430
+ // No validateHolder (rotation-only) and no confirmActivation (standardActivate-only): legacy uses runLegacyActivationFsm.
1431
+ };
1432
+ }
1433
+ /** Drive the classified migration to `active` (or a local recovery). Runs INSIDE the bound `withMigrationLease` callback. */
1434
+ async function driveMigrate(resolved, deps) {
1435
+ const name = resolved.profileName;
1436
+ if (resolved.mode === 'resume' && resolved.recovery === 'active')
1437
+ return migrateOutput(name, resolved.profile); // local recovery
1438
+ const bearer = resolved.mode === 'fresh' ? resolved.bearer : pstr(resolved.profile, 'bearer');
1439
+ const ctx = { profileName: name, serviceAccountId: resolved.serviceAccountId, baseUrl: resolved.baseUrl, bearer };
1440
+ const binding = { flow: 'legacy', serviceAccountId: resolved.serviceAccountId, baseUrl: resolved.baseUrl, credentialId: null, legacyBearer: bearer };
1441
+ const result = await mapCoordinatorErrors(() => runCredentialLifecycle(binding, makeMigrateRuntime(deps), { checkpoint: makeMigrateCheckpoint(deps, ctx, resolved), custody: PASSIVE_CUSTODY }));
1442
+ return { profile: name, serviceAccountId: result.serviceAccountId, credentialId: result.credentialId, patId: result.patId, stage: 'active' };
1443
+ }
1444
+ /**
1445
+ * `airctrl sa migrate <serviceAccountId> --profile <name>` (§10.c#20 + §10.c#20.1). Order: parse → preflight (UUID +
1446
+ * `--profile` + env authority, BEFORE fs/lock/unlock/HTTP) → acquire the migration lease → the bound combinator
1447
+ * resolves fresh/resume ONCE, drives the FSM, and releases the SAME lease → ONE JSON line AFTER the release.
1448
+ */
1449
+ async function saMigrate(argv, deps) {
1450
+ const parsed = parseArgv(argv, SA_SPECS.migrate); // parse FIRST — junk/missing flags fail before any IO
1451
+ const pre = preflightMigratePrincipal({ serviceAccountId: parsed.positionals[0], profileName: parsed.flags.profile, env: deps.env });
1452
+ const ctx = acquireMigrationLeaseContext(deps.root, pre.profileName, deps.fs); // migration lease FIRST (O_EXCL, held whole flow)
1453
+ const output = await withMigrationLease(pre, ctx, (resolved) => driveMigrate(resolved, deps));
1454
+ deps.stdout(`${JSON.stringify(output)}\n`); // ONE JSON line, only after a successful lease release
1455
+ return 0;
1456
+ }
1457
+ export async function runSaCommand(argv, deps) {
1458
+ const [sub, ...rest] = argv;
1459
+ switch (sub) {
1460
+ case 'authorize':
1461
+ return saAuthorize(rest, deps);
1462
+ case 'cancel':
1463
+ return saCancel(rest, deps);
1464
+ case 'tokens':
1465
+ return saTokens(rest, deps);
1466
+ case 'revoke-token':
1467
+ return saRevokeToken(rest, deps);
1468
+ case 'bootstrap':
1469
+ return saBootstrap(rest, deps);
1470
+ case 'verify':
1471
+ return saVerify(rest, deps);
1472
+ case 'status':
1473
+ return saStatus(rest, deps);
1474
+ case 'reconcile':
1475
+ return saReconcile(rest, deps);
1476
+ case 'rotate':
1477
+ return saRotate(rest, deps);
1478
+ case 'rotate-identity':
1479
+ return saRotateIdentity(rest, deps);
1480
+ case 'migrate':
1481
+ return saMigrate(rest, deps);
1482
+ default:
1483
+ throw new ParseError('cli_unknown_command');
1484
+ }
1485
+ }