primitive-admin 1.3.0-alpha.0 → 1.3.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/README.md +45 -0
  2. package/dist/src/commands/auth.js +32 -6
  3. package/dist/src/commands/auth.js.map +1 -1
  4. package/dist/src/commands/db3-types.d.ts +27 -0
  5. package/dist/src/commands/db3-types.js +288 -2
  6. package/dist/src/commands/db3-types.js.map +1 -1
  7. package/dist/src/commands/db3.d.ts +16 -2
  8. package/dist/src/commands/db3.js +614 -5
  9. package/dist/src/commands/db3.js.map +1 -1
  10. package/dist/src/commands/documents.js +7 -0
  11. package/dist/src/commands/documents.js.map +1 -1
  12. package/dist/src/commands/functions.js +8 -3
  13. package/dist/src/commands/functions.js.map +1 -1
  14. package/dist/src/commands/hosting.js +177 -14
  15. package/dist/src/commands/hosting.js.map +1 -1
  16. package/dist/src/commands/metadata.js +14 -6
  17. package/dist/src/commands/metadata.js.map +1 -1
  18. package/dist/src/commands/secrets.d.ts +38 -0
  19. package/dist/src/commands/secrets.js +102 -4
  20. package/dist/src/commands/secrets.js.map +1 -1
  21. package/dist/src/commands/spent-tokens.d.ts +19 -0
  22. package/dist/src/commands/spent-tokens.js +79 -0
  23. package/dist/src/commands/spent-tokens.js.map +1 -0
  24. package/dist/src/commands/sync-app-settings.d.ts +58 -0
  25. package/dist/src/commands/sync-app-settings.js +119 -2
  26. package/dist/src/commands/sync-app-settings.js.map +1 -1
  27. package/dist/src/commands/sync.d.ts +62 -2
  28. package/dist/src/commands/sync.js +295 -46
  29. package/dist/src/commands/sync.js.map +1 -1
  30. package/dist/src/commands/usage.d.ts +24 -0
  31. package/dist/src/commands/usage.js +54 -0
  32. package/dist/src/commands/usage.js.map +1 -1
  33. package/dist/src/commands/users.js +41 -1
  34. package/dist/src/commands/users.js.map +1 -1
  35. package/dist/src/lib/api-client.d.ts +165 -0
  36. package/dist/src/lib/api-client.js +134 -10
  37. package/dist/src/lib/api-client.js.map +1 -1
  38. package/dist/src/lib/app-settings-descriptor.d.ts +13 -1
  39. package/dist/src/lib/app-settings-descriptor.js +49 -1
  40. package/dist/src/lib/app-settings-descriptor.js.map +1 -1
  41. package/dist/src/lib/auth-flow.d.ts +13 -0
  42. package/dist/src/lib/auth-flow.js +23 -2
  43. package/dist/src/lib/auth-flow.js.map +1 -1
  44. package/dist/src/lib/command-groups.js +2 -0
  45. package/dist/src/lib/command-groups.js.map +1 -1
  46. package/dist/src/lib/config-object-descriptor.js +6 -1
  47. package/dist/src/lib/config-object-descriptor.js.map +1 -1
  48. package/dist/src/lib/credentials-store.d.ts +19 -0
  49. package/dist/src/lib/credentials-store.js +66 -2
  50. package/dist/src/lib/credentials-store.js.map +1 -1
  51. package/dist/src/lib/db-codegen/dbTypeIR.d.ts +2 -0
  52. package/dist/src/lib/db-codegen/dbTypeIR.js +3 -1
  53. package/dist/src/lib/db-codegen/dbTypeIR.js.map +1 -1
  54. package/dist/src/lib/db-type-records.d.ts +20 -1
  55. package/dist/src/lib/db-type-records.js +17 -4
  56. package/dist/src/lib/db-type-records.js.map +1 -1
  57. package/dist/src/lib/db3-export.d.ts +43 -8
  58. package/dist/src/lib/db3-export.js +133 -13
  59. package/dist/src/lib/db3-export.js.map +1 -1
  60. package/dist/src/lib/db3-json-fields.d.ts +49 -0
  61. package/dist/src/lib/db3-json-fields.js +195 -0
  62. package/dist/src/lib/db3-json-fields.js.map +1 -0
  63. package/dist/src/lib/db3-type-archive.d.ts +59 -0
  64. package/dist/src/lib/db3-type-archive.js +95 -0
  65. package/dist/src/lib/db3-type-archive.js.map +1 -0
  66. package/dist/src/lib/db3-type-models.d.ts +15 -1
  67. package/dist/src/lib/db3-type-models.js +147 -16
  68. package/dist/src/lib/db3-type-models.js.map +1 -1
  69. package/dist/src/lib/document-export-record-log.d.ts +7 -0
  70. package/dist/src/lib/document-export-record-log.js +9 -0
  71. package/dist/src/lib/document-export-record-log.js.map +1 -1
  72. package/dist/src/lib/document-ingest-artifact.d.ts +6 -0
  73. package/dist/src/lib/document-ingest-artifact.js +20 -1
  74. package/dist/src/lib/document-ingest-artifact.js.map +1 -1
  75. package/dist/src/lib/function-authorize-view.d.ts +9 -0
  76. package/dist/src/lib/function-authorize-view.js +22 -0
  77. package/dist/src/lib/function-authorize-view.js.map +1 -1
  78. package/dist/src/lib/function-collect.d.ts +22 -0
  79. package/dist/src/lib/function-collect.js +120 -1
  80. package/dist/src/lib/function-collect.js.map +1 -1
  81. package/dist/src/lib/function-db-types.js +31 -2
  82. package/dist/src/lib/function-db-types.js.map +1 -1
  83. package/dist/src/lib/function-grants-preflight.d.ts +99 -0
  84. package/dist/src/lib/function-grants-preflight.js +154 -2
  85. package/dist/src/lib/function-grants-preflight.js.map +1 -1
  86. package/dist/src/lib/function-lint.d.ts +29 -1
  87. package/dist/src/lib/function-lint.js +208 -0
  88. package/dist/src/lib/function-lint.js.map +1 -1
  89. package/dist/src/lib/function-sync.d.ts +11 -0
  90. package/dist/src/lib/function-sync.js +40 -2
  91. package/dist/src/lib/function-sync.js.map +1 -1
  92. package/dist/src/lib/generated-command-status.js +41 -8
  93. package/dist/src/lib/generated-command-status.js.map +1 -1
  94. package/dist/src/lib/generated-config-surfaces.d.ts +276 -9
  95. package/dist/src/lib/generated-config-surfaces.js +791 -24
  96. package/dist/src/lib/generated-config-surfaces.js.map +1 -1
  97. package/dist/src/lib/generated-sdk-types.d.ts +1 -1
  98. package/dist/src/lib/generated-sdk-types.js +1 -1
  99. package/dist/src/lib/generated-sdk-types.js.map +1 -1
  100. package/dist/src/lib/hosting-trust-step.d.ts +67 -0
  101. package/dist/src/lib/hosting-trust-step.js +279 -0
  102. package/dist/src/lib/hosting-trust-step.js.map +1 -0
  103. package/dist/src/lib/hosting-trust.d.ts +77 -0
  104. package/dist/src/lib/hosting-trust.js +194 -0
  105. package/dist/src/lib/hosting-trust.js.map +1 -0
  106. package/dist/src/lib/primitive-declaration.js +89 -10
  107. package/dist/src/lib/primitive-declaration.js.map +1 -1
  108. package/dist/src/lib/refresh-admin-credentials.d.ts +34 -4
  109. package/dist/src/lib/refresh-admin-credentials.js +85 -29
  110. package/dist/src/lib/refresh-admin-credentials.js.map +1 -1
  111. package/dist/src/lib/refresh-stored-login.d.ts +85 -0
  112. package/dist/src/lib/refresh-stored-login.js +233 -0
  113. package/dist/src/lib/refresh-stored-login.js.map +1 -0
  114. package/dist/src/lib/row-field-rename.d.ts +18 -0
  115. package/dist/src/lib/row-field-rename.js +32 -0
  116. package/dist/src/lib/row-field-rename.js.map +1 -0
  117. package/dist/src/lib/schema-codegen/generated-field-grammar.d.ts +13 -2
  118. package/dist/src/lib/schema-codegen/generated-field-grammar.js +24 -1
  119. package/dist/src/lib/schema-codegen/generated-field-grammar.js.map +1 -1
  120. package/dist/src/lib/schema-defs-module.d.ts +29 -0
  121. package/dist/src/lib/schema-defs-module.js +103 -0
  122. package/dist/src/lib/schema-defs-module.js.map +1 -0
  123. package/dist/src/lib/swift-codegen/sharedGenerator.d.ts +6 -0
  124. package/dist/src/lib/swift-codegen/sharedGenerator.js +74 -0
  125. package/dist/src/lib/swift-codegen/sharedGenerator.js.map +1 -1
  126. package/dist/src/lib/toml-list-edit.d.ts +33 -0
  127. package/dist/src/lib/toml-list-edit.js +481 -0
  128. package/dist/src/lib/toml-list-edit.js.map +1 -0
  129. package/dist/src/lib/toml-scalar-edit.d.ts +9 -0
  130. package/dist/src/lib/toml-scalar-edit.js +67 -1
  131. package/dist/src/lib/toml-scalar-edit.js.map +1 -1
  132. package/dist/src/lib/usage-meters.d.ts +16 -0
  133. package/dist/src/lib/usage-meters.js +52 -0
  134. package/dist/src/lib/usage-meters.js.map +1 -0
  135. package/package.json +2 -2
@@ -20,13 +20,14 @@ import { cachedVarsNote, layerVars, planVarsOverridePull, varsOverridePath as re
20
20
  import { resolveSyncDir, resolveSnapshotsRoot, resolveSyncStateReadPath, resolveSyncStateWritePath, SYNC_STATE_FILENAME, checkLegacyDatabaseTypesDir, } from "../lib/sync-paths.js";
21
21
  import { createSnapshot, listSnapshots, resolveSnapshot, restoreSnapshot, pruneSnapshots, } from "../lib/snapshots.js";
22
22
  import { FieldTableError, parseConfigToml, parseRawToml, stringifyConfigToml } from "../lib/config-toml.js";
23
- import { cloneTomlValue, planDb3TypePull, readDb3TypeContext, readDb3TypesDir, resolveDb3TypeModels } from "../lib/db3-type-models.js";
23
+ import { cloneTomlValue, databaseTypeConfigJsonRefusals, planDb3TypePull, readDb3TypeContext, readDb3TypesDir, resolveDb3TypeModels, } from "../lib/db3-type-models.js";
24
+ import { db3JsonDefRefusals } from "../lib/db3-json-fields.js";
24
25
  import { canonicalizeIntegrationRequestConfig } from "../lib/integration-request-config.js";
25
26
  import { canonicalizeServerTextFields } from "../lib/server-text-normalization.js";
26
27
  import { canonicalJsonStringify } from "../lib/canonical-json.js";
27
28
  import { newPullWriteTally, writePulledFile, } from "../lib/pull-write.js";
28
29
  import { serializeSection, parseTomlToAppSettings, buildAppSettingsPayload, settingsProtectionLevel, } from "../lib/app-settings-descriptor.js";
29
- import { collectAppSettingsPushErrors, writePulledAppSettings, diffAppSettings, appSettingsFieldDiffs, appSettingsNameExcluded, appSettingsNameExcludedForState, hashAppSettingsForDiff, } from "./sync-app-settings.js";
30
+ import { collectAppSettingsPushErrors, writePulledAppSettings, diffAppSettings, appSettingsFieldDiffs, appSettingsNameExcluded, appSettingsNameExcludedForState, hashAppSettingsForDiff, appSettingsLoweredMinimums, appSettingsWriteBody, clientVersionsWriteFailure, confirmClientVersionLowering, } from "./sync-app-settings.js";
30
31
  // #2644 — the one definition per configuration object, vendored from the server.
31
32
  import { BLOB_BUCKET_TABLE, DATABASE_TYPE_TABLE, DB3_TYPE_TABLE, EMAIL_TEMPLATE_TABLE, INTEGRATION_TABLE, METADATA_CATEGORY_CONFIG_TABLE, PROMPT_CONFIG_TABLE, PROMPT_TABLE, RULE_SET_TABLE, SERVER_FUNCTION_TABLE, TEST_CASE_SURFACE, TEST_CASE_TABLE, configDeclaredTypeErrors, deprecatedConfigKey, fieldServerDefault, findMisshapenTables, findUnknownDocumentKeys, findUnknownGroupedTomlKeys, findUnknownTomlKeys, misshapenTableMessage, retiredTomlKey, retiredDocumentKey, spellsDecimalNumber, unrecognizedPushKeysMessage, unrecognizedPushTablesMessage, warnUnrecognizedServerKeys, } from "../lib/config-surface.js";
32
33
  import { buildPayloadFromToml, projectEntityToPayload, projectRecordToToml, tomlOwned, } from "../lib/config-payload.js";
@@ -53,7 +54,7 @@ import { agentFunctionChangeRefusals, agentFunctionUses, } from "../lib/generate
53
54
  import { resolvePromptStrictOutput } from "../lib/generated-config-surfaces.js";
54
55
  // #3179 — the function's two halves: the header payloads and the envelope
55
56
  // `config push` sends, and the bytes `config pull` writes back.
56
- import { applyFunctionPull, buildFunctionConfigPush, buildFunctionConfigPushDetailed, createDocumentSchemaDropWarner, documentSchemaRetentionFailure, buildFunctionCreatePayload, buildFunctionUpdatePayload, functionDiffEntity, functionTomlPreflightErrors, functionPushPreRefusal, functionVersionRefusalMessage, unchangedAccessWarning, planDocumentSchemaPull, planFunctionPull, serializeFunction, } from "../lib/function-sync.js";
57
+ import { applyFunctionPull, buildFunctionConfigPush, buildFunctionConfigPushDetailed, createDocumentSchemaDropWarner, documentSchemaRetentionFailure, buildFunctionCreatePayload, buildFunctionUpdatePayload, functionDiffEntity, functionTomlPreflightErrors, functionVersionPushWarnings, functionPushPreRefusal, functionVersionRefusalMessage, unchangedAccessWarning, planDocumentSchemaPull, planFunctionPull, serializeFunction, } from "../lib/function-sync.js";
57
58
  import { compileFunctionToml, functionFileLabel } from "../lib/function-schema-refs.js";
58
59
  import { compilePromptToml, promptSchemaCycleError, promptSchemaKeywordRefusals, preparePromptSchemaRefs, promptConfigSchemaPayload, promptDependenciesOf, promptPlacementErrors, promptPushDependencies, promptSchemaPayload, withSchemaPayload, } from "../lib/prompt-schema-refs.js";
59
60
  import { promptFamilyIndexLoader, rememberRemoteFunctions, rememberRemotePrompts } from "../lib/schema-family-index.js";
@@ -67,7 +68,7 @@ import { FunctionBuildError } from "../lib/function-bundle.js";
67
68
  import { previewNamesOf } from "../lib/primitive-declaration.js";
68
69
  // #3182 — the local half of capability validation. The grammar is the vendored
69
70
  // module the server also imports; this is where an author's own file is read.
70
- import { configObjectKeysFromTree, functionGrantErrors, mergeKnownGrantTargets, } from "../lib/function-grants-preflight.js";
71
+ import { configObjectKeysFromTree, functionGrantErrors, functionReservedSecretPreflight, mergeKnownGrantTargets, } from "../lib/function-grants-preflight.js";
71
72
  // #3182 — the typed handle's generated declarations and the compiler wiring
72
73
  // that makes an editor load them.
73
74
  import { functionTypeWiringProblems, applyFunctionTypeArtifacts, functionTypeRemovalLine, staleFunctionTypeArtifacts, } from "../lib/function-db-types.js";
@@ -2225,6 +2226,20 @@ export async function runConfigPushPreflight(input) {
2225
2226
  // the integrations the server already has. If the live listing cannot
2226
2227
  // be fetched and the tree declares none, the target check is skipped
2227
2228
  // and the server — which is authoritative — has the last word.
2229
+ // The app's functions, listed at most once for the #6119, #3798 and #4441 checks.
2230
+ // `null` when the listing failed.
2231
+ let liveFunctionRows;
2232
+ const liveFunctionListing = async () => {
2233
+ if (liveFunctionRows === undefined) {
2234
+ try {
2235
+ liveFunctionRows = (await client.listFunctions(resolvedAppId)).items;
2236
+ }
2237
+ catch {
2238
+ liveFunctionRows = null;
2239
+ }
2240
+ }
2241
+ return liveFunctionRows;
2242
+ };
2228
2243
  const preflightFunctionsDir = join(configDir, "functions");
2229
2244
  if (existsSync(preflightFunctionsDir)) {
2230
2245
  const functionFiles = selectFiles("function", preflightFunctionsDir, readdirSync(preflightFunctionsDir).filter(isFunctionDeclarationFile));
@@ -2264,6 +2279,7 @@ export async function runConfigPushPreflight(input) {
2264
2279
  configDir,
2265
2280
  functionFiles: functionFiles.map((file) => join(preflightFunctionsDir, file)),
2266
2281
  });
2282
+ const reservedSecretFiles = [];
2267
2283
  for (const file of functionFiles) {
2268
2284
  const filePath = join(preflightFunctionsDir, file);
2269
2285
  let tomlData;
@@ -2295,6 +2311,7 @@ export async function runConfigPushPreflight(input) {
2295
2311
  // Bounded by the same `selectFiles` above, so `--only` keeps its
2296
2312
  // posture (#2645).
2297
2313
  const functionKey = tomlData?.function?.key || basename(file, ".toml");
2314
+ reservedSecretFiles.push({ filePath, functionKey, tomlData });
2298
2315
  for (const message of functionTomlPreflightErrors({
2299
2316
  filePath,
2300
2317
  functionKey,
@@ -2306,6 +2323,21 @@ export async function runConfigPushPreflight(input) {
2306
2323
  : ` ${filePath}: ${message}`);
2307
2324
  }
2308
2325
  }
2326
+ // #6119 — a `secret:` capability naming a reserved app secret the
2327
+ // function's active version does not already hold is refused here, with
2328
+ // the server's sentence. Reads nothing unless a selected file names one;
2329
+ // a listing or envelope that cannot be read skips the check with a
2330
+ // warning, and the server still refuses.
2331
+ const reservedSecrets = await functionReservedSecretPreflight({
2332
+ files: reservedSecretFiles,
2333
+ listFunctions: liveFunctionListing,
2334
+ getEnvelope: (functionId, configId) => client.getFunctionConfigEnvelope(resolvedAppId, functionId, configId),
2335
+ });
2336
+ for (const message of reservedSecrets.warnings)
2337
+ warn(` ${message}`);
2338
+ for (const message of reservedSecrets.errors) {
2339
+ preflightValidationErrors.push(` ${message}`);
2340
+ }
2309
2341
  }
2310
2342
  }
2311
2343
  // #5534 — the prompt files are compiled with the server's own module, by
@@ -2369,20 +2401,6 @@ export async function runConfigPushPreflight(input) {
2369
2401
  // #3798 — the functions an agent's references are checked against, read
2370
2402
  // once and only when a selected prompt is an agent that names one.
2371
2403
  let agentFunctions = null;
2372
- // The app's functions, listed at most once for the #3798 and #4441 checks.
2373
- // `null` when the listing failed.
2374
- let liveFunctionRows;
2375
- const liveFunctionListing = async () => {
2376
- if (liveFunctionRows === undefined) {
2377
- try {
2378
- liveFunctionRows = (await client.listFunctions(resolvedAppId)).items;
2379
- }
2380
- catch {
2381
- liveFunctionRows = null;
2382
- }
2383
- }
2384
- return liveFunctionRows;
2385
- };
2386
2404
  if (existsSync(preflightPromptsDir)) {
2387
2405
  for (const file of selectFiles("prompt", preflightPromptsDir, readdirSync(preflightPromptsDir).filter((f) => f.endsWith(".toml")))) {
2388
2406
  const filePath = join(preflightPromptsDir, file);
@@ -3336,6 +3354,16 @@ export function configFileValidationMessages(filePath, tomlData, surface, tables
3336
3354
  if (surface.label === "prompt") {
3337
3355
  messages.push(...promptKindFileErrors(filePath, tomlData));
3338
3356
  }
3357
+ // #6020 — `archived` is a key, not a field, so the declared-type check above does not see it.
3358
+ if (surface.label === "db3-type") {
3359
+ const archivedError = db3TypeArchivedKeyError(filePath, tomlData);
3360
+ if (archivedError)
3361
+ messages.push(archivedError);
3362
+ // #5998 — `create` is a key too.
3363
+ const createError = db3TypeCreateKeyError(filePath, tomlData);
3364
+ if (createError)
3365
+ messages.push(createError);
3366
+ }
3339
3367
  return messages;
3340
3368
  }
3341
3369
  /**
@@ -3407,8 +3435,15 @@ export function collectConfigFileValidationErrors(configDir, experimental = EXPE
3407
3435
  // #5025 — a db3 type naming a model declared in another file of the
3408
3436
  // directory: an undeclared or self reference, or two files declaring one
3409
3437
  // model differently, refuses every file it is about.
3410
- if (dir === "db3-types") {
3411
- for (const refusal of resolveDb3TypeModels(typeDir).refusals) {
3438
+ // #5899 — a JSON field's def may use only the keywords the client validators implement, and a JSON field belongs to
3439
+ // a db3 type in db3-types/.
3440
+ const treeRefusals = dir === "db3-types"
3441
+ ? [...resolveDb3TypeModels(typeDir).refusals, ...db3JsonDefRefusals(configDir).map(({ file, message }) => ({ files: [file], message }))]
3442
+ : dir === "database-type-configs"
3443
+ ? databaseTypeConfigJsonRefusals(configDir)
3444
+ : null;
3445
+ if (treeRefusals) {
3446
+ for (const refusal of treeRefusals) {
3412
3447
  for (const file of refusal.files) {
3413
3448
  const filePath = join(typeDir, file);
3414
3449
  let tomlData;
@@ -3611,14 +3646,51 @@ export function serializeDatabaseType(typeConfig, ruleSetIdToName, options = {})
3611
3646
  */
3612
3647
  export function serializeDb3Type(typeConfig, ruleSetIdToName, options = {}) {
3613
3648
  warnUnrecognizedServerKeys(typeConfig, DB3_TYPE_TABLE, `db3-types/${typeConfig?.databaseType}.toml`, options.logger);
3614
- return stringifyConfigToml(buildDatabaseTypeTomlData(typeConfig, ruleSetIdToName, DB3_TYPE_TABLE));
3649
+ const data = buildDatabaseTypeTomlData(typeConfig, ruleSetIdToName, DB3_TYPE_TABLE);
3650
+ // #6020 — only an archived type's file carries the key, so every other
3651
+ // type's pulled file is as it was.
3652
+ if (typeConfig?.archived === true)
3653
+ data.type = { ...data.type, archived: true };
3654
+ // #5998 — likewise only a restricted type's file carries `create`.
3655
+ if (typeConfig?.create === "admins")
3656
+ data.type = { ...data.type, create: "admins" };
3657
+ return stringifyConfigToml(data);
3615
3658
  }
3616
3659
  /**
3617
3660
  * #4802 — a `db3-types/<name>.toml` file as the payload `PUT db3-types/:name`
3618
3661
  * takes: the database type file's, its type read from `[type] name`.
3662
+ * #6020 — `[type] archived = true` reads as `archived: true`; `false` and an
3663
+ * absent key both read as active (no key), the spelling a pull writes.
3619
3664
  */
3620
3665
  export function parseDb3TypeToml(tomlData) {
3621
- return parseDatabaseTypeToml(tomlData, DB3_TYPE_TABLE);
3666
+ const parsed = parseDatabaseTypeToml(tomlData, DB3_TYPE_TABLE);
3667
+ if (tomlData?.type?.archived === true)
3668
+ parsed.typeConfig.archived = true;
3669
+ // #5998 — `[type] create = "admins"` reads as `create: "admins"`; `"members"`
3670
+ // and an absent key both read as open (no key), the spelling a pull writes.
3671
+ if (tomlData?.type?.create === "admins")
3672
+ parsed.typeConfig.create = "admins";
3673
+ return parsed;
3674
+ }
3675
+ /**
3676
+ * #5998 — the preflight refusal of a `db3-types/` file whose `[type] create`
3677
+ * is not `"admins"` or `"members"`, or `null` when it is one or absent.
3678
+ */
3679
+ export function db3TypeCreateKeyError(filePath, tomlData) {
3680
+ const value = tomlData?.type?.create;
3681
+ if (value === undefined || value === "admins" || value === "members")
3682
+ return null;
3683
+ return `${filePath}: [type] create must be "admins" or "members", not ${JSON.stringify(value)}`;
3684
+ }
3685
+ /**
3686
+ * #6020 — the preflight refusal of a `db3-types/` file whose `[type]
3687
+ * archived` is not a boolean, or `null` when it is one or absent.
3688
+ */
3689
+ export function db3TypeArchivedKeyError(filePath, tomlData) {
3690
+ const value = tomlData?.type?.archived;
3691
+ if (value === undefined || typeof value === "boolean")
3692
+ return null;
3693
+ return `${filePath}: [type] archived must be a boolean (true or false), not ${JSON.stringify(value)}`;
3622
3694
  }
3623
3695
  /**
3624
3696
  * Flatten an email-template detail response onto its field surface.
@@ -4688,6 +4760,11 @@ export const DB3_TYPE_DIFF_SPEC = {
4688
4760
  schema: entity.schema ?? null,
4689
4761
  triggers: entity.triggers ?? null,
4690
4762
  metadataManifest: entity.metadataManifest ?? null,
4763
+ // #6020 — only when archived, so a type never archived projects (and
4764
+ // hashes) exactly as before, and an absent key reads as `false`.
4765
+ ...(entity.archived === true ? { archived: true } : {}),
4766
+ // #5998 — likewise only when restricted, so `create = "members"` is no drift.
4767
+ ...(entity.create === "admins" ? { create: "admins" } : {}),
4691
4768
  }),
4692
4769
  describe: (entity) => `db3 type "${entity?.databaseType}"`,
4693
4770
  };
@@ -4754,6 +4831,10 @@ export function buildDb3TypePushBody(typeConfig, options) {
4754
4831
  ...buildOwnedScalarUpdate(typeConfig, DB3_TYPE_OWNED_SCALARS),
4755
4832
  triggers: typeConfig.triggers ?? null,
4756
4833
  metadataManifest: typeConfig.metadataManifest ?? null,
4834
+ // #6020 — the file owns the archived state: a file without the key unarchives.
4835
+ archived: typeConfig.archived === true,
4836
+ // #5998 — the file owns the create setting: a file without the key opens the type.
4837
+ create: typeConfig.create === "admins" ? "admins" : "members",
4757
4838
  };
4758
4839
  if (typeof typeConfig.schema === "string" && typeConfig.schema.trim().length > 0)
4759
4840
  body.schema = typeConfig.schema;
@@ -4765,6 +4846,34 @@ export function buildDb3TypePushBody(typeConfig, options) {
4765
4846
  export function appendOnlyReasonLines(type, reasons) {
4766
4847
  return reasons.map((r) => `${type}: ${r.path}: ${r.reason}`);
4767
4848
  }
4849
+ /**
4850
+ * What a type write's answer says about the type's field lifecycle, as
4851
+ * `config push` prints it: `deprecatedFields` as a reminder, and
4852
+ * `unclearedFields` as a warning that the return is partial.
4853
+ */
4854
+ export function fieldLifecycleLines(type, answer) {
4855
+ const info = [];
4856
+ const warn = [];
4857
+ const deprecated = Array.isArray(answer?.deprecatedFields) ? answer.deprecatedFields : [];
4858
+ if (deprecated.length) {
4859
+ info.push(`${type}: ${deprecated.length} deprecated field${deprecated.length === 1 ? "" : "s"} still present: ${deprecated.join(", ")}`);
4860
+ }
4861
+ const uncleared = Array.isArray(answer?.unclearedFields) ? answer.unclearedFields : [];
4862
+ if (uncleared.length) {
4863
+ warn.push(`${type}: un-cleared ${uncleared.join(", ")}. The return is partial: every server read returns each value not yet dropped, ` +
4864
+ `values a db3 already dropped stay unset, and registered indexes the clear dropped are not restored. ` +
4865
+ `On devices, a device keeps its local copy until it next downloads the db3 whole.`);
4866
+ }
4867
+ return { info, warn };
4868
+ }
4869
+ /** Print {@link fieldLifecycleLines} for one type's write. */
4870
+ function printFieldLifecycle(type, answer) {
4871
+ const { info: notes, warn: warnings } = fieldLifecycleLines(type, answer);
4872
+ for (const line of notes)
4873
+ info(` ${line}`);
4874
+ for (const line of warnings)
4875
+ warn(` ${line}`);
4876
+ }
4768
4877
  /** The reasons of a `409 DB3_TYPE_NOT_APPEND_ONLY`, or `null` for any other error. */
4769
4878
  export function appendOnlyReasonsOf(err) {
4770
4879
  if (!(err instanceof ApiError) || err.code !== "DB3_TYPE_NOT_APPEND_ONLY")
@@ -4971,6 +5080,79 @@ export function db3TypeWriteBaseline(answerType, name, maps) {
4971
5080
  returned: { ...row, databaseType: row.databaseType ?? typeName ?? name },
4972
5081
  });
4973
5082
  }
5083
+ /**
5084
+ * #6020 — the environment variable naming the file `config push`'s db3 type
5085
+ * step writes each type's outcome to. Set only by `db3-types archive` and
5086
+ * `unarchive`, which run `config push --only db3-type/<type>` and must tell a
5087
+ * refusal from a write whose answer was lost.
5088
+ */
5089
+ export const DB3_TYPE_PUSH_REPORT_ENV = "PRIMITIVE_INTERNAL_DB3_TYPE_PUSH_REPORT";
5090
+ /** Write `report` for `name` to the report file, when one is named; never fails the push. */
5091
+ function reportDb3TypePush(name, report) {
5092
+ const path = process.env[DB3_TYPE_PUSH_REPORT_ENV];
5093
+ if (!path)
5094
+ return;
5095
+ try {
5096
+ let all = {};
5097
+ if (existsSync(path)) {
5098
+ try {
5099
+ all = JSON.parse(readFileSync(path, "utf-8")) ?? {};
5100
+ }
5101
+ catch {
5102
+ all = {};
5103
+ }
5104
+ }
5105
+ all[name] = report;
5106
+ writeFileSync(path, JSON.stringify(all));
5107
+ }
5108
+ catch {
5109
+ // The report is advisory; the push's own output and exit code stand.
5110
+ }
5111
+ }
5112
+ /** The failure a thrown push error is reported as: its status and code when it has them. */
5113
+ function db3TypePushFailureOf(err) {
5114
+ const e = err;
5115
+ return {
5116
+ ...(typeof e?.name === "string" ? { name: e.name } : {}),
5117
+ message: e instanceof Error ? e.message : String(err),
5118
+ ...(typeof e?.statusCode === "number" ? { statusCode: e.statusCode } : {}),
5119
+ ...(typeof e?.code === "string" ? { code: e.code } : {}),
5120
+ };
5121
+ }
5122
+ /**
5123
+ * The sync baseline of one `db3-types/` file: the row's `modifiedAt`, the
5124
+ * file's bytes, the semantic hash of the row and whether it holds a schema.
5125
+ * The legacy twin's baseline moves with the row, so its prune and its next
5126
+ * push read no drift. Shared by `config push` and `db3-types archive` (#6020).
5127
+ */
5128
+ export function recordDb3TypeBaseline(syncState, name, filePath, modifiedAt, semanticHash, hasSchema) {
5129
+ if (!syncState.entities.db3Types)
5130
+ syncState.entities.db3Types = {};
5131
+ syncState.entities.db3Types[name] = {
5132
+ name,
5133
+ modifiedAt,
5134
+ contentHash: computeFileHash(filePath),
5135
+ ...(semanticHash ? { semanticHash } : {}),
5136
+ ...(hasSchema !== undefined ? { hasSchema } : {}),
5137
+ };
5138
+ const legacy = syncState.entities.databaseTypes?.[name];
5139
+ if (legacy)
5140
+ legacy.modifiedAt = modifiedAt;
5141
+ }
5142
+ /**
5143
+ * #6020 — stamp the sync baseline of one `db3-types/` file from a type read
5144
+ * back from `GET db3-types/:name` (the db3 type answer), as a push's answer
5145
+ * stamps it: used when the push's own answer was lost and the read confirmed
5146
+ * the write. Writes nothing when this tree has no sync state for the app.
5147
+ */
5148
+ export function stampDb3TypeBaselineFromRead(name, filePath, type) {
5149
+ const state = loadSyncState();
5150
+ if (!state)
5151
+ return;
5152
+ const maps = { ruleSetIdToName: new Map(), ruleSetNameToId: new Map() };
5153
+ recordDb3TypeBaseline(state, name, filePath, type?.modifiedAt || new Date().toISOString(), db3TypeWriteBaseline(type, name, maps), typeof type?.schema === "string" && type.schema.length > 0);
5154
+ saveSyncState(state);
5155
+ }
4974
5156
  /**
4975
5157
  * #5025 — the hint a declined `db3-types/` push carries: the conflict hint
4976
5158
  * when the row is live but this tree holds no baseline for it, none otherwise.
@@ -5022,7 +5204,9 @@ export function classifyDb3TypeTwins(configDir, maps = { ruleSetIdToName: new Ma
5022
5204
  continue;
5023
5205
  let same = false;
5024
5206
  try {
5025
- const db3Side = projectLocalConfig(DB3_TYPE_DIFF_SPEC, parsed, maps);
5207
+ // #6020 — a legacy file cannot carry `archived`, so the db3 side's is left out.
5208
+ // #5998 — nor `create`.
5209
+ const { archived: _archived, create: _create, ...db3Side } = projectLocalConfig(DB3_TYPE_DIFF_SPEC, parsed, maps);
5026
5210
  // #5993 — a db3 type takes no rule set, so the legacy file's is left
5027
5211
  // out, resolved (`ruleSetId`) or not (`_unresolvedRuleSetName`).
5028
5212
  const { ruleSetId: _ruleSetId, _unresolvedRuleSetName: _unresolved, ...legacySide } = projectLocalConfig(configDiffSpec("database-type-config"), twin.parsed, maps);
@@ -9477,9 +9661,9 @@ export function registerConfigSyncCommands(sync, options = {}) {
9477
9661
  // `--only`, so `--only workflow/a --only prompt/b` would silently apply
9478
9662
  // just the prompt and report success.
9479
9663
  (value, previous) => [...(previous ?? []), value], [])
9480
- .option("--prune", "Delete remote entities whose local TOML was removed since the last sync (issue #1655)")
9481
- .option("-y, --yes", "Skip the interactive confirmation before pruning (for CI / automation)")
9482
- .option("--accept-warnings", "Commit schema diffs that have operations with dynamic refs (issue #666 SCHEMA_HAS_UNCHECKABLE_OPS escape hatch)")
9664
+ .option("--prune", "Delete remote entities whose local TOML was removed since the last sync")
9665
+ .option("-y, --yes", "Skip the interactive confirmation before pruning or before lowering or removing a client version minimum in app.toml (for CI / automation)")
9666
+ .option("--accept-warnings", "Commit schema diffs that have operations with dynamic refs, via the SCHEMA_HAS_UNCHECKABLE_OPS escape hatch")
9483
9667
  .option("--allow-field-removal", "Push db3 type changes that would make stored records unreadable (removed fields or models, changed types). Needs `[app] allowFieldRemoval = true` already stored by an earlier push")
9484
9668
  // #3320 — what this command actually guarantees, said where it is run.
9485
9669
  // Two stages, and only the first is all-or-nothing.
@@ -9502,7 +9686,7 @@ What a push guarantees (two stages):
9502
9686
  secret exists, whether a scheme's config is valid under this environment's
9503
9687
  policy, per-app caps, key collisions. Those surface during apply.
9504
9688
  `)
9505
- .option("--no-typecheck", "Ship function code without typechecking it against the declarations this push generates (issue #3331)")
9689
+ .option("--no-typecheck", "Ship function code without typechecking it against the declarations this push generates")
9506
9690
  .action(async (options) => {
9507
9691
  const resolvedAppId = getCurrentAppId();
9508
9692
  const configDir = resolveSyncDir();
@@ -10372,7 +10556,7 @@ What a push guarantees (two stages):
10372
10556
  },
10373
10557
  });
10374
10558
  const fields = appSettingsFieldDiffs(appPayload, liveSettings ?? {}, compareOptions).map((d) => ({
10375
- field: `[${d.section}].${d.key}`,
10559
+ field: d.label,
10376
10560
  local: d.local,
10377
10561
  server: d.remote,
10378
10562
  }));
@@ -10420,10 +10604,56 @@ What a push guarantees (two stages):
10420
10604
  applyAppSettings = false;
10421
10605
  }
10422
10606
  }
10607
+ // #6034 — a push that lowers or removes a stored client version
10608
+ // minimum names each change and proceeds only on confirmation
10609
+ // (`--yes`, or the prompt); with no terminal it is an apply failure
10610
+ // and app.toml is not sent. Compared against the TARGET app's live
10611
+ // policy, whichever app the tree came from.
10423
10612
  if (applyAppSettings) {
10424
- changes.push({ type: "app", action: "update", key: "settings" });
10613
+ const lowering = await confirmClientVersionLowering({
10614
+ lowered: appLiveOk
10615
+ ? appSettingsLoweredMinimums(liveSettings, appPayload)
10616
+ : [],
10617
+ compared: appLiveOk,
10618
+ dryRun: !!options.dryRun,
10619
+ yes: !!options.yes,
10620
+ confirm: (message) => confirmPrompt(message),
10621
+ print: (line) => warn(line),
10622
+ });
10623
+ if (lowering.proceed === false) {
10624
+ applyFailures.push({
10625
+ type: "app-settings",
10626
+ key: "app.toml",
10627
+ message: lowering.failure,
10628
+ });
10629
+ applyAppSettings = false;
10630
+ }
10631
+ }
10632
+ if (applyAppSettings) {
10633
+ let updated;
10634
+ let appWriteRefused = false;
10425
10635
  if (!options.dryRun) {
10426
- const updated = await client.updateAppSettings(resolvedAppId, appPayload);
10636
+ // The body carries the policy the push compared against
10637
+ // (#6034): the server writes only if it is still the stored one.
10638
+ try {
10639
+ updated = await client.updateAppSettings(resolvedAppId, appSettingsWriteBody(appPayload, {
10640
+ liveRead: appLiveOk,
10641
+ liveSettings,
10642
+ force: !!options.force,
10643
+ }));
10644
+ }
10645
+ catch (err) {
10646
+ const failure = clientVersionsWriteFailure(err);
10647
+ if (!failure)
10648
+ throw err;
10649
+ applyFailures.push(failure);
10650
+ appWriteRefused = true;
10651
+ }
10652
+ }
10653
+ if (!appWriteRefused) {
10654
+ changes.push({ type: "app", action: "update", key: "settings" });
10655
+ }
10656
+ if (!options.dryRun && !appWriteRefused) {
10427
10657
  info(" Updated app settings");
10428
10658
  // Stamped from what the server RETURNED, not from the body sent:
10429
10659
  // `PUT /settings` normalizes (a trailing slash off `baseUrl`, a
@@ -12278,6 +12508,9 @@ What a push guarantees (two stages):
12278
12508
  }
12279
12509
  }
12280
12510
  const db3TwinNames = new Set();
12511
+ // The row each db3 type push in this run left (its modifiedAt), so a
12512
+ // legacy twin pushed after it can read that write as its baseline.
12513
+ const db3WrittenThisRun = new Map();
12281
12514
  const db3TypesDir = join(configDir, "db3-types");
12282
12515
  if (existsSync(db3TypesDir)) {
12283
12516
  const files = selectFiles("db3-type", db3TypesDir, readdirSync(db3TypesDir).filter((f) => f.endsWith(".toml")));
@@ -12314,20 +12547,7 @@ What a push guarantees (two stages):
12314
12547
  const record = (modifiedAt, semanticHash, hasSchema) => {
12315
12548
  if (!syncState || options.dryRun)
12316
12549
  return;
12317
- if (!syncState.entities.db3Types)
12318
- syncState.entities.db3Types = {};
12319
- syncState.entities.db3Types[name] = {
12320
- name,
12321
- modifiedAt,
12322
- contentHash: computeFileHash(filePath),
12323
- ...(semanticHash ? { semanticHash } : {}),
12324
- ...(hasSchema !== undefined ? { hasSchema } : {}),
12325
- };
12326
- // The legacy twin's baseline moves with the row, so its prune
12327
- // and its next push read no drift.
12328
- const legacy = syncState.entities.databaseTypes?.[name];
12329
- if (legacy)
12330
- legacy.modifiedAt = modifiedAt;
12550
+ recordDb3TypeBaseline(syncState, name, filePath, modifiedAt, semanticHash, hasSchema);
12331
12551
  };
12332
12552
  let gate;
12333
12553
  if (db3TypesLiveOk && !live) {
@@ -12345,10 +12565,12 @@ What a push guarantees (two stages):
12345
12565
  if (gate.action === "skip") {
12346
12566
  skippedCount++;
12347
12567
  record(live.modifiedAt || entry?.modifiedAt || new Date().toISOString(), gate.remoteHash, typeof live.schema === "string" && live.schema.trim().length > 0);
12568
+ reportDb3TypePush(name, { outcome: "skipped" });
12348
12569
  continue;
12349
12570
  }
12350
12571
  if (gate.action === "drift" || gate.action === "conflict" || gate.action === "immutable") {
12351
12572
  recordDeclined("db3-type", name, gate, entry?.modifiedAt, db3TypeDeclineHint(name, gate));
12573
+ reportDb3TypePush(name, { outcome: "declined", action: gate.action });
12352
12574
  continue;
12353
12575
  }
12354
12576
  }
@@ -12360,10 +12582,12 @@ What a push guarantees (two stages):
12360
12582
  });
12361
12583
  if (degraded.action === "skip") {
12362
12584
  skippedCount++;
12585
+ reportDb3TypePush(name, { outcome: "skipped" });
12363
12586
  continue;
12364
12587
  }
12365
12588
  if (degraded.action === "decline") {
12366
12589
  recordDeclined("db3-type", name, { action: "live-unavailable" }, entry?.modifiedAt);
12590
+ reportDb3TypePush(name, { outcome: "declined", action: "live-unavailable" });
12367
12591
  continue;
12368
12592
  }
12369
12593
  }
@@ -12380,7 +12604,10 @@ What a push guarantees (two stages):
12380
12604
  if (options.dryRun)
12381
12605
  continue;
12382
12606
  info(` ${answer.created ? "Created" : "Updated"} db3 type: ${name}`);
12607
+ if (typeof answer.type?.modifiedAt === "string")
12608
+ db3WrittenThisRun.set(name, answer.type.modifiedAt);
12383
12609
  printAppendOnlyOverride(name, answer);
12610
+ printFieldLifecycle(name, answer);
12384
12611
  printStaleInstanceWarning(answer);
12385
12612
  if (answer.push?.runId) {
12386
12613
  info(` Pushing revision ${answer.revision.generation} to the db3s of ${name}: run ${answer.push.runId} — ` +
@@ -12390,8 +12617,10 @@ What a push guarantees (two stages):
12390
12617
  warn(` The push to the db3s of ${name} did not start: ${answer.push.error}`);
12391
12618
  }
12392
12619
  record(answer.type?.modifiedAt || new Date().toISOString(), db3TypeWriteBaseline(answer.type, name, pushDiffMaps), typeof answer.type?.schema === "string" && answer.type.schema.length > 0);
12620
+ reportDb3TypePush(name, { outcome: "applied", answer });
12393
12621
  }
12394
12622
  catch (err) {
12623
+ reportDb3TypePush(name, { outcome: "failed", failure: db3TypePushFailureOf(err) });
12395
12624
  if (err instanceof ConflictError) {
12396
12625
  conflicts.push({
12397
12626
  type: "db3-type",
@@ -12504,6 +12733,18 @@ What a push guarantees (two stages):
12504
12733
  dbTypeGate = { action: "create" };
12505
12734
  }
12506
12735
  else if (databaseTypesLiveOk && liveDatabaseType) {
12736
+ // A legacy twin with no baseline (a cross-app push resets them)
12737
+ // whose row this run's db3 push just wrote, and nobody has moved
12738
+ // since: that write is the baseline, so its rule set is an edit
12739
+ // over it, not a change of unknown direction (#5993).
12740
+ const writtenAt = db3WrittenThisRun.get(dbType);
12741
+ const gateEntry = !existingEntry && writtenAt !== undefined && liveDatabaseType.modifiedAt === writtenAt
12742
+ ? {
12743
+ databaseType: dbType,
12744
+ modifiedAt: writtenAt,
12745
+ semanticHash: hashRemoteConfigForDiff(databaseTypeSpec, liveDatabaseType, pushDiffMaps),
12746
+ }
12747
+ : existingEntry;
12507
12748
  dbTypeGate = decidePushForConfig({
12508
12749
  spec: databaseTypeSpec,
12509
12750
  maps: pushDiffMaps,
@@ -12513,7 +12754,7 @@ What a push guarantees (two stages):
12513
12754
  extra: {},
12514
12755
  modifiedAt: liveDatabaseType.modifiedAt,
12515
12756
  },
12516
- entry: existingEntry,
12757
+ entry: gateEntry,
12517
12758
  localFileHash: computeFileHash(filePath),
12518
12759
  force: options.force,
12519
12760
  });
@@ -12798,6 +13039,7 @@ What a push guarantees (two stages):
12798
13039
  });
12799
13040
  info(` Updated database type: ${dbType}`);
12800
13041
  printAppendOnlyOverride(dbType, updated);
13042
+ printFieldLifecycle(dbType, updated);
12801
13043
  // Issue #1567: name each owned scalar this push cleared, so
12802
13044
  // removing a rule (triggers, autoPopulatedFields) is never
12803
13045
  // silent.
@@ -12875,6 +13117,7 @@ What a push guarantees (two stages):
12875
13117
  try {
12876
13118
  const created = await client.createDatabaseTypeConfig(resolvedAppId, createData);
12877
13119
  info(` Created database type: ${dbType}`);
13120
+ printFieldLifecycle(dbType, created);
12878
13121
  if (syncState) {
12879
13122
  if (!syncState.entities.databaseTypes) {
12880
13123
  syncState.entities.databaseTypes = {};
@@ -13004,6 +13247,7 @@ What a push guarantees (two stages):
13004
13247
  });
13005
13248
  printStaleInstanceWarning(reconciled);
13006
13249
  printAppendOnlyOverride(dbType, reconciled);
13250
+ printFieldLifecycle(dbType, reconciled);
13007
13251
  if (syncState?.entities?.databaseTypes?.[dbType] &&
13008
13252
  reconciled?.modifiedAt) {
13009
13253
  syncState.entities.databaseTypes[dbType].modifiedAt =
@@ -13483,6 +13727,11 @@ What a push guarantees (two stages):
13483
13727
  await warnIfDroppingDocumentSchema(String(functionId), liveFunction?.activeConfigId
13484
13728
  ? String(liveFunction.activeConfigId)
13485
13729
  : undefined);
13730
+ // #6118 — the server's lines about this version (a Turnstile
13731
+ // function whose app lacks its site key or secret). The push has
13732
+ // landed; they change neither the exit code nor the sync state.
13733
+ for (const line of functionVersionPushWarnings(pushedVersion))
13734
+ warn(` ${line}`);
13486
13735
  if (pushedVersion?.created === false) {
13487
13736
  info(` Function ${key}: code unchanged (no new version)`);
13488
13737
  }
@@ -15380,7 +15629,7 @@ What a push guarantees (two stages):
15380
15629
  else {
15381
15630
  appRow("modified", `${fieldDiffs.length} field(s) differ: ` +
15382
15631
  fieldDiffs
15383
- .map((d) => `[${d.section}].${d.key}`)
15632
+ .map((d) => d.label)
15384
15633
  .join(", ") +
15385
15634
  " — `config diff --only app` shows the values");
15386
15635
  }