@tiangong-lca/cli 0.0.25 → 0.0.26

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.
@@ -1,12 +1,14 @@
1
- import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync, } from 'node:fs';
1
+ import { appendFileSync, chmodSync, existsSync } from 'node:fs';
2
2
  import path from 'node:path';
3
- import { buildAliasPlanRequest, loadMaintenanceDesiredPayload, } from './dataset-maintenance-alias-request.js';
4
- import { MAINTENANCE_SCAN_TABLES, isJsonObject, maintenanceRowKey, parseMaintenancePlan, readJsonFile, sha256Json, sha256Text, snapshotRemoteRow, stableJsonText, } from './dataset-maintenance-contract.js';
5
- import { PROTECTED_EXECUTION_CONTRACT, assertProtectedApprovalBindings, assertProtectedFreezeMatchesPlan, buildProtectedAdmitRequest, buildProtectedExecutionIdentity, buildProtectedPreflightRequest, parseProtectedAdmissionProof, parseProtectedApproval, parseProtectedDerivativeSnapshot, parseProtectedFreeze, parseProtectedGateProof, parseProtectedPreflightProof, parseProtectedStatusProof, } from './dataset-maintenance-protected-contract.js';
3
+ import { buildAliasPlanRequest } from './dataset-maintenance-alias-request.js';
4
+ import { ensurePrivateArtifactDirectory, readProtectedJsonArtifact, writePrivateImmutableJson, } from './dataset-maintenance-protected-artifacts.js';
5
+ import { assertDerivativeBaselines as assertSharedDerivativeBaselines, assertStrictBeforeState as assertSharedStrictBeforeState, assertSupportSnapshots as assertSharedSupportSnapshots, projectedRows as sharedProjectedRows, } from './dataset-maintenance-protected-before.js';
6
+ import { isJsonObject, parseMaintenancePlan, readJsonFile, sha256Json, sha256Text, stableJsonText, } from './dataset-maintenance-contract.js';
7
+ import { PROTECTED_EXECUTION_CONTRACT, assertProtectedApprovalBindings, assertProtectedFreezeMatchesPlan, buildProtectedAdmitRequest, buildProtectedExecutionIdentity, buildProtectedPreflightRequest, parseProtectedAdmissionProof, parseProtectedApproval, parseProtectedFreeze, parseProtectedGateProof, parseProtectedPreflightProof, parseProtectedStatusProof, } from './dataset-maintenance-protected-contract.js';
8
+ import { assertProtectedPreparationPlanSha256, assertProtectedProductionProjectRef, } from './dataset-maintenance-protected-preparation.js';
6
9
  import { verifyProtectedExecution, } from './dataset-maintenance-protected-verify.js';
7
10
  import { maintenanceProjectedReferenceFingerprint } from './dataset-maintenance-plan.js';
8
- import { isSnapshotCompletenessCompatible } from './dataset-maintenance-pagination.js';
9
- import { admitMaintenanceAliasExecution, captureMaintenanceAliasExecutionGate, fetchMaintenanceAccountRows, fetchMaintenanceDerivativeSnapshot, fetchMaintenanceExactRows, normalizeMaintenancePageSize, preflightMaintenanceAliasExecution, readMaintenanceAliasExecution, resolveMaintenanceRemoteContext, } from './dataset-maintenance-remote.js';
11
+ import { admitMaintenanceAliasExecution, captureMaintenanceAliasExecutionGate, fetchMaintenanceAccountRows, normalizeMaintenancePageSize, preflightMaintenanceAliasExecution, readMaintenanceAliasExecution, resolveMaintenanceRemoteContext, } from './dataset-maintenance-remote.js';
10
12
  import { CliError } from './errors.js';
11
13
  import { withStateFileLock } from './state-lock.js';
12
14
  const DEFAULT_POLL_MS = 10_000;
@@ -44,34 +46,24 @@ function errorDetails(error) {
44
46
  };
45
47
  }
46
48
  function readArtifact(options) {
47
- const resolved = path.resolve(options.filePath);
48
- const text = readFileSync(resolved, 'utf8');
49
+ const artifact = readProtectedJsonArtifact(options);
49
50
  return {
50
- resolved,
51
- value: readJsonFile(resolved, options.label),
52
- file_sha256: sha256Text(text),
51
+ resolved: artifact.resolved,
52
+ value: artifact.value,
53
+ text: artifact.text,
54
+ file_sha256: artifact.file_sha256,
53
55
  };
54
56
  }
55
- function ensurePrivateDirectory(directory) {
56
- mkdirSync(directory, { recursive: true, mode: 0o700 });
57
- chmodSync(directory, 0o700);
58
- }
59
- function writePrivateImmutableJson(filePath, value) {
60
- const resolved = path.resolve(filePath);
61
- const text = `${stableJsonText(value)}\n`;
62
- ensurePrivateDirectory(path.dirname(resolved));
63
- if (existsSync(resolved)) {
64
- if (readFileSync(resolved, 'utf8') !== text) {
65
- throw new CliError(`Refusing to overwrite protected evidence: ${resolved}`, {
66
- code: 'DATASET_MAINTENANCE_PROTECTED_ARTIFACT_IMMUTABLE',
67
- exitCode: 1,
68
- });
69
- }
70
- chmodSync(resolved, 0o600);
71
- return resolved;
57
+ function assertCanonicalParsedArtifact(options) {
58
+ if (options.text !== `${stableJsonText(options.value)}\n`) {
59
+ throw new CliError(`${options.label} must be canonical JSON with exactly one final newline.`, {
60
+ code: 'DATASET_MAINTENANCE_PROTECTED_ARTIFACT_NONCANONICAL',
61
+ exitCode: 2,
62
+ });
72
63
  }
73
- writeFileSync(resolved, text, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
74
- return resolved;
64
+ }
65
+ function ensurePrivateDirectory(directory) {
66
+ ensurePrivateArtifactDirectory(directory);
75
67
  }
76
68
  function appendPrivateJsonLine(filePath, value) {
77
69
  const resolved = path.resolve(filePath);
@@ -149,11 +141,24 @@ function prepareProtectedExecutionWithDependencies(options, dependencies) {
149
141
  label: 'Protected execution approval',
150
142
  });
151
143
  const plan = dependencies.parsePlan(planArtifact.value);
144
+ if (options.commit) {
145
+ assertProtectedPreparationPlanSha256(plan.plan_sha256, 'plan.plan_sha256');
146
+ }
152
147
  const planPath = planArtifact.resolved;
153
148
  const planDir = path.dirname(planPath);
154
149
  const aliasPlanRequest = dependencies.buildAliasPlan({ plan, planDir });
155
150
  const freeze = dependencies.parseFreeze(freezeArtifact.value);
156
151
  const approval = dependencies.parseApproval(approvalArtifact.value);
152
+ assertCanonicalParsedArtifact({
153
+ label: 'Protected execution freeze',
154
+ text: freezeArtifact.text,
155
+ value: freeze,
156
+ });
157
+ assertCanonicalParsedArtifact({
158
+ label: 'Protected execution approval',
159
+ text: approvalArtifact.text,
160
+ value: approval,
161
+ });
157
162
  dependencies.assertFreezeMatchesPlan({
158
163
  plan,
159
164
  planFileSha256: planArtifact.file_sha256,
@@ -175,6 +180,9 @@ function prepareProtectedExecutionWithDependencies(options, dependencies) {
175
180
  freezeFileSha256: freezeArtifact.file_sha256,
176
181
  approvalFileSha256: approvalArtifact.file_sha256,
177
182
  });
183
+ if (options.commit) {
184
+ assertProtectedProductionProjectRef(identity.project_ref);
185
+ }
178
186
  const outDir = path.resolve(options.outDir);
179
187
  const artifacts = {
180
188
  execution_seal: path.join(outDir, 'protected-execution-seal.json'),
@@ -235,143 +243,30 @@ function assertContextBindings(options) {
235
243
  }
236
244
  }
237
245
  function projectedRows(options) {
238
- const projected = new Map(options.currentRows.map((row) => [maintenanceRowKey(row), { ...row }]));
239
- for (const action of options.plan.actions) {
240
- const row = projected.get(maintenanceRowKey(action));
241
- if (row) {
242
- projected.set(maintenanceRowKey(action), {
243
- ...row,
244
- json_ordered: loadMaintenanceDesiredPayload(options.planDir, action),
245
- });
246
- }
247
- }
248
- return [...projected.values()].sort((left, right) => maintenanceRowKey(left).localeCompare(maintenanceRowKey(right)));
246
+ return sharedProjectedRows(options);
249
247
  }
250
248
  function assertStrictBeforeState(options) {
251
- const { plan } = options.prepared;
252
- if (!plan.snapshot_completeness ||
253
- !isSnapshotCompletenessCompatible(options.completeness, plan.snapshot_completeness, MAINTENANCE_SCAN_TABLES)) {
254
- throw new CliError('Production RLS census does not match the frozen complete snapshot.', {
255
- code: 'DATASET_MAINTENANCE_PROTECTED_SNAPSHOT_INCOMPLETE',
256
- exitCode: 1,
257
- });
258
- }
259
- const snapshots = options.currentRows
260
- .map(snapshotRemoteRow)
261
- .sort((left, right) => maintenanceRowKey(left).localeCompare(maintenanceRowKey(right)));
262
- if (sha256Json(snapshots) !== plan.visible_snapshot_sha256) {
263
- throw new CliError('Production RLS visible snapshot drifted after the freeze.', {
264
- code: 'DATASET_MAINTENANCE_PROTECTED_VISIBLE_SNAPSHOT_DRIFT',
265
- exitCode: 1,
266
- });
267
- }
268
- const expectedKeys = new Set([
269
- ...plan.actions.map(maintenanceRowKey),
270
- ...plan.protected_rows.map(maintenanceRowKey),
271
- ]);
272
- if (expectedKeys.size !== options.currentRows.length ||
273
- options.currentRows.some((row) => !expectedKeys.has(maintenanceRowKey(row)))) {
274
- throw new CliError('Production owner account contains missing or unexpected rows.', {
275
- code: 'DATASET_MAINTENANCE_PROTECTED_ACCOUNT_CENSUS_DRIFT',
276
- exitCode: 1,
277
- });
278
- }
279
- const current = new Map(options.currentRows.map((row) => [maintenanceRowKey(row), row]));
280
- for (const row of plan.protected_rows) {
281
- const observed = current.get(maintenanceRowKey(row));
282
- if (!observed || snapshotRemoteRow(observed).row_sha256 !== row.row_sha256) {
283
- throw new CliError(`Protected row drifted: ${row.id}`, {
284
- code: 'DATASET_MAINTENANCE_PROTECTED_ROW_DRIFT',
285
- exitCode: 1,
286
- details: row,
287
- });
288
- }
289
- }
290
- for (const action of plan.actions) {
291
- const observed = current.get(maintenanceRowKey(action));
292
- if (!action.before ||
293
- !observed ||
294
- observed.user_id !== action.expected_user_id ||
295
- observed.state_code !== 0 ||
296
- snapshotRemoteRow(observed).row_sha256 !== action.before.row_sha256) {
297
- throw new CliError(`Action row is no longer in the exact frozen before state: ${action.action_id}`, {
298
- code: 'DATASET_MAINTENANCE_PROTECTED_ACTION_DRIFT',
299
- exitCode: 1,
300
- });
301
- }
302
- }
303
- const finalRows = projectedRows({
304
- plan,
249
+ assertSharedStrictBeforeState({
250
+ plan: options.prepared.plan,
305
251
  planDir: options.prepared.planDir,
252
+ actorUserId: options.prepared.identity.actor.user_id,
306
253
  currentRows: options.currentRows,
254
+ completeness: options.completeness,
307
255
  });
308
- if (sha256Json(maintenanceProjectedReferenceFingerprint(finalRows)) !==
309
- plan.projected_reference_sha256) {
310
- throw new CliError('Projected reference closure drifted before protected execution.', {
311
- code: 'DATASET_MAINTENANCE_PROTECTED_REFERENCE_DRIFT',
312
- exitCode: 1,
313
- });
314
- }
315
256
  }
316
257
  async function assertSupportSnapshots(options) {
317
- for (const batch of options.prepared.plan.alias_batches ?? []) {
318
- for (const snapshot of [
319
- batch.target_snapshots.unitgroup,
320
- batch.target_snapshots.flowproperty,
321
- batch.target_snapshots.source_unitgroup,
322
- ]) {
323
- if (!snapshot) {
324
- throw new CliError(`Alias support snapshot is absent for ${batch.batch_id}.`, {
325
- code: 'DATASET_MAINTENANCE_PROTECTED_SUPPORT_DRIFT',
326
- exitCode: 1,
327
- });
328
- }
329
- const exact = await fetchMaintenanceExactRows({
330
- context: options.context,
331
- table: snapshot.table,
332
- id: snapshot.id,
333
- version: snapshot.version,
334
- });
335
- const row = exact.rows.length === 1 ? exact.rows[0] : null;
336
- if (!row ||
337
- row.user_id !== options.prepared.identity.actor.user_id ||
338
- row.state_code !== 0 ||
339
- snapshotRemoteRow(row).row_sha256 !== snapshot.row_sha256) {
340
- throw new CliError(`Alias support row drifted for ${batch.batch_id}.`, {
341
- code: 'DATASET_MAINTENANCE_PROTECTED_SUPPORT_DRIFT',
342
- exitCode: 1,
343
- details: { table: snapshot.table, id: snapshot.id, version: snapshot.version },
344
- });
345
- }
346
- }
347
- }
258
+ await assertSharedSupportSnapshots({
259
+ plan: options.prepared.plan,
260
+ actorUserId: options.prepared.identity.actor.user_id,
261
+ context: options.context,
262
+ });
348
263
  }
349
264
  async function assertDerivativeBaselines(options) {
350
- const targets = options.prepared.identity.derivative_targets;
351
- for (let offset = 0; offset < targets.length; offset += 5) {
352
- const chunk = targets.slice(offset, offset + 5);
353
- const snapshots = await Promise.all(chunk.map(async (target) => parseProtectedDerivativeSnapshot(await fetchMaintenanceDerivativeSnapshot({
354
- context: options.context,
355
- table: target.table,
356
- id: target.id,
357
- version: target.version,
358
- }), {
359
- table: target.table,
360
- id: target.id,
361
- version: target.version,
362
- userId: target.user_id,
363
- })));
364
- for (const [index, snapshot] of snapshots.entries()) {
365
- const target = chunk[index];
366
- if (snapshot.snapshot_sha256 !== target.baseline_snapshot_sha256) {
367
- throw new CliError('A protected derivative baseline drifted before preflight.', {
368
- code: 'DATASET_MAINTENANCE_PROTECTED_DERIVATIVE_BASELINE_DRIFT',
369
- exitCode: 1,
370
- details: { table: target.table, id: target.id, version: target.version },
371
- });
372
- }
373
- }
374
- }
265
+ await assertSharedDerivativeBaselines({
266
+ actorUserId: options.prepared.identity.actor.user_id,
267
+ context: options.context,
268
+ derivativeTargets: options.prepared.identity.derivative_targets,
269
+ });
375
270
  }
376
271
  async function captureProtectedGatesWithDependencies(options, dependencies) {
377
272
  const gateNames = ['primary_support_plan', 'execution_unused', 'derivative_quiescence'];
@@ -744,6 +639,7 @@ export async function runDatasetMaintenanceProtected(options) {
744
639
  export const __testInternals = {
745
640
  allocateAttemptArtifacts,
746
641
  appendPrivateJsonLine,
642
+ assertCanonicalParsedArtifact,
747
643
  assertContextBindings,
748
644
  assertDerivativeBaselines,
749
645
  assertStrictBeforeState,
@@ -1 +1 @@
1
- {"version":3,"file":"dataset-maintenance-protected-run.js","sourceRoot":"","sources":["../../../src/lib/dataset-maintenance-protected-run.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,SAAS,EACT,UAAU,EACV,SAAS,EACT,YAAY,EACZ,aAAa,GACd,MAAM,SAAS,CAAC;AACjB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EACL,qBAAqB,EACrB,6BAA6B,GAC9B,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACL,uBAAuB,EACvB,YAAY,EACZ,iBAAiB,EACjB,oBAAoB,EACpB,YAAY,EACZ,UAAU,EACV,UAAU,EACV,iBAAiB,EACjB,cAAc,GAIf,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,4BAA4B,EAC5B,+BAA+B,EAC/B,gCAAgC,EAChC,0BAA0B,EAC1B,+BAA+B,EAC/B,8BAA8B,EAC9B,4BAA4B,EAC5B,sBAAsB,EACtB,gCAAgC,EAChC,oBAAoB,EACpB,uBAAuB,EACvB,4BAA4B,EAC5B,yBAAyB,GAS1B,MAAM,6CAA6C,CAAC;AACrD,OAAO,EACL,wBAAwB,GAEzB,MAAM,2CAA2C,CAAC;AACnD,OAAO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AoB;IACpB,yBAAyB;IACzB,yCAAyC;IACzC,aAAa;IACb,YAAY;IACZ,aAAa;IACb,6BAA6B;IAC7B,6BAA6B;IAC7B,qBAAqB;IACrB,qCAAqC;IACrC,4BAA4B;IAC5B,sBAAsB;IACtB,yBAAyB;CAC1B,CAAC","sourcesContent":["import {\n appendFileSync,\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n} from 'node:fs';\nimport path from 'node:path';\nimport {\n buildAliasPlanRequest,\n loadMaintenanceDesiredPayload,\n} from './dataset-maintenance-alias-request.js';\nimport {\n MAINTENANCE_SCAN_TABLES,\n isJsonObject,\n maintenanceRowKey,\n parseMaintenancePlan,\n readJsonFile,\n sha256Json,\n sha256Text,\n snapshotRemoteRow,\n stableJsonText,\n type DatasetMaintenancePlan,\n type DatasetMaintenanceRemoteRow,\n type JsonObject,\n} from './dataset-maintenance-contract.js';\nimport {\n PROTECTED_EXECUTION_CONTRACT,\n assertProtectedApprovalBindings,\n assertProtectedFreezeMatchesPlan,\n buildProtectedAdmitRequest,\n buildProtectedExecutionIdentity,\n buildProtectedPreflightRequest,\n parseProtectedAdmissionProof,\n parseProtectedApproval,\n parseProtectedDerivativeSnapshot,\n parseProtectedFreeze,\n parseProtectedGateProof,\n parseProtectedPreflightProof,\n parseProtectedStatusProof,\n type DatasetMaintenanceProtectedApproval,\n type DatasetMaintenanceProtectedFreeze,\n type ProtectedAdmissionProof,\n type ProtectedExecutionIdentity,\n type ProtectedExecutionStatusProof,\n type ProtectedGateProof,\n type ProtectedPreflightProof,\n type ProtectedReportStatus,\n} from './dataset-maintenance-protected-contract.js';\nimport {\n verifyProtectedExecution,\n type ProtectedVerificationResult,\n} from './dataset-maintenance-protected-verify.js';\nimport { maintenanceProjectedReferenceFingerprint } from './dataset-maintenance-plan.js';\nimport { isSnapshotCompletenessCompatible } from './dataset-maintenance-pagination.js';\nimport {\n admitMaintenanceAliasExecution,\n captureMaintenanceAliasExecutionGate,\n fetchMaintenanceAccountRows,\n fetchMaintenanceDerivativeSnapshot,\n fetchMaintenanceExactRows,\n normalizeMaintenancePageSize,\n preflightMaintenanceAliasExecution,\n readMaintenanceAliasExecution,\n resolveMaintenanceRemoteContext,\n type DatasetMaintenanceRemoteContext,\n} from './dataset-maintenance-remote.js';\nimport { CliError } from './errors.js';\nimport type { FetchLike } from './http.js';\nimport { withStateFileLock } from './state-lock.js';\n\nexport type RunDatasetMaintenanceProtectedOptions = {\n planPath: string;\n freezePath: string;\n approvalPath: string;\n outDir: string;\n commit: boolean;\n statusOnly: boolean;\n approveExecution?: string;\n confirm?: string;\n waitSeconds?: number;\n pollMs?: number;\n pageSize?: number;\n timeoutMs?: number;\n env: NodeJS.ProcessEnv;\n fetchImpl: FetchLike;\n now?: Date;\n sleep?: (ms: number) => Promise<void>;\n};\n\nexport type DatasetMaintenanceProtectedReport = {\n schema_version: typeof PROTECTED_EXECUTION_CONTRACT.report_schema;\n generated_at_utc: string;\n mode: 'commit' | 'status_only';\n status: ProtectedReportStatus;\n request_id: string;\n identity_sha256: string;\n plan_sha256: string;\n operation_id: string;\n actor: { user_id: string; email: string };\n project_ref: string;\n admission: ProtectedAdmissionProof | null;\n database_status: ProtectedExecutionStatusProof | null;\n issues: Array<{ code: string; message: string; details?: unknown }>;\n artifacts: {\n execution_seal: string;\n preflight_evidence: string;\n gate_receipts: string;\n submission_attempt: string;\n admission_response: string;\n admission_transport_error: string;\n status_progress: string;\n primary_readback: string;\n reference_readback: string;\n audit_readback: string;\n derivative_readback: string;\n terminal_report: string;\n attempt_report: string;\n };\n};\n\ntype PreparedProtectedExecution = {\n planPath: string;\n planDir: string;\n freezePath: string;\n approvalPath: string;\n outDir: string;\n plan: DatasetMaintenancePlan;\n freeze: DatasetMaintenanceProtectedFreeze;\n approval: DatasetMaintenanceProtectedApproval;\n identity: ProtectedExecutionIdentity;\n aliasPlanRequest: JsonObject;\n artifacts: DatasetMaintenanceProtectedReport['artifacts'];\n};\n\nconst DEFAULT_POLL_MS = 10_000;\nconst SHA256 = /^[a-f0-9]{64}$/u;\n\nfunction normalizeWaitSeconds(value?: number): number {\n const normalized = value ?? 0;\n if (!Number.isInteger(normalized) || normalized < 0 || normalized > 86_400) {\n throw new CliError('waitSeconds must be an integer between 0 and 86400.', {\n code: 'DATASET_MAINTENANCE_PROTECTED_WAIT_INVALID',\n exitCode: 2,\n });\n }\n return normalized;\n}\n\nfunction normalizePollMs(value?: number): number {\n const normalized = value ?? DEFAULT_POLL_MS;\n if (!Number.isInteger(normalized) || normalized < 100 || normalized > 60_000) {\n throw new CliError('pollMs must be an integer between 100 and 60000.', {\n code: 'DATASET_MAINTENANCE_PROTECTED_POLL_INVALID',\n exitCode: 2,\n });\n }\n return normalized;\n}\n\nfunction clock(options: RunDatasetMaintenanceProtectedOptions): Date {\n return options.now ?? new Date();\n}\n\nfunction errorDetails(error: unknown): { name: string; message: string; code: string | null } {\n return {\n name: error instanceof Error ? error.name : 'Error',\n message: error instanceof Error ? error.message : String(error),\n code:\n error && typeof error === 'object' && 'code' in error && typeof error.code === 'string'\n ? error.code\n : null,\n };\n}\n\nfunction readArtifact(options: { filePath: string; label: string }): {\n resolved: string;\n value: unknown;\n file_sha256: string;\n} {\n const resolved = path.resolve(options.filePath);\n const text = readFileSync(resolved, 'utf8');\n return {\n resolved,\n value: readJsonFile(resolved, options.label),\n file_sha256: sha256Text(text),\n };\n}\n\nfunction ensurePrivateDirectory(directory: string): void {\n mkdirSync(directory, { recursive: true, mode: 0o700 });\n chmodSync(directory, 0o700);\n}\n\nfunction writePrivateImmutableJson(filePath: string, value: unknown): string {\n const resolved = path.resolve(filePath);\n const text = `${stableJsonText(value)}\\n`;\n ensurePrivateDirectory(path.dirname(resolved));\n if (existsSync(resolved)) {\n if (readFileSync(resolved, 'utf8') !== text) {\n throw new CliError(`Refusing to overwrite protected evidence: ${resolved}`, {\n code: 'DATASET_MAINTENANCE_PROTECTED_ARTIFACT_IMMUTABLE',\n exitCode: 1,\n });\n }\n chmodSync(resolved, 0o600);\n return resolved;\n }\n writeFileSync(resolved, text, { encoding: 'utf8', flag: 'wx', mode: 0o600 });\n return resolved;\n}\n\nfunction appendPrivateJsonLine(filePath: string, value: unknown): string {\n const resolved = path.resolve(filePath);\n ensurePrivateDirectory(path.dirname(resolved));\n appendFileSync(resolved, `${stableJsonText(value)}\\n`, {\n encoding: 'utf8',\n flag: 'a',\n mode: 0o600,\n });\n chmodSync(resolved, 0o600);\n return resolved;\n}\n\nfunction nextAttemptReportPath(outDir: string): string {\n let attempt = 1;\n while (attemptArtifactPaths(outDir, attempt).some((filePath) => existsSync(filePath))) {\n attempt += 1;\n }\n return attemptArtifactPaths(outDir, attempt)[0]!;\n}\n\nfunction attemptArtifactPaths(outDir: string, attempt: number): string[] {\n const suffix = `attempt-${String(attempt).padStart(4, '0')}`;\n return [\n path.join(outDir, `protected-run-report.${suffix}.json`),\n path.join(outDir, `protected-audit-readback.${suffix}.json`),\n path.join(outDir, `protected-primary-readback.${suffix}.json`),\n path.join(outDir, `protected-reference-readback.${suffix}.json`),\n path.join(outDir, `protected-derivative-readback.${suffix}.json`),\n ];\n}\n\nfunction allocateAttemptArtifacts(\n prepared: PreparedProtectedExecution,\n): PreparedProtectedExecution {\n const attemptReport = nextAttemptReportPath(prepared.outDir);\n const suffix = path.basename(attemptReport, '.json').replace('protected-run-report.', '');\n return {\n ...prepared,\n artifacts: {\n ...prepared.artifacts,\n audit_readback: path.join(prepared.outDir, `protected-audit-readback.${suffix}.json`),\n primary_readback: path.join(prepared.outDir, `protected-primary-readback.${suffix}.json`),\n reference_readback: path.join(prepared.outDir, `protected-reference-readback.${suffix}.json`),\n derivative_readback: path.join(\n prepared.outDir,\n `protected-derivative-readback.${suffix}.json`,\n ),\n attempt_report: attemptReport,\n },\n };\n}\n\ntype ProtectedPreparationDependencies = {\n readArtifact: typeof readArtifact;\n parsePlan: typeof parseMaintenancePlan;\n buildAliasPlan: typeof buildAliasPlanRequest;\n parseFreeze: typeof parseProtectedFreeze;\n parseApproval: typeof parseProtectedApproval;\n assertFreezeMatchesPlan: typeof assertProtectedFreezeMatchesPlan;\n assertApprovalBindings: typeof assertProtectedApprovalBindings;\n buildIdentity: typeof buildProtectedExecutionIdentity;\n};\n\nfunction prepareProtectedExecutionWithDependencies(\n options: RunDatasetMaintenanceProtectedOptions,\n dependencies: ProtectedPreparationDependencies,\n): PreparedProtectedExecution {\n if (options.commit === options.statusOnly) {\n throw new CliError('Choose exactly one of commit or statusOnly.', {\n code: 'DATASET_MAINTENANCE_PROTECTED_MODE_INVALID',\n exitCode: 2,\n });\n }\n if (\n options.commit &&\n (!options.approveExecution ||\n !SHA256.test(options.approveExecution) ||\n typeof options.confirm !== 'string' ||\n !options.confirm.trim())\n ) {\n throw new CliError('Protected commit requires the exact approval hash and account email.', {\n code: 'DATASET_MAINTENANCE_PROTECTED_APPROVAL_REQUIRED',\n exitCode: 2,\n });\n }\n normalizeWaitSeconds(options.waitSeconds);\n normalizePollMs(options.pollMs);\n normalizeMaintenancePageSize(options.pageSize);\n\n const planArtifact = dependencies.readArtifact({\n filePath: options.planPath,\n label: 'Maintenance plan',\n });\n const freezeArtifact = dependencies.readArtifact({\n filePath: options.freezePath,\n label: 'Protected execution freeze',\n });\n const approvalArtifact = dependencies.readArtifact({\n filePath: options.approvalPath,\n label: 'Protected execution approval',\n });\n const plan = dependencies.parsePlan(planArtifact.value);\n const planPath = planArtifact.resolved;\n const planDir = path.dirname(planPath);\n const aliasPlanRequest = dependencies.buildAliasPlan({ plan, planDir });\n const freeze = dependencies.parseFreeze(freezeArtifact.value);\n const approval = dependencies.parseApproval(approvalArtifact.value);\n dependencies.assertFreezeMatchesPlan({\n plan,\n planFileSha256: planArtifact.file_sha256,\n aliasPlanRequestSha256: sha256Json(aliasPlanRequest),\n freeze,\n });\n dependencies.assertApprovalBindings({\n approval,\n freeze,\n freezeFileSha256: freezeArtifact.file_sha256,\n approvalFileSha256: approvalArtifact.file_sha256,\n approveExecution: options.statusOnly\n ? approval.approval_identity_sha256\n : options.approveExecution,\n });\n const identity = dependencies.buildIdentity({\n freeze,\n approval,\n freezeFileSha256: freezeArtifact.file_sha256,\n approvalFileSha256: approvalArtifact.file_sha256,\n });\n const outDir = path.resolve(options.outDir);\n const artifacts = {\n execution_seal: path.join(outDir, 'protected-execution-seal.json'),\n preflight_evidence: path.join(outDir, 'protected-preflight-evidence.json'),\n gate_receipts: path.join(outDir, 'protected-gate-receipts.jsonl'),\n submission_attempt: path.join(outDir, 'protected-submission-attempt.json'),\n admission_response: path.join(outDir, 'protected-admission-response.json'),\n admission_transport_error: path.join(outDir, 'protected-admission-transport-error.json'),\n status_progress: path.join(outDir, 'protected-status-progress.jsonl'),\n primary_readback: path.join(outDir, 'protected-primary-readback.json'),\n reference_readback: path.join(outDir, 'protected-reference-readback.json'),\n audit_readback: path.join(outDir, 'protected-audit-readback.json'),\n derivative_readback: path.join(outDir, 'protected-derivative-readback.json'),\n terminal_report: path.join(outDir, 'protected-terminal-report.json'),\n attempt_report: path.join(outDir, 'protected-run-report.unallocated.json'),\n };\n return {\n planPath,\n planDir,\n freezePath: freezeArtifact.resolved,\n approvalPath: approvalArtifact.resolved,\n outDir,\n plan,\n freeze,\n approval,\n identity,\n aliasPlanRequest,\n artifacts,\n };\n}\n\nfunction prepareProtectedExecution(\n options: RunDatasetMaintenanceProtectedOptions,\n): PreparedProtectedExecution {\n return prepareProtectedExecutionWithDependencies(options, {\n readArtifact,\n parsePlan: parseMaintenancePlan,\n buildAliasPlan: buildAliasPlanRequest,\n parseFreeze: parseProtectedFreeze,\n parseApproval: parseProtectedApproval,\n assertFreezeMatchesPlan: assertProtectedFreezeMatchesPlan,\n assertApprovalBindings: assertProtectedApprovalBindings,\n buildIdentity: buildProtectedExecutionIdentity,\n });\n}\n\nfunction assertContextBindings(options: {\n prepared: PreparedProtectedExecution;\n context: DatasetMaintenanceRemoteContext;\n confirm?: string;\n commit: boolean;\n}): void {\n if (\n options.context.project_ref !== options.prepared.identity.project_ref ||\n options.context.account.user_id !== options.prepared.identity.actor.user_id ||\n options.context.account.email !== options.prepared.identity.actor.email ||\n (options.commit && options.confirm !== options.context.account.email)\n ) {\n throw new CliError(\n 'Authenticated RLS context does not match the sealed production project, actor, and confirmation.',\n {\n code: 'DATASET_MAINTENANCE_PROTECTED_CONTEXT_MISMATCH',\n exitCode: 1,\n details: {\n expected_project_ref: options.prepared.identity.project_ref,\n observed_project_ref: options.context.project_ref,\n expected_user_id: options.prepared.identity.actor.user_id,\n observed_user_id: options.context.account.user_id,\n },\n },\n );\n }\n}\n\nfunction projectedRows(options: {\n plan: DatasetMaintenancePlan;\n planDir: string;\n currentRows: DatasetMaintenanceRemoteRow[];\n}): DatasetMaintenanceRemoteRow[] {\n const projected = new Map(options.currentRows.map((row) => [maintenanceRowKey(row), { ...row }]));\n for (const action of options.plan.actions) {\n const row = projected.get(maintenanceRowKey(action));\n if (row) {\n projected.set(maintenanceRowKey(action), {\n ...row,\n json_ordered: loadMaintenanceDesiredPayload(options.planDir, action),\n });\n }\n }\n return [...projected.values()].sort((left, right) =>\n maintenanceRowKey(left).localeCompare(maintenanceRowKey(right)),\n );\n}\n\nfunction assertStrictBeforeState(options: {\n prepared: PreparedProtectedExecution;\n currentRows: DatasetMaintenanceRemoteRow[];\n completeness: unknown;\n}): void {\n const { plan } = options.prepared;\n if (\n !plan.snapshot_completeness ||\n !isSnapshotCompletenessCompatible(\n options.completeness,\n plan.snapshot_completeness,\n MAINTENANCE_SCAN_TABLES,\n )\n ) {\n throw new CliError('Production RLS census does not match the frozen complete snapshot.', {\n code: 'DATASET_MAINTENANCE_PROTECTED_SNAPSHOT_INCOMPLETE',\n exitCode: 1,\n });\n }\n const snapshots = options.currentRows\n .map(snapshotRemoteRow)\n .sort((left, right) => maintenanceRowKey(left).localeCompare(maintenanceRowKey(right)));\n if (sha256Json(snapshots) !== plan.visible_snapshot_sha256) {\n throw new CliError('Production RLS visible snapshot drifted after the freeze.', {\n code: 'DATASET_MAINTENANCE_PROTECTED_VISIBLE_SNAPSHOT_DRIFT',\n exitCode: 1,\n });\n }\n const expectedKeys = new Set([\n ...plan.actions.map(maintenanceRowKey),\n ...plan.protected_rows.map(maintenanceRowKey),\n ]);\n if (\n expectedKeys.size !== options.currentRows.length ||\n options.currentRows.some((row) => !expectedKeys.has(maintenanceRowKey(row)))\n ) {\n throw new CliError('Production owner account contains missing or unexpected rows.', {\n code: 'DATASET_MAINTENANCE_PROTECTED_ACCOUNT_CENSUS_DRIFT',\n exitCode: 1,\n });\n }\n const current = new Map(options.currentRows.map((row) => [maintenanceRowKey(row), row]));\n for (const row of plan.protected_rows) {\n const observed = current.get(maintenanceRowKey(row));\n if (!observed || snapshotRemoteRow(observed).row_sha256 !== row.row_sha256) {\n throw new CliError(`Protected row drifted: ${row.id}`, {\n code: 'DATASET_MAINTENANCE_PROTECTED_ROW_DRIFT',\n exitCode: 1,\n details: row,\n });\n }\n }\n for (const action of plan.actions) {\n const observed = current.get(maintenanceRowKey(action));\n if (\n !action.before ||\n !observed ||\n observed.user_id !== action.expected_user_id ||\n observed.state_code !== 0 ||\n snapshotRemoteRow(observed).row_sha256 !== action.before.row_sha256\n ) {\n throw new CliError(\n `Action row is no longer in the exact frozen before state: ${action.action_id}`,\n {\n code: 'DATASET_MAINTENANCE_PROTECTED_ACTION_DRIFT',\n exitCode: 1,\n },\n );\n }\n }\n const finalRows = projectedRows({\n plan,\n planDir: options.prepared.planDir,\n currentRows: options.currentRows,\n });\n if (\n sha256Json(maintenanceProjectedReferenceFingerprint(finalRows)) !==\n plan.projected_reference_sha256\n ) {\n throw new CliError('Projected reference closure drifted before protected execution.', {\n code: 'DATASET_MAINTENANCE_PROTECTED_REFERENCE_DRIFT',\n exitCode: 1,\n });\n }\n}\n\nasync function assertSupportSnapshots(options: {\n prepared: PreparedProtectedExecution;\n context: DatasetMaintenanceRemoteContext;\n}): Promise<void> {\n for (const batch of options.prepared.plan.alias_batches ?? []) {\n for (const snapshot of [\n batch.target_snapshots.unitgroup,\n batch.target_snapshots.flowproperty,\n batch.target_snapshots.source_unitgroup,\n ]) {\n if (!snapshot) {\n throw new CliError(`Alias support snapshot is absent for ${batch.batch_id}.`, {\n code: 'DATASET_MAINTENANCE_PROTECTED_SUPPORT_DRIFT',\n exitCode: 1,\n });\n }\n const exact = await fetchMaintenanceExactRows({\n context: options.context,\n table: snapshot.table,\n id: snapshot.id,\n version: snapshot.version,\n });\n const row = exact.rows.length === 1 ? exact.rows[0] : null;\n if (\n !row ||\n row.user_id !== options.prepared.identity.actor.user_id ||\n row.state_code !== 0 ||\n snapshotRemoteRow(row).row_sha256 !== snapshot.row_sha256\n ) {\n throw new CliError(`Alias support row drifted for ${batch.batch_id}.`, {\n code: 'DATASET_MAINTENANCE_PROTECTED_SUPPORT_DRIFT',\n exitCode: 1,\n details: { table: snapshot.table, id: snapshot.id, version: snapshot.version },\n });\n }\n }\n }\n}\n\nasync function assertDerivativeBaselines(options: {\n prepared: PreparedProtectedExecution;\n context: DatasetMaintenanceRemoteContext;\n}): Promise<void> {\n const targets = options.prepared.identity.derivative_targets;\n for (let offset = 0; offset < targets.length; offset += 5) {\n const chunk = targets.slice(offset, offset + 5);\n const snapshots = await Promise.all(\n chunk.map(async (target) =>\n parseProtectedDerivativeSnapshot(\n await fetchMaintenanceDerivativeSnapshot({\n context: options.context,\n table: target.table,\n id: target.id,\n version: target.version,\n }),\n {\n table: target.table,\n id: target.id,\n version: target.version,\n userId: target.user_id,\n },\n ),\n ),\n );\n for (const [index, snapshot] of snapshots.entries()) {\n const target = chunk[index]!;\n if (snapshot.snapshot_sha256 !== target.baseline_snapshot_sha256) {\n throw new CliError('A protected derivative baseline drifted before preflight.', {\n code: 'DATASET_MAINTENANCE_PROTECTED_DERIVATIVE_BASELINE_DRIFT',\n exitCode: 1,\n details: { table: target.table, id: target.id, version: target.version },\n });\n }\n }\n }\n}\n\ntype ProtectedGateDependencies = {\n captureGate: typeof captureMaintenanceAliasExecutionGate;\n parseGate: typeof parseProtectedGateProof;\n appendReceipt: typeof appendPrivateJsonLine;\n nowIso: () => string;\n};\n\nasync function captureProtectedGatesWithDependencies(\n options: {\n prepared: PreparedProtectedExecution;\n context: DatasetMaintenanceRemoteContext;\n preflight: ProtectedPreflightProof;\n receiptPath: string;\n },\n dependencies: ProtectedGateDependencies,\n): Promise<{\n proofs: ProtectedGateProof[];\n results: {\n primary_support_plan: ProtectedGateProof['result'];\n execution_unused: ProtectedGateProof['result'];\n derivative_quiescence: ProtectedGateProof['result'];\n };\n}> {\n const gateNames = ['primary_support_plan', 'execution_unused', 'derivative_quiescence'] as const;\n const proofs: ProtectedGateProof[] = [];\n for (const gate of gateNames) {\n const raw = await dependencies.captureGate({\n context: options.context,\n requestId: options.prepared.identity.request_id,\n preflightToken: options.preflight.preflight_token,\n gateName: gate,\n });\n const proof = dependencies.parseGate(raw, {\n identity: options.prepared.identity,\n preflight: options.preflight,\n gate,\n });\n dependencies.appendReceipt(options.receiptPath, {\n observed_at_utc: dependencies.nowIso(),\n proof,\n raw_response_sha256: sha256Json(raw),\n });\n proofs.push(proof);\n }\n return {\n proofs,\n results: {\n primary_support_plan: proofs[0]!.result,\n execution_unused: proofs[1]!.result,\n derivative_quiescence: proofs[2]!.result,\n },\n };\n}\n\nasync function captureProtectedGates(options: {\n prepared: PreparedProtectedExecution;\n context: DatasetMaintenanceRemoteContext;\n preflight: ProtectedPreflightProof;\n receiptPath: string;\n}): Promise<{\n proofs: ProtectedGateProof[];\n results: {\n primary_support_plan: ProtectedGateProof['result'];\n execution_unused: ProtectedGateProof['result'];\n derivative_quiescence: ProtectedGateProof['result'];\n };\n}> {\n return captureProtectedGatesWithDependencies(options, {\n captureGate: captureMaintenanceAliasExecutionGate,\n parseGate: parseProtectedGateProof,\n appendReceipt: appendPrivateJsonLine,\n nowIso: () => new Date().toISOString(),\n });\n}\n\nfunction validateExistingMarker(\n markerPath: string,\n identity: ProtectedExecutionIdentity,\n): JsonObject | null {\n if (!existsSync(markerPath)) return null;\n const marker = readJsonFile(markerPath, 'Protected submission attempt');\n if (\n !isJsonObject(marker) ||\n marker.schema_version !== PROTECTED_EXECUTION_CONTRACT.marker_schema ||\n marker.request_id !== identity.request_id ||\n marker.identity_sha256 !== identity.identity_sha256 ||\n marker.plan_sha256 !== identity.plan_sha256 ||\n marker.operation_id !== identity.operation_id ||\n marker.max_admit_posts !== 1 ||\n marker.automatic_retry !== false\n ) {\n throw new CliError('Existing protected submission marker is foreign or malformed.', {\n code: 'DATASET_MAINTENANCE_PROTECTED_MARKER_INVALID',\n exitCode: 1,\n });\n }\n return marker;\n}\n\ntype ProtectedReadDependencies = {\n readExecution: typeof readMaintenanceAliasExecution;\n parseStatus: typeof parseProtectedStatusProof;\n verifyExecution: typeof verifyProtectedExecution;\n nowMs: () => number;\n};\n\nasync function readAndVerifyWithDependencies(\n options: {\n command: RunDatasetMaintenanceProtectedOptions;\n prepared: PreparedProtectedExecution;\n context: DatasetMaintenanceRemoteContext;\n },\n dependencies: ProtectedReadDependencies,\n): Promise<{\n proof: ProtectedExecutionStatusProof | null;\n verification: ProtectedVerificationResult;\n}> {\n const waitSeconds = normalizeWaitSeconds(options.command.waitSeconds);\n const pollMs = normalizePollMs(options.command.pollMs);\n const deadline = dependencies.nowMs() + waitSeconds * 1_000;\n const sleep =\n options.command.sleep ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));\n while (true) {\n let raw: JsonObject;\n try {\n raw = await dependencies.readExecution({\n context: options.context,\n requestId: options.prepared.identity.request_id,\n });\n } catch (error) {\n appendPrivateJsonLine(options.prepared.artifacts.status_progress, {\n observed_at_utc: new Date().toISOString(),\n result: 'read_error',\n retry_scope: 'status_read_only',\n error: errorDetails(error),\n });\n if (dependencies.nowMs() < deadline) {\n await sleep(Math.min(pollMs, Math.max(deadline - dependencies.nowMs(), 0)));\n continue;\n }\n return {\n proof: null,\n verification: {\n status: 'indeterminate',\n issues: [\n {\n code: 'PROTECTED_STATUS_READ_UNAVAILABLE',\n message:\n 'Protected execution status could not be read; admission must not be retried.',\n details: errorDetails(error),\n },\n ],\n account_readback: null,\n derivative_readback: null,\n },\n };\n }\n const proof = dependencies.parseStatus(raw, options.prepared.identity);\n appendPrivateJsonLine(options.prepared.artifacts.status_progress, {\n observed_at_utc: new Date().toISOString(),\n proof,\n raw_response_sha256: sha256Json(raw),\n });\n const waitForAdmissionVisibility =\n proof.execution_status === 'not_admitted' && dependencies.nowMs() < deadline;\n if (\n (proof.status !== 'pending' && !waitForAdmissionVisibility) ||\n dependencies.nowMs() >= deadline\n ) {\n try {\n return {\n proof,\n verification: await dependencies.verifyExecution({\n plan: options.prepared.plan,\n planDir: options.prepared.planDir,\n identity: options.prepared.identity,\n proof,\n context: options.context,\n pageSize: options.command.pageSize,\n }),\n };\n } catch (error) {\n appendPrivateJsonLine(options.prepared.artifacts.status_progress, {\n observed_at_utc: new Date().toISOString(),\n result: 'verification_error',\n retry_scope: 'independent_readback_only',\n request_id: proof.request_id,\n error: errorDetails(error),\n });\n if (dependencies.nowMs() < deadline) {\n await sleep(Math.min(pollMs, Math.max(deadline - dependencies.nowMs(), 0)));\n continue;\n }\n return {\n proof,\n verification: {\n status: 'indeterminate',\n issues: [\n {\n code: 'PROTECTED_TERMINAL_READBACK_UNAVAILABLE',\n message:\n 'Terminal proof was returned but independent RLS readback was unavailable.',\n details: errorDetails(error),\n },\n ],\n account_readback: null,\n derivative_readback: null,\n },\n };\n }\n }\n await sleep(Math.min(pollMs, Math.max(deadline - dependencies.nowMs(), 0)));\n }\n}\n\nasync function readAndVerify(options: {\n command: RunDatasetMaintenanceProtectedOptions;\n prepared: PreparedProtectedExecution;\n context: DatasetMaintenanceRemoteContext;\n}): Promise<{\n proof: ProtectedExecutionStatusProof | null;\n verification: ProtectedVerificationResult;\n}> {\n return readAndVerifyWithDependencies(options, {\n readExecution: readMaintenanceAliasExecution,\n parseStatus: parseProtectedStatusProof,\n verifyExecution: verifyProtectedExecution,\n nowMs: Date.now,\n });\n}\n\nfunction buildReport(options: {\n command: RunDatasetMaintenanceProtectedOptions;\n prepared: PreparedProtectedExecution;\n admission: ProtectedAdmissionProof | null;\n proof: ProtectedExecutionStatusProof | null;\n verification: ProtectedVerificationResult;\n}): DatasetMaintenanceProtectedReport {\n return {\n schema_version: PROTECTED_EXECUTION_CONTRACT.report_schema,\n generated_at_utc: new Date().toISOString(),\n mode: options.command.statusOnly ? 'status_only' : 'commit',\n status: options.verification.status,\n request_id: options.prepared.identity.request_id,\n identity_sha256: options.prepared.identity.identity_sha256,\n plan_sha256: options.prepared.plan.plan_sha256,\n operation_id: options.prepared.plan.operation_id,\n actor: options.prepared.identity.actor,\n project_ref: options.prepared.identity.project_ref,\n admission: options.admission,\n database_status: options.proof,\n issues: options.verification.issues,\n artifacts: options.prepared.artifacts,\n };\n}\n\nfunction canonicalTerminalReport(report: DatasetMaintenanceProtectedReport): JsonObject {\n return {\n schema_version: report.schema_version,\n artifact_kind: 'protected_terminal_canonical',\n status: report.status,\n request_id: report.request_id,\n identity_sha256: report.identity_sha256,\n plan_sha256: report.plan_sha256,\n operation_id: report.operation_id,\n actor: report.actor,\n project_ref: report.project_ref,\n database_status: report.database_status,\n issues: report.issues,\n };\n}\n\nfunction persistVerificationArtifacts(options: {\n prepared: PreparedProtectedExecution;\n proof: ProtectedExecutionStatusProof | null;\n verification: ProtectedVerificationResult;\n report: DatasetMaintenanceProtectedReport;\n}): void {\n if (options.proof?.primary_readback) {\n writePrivateImmutableJson(\n options.prepared.artifacts.audit_readback,\n options.proof.primary_readback,\n );\n }\n if (options.verification.account_readback) {\n writePrivateImmutableJson(\n options.prepared.artifacts.primary_readback,\n options.verification.account_readback,\n );\n writePrivateImmutableJson(options.prepared.artifacts.reference_readback, {\n projected_reference_sha256: sha256Json(\n maintenanceProjectedReferenceFingerprint(options.verification.account_readback.rows),\n ),\n expected_projected_reference_sha256: options.prepared.plan.projected_reference_sha256,\n });\n }\n if (options.verification.derivative_readback) {\n writePrivateImmutableJson(\n options.prepared.artifacts.derivative_readback,\n options.verification.derivative_readback,\n );\n }\n const terminalReadbackRetryable = options.verification.issues.some(\n (entry) => entry.code === 'PROTECTED_TERMINAL_READBACK_UNAVAILABLE',\n );\n writePrivateImmutableJson(options.prepared.artifacts.attempt_report, options.report);\n if (\n options.proof &&\n options.proof.status !== 'pending' &&\n options.proof.execution_status !== 'not_admitted' &&\n !terminalReadbackRetryable &&\n !existsSync(options.prepared.artifacts.terminal_report)\n ) {\n writePrivateImmutableJson(\n options.prepared.artifacts.terminal_report,\n canonicalTerminalReport(options.report),\n );\n }\n}\n\ntype ProtectedRuntimeDependencies = {\n withStateLock: typeof withStateFileLock;\n resolveContext: typeof resolveMaintenanceRemoteContext;\n fetchAccountRows: typeof fetchMaintenanceAccountRows;\n assertSupport: typeof assertSupportSnapshots;\n assertBaselines: typeof assertDerivativeBaselines;\n buildPreflightRequest: typeof buildProtectedPreflightRequest;\n preflightExecution: typeof preflightMaintenanceAliasExecution;\n parsePreflight: typeof parseProtectedPreflightProof;\n captureGates: typeof captureProtectedGates;\n buildAdmitRequest: typeof buildProtectedAdmitRequest;\n admitExecution: typeof admitMaintenanceAliasExecution;\n parseAdmission: typeof parseProtectedAdmissionProof;\n readAndVerify: typeof readAndVerify;\n};\n\nasync function runPreparedProtectedExecution(\n options: RunDatasetMaintenanceProtectedOptions,\n basePrepared: PreparedProtectedExecution,\n dependencies: ProtectedRuntimeDependencies,\n): Promise<DatasetMaintenanceProtectedReport> {\n ensurePrivateDirectory(basePrepared.outDir);\n return dependencies.withStateLock(\n basePrepared.artifacts.submission_attempt,\n { reason: `dataset_maintenance_protected_${basePrepared.identity.request_id}` },\n async () => {\n writePrivateImmutableJson(basePrepared.artifacts.execution_seal, {\n schema_version: PROTECTED_EXECUTION_CONTRACT.freeze_schema,\n request_id: basePrepared.identity.request_id,\n identity_sha256: basePrepared.identity.identity_sha256,\n plan_path: basePrepared.planPath,\n freeze_path: basePrepared.freezePath,\n approval_path: basePrepared.approvalPath,\n plan_sha256: basePrepared.plan.plan_sha256,\n operation_id: basePrepared.plan.operation_id,\n project_ref: basePrepared.identity.project_ref,\n actor: basePrepared.identity.actor,\n bindings: basePrepared.identity.bindings,\n });\n const prepared = allocateAttemptArtifacts(basePrepared);\n const existingMarker = validateExistingMarker(\n prepared.artifacts.submission_attempt,\n prepared.identity,\n );\n if (options.commit && existingMarker) {\n throw new CliError(\n 'A protected submission marker already exists. Use status-only; admission cannot be retried.',\n {\n code: 'DATASET_MAINTENANCE_PROTECTED_ATTEMPT_EXISTS',\n exitCode: 1,\n },\n );\n }\n const context = await dependencies.resolveContext({\n env: options.env,\n fetchImpl: options.fetchImpl,\n timeoutMs: options.timeoutMs,\n now: options.now,\n });\n assertContextBindings({\n prepared,\n context,\n confirm: options.confirm,\n commit: options.commit,\n });\n\n let admission: ProtectedAdmissionProof | null = null;\n if (options.commit) {\n const current = await dependencies.fetchAccountRows({\n context,\n userId: prepared.identity.actor.user_id,\n pageSize: options.pageSize,\n });\n assertStrictBeforeState({\n prepared,\n currentRows: current.rows,\n completeness: current.completeness,\n });\n await dependencies.assertSupport({ prepared, context });\n await dependencies.assertBaselines({ prepared, context });\n\n const preflightRequest = dependencies.buildPreflightRequest({\n identity: prepared.identity,\n plan: prepared.aliasPlanRequest,\n freeze: prepared.freeze,\n approval: prepared.approval,\n });\n const preflightRaw = await dependencies.preflightExecution({\n context,\n request: preflightRequest,\n });\n const preflight = dependencies.parsePreflight(\n preflightRaw,\n prepared.identity,\n clock(options),\n );\n const { preflight_token: preflightToken, ...preflightEvidence } = preflight;\n writePrivateImmutableJson(prepared.artifacts.preflight_evidence, {\n proof: preflightEvidence,\n preflight_token_sha256: sha256Text(preflightToken),\n raw_response_sha256: sha256Json(preflightRaw),\n });\n const gates = await dependencies.captureGates({\n prepared,\n context,\n preflight,\n receiptPath: prepared.artifacts.gate_receipts,\n });\n writePrivateImmutableJson(prepared.artifacts.submission_attempt, {\n schema_version: PROTECTED_EXECUTION_CONTRACT.marker_schema,\n prepared_at_utc: clock(options).toISOString(),\n request_id: prepared.identity.request_id,\n identity_sha256: prepared.identity.identity_sha256,\n plan_sha256: prepared.identity.plan_sha256,\n operation_id: prepared.identity.operation_id,\n actor: prepared.identity.actor,\n project_ref: prepared.identity.project_ref,\n preflight_proof_sha256: preflight.preflight_proof_sha256,\n preflight_token_sha256: sha256Text(preflight.preflight_token),\n preflight_completed_at: preflight.completed_at,\n preflight_expires_at: preflight.expires_at,\n gate_results: gates.results,\n gate_receipt_sha256: Object.fromEntries(\n gates.proofs.map((proof) => [proof.gate, proof.receipt_sha256]),\n ),\n max_admit_posts: 1,\n automatic_retry: false,\n });\n\n const admitRequest = dependencies.buildAdmitRequest({\n preflight,\n gateResults: gates.results,\n });\n try {\n const admissionRaw = await dependencies.admitExecution({\n context,\n request: admitRequest,\n });\n admission = dependencies.parseAdmission(admissionRaw, prepared.identity, preflight);\n writePrivateImmutableJson(prepared.artifacts.admission_response, {\n proof: admission,\n raw_response_sha256: sha256Json(admissionRaw),\n });\n } catch (error) {\n writePrivateImmutableJson(prepared.artifacts.admission_transport_error, {\n schema_version: 1,\n request_id: prepared.identity.request_id,\n observed_at_utc: new Date().toISOString(),\n classification: 'ambiguous_consumed_attempt',\n error: errorDetails(error),\n });\n }\n }\n\n const readback = await dependencies.readAndVerify({ command: options, prepared, context });\n const report = buildReport({\n command: options,\n prepared,\n admission,\n proof: readback.proof,\n verification: readback.verification,\n });\n persistVerificationArtifacts({\n prepared,\n proof: readback.proof,\n verification: readback.verification,\n report,\n });\n return report;\n },\n );\n}\n\nexport async function runDatasetMaintenanceProtected(\n options: RunDatasetMaintenanceProtectedOptions,\n): Promise<DatasetMaintenanceProtectedReport> {\n const prepared = prepareProtectedExecution(options);\n return runPreparedProtectedExecution(options, prepared, {\n withStateLock: withStateFileLock,\n resolveContext: resolveMaintenanceRemoteContext,\n fetchAccountRows: fetchMaintenanceAccountRows,\n assertSupport: assertSupportSnapshots,\n assertBaselines: assertDerivativeBaselines,\n buildPreflightRequest: buildProtectedPreflightRequest,\n preflightExecution: preflightMaintenanceAliasExecution,\n parsePreflight: parseProtectedPreflightProof,\n captureGates: captureProtectedGates,\n buildAdmitRequest: buildProtectedAdmitRequest,\n admitExecution: admitMaintenanceAliasExecution,\n parseAdmission: parseProtectedAdmissionProof,\n readAndVerify,\n });\n}\n\nexport const __testInternals = {\n allocateAttemptArtifacts,\n appendPrivateJsonLine,\n assertContextBindings,\n assertDerivativeBaselines,\n assertStrictBeforeState,\n assertSupportSnapshots,\n buildReport,\n canonicalTerminalReport,\n clock,\n errorDetails,\n nextAttemptReportPath,\n normalizePollMs,\n normalizeWaitSeconds,\n prepareProtectedExecution,\n prepareProtectedExecutionWithDependencies,\n projectedRows,\n readArtifact,\n readAndVerify,\n readAndVerifyWithDependencies,\n runPreparedProtectedExecution,\n captureProtectedGates,\n captureProtectedGatesWithDependencies,\n persistVerificationArtifacts,\n validateExistingMarker,\n writePrivateImmutableJson,\n};\n"]}
1
+ {"version":3,"file":"dataset-maintenance-protected-run.js","sourceRoot":"","sources":["../../../src/lib/dataset-maintenance-protected-run.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAChE,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,qBAAqB,EAAE,MAAM,wCAAwC,CAAC;AAC/E,OAAO,EACL,8BAA8B,EAC9B,yBAAyB,EACzB,yBAAyB,GAC1B,MAAM,8CAA8C,CAAC;AACtD,OAAO,EACL,yBAAyB,IAAI,+BAA+B,EAC5D,uBAAuB,IAAI,6BAA6B,EACxD,sBAAsB,IAAI,4BAA4B,EACtD,aAAa,IAAI,mBAAmB,GACrC,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,YAAY,EACZ,oBAAoB,EACpB,YAAY,EACZ,UAAU,EACV,UAAU,EACV,cAAc,GAIf,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,4BAA4B,EAC5B,+BAA+B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AAED,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAClD,OAA8C;IAE9C,MAAM,QAAQ,GAAG,yBAAyB,CAAC,OAAO,CAAC,CAAC;IACpD,OAAO,6BAA6B,CAAC,OAAO,EAAE,QAAQ,EAAE;QACtD,aAAa,EAAE,iBAAiB;QAChC,cAAc,EAAE,+BAA+B;QAC/C,gBAAgB,EAAE,2BAA2B;QAC7C,aAAa,EAAE,sBAAsB;QACrC,eAAe,EAAE,yBAAyB;QAC1C,qBAAqB,EAAE,8BAA8B;QACrD,kBAAkB,EAAE,kCAAkC;QACtD,cAAc,EAAE,4BAA4B;QAC5C,YAAY,EAAE,qBAAqB;QACnC,iBAAiB,EAAE,0BAA0B;QAC7C,cAAc,EAAE,8BAA8B;QAC9C,cAAc,EAAE,4BAA4B;QAC5C,aAAa;KACd,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,wBAAwB;IACxB,qBAAqB;IACrB,6BAA6B;IAC7B,qBAAqB;IACrB,yBAAyB;IACzB,uBAAuB;IACvB,sBAAsB;IACtB,WAAW;IACX,uBAAuB;IACvB,KAAK;IACL,YAAY;IACZ,qBAAqB;IACrB,eAAe;IACf,oBAAoB;IACpB,yBAAyB;IACzB,yCAAyC;IACzC,aAAa;IACb,YAAY;IACZ,aAAa;IACb,6BAA6B;IAC7B,6BAA6B;IAC7B,qBAAqB;IACrB,qCAAqC;IACrC,4BAA4B;IAC5B,sBAAsB;IACtB,yBAAyB;CAC1B,CAAC","sourcesContent":["import { appendFileSync, chmodSync, existsSync } from 'node:fs';\nimport path from 'node:path';\nimport { buildAliasPlanRequest } from './dataset-maintenance-alias-request.js';\nimport {\n ensurePrivateArtifactDirectory,\n readProtectedJsonArtifact,\n writePrivateImmutableJson,\n} from './dataset-maintenance-protected-artifacts.js';\nimport {\n assertDerivativeBaselines as assertSharedDerivativeBaselines,\n assertStrictBeforeState as assertSharedStrictBeforeState,\n assertSupportSnapshots as assertSharedSupportSnapshots,\n projectedRows as sharedProjectedRows,\n} from './dataset-maintenance-protected-before.js';\nimport {\n isJsonObject,\n parseMaintenancePlan,\n readJsonFile,\n sha256Json,\n sha256Text,\n stableJsonText,\n type DatasetMaintenancePlan,\n type DatasetMaintenanceRemoteRow,\n type JsonObject,\n} from './dataset-maintenance-contract.js';\nimport {\n PROTECTED_EXECUTION_CONTRACT,\n assertProtectedApprovalBindings,\n assertProtectedFreezeMatchesPlan,\n buildProtectedAdmitRequest,\n buildProtectedExecutionIdentity,\n buildProtectedPreflightRequest,\n parseProtectedAdmissionProof,\n parseProtectedApproval,\n parseProtectedFreeze,\n parseProtectedGateProof,\n parseProtectedPreflightProof,\n parseProtectedStatusProof,\n type DatasetMaintenanceProtectedApproval,\n type DatasetMaintenanceProtectedFreeze,\n type ProtectedAdmissionProof,\n type ProtectedExecutionIdentity,\n type ProtectedExecutionStatusProof,\n type ProtectedGateProof,\n type ProtectedPreflightProof,\n type ProtectedReportStatus,\n} from './dataset-maintenance-protected-contract.js';\nimport {\n assertProtectedPreparationPlanSha256,\n assertProtectedProductionProjectRef,\n} from './dataset-maintenance-protected-preparation.js';\nimport {\n verifyProtectedExecution,\n type ProtectedVerificationResult,\n} from './dataset-maintenance-protected-verify.js';\nimport { maintenanceProjectedReferenceFingerprint } from './dataset-maintenance-plan.js';\nimport {\n admitMaintenanceAliasExecution,\n captureMaintenanceAliasExecutionGate,\n fetchMaintenanceAccountRows,\n normalizeMaintenancePageSize,\n preflightMaintenanceAliasExecution,\n readMaintenanceAliasExecution,\n resolveMaintenanceRemoteContext,\n type DatasetMaintenanceRemoteContext,\n} from './dataset-maintenance-remote.js';\nimport { CliError } from './errors.js';\nimport type { FetchLike } from './http.js';\nimport { withStateFileLock } from './state-lock.js';\n\nexport type RunDatasetMaintenanceProtectedOptions = {\n planPath: string;\n freezePath: string;\n approvalPath: string;\n outDir: string;\n commit: boolean;\n statusOnly: boolean;\n approveExecution?: string;\n confirm?: string;\n waitSeconds?: number;\n pollMs?: number;\n pageSize?: number;\n timeoutMs?: number;\n env: NodeJS.ProcessEnv;\n fetchImpl: FetchLike;\n now?: Date;\n sleep?: (ms: number) => Promise<void>;\n};\n\nexport type DatasetMaintenanceProtectedReport = {\n schema_version: typeof PROTECTED_EXECUTION_CONTRACT.report_schema;\n generated_at_utc: string;\n mode: 'commit' | 'status_only';\n status: ProtectedReportStatus;\n request_id: string;\n identity_sha256: string;\n plan_sha256: string;\n operation_id: string;\n actor: { user_id: string; email: string };\n project_ref: string;\n admission: ProtectedAdmissionProof | null;\n database_status: ProtectedExecutionStatusProof | null;\n issues: Array<{ code: string; message: string; details?: unknown }>;\n artifacts: {\n execution_seal: string;\n preflight_evidence: string;\n gate_receipts: string;\n submission_attempt: string;\n admission_response: string;\n admission_transport_error: string;\n status_progress: string;\n primary_readback: string;\n reference_readback: string;\n audit_readback: string;\n derivative_readback: string;\n terminal_report: string;\n attempt_report: string;\n };\n};\n\ntype PreparedProtectedExecution = {\n planPath: string;\n planDir: string;\n freezePath: string;\n approvalPath: string;\n outDir: string;\n plan: DatasetMaintenancePlan;\n freeze: DatasetMaintenanceProtectedFreeze;\n approval: DatasetMaintenanceProtectedApproval;\n identity: ProtectedExecutionIdentity;\n aliasPlanRequest: JsonObject;\n artifacts: DatasetMaintenanceProtectedReport['artifacts'];\n};\n\nconst DEFAULT_POLL_MS = 10_000;\nconst SHA256 = /^[a-f0-9]{64}$/u;\n\nfunction normalizeWaitSeconds(value?: number): number {\n const normalized = value ?? 0;\n if (!Number.isInteger(normalized) || normalized < 0 || normalized > 86_400) {\n throw new CliError('waitSeconds must be an integer between 0 and 86400.', {\n code: 'DATASET_MAINTENANCE_PROTECTED_WAIT_INVALID',\n exitCode: 2,\n });\n }\n return normalized;\n}\n\nfunction normalizePollMs(value?: number): number {\n const normalized = value ?? DEFAULT_POLL_MS;\n if (!Number.isInteger(normalized) || normalized < 100 || normalized > 60_000) {\n throw new CliError('pollMs must be an integer between 100 and 60000.', {\n code: 'DATASET_MAINTENANCE_PROTECTED_POLL_INVALID',\n exitCode: 2,\n });\n }\n return normalized;\n}\n\nfunction clock(options: RunDatasetMaintenanceProtectedOptions): Date {\n return options.now ?? new Date();\n}\n\nfunction errorDetails(error: unknown): { name: string; message: string; code: string | null } {\n return {\n name: error instanceof Error ? error.name : 'Error',\n message: error instanceof Error ? error.message : String(error),\n code:\n error && typeof error === 'object' && 'code' in error && typeof error.code === 'string'\n ? error.code\n : null,\n };\n}\n\nfunction readArtifact(options: { filePath: string; label: string }): {\n resolved: string;\n value: unknown;\n text: string;\n file_sha256: string;\n} {\n const artifact = readProtectedJsonArtifact(options);\n return {\n resolved: artifact.resolved,\n value: artifact.value,\n text: artifact.text,\n file_sha256: artifact.file_sha256,\n };\n}\n\nfunction assertCanonicalParsedArtifact(options: {\n label: string;\n text: string;\n value: unknown;\n}): void {\n if (options.text !== `${stableJsonText(options.value)}\\n`) {\n throw new CliError(`${options.label} must be canonical JSON with exactly one final newline.`, {\n code: 'DATASET_MAINTENANCE_PROTECTED_ARTIFACT_NONCANONICAL',\n exitCode: 2,\n });\n }\n}\n\nfunction ensurePrivateDirectory(directory: string): void {\n ensurePrivateArtifactDirectory(directory);\n}\n\nfunction appendPrivateJsonLine(filePath: string, value: unknown): string {\n const resolved = path.resolve(filePath);\n ensurePrivateDirectory(path.dirname(resolved));\n appendFileSync(resolved, `${stableJsonText(value)}\\n`, {\n encoding: 'utf8',\n flag: 'a',\n mode: 0o600,\n });\n chmodSync(resolved, 0o600);\n return resolved;\n}\n\nfunction nextAttemptReportPath(outDir: string): string {\n let attempt = 1;\n while (attemptArtifactPaths(outDir, attempt).some((filePath) => existsSync(filePath))) {\n attempt += 1;\n }\n return attemptArtifactPaths(outDir, attempt)[0]!;\n}\n\nfunction attemptArtifactPaths(outDir: string, attempt: number): string[] {\n const suffix = `attempt-${String(attempt).padStart(4, '0')}`;\n return [\n path.join(outDir, `protected-run-report.${suffix}.json`),\n path.join(outDir, `protected-audit-readback.${suffix}.json`),\n path.join(outDir, `protected-primary-readback.${suffix}.json`),\n path.join(outDir, `protected-reference-readback.${suffix}.json`),\n path.join(outDir, `protected-derivative-readback.${suffix}.json`),\n ];\n}\n\nfunction allocateAttemptArtifacts(\n prepared: PreparedProtectedExecution,\n): PreparedProtectedExecution {\n const attemptReport = nextAttemptReportPath(prepared.outDir);\n const suffix = path.basename(attemptReport, '.json').replace('protected-run-report.', '');\n return {\n ...prepared,\n artifacts: {\n ...prepared.artifacts,\n audit_readback: path.join(prepared.outDir, `protected-audit-readback.${suffix}.json`),\n primary_readback: path.join(prepared.outDir, `protected-primary-readback.${suffix}.json`),\n reference_readback: path.join(prepared.outDir, `protected-reference-readback.${suffix}.json`),\n derivative_readback: path.join(\n prepared.outDir,\n `protected-derivative-readback.${suffix}.json`,\n ),\n attempt_report: attemptReport,\n },\n };\n}\n\ntype ProtectedPreparationDependencies = {\n readArtifact: typeof readArtifact;\n parsePlan: typeof parseMaintenancePlan;\n buildAliasPlan: typeof buildAliasPlanRequest;\n parseFreeze: typeof parseProtectedFreeze;\n parseApproval: typeof parseProtectedApproval;\n assertFreezeMatchesPlan: typeof assertProtectedFreezeMatchesPlan;\n assertApprovalBindings: typeof assertProtectedApprovalBindings;\n buildIdentity: typeof buildProtectedExecutionIdentity;\n};\n\nfunction prepareProtectedExecutionWithDependencies(\n options: RunDatasetMaintenanceProtectedOptions,\n dependencies: ProtectedPreparationDependencies,\n): PreparedProtectedExecution {\n if (options.commit === options.statusOnly) {\n throw new CliError('Choose exactly one of commit or statusOnly.', {\n code: 'DATASET_MAINTENANCE_PROTECTED_MODE_INVALID',\n exitCode: 2,\n });\n }\n if (\n options.commit &&\n (!options.approveExecution ||\n !SHA256.test(options.approveExecution) ||\n typeof options.confirm !== 'string' ||\n !options.confirm.trim())\n ) {\n throw new CliError('Protected commit requires the exact approval hash and account email.', {\n code: 'DATASET_MAINTENANCE_PROTECTED_APPROVAL_REQUIRED',\n exitCode: 2,\n });\n }\n normalizeWaitSeconds(options.waitSeconds);\n normalizePollMs(options.pollMs);\n normalizeMaintenancePageSize(options.pageSize);\n\n const planArtifact = dependencies.readArtifact({\n filePath: options.planPath,\n label: 'Maintenance plan',\n });\n const freezeArtifact = dependencies.readArtifact({\n filePath: options.freezePath,\n label: 'Protected execution freeze',\n });\n const approvalArtifact = dependencies.readArtifact({\n filePath: options.approvalPath,\n label: 'Protected execution approval',\n });\n const plan = dependencies.parsePlan(planArtifact.value);\n if (options.commit) {\n assertProtectedPreparationPlanSha256(plan.plan_sha256, 'plan.plan_sha256');\n }\n const planPath = planArtifact.resolved;\n const planDir = path.dirname(planPath);\n const aliasPlanRequest = dependencies.buildAliasPlan({ plan, planDir });\n const freeze = dependencies.parseFreeze(freezeArtifact.value);\n const approval = dependencies.parseApproval(approvalArtifact.value);\n assertCanonicalParsedArtifact({\n label: 'Protected execution freeze',\n text: freezeArtifact.text,\n value: freeze,\n });\n assertCanonicalParsedArtifact({\n label: 'Protected execution approval',\n text: approvalArtifact.text,\n value: approval,\n });\n dependencies.assertFreezeMatchesPlan({\n plan,\n planFileSha256: planArtifact.file_sha256,\n aliasPlanRequestSha256: sha256Json(aliasPlanRequest),\n freeze,\n });\n dependencies.assertApprovalBindings({\n approval,\n freeze,\n freezeFileSha256: freezeArtifact.file_sha256,\n approvalFileSha256: approvalArtifact.file_sha256,\n approveExecution: options.statusOnly\n ? approval.approval_identity_sha256\n : options.approveExecution,\n });\n const identity = dependencies.buildIdentity({\n freeze,\n approval,\n freezeFileSha256: freezeArtifact.file_sha256,\n approvalFileSha256: approvalArtifact.file_sha256,\n });\n if (options.commit) {\n assertProtectedProductionProjectRef(identity.project_ref);\n }\n const outDir = path.resolve(options.outDir);\n const artifacts = {\n execution_seal: path.join(outDir, 'protected-execution-seal.json'),\n preflight_evidence: path.join(outDir, 'protected-preflight-evidence.json'),\n gate_receipts: path.join(outDir, 'protected-gate-receipts.jsonl'),\n submission_attempt: path.join(outDir, 'protected-submission-attempt.json'),\n admission_response: path.join(outDir, 'protected-admission-response.json'),\n admission_transport_error: path.join(outDir, 'protected-admission-transport-error.json'),\n status_progress: path.join(outDir, 'protected-status-progress.jsonl'),\n primary_readback: path.join(outDir, 'protected-primary-readback.json'),\n reference_readback: path.join(outDir, 'protected-reference-readback.json'),\n audit_readback: path.join(outDir, 'protected-audit-readback.json'),\n derivative_readback: path.join(outDir, 'protected-derivative-readback.json'),\n terminal_report: path.join(outDir, 'protected-terminal-report.json'),\n attempt_report: path.join(outDir, 'protected-run-report.unallocated.json'),\n };\n return {\n planPath,\n planDir,\n freezePath: freezeArtifact.resolved,\n approvalPath: approvalArtifact.resolved,\n outDir,\n plan,\n freeze,\n approval,\n identity,\n aliasPlanRequest,\n artifacts,\n };\n}\n\nfunction prepareProtectedExecution(\n options: RunDatasetMaintenanceProtectedOptions,\n): PreparedProtectedExecution {\n return prepareProtectedExecutionWithDependencies(options, {\n readArtifact,\n parsePlan: parseMaintenancePlan,\n buildAliasPlan: buildAliasPlanRequest,\n parseFreeze: parseProtectedFreeze,\n parseApproval: parseProtectedApproval,\n assertFreezeMatchesPlan: assertProtectedFreezeMatchesPlan,\n assertApprovalBindings: assertProtectedApprovalBindings,\n buildIdentity: buildProtectedExecutionIdentity,\n });\n}\n\nfunction assertContextBindings(options: {\n prepared: PreparedProtectedExecution;\n context: DatasetMaintenanceRemoteContext;\n confirm?: string;\n commit: boolean;\n}): void {\n if (\n options.context.project_ref !== options.prepared.identity.project_ref ||\n options.context.account.user_id !== options.prepared.identity.actor.user_id ||\n options.context.account.email !== options.prepared.identity.actor.email ||\n (options.commit && options.confirm !== options.context.account.email)\n ) {\n throw new CliError(\n 'Authenticated RLS context does not match the sealed production project, actor, and confirmation.',\n {\n code: 'DATASET_MAINTENANCE_PROTECTED_CONTEXT_MISMATCH',\n exitCode: 1,\n details: {\n expected_project_ref: options.prepared.identity.project_ref,\n observed_project_ref: options.context.project_ref,\n expected_user_id: options.prepared.identity.actor.user_id,\n observed_user_id: options.context.account.user_id,\n },\n },\n );\n }\n}\n\nfunction projectedRows(options: {\n plan: DatasetMaintenancePlan;\n planDir: string;\n currentRows: DatasetMaintenanceRemoteRow[];\n}): DatasetMaintenanceRemoteRow[] {\n return sharedProjectedRows(options);\n}\n\nfunction assertStrictBeforeState(options: {\n prepared: PreparedProtectedExecution;\n currentRows: DatasetMaintenanceRemoteRow[];\n completeness: unknown;\n}): void {\n assertSharedStrictBeforeState({\n plan: options.prepared.plan,\n planDir: options.prepared.planDir,\n actorUserId: options.prepared.identity.actor.user_id,\n currentRows: options.currentRows,\n completeness: options.completeness,\n });\n}\n\nasync function assertSupportSnapshots(options: {\n prepared: PreparedProtectedExecution;\n context: DatasetMaintenanceRemoteContext;\n}): Promise<void> {\n await assertSharedSupportSnapshots({\n plan: options.prepared.plan,\n actorUserId: options.prepared.identity.actor.user_id,\n context: options.context,\n });\n}\n\nasync function assertDerivativeBaselines(options: {\n prepared: PreparedProtectedExecution;\n context: DatasetMaintenanceRemoteContext;\n}): Promise<void> {\n await assertSharedDerivativeBaselines({\n actorUserId: options.prepared.identity.actor.user_id,\n context: options.context,\n derivativeTargets: options.prepared.identity.derivative_targets,\n });\n}\n\ntype ProtectedGateDependencies = {\n captureGate: typeof captureMaintenanceAliasExecutionGate;\n parseGate: typeof parseProtectedGateProof;\n appendReceipt: typeof appendPrivateJsonLine;\n nowIso: () => string;\n};\n\nasync function captureProtectedGatesWithDependencies(\n options: {\n prepared: PreparedProtectedExecution;\n context: DatasetMaintenanceRemoteContext;\n preflight: ProtectedPreflightProof;\n receiptPath: string;\n },\n dependencies: ProtectedGateDependencies,\n): Promise<{\n proofs: ProtectedGateProof[];\n results: {\n primary_support_plan: ProtectedGateProof['result'];\n execution_unused: ProtectedGateProof['result'];\n derivative_quiescence: ProtectedGateProof['result'];\n };\n}> {\n const gateNames = ['primary_support_plan', 'execution_unused', 'derivative_quiescence'] as const;\n const proofs: ProtectedGateProof[] = [];\n for (const gate of gateNames) {\n const raw = await dependencies.captureGate({\n context: options.context,\n requestId: options.prepared.identity.request_id,\n preflightToken: options.preflight.preflight_token,\n gateName: gate,\n });\n const proof = dependencies.parseGate(raw, {\n identity: options.prepared.identity,\n preflight: options.preflight,\n gate,\n });\n dependencies.appendReceipt(options.receiptPath, {\n observed_at_utc: dependencies.nowIso(),\n proof,\n raw_response_sha256: sha256Json(raw),\n });\n proofs.push(proof);\n }\n return {\n proofs,\n results: {\n primary_support_plan: proofs[0]!.result,\n execution_unused: proofs[1]!.result,\n derivative_quiescence: proofs[2]!.result,\n },\n };\n}\n\nasync function captureProtectedGates(options: {\n prepared: PreparedProtectedExecution;\n context: DatasetMaintenanceRemoteContext;\n preflight: ProtectedPreflightProof;\n receiptPath: string;\n}): Promise<{\n proofs: ProtectedGateProof[];\n results: {\n primary_support_plan: ProtectedGateProof['result'];\n execution_unused: ProtectedGateProof['result'];\n derivative_quiescence: ProtectedGateProof['result'];\n };\n}> {\n return captureProtectedGatesWithDependencies(options, {\n captureGate: captureMaintenanceAliasExecutionGate,\n parseGate: parseProtectedGateProof,\n appendReceipt: appendPrivateJsonLine,\n nowIso: () => new Date().toISOString(),\n });\n}\n\nfunction validateExistingMarker(\n markerPath: string,\n identity: ProtectedExecutionIdentity,\n): JsonObject | null {\n if (!existsSync(markerPath)) return null;\n const marker = readJsonFile(markerPath, 'Protected submission attempt');\n if (\n !isJsonObject(marker) ||\n marker.schema_version !== PROTECTED_EXECUTION_CONTRACT.marker_schema ||\n marker.request_id !== identity.request_id ||\n marker.identity_sha256 !== identity.identity_sha256 ||\n marker.plan_sha256 !== identity.plan_sha256 ||\n marker.operation_id !== identity.operation_id ||\n marker.max_admit_posts !== 1 ||\n marker.automatic_retry !== false\n ) {\n throw new CliError('Existing protected submission marker is foreign or malformed.', {\n code: 'DATASET_MAINTENANCE_PROTECTED_MARKER_INVALID',\n exitCode: 1,\n });\n }\n return marker;\n}\n\ntype ProtectedReadDependencies = {\n readExecution: typeof readMaintenanceAliasExecution;\n parseStatus: typeof parseProtectedStatusProof;\n verifyExecution: typeof verifyProtectedExecution;\n nowMs: () => number;\n};\n\nasync function readAndVerifyWithDependencies(\n options: {\n command: RunDatasetMaintenanceProtectedOptions;\n prepared: PreparedProtectedExecution;\n context: DatasetMaintenanceRemoteContext;\n },\n dependencies: ProtectedReadDependencies,\n): Promise<{\n proof: ProtectedExecutionStatusProof | null;\n verification: ProtectedVerificationResult;\n}> {\n const waitSeconds = normalizeWaitSeconds(options.command.waitSeconds);\n const pollMs = normalizePollMs(options.command.pollMs);\n const deadline = dependencies.nowMs() + waitSeconds * 1_000;\n const sleep =\n options.command.sleep ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));\n while (true) {\n let raw: JsonObject;\n try {\n raw = await dependencies.readExecution({\n context: options.context,\n requestId: options.prepared.identity.request_id,\n });\n } catch (error) {\n appendPrivateJsonLine(options.prepared.artifacts.status_progress, {\n observed_at_utc: new Date().toISOString(),\n result: 'read_error',\n retry_scope: 'status_read_only',\n error: errorDetails(error),\n });\n if (dependencies.nowMs() < deadline) {\n await sleep(Math.min(pollMs, Math.max(deadline - dependencies.nowMs(), 0)));\n continue;\n }\n return {\n proof: null,\n verification: {\n status: 'indeterminate',\n issues: [\n {\n code: 'PROTECTED_STATUS_READ_UNAVAILABLE',\n message:\n 'Protected execution status could not be read; admission must not be retried.',\n details: errorDetails(error),\n },\n ],\n account_readback: null,\n derivative_readback: null,\n },\n };\n }\n const proof = dependencies.parseStatus(raw, options.prepared.identity);\n appendPrivateJsonLine(options.prepared.artifacts.status_progress, {\n observed_at_utc: new Date().toISOString(),\n proof,\n raw_response_sha256: sha256Json(raw),\n });\n const waitForAdmissionVisibility =\n proof.execution_status === 'not_admitted' && dependencies.nowMs() < deadline;\n if (\n (proof.status !== 'pending' && !waitForAdmissionVisibility) ||\n dependencies.nowMs() >= deadline\n ) {\n try {\n return {\n proof,\n verification: await dependencies.verifyExecution({\n plan: options.prepared.plan,\n planDir: options.prepared.planDir,\n identity: options.prepared.identity,\n proof,\n context: options.context,\n pageSize: options.command.pageSize,\n }),\n };\n } catch (error) {\n appendPrivateJsonLine(options.prepared.artifacts.status_progress, {\n observed_at_utc: new Date().toISOString(),\n result: 'verification_error',\n retry_scope: 'independent_readback_only',\n request_id: proof.request_id,\n error: errorDetails(error),\n });\n if (dependencies.nowMs() < deadline) {\n await sleep(Math.min(pollMs, Math.max(deadline - dependencies.nowMs(), 0)));\n continue;\n }\n return {\n proof,\n verification: {\n status: 'indeterminate',\n issues: [\n {\n code: 'PROTECTED_TERMINAL_READBACK_UNAVAILABLE',\n message:\n 'Terminal proof was returned but independent RLS readback was unavailable.',\n details: errorDetails(error),\n },\n ],\n account_readback: null,\n derivative_readback: null,\n },\n };\n }\n }\n await sleep(Math.min(pollMs, Math.max(deadline - dependencies.nowMs(), 0)));\n }\n}\n\nasync function readAndVerify(options: {\n command: RunDatasetMaintenanceProtectedOptions;\n prepared: PreparedProtectedExecution;\n context: DatasetMaintenanceRemoteContext;\n}): Promise<{\n proof: ProtectedExecutionStatusProof | null;\n verification: ProtectedVerificationResult;\n}> {\n return readAndVerifyWithDependencies(options, {\n readExecution: readMaintenanceAliasExecution,\n parseStatus: parseProtectedStatusProof,\n verifyExecution: verifyProtectedExecution,\n nowMs: Date.now,\n });\n}\n\nfunction buildReport(options: {\n command: RunDatasetMaintenanceProtectedOptions;\n prepared: PreparedProtectedExecution;\n admission: ProtectedAdmissionProof | null;\n proof: ProtectedExecutionStatusProof | null;\n verification: ProtectedVerificationResult;\n}): DatasetMaintenanceProtectedReport {\n return {\n schema_version: PROTECTED_EXECUTION_CONTRACT.report_schema,\n generated_at_utc: new Date().toISOString(),\n mode: options.command.statusOnly ? 'status_only' : 'commit',\n status: options.verification.status,\n request_id: options.prepared.identity.request_id,\n identity_sha256: options.prepared.identity.identity_sha256,\n plan_sha256: options.prepared.plan.plan_sha256,\n operation_id: options.prepared.plan.operation_id,\n actor: options.prepared.identity.actor,\n project_ref: options.prepared.identity.project_ref,\n admission: options.admission,\n database_status: options.proof,\n issues: options.verification.issues,\n artifacts: options.prepared.artifacts,\n };\n}\n\nfunction canonicalTerminalReport(report: DatasetMaintenanceProtectedReport): JsonObject {\n return {\n schema_version: report.schema_version,\n artifact_kind: 'protected_terminal_canonical',\n status: report.status,\n request_id: report.request_id,\n identity_sha256: report.identity_sha256,\n plan_sha256: report.plan_sha256,\n operation_id: report.operation_id,\n actor: report.actor,\n project_ref: report.project_ref,\n database_status: report.database_status,\n issues: report.issues,\n };\n}\n\nfunction persistVerificationArtifacts(options: {\n prepared: PreparedProtectedExecution;\n proof: ProtectedExecutionStatusProof | null;\n verification: ProtectedVerificationResult;\n report: DatasetMaintenanceProtectedReport;\n}): void {\n if (options.proof?.primary_readback) {\n writePrivateImmutableJson(\n options.prepared.artifacts.audit_readback,\n options.proof.primary_readback,\n );\n }\n if (options.verification.account_readback) {\n writePrivateImmutableJson(\n options.prepared.artifacts.primary_readback,\n options.verification.account_readback,\n );\n writePrivateImmutableJson(options.prepared.artifacts.reference_readback, {\n projected_reference_sha256: sha256Json(\n maintenanceProjectedReferenceFingerprint(options.verification.account_readback.rows),\n ),\n expected_projected_reference_sha256: options.prepared.plan.projected_reference_sha256,\n });\n }\n if (options.verification.derivative_readback) {\n writePrivateImmutableJson(\n options.prepared.artifacts.derivative_readback,\n options.verification.derivative_readback,\n );\n }\n const terminalReadbackRetryable = options.verification.issues.some(\n (entry) => entry.code === 'PROTECTED_TERMINAL_READBACK_UNAVAILABLE',\n );\n writePrivateImmutableJson(options.prepared.artifacts.attempt_report, options.report);\n if (\n options.proof &&\n options.proof.status !== 'pending' &&\n options.proof.execution_status !== 'not_admitted' &&\n !terminalReadbackRetryable &&\n !existsSync(options.prepared.artifacts.terminal_report)\n ) {\n writePrivateImmutableJson(\n options.prepared.artifacts.terminal_report,\n canonicalTerminalReport(options.report),\n );\n }\n}\n\ntype ProtectedRuntimeDependencies = {\n withStateLock: typeof withStateFileLock;\n resolveContext: typeof resolveMaintenanceRemoteContext;\n fetchAccountRows: typeof fetchMaintenanceAccountRows;\n assertSupport: typeof assertSupportSnapshots;\n assertBaselines: typeof assertDerivativeBaselines;\n buildPreflightRequest: typeof buildProtectedPreflightRequest;\n preflightExecution: typeof preflightMaintenanceAliasExecution;\n parsePreflight: typeof parseProtectedPreflightProof;\n captureGates: typeof captureProtectedGates;\n buildAdmitRequest: typeof buildProtectedAdmitRequest;\n admitExecution: typeof admitMaintenanceAliasExecution;\n parseAdmission: typeof parseProtectedAdmissionProof;\n readAndVerify: typeof readAndVerify;\n};\n\nasync function runPreparedProtectedExecution(\n options: RunDatasetMaintenanceProtectedOptions,\n basePrepared: PreparedProtectedExecution,\n dependencies: ProtectedRuntimeDependencies,\n): Promise<DatasetMaintenanceProtectedReport> {\n ensurePrivateDirectory(basePrepared.outDir);\n return dependencies.withStateLock(\n basePrepared.artifacts.submission_attempt,\n { reason: `dataset_maintenance_protected_${basePrepared.identity.request_id}` },\n async () => {\n writePrivateImmutableJson(basePrepared.artifacts.execution_seal, {\n schema_version: PROTECTED_EXECUTION_CONTRACT.freeze_schema,\n request_id: basePrepared.identity.request_id,\n identity_sha256: basePrepared.identity.identity_sha256,\n plan_path: basePrepared.planPath,\n freeze_path: basePrepared.freezePath,\n approval_path: basePrepared.approvalPath,\n plan_sha256: basePrepared.plan.plan_sha256,\n operation_id: basePrepared.plan.operation_id,\n project_ref: basePrepared.identity.project_ref,\n actor: basePrepared.identity.actor,\n bindings: basePrepared.identity.bindings,\n });\n const prepared = allocateAttemptArtifacts(basePrepared);\n const existingMarker = validateExistingMarker(\n prepared.artifacts.submission_attempt,\n prepared.identity,\n );\n if (options.commit && existingMarker) {\n throw new CliError(\n 'A protected submission marker already exists. Use status-only; admission cannot be retried.',\n {\n code: 'DATASET_MAINTENANCE_PROTECTED_ATTEMPT_EXISTS',\n exitCode: 1,\n },\n );\n }\n const context = await dependencies.resolveContext({\n env: options.env,\n fetchImpl: options.fetchImpl,\n timeoutMs: options.timeoutMs,\n now: options.now,\n });\n assertContextBindings({\n prepared,\n context,\n confirm: options.confirm,\n commit: options.commit,\n });\n\n let admission: ProtectedAdmissionProof | null = null;\n if (options.commit) {\n const current = await dependencies.fetchAccountRows({\n context,\n userId: prepared.identity.actor.user_id,\n pageSize: options.pageSize,\n });\n assertStrictBeforeState({\n prepared,\n currentRows: current.rows,\n completeness: current.completeness,\n });\n await dependencies.assertSupport({ prepared, context });\n await dependencies.assertBaselines({ prepared, context });\n\n const preflightRequest = dependencies.buildPreflightRequest({\n identity: prepared.identity,\n plan: prepared.aliasPlanRequest,\n freeze: prepared.freeze,\n approval: prepared.approval,\n });\n const preflightRaw = await dependencies.preflightExecution({\n context,\n request: preflightRequest,\n });\n const preflight = dependencies.parsePreflight(\n preflightRaw,\n prepared.identity,\n clock(options),\n );\n const { preflight_token: preflightToken, ...preflightEvidence } = preflight;\n writePrivateImmutableJson(prepared.artifacts.preflight_evidence, {\n proof: preflightEvidence,\n preflight_token_sha256: sha256Text(preflightToken),\n raw_response_sha256: sha256Json(preflightRaw),\n });\n const gates = await dependencies.captureGates({\n prepared,\n context,\n preflight,\n receiptPath: prepared.artifacts.gate_receipts,\n });\n writePrivateImmutableJson(prepared.artifacts.submission_attempt, {\n schema_version: PROTECTED_EXECUTION_CONTRACT.marker_schema,\n prepared_at_utc: clock(options).toISOString(),\n request_id: prepared.identity.request_id,\n identity_sha256: prepared.identity.identity_sha256,\n plan_sha256: prepared.identity.plan_sha256,\n operation_id: prepared.identity.operation_id,\n actor: prepared.identity.actor,\n project_ref: prepared.identity.project_ref,\n preflight_proof_sha256: preflight.preflight_proof_sha256,\n preflight_token_sha256: sha256Text(preflight.preflight_token),\n preflight_completed_at: preflight.completed_at,\n preflight_expires_at: preflight.expires_at,\n gate_results: gates.results,\n gate_receipt_sha256: Object.fromEntries(\n gates.proofs.map((proof) => [proof.gate, proof.receipt_sha256]),\n ),\n max_admit_posts: 1,\n automatic_retry: false,\n });\n\n const admitRequest = dependencies.buildAdmitRequest({\n preflight,\n gateResults: gates.results,\n });\n try {\n const admissionRaw = await dependencies.admitExecution({\n context,\n request: admitRequest,\n });\n admission = dependencies.parseAdmission(admissionRaw, prepared.identity, preflight);\n writePrivateImmutableJson(prepared.artifacts.admission_response, {\n proof: admission,\n raw_response_sha256: sha256Json(admissionRaw),\n });\n } catch (error) {\n writePrivateImmutableJson(prepared.artifacts.admission_transport_error, {\n schema_version: 1,\n request_id: prepared.identity.request_id,\n observed_at_utc: new Date().toISOString(),\n classification: 'ambiguous_consumed_attempt',\n error: errorDetails(error),\n });\n }\n }\n\n const readback = await dependencies.readAndVerify({ command: options, prepared, context });\n const report = buildReport({\n command: options,\n prepared,\n admission,\n proof: readback.proof,\n verification: readback.verification,\n });\n persistVerificationArtifacts({\n prepared,\n proof: readback.proof,\n verification: readback.verification,\n report,\n });\n return report;\n },\n );\n}\n\nexport async function runDatasetMaintenanceProtected(\n options: RunDatasetMaintenanceProtectedOptions,\n): Promise<DatasetMaintenanceProtectedReport> {\n const prepared = prepareProtectedExecution(options);\n return runPreparedProtectedExecution(options, prepared, {\n withStateLock: withStateFileLock,\n resolveContext: resolveMaintenanceRemoteContext,\n fetchAccountRows: fetchMaintenanceAccountRows,\n assertSupport: assertSupportSnapshots,\n assertBaselines: assertDerivativeBaselines,\n buildPreflightRequest: buildProtectedPreflightRequest,\n preflightExecution: preflightMaintenanceAliasExecution,\n parsePreflight: parseProtectedPreflightProof,\n captureGates: captureProtectedGates,\n buildAdmitRequest: buildProtectedAdmitRequest,\n admitExecution: admitMaintenanceAliasExecution,\n parseAdmission: parseProtectedAdmissionProof,\n readAndVerify,\n });\n}\n\nexport const __testInternals = {\n allocateAttemptArtifacts,\n appendPrivateJsonLine,\n assertCanonicalParsedArtifact,\n assertContextBindings,\n assertDerivativeBaselines,\n assertStrictBeforeState,\n assertSupportSnapshots,\n buildReport,\n canonicalTerminalReport,\n clock,\n errorDetails,\n nextAttemptReportPath,\n normalizePollMs,\n normalizeWaitSeconds,\n prepareProtectedExecution,\n prepareProtectedExecutionWithDependencies,\n projectedRows,\n readArtifact,\n readAndVerify,\n readAndVerifyWithDependencies,\n runPreparedProtectedExecution,\n captureProtectedGates,\n captureProtectedGatesWithDependencies,\n persistVerificationArtifacts,\n validateExistingMarker,\n writePrivateImmutableJson,\n};\n"]}