@wildo-ai/platform-config-lib 1.1.9 → 1.1.11
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.
- package/dist/esm/_unimplemented/unimplemented-field-warning.d.ts +1 -1
- package/dist/esm/_unimplemented/unimplemented-field-warning.js +1 -1
- package/dist/esm/_unimplemented/unimplemented-field-warning.js.map +1 -1
- package/dist/esm/blueprint/anchored-region.d.ts +83 -0
- package/dist/esm/blueprint/anchored-region.d.ts.map +1 -0
- package/dist/esm/blueprint/anchored-region.js +263 -0
- package/dist/esm/blueprint/anchored-region.js.map +1 -0
- package/dist/esm/blueprint/blueprint.schemas.d.ts +689 -0
- package/dist/esm/blueprint/blueprint.schemas.d.ts.map +1 -0
- package/dist/esm/blueprint/blueprint.schemas.js +638 -0
- package/dist/esm/blueprint/blueprint.schemas.js.map +1 -0
- package/dist/esm/bootstrap/bootstrap.contracts.d.ts +13 -1
- package/dist/esm/bootstrap/bootstrap.contracts.d.ts.map +1 -1
- package/dist/esm/bootstrap/bootstrap.contracts.js +6 -0
- package/dist/esm/bootstrap/bootstrap.contracts.js.map +1 -1
- package/dist/esm/bootstrap/bootstrap.schemas.d.ts +21 -3
- package/dist/esm/bootstrap/bootstrap.schemas.d.ts.map +1 -1
- package/dist/esm/bootstrap/bootstrap.schemas.js +14 -3
- package/dist/esm/bootstrap/bootstrap.schemas.js.map +1 -1
- package/dist/esm/bootstrap/platform-runtime-env.contracts.d.ts +121 -0
- package/dist/esm/bootstrap/platform-runtime-env.contracts.d.ts.map +1 -1
- package/dist/esm/bootstrap/platform-runtime-env.contracts.js +129 -0
- package/dist/esm/bootstrap/platform-runtime-env.contracts.js.map +1 -1
- package/dist/esm/bootstrap/runtime-response-integrity.d.ts +249 -0
- package/dist/esm/bootstrap/runtime-response-integrity.d.ts.map +1 -0
- package/dist/esm/bootstrap/runtime-response-integrity.js +353 -0
- package/dist/esm/bootstrap/runtime-response-integrity.js.map +1 -0
- package/dist/esm/bootstrap/runtime-secret-env.contracts.d.ts +32 -0
- package/dist/esm/bootstrap/runtime-secret-env.contracts.d.ts.map +1 -0
- package/dist/esm/bootstrap/runtime-secret-env.contracts.js +43 -0
- package/dist/esm/bootstrap/runtime-secret-env.contracts.js.map +1 -0
- package/dist/esm/canonical-json/rfc8785-canonical-json.d.ts +51 -0
- package/dist/esm/canonical-json/rfc8785-canonical-json.d.ts.map +1 -0
- package/dist/esm/canonical-json/rfc8785-canonical-json.js +231 -0
- package/dist/esm/canonical-json/rfc8785-canonical-json.js.map +1 -0
- package/dist/esm/index.d.ts +15 -0
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +15 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/key-management/approval-seal-verifier.d.ts +216 -0
- package/dist/esm/key-management/approval-seal-verifier.d.ts.map +1 -0
- package/dist/esm/key-management/approval-seal-verifier.js +233 -0
- package/dist/esm/key-management/approval-seal-verifier.js.map +1 -0
- package/dist/esm/key-management/approval-seal.contracts.d.ts +131 -0
- package/dist/esm/key-management/approval-seal.contracts.d.ts.map +1 -0
- package/dist/esm/key-management/approval-seal.contracts.js +115 -0
- package/dist/esm/key-management/approval-seal.contracts.js.map +1 -0
- package/dist/esm/key-management/data-key.contracts.d.ts +108 -0
- package/dist/esm/key-management/data-key.contracts.d.ts.map +1 -0
- package/dist/esm/key-management/data-key.contracts.js +54 -0
- package/dist/esm/key-management/data-key.contracts.js.map +1 -0
- package/dist/esm/key-management/es256-jws.d.ts +60 -0
- package/dist/esm/key-management/es256-jws.d.ts.map +1 -0
- package/dist/esm/key-management/es256-jws.js +135 -0
- package/dist/esm/key-management/es256-jws.js.map +1 -0
- package/dist/esm/key-management/key-provider.spi.d.ts +151 -0
- package/dist/esm/key-management/key-provider.spi.d.ts.map +1 -0
- package/dist/esm/key-management/key-provider.spi.js +38 -0
- package/dist/esm/key-management/key-provider.spi.js.map +1 -0
- package/dist/esm/key-management/keyring-rotation.contracts.d.ts +93 -0
- package/dist/esm/key-management/keyring-rotation.contracts.d.ts.map +1 -0
- package/dist/esm/key-management/keyring-rotation.contracts.js +101 -0
- package/dist/esm/key-management/keyring-rotation.contracts.js.map +1 -0
- package/dist/esm/key-management/keyring-status.contracts.d.ts +66 -0
- package/dist/esm/key-management/keyring-status.contracts.d.ts.map +1 -0
- package/dist/esm/key-management/keyring-status.contracts.js +45 -0
- package/dist/esm/key-management/keyring-status.contracts.js.map +1 -0
- package/dist/esm/key-management/signature-request.contracts.d.ts +95 -0
- package/dist/esm/key-management/signature-request.contracts.d.ts.map +1 -0
- package/dist/esm/key-management/signature-request.contracts.js +96 -0
- package/dist/esm/key-management/signature-request.contracts.js.map +1 -0
- package/dist/esm/key-management/signing-log-export.contracts.d.ts +216 -0
- package/dist/esm/key-management/signing-log-export.contracts.d.ts.map +1 -0
- package/dist/esm/key-management/signing-log-export.contracts.js +268 -0
- package/dist/esm/key-management/signing-log-export.contracts.js.map +1 -0
- package/dist/esm/key-management/vault-custody.contracts.d.ts +55 -0
- package/dist/esm/key-management/vault-custody.contracts.d.ts.map +1 -0
- package/dist/esm/key-management/vault-custody.contracts.js +88 -0
- package/dist/esm/key-management/vault-custody.contracts.js.map +1 -0
- package/dist/esm/lockfile/lockfile-io.d.ts +7 -9
- package/dist/esm/lockfile/lockfile-io.d.ts.map +1 -1
- package/dist/esm/lockfile/lockfile-io.js +23 -22
- package/dist/esm/lockfile/lockfile-io.js.map +1 -1
- package/dist/esm/lockfile/materialize-infra-section.d.ts +17 -14
- package/dist/esm/lockfile/materialize-infra-section.d.ts.map +1 -1
- package/dist/esm/lockfile/materialize-infra-section.js +9 -9
- package/dist/esm/lockfile/materialize-infra-section.js.map +1 -1
- package/dist/esm/lockfile/wildo-saas-lock.shared.schemas.d.ts +26 -2
- package/dist/esm/lockfile/wildo-saas-lock.shared.schemas.d.ts.map +1 -1
- package/dist/esm/lockfile/wildo-saas-lock.shared.schemas.js +27 -2
- package/dist/esm/lockfile/wildo-saas-lock.shared.schemas.js.map +1 -1
- package/dist/esm/project-config/application-public-pricing-catalog.loader.d.ts.map +1 -1
- package/dist/esm/project-config/application-public-pricing-catalog.loader.js +9 -2
- package/dist/esm/project-config/application-public-pricing-catalog.loader.js.map +1 -1
- package/dist/esm/project-config/application-served-public-documents.loader.d.ts +26 -0
- package/dist/esm/project-config/application-served-public-documents.loader.d.ts.map +1 -0
- package/dist/esm/project-config/application-served-public-documents.loader.js +78 -0
- package/dist/esm/project-config/application-served-public-documents.loader.js.map +1 -0
- package/dist/esm/project-config/define-infra-env-config.d.ts +236 -15
- package/dist/esm/project-config/define-infra-env-config.d.ts.map +1 -1
- package/dist/esm/project-config/define-infra-env-config.js +104 -91
- package/dist/esm/project-config/define-infra-env-config.js.map +1 -1
- package/dist/esm/project-config/define-saas-config.d.ts +133 -3
- package/dist/esm/project-config/define-saas-config.d.ts.map +1 -1
- package/dist/esm/project-config/define-saas-config.js +170 -19
- package/dist/esm/project-config/define-saas-config.js.map +1 -1
- package/dist/esm/project-config/hosted-infra-env-config.d.ts.map +1 -1
- package/dist/esm/project-config/hosted-infra-env-config.js +3 -0
- package/dist/esm/project-config/hosted-infra-env-config.js.map +1 -1
- package/dist/esm/project-config/index.d.ts +3 -0
- package/dist/esm/project-config/index.d.ts.map +1 -1
- package/dist/esm/project-config/index.js +3 -0
- package/dist/esm/project-config/index.js.map +1 -1
- package/dist/esm/project-config/npm-version-range.d.ts.map +1 -1
- package/dist/esm/project-config/npm-version-range.js +39 -16
- package/dist/esm/project-config/npm-version-range.js.map +1 -1
- package/dist/esm/project-config/owning-package-tsconfig.d.ts +15 -0
- package/dist/esm/project-config/owning-package-tsconfig.d.ts.map +1 -0
- package/dist/esm/project-config/owning-package-tsconfig.js +29 -0
- package/dist/esm/project-config/owning-package-tsconfig.js.map +1 -0
- package/dist/esm/project-config/provider-companion-discovery.d.ts +4 -4
- package/dist/esm/project-config/provider-companion-discovery.d.ts.map +1 -1
- package/dist/esm/project-config/provider-companion-discovery.js +13 -9
- package/dist/esm/project-config/provider-companion-discovery.js.map +1 -1
- package/dist/esm/project-config/provider-runtime-artifacts.d.ts +32 -3
- package/dist/esm/project-config/provider-runtime-artifacts.d.ts.map +1 -1
- package/dist/esm/project-config/provider-runtime-artifacts.js +67 -13
- package/dist/esm/project-config/provider-runtime-artifacts.js.map +1 -1
- package/dist/esm/project-config/shared/csp-defaults.d.ts +4 -5
- package/dist/esm/project-config/shared/csp-defaults.d.ts.map +1 -1
- package/dist/esm/project-config/shared/csp-defaults.js +4 -5
- package/dist/esm/project-config/shared/csp-defaults.js.map +1 -1
- package/dist/esm/project-config/shared/csp.schemas.d.ts +1 -2
- package/dist/esm/project-config/shared/csp.schemas.d.ts.map +1 -1
- package/dist/esm/project-config/shared/csp.schemas.js +1 -2
- package/dist/esm/project-config/shared/csp.schemas.js.map +1 -1
- package/dist/esm/project-config/shared/environment.schemas.d.ts +6 -0
- package/dist/esm/project-config/shared/environment.schemas.d.ts.map +1 -1
- package/dist/esm/project-config/shared/environment.schemas.js +8 -1
- package/dist/esm/project-config/shared/environment.schemas.js.map +1 -1
- package/dist/esm/project-config/shared/infrastructure-defaults.schemas.d.ts +1 -0
- package/dist/esm/project-config/shared/infrastructure-defaults.schemas.d.ts.map +1 -1
- package/dist/esm/project-config/shared/infrastructure-defaults.schemas.js +3 -0
- package/dist/esm/project-config/shared/infrastructure-defaults.schemas.js.map +1 -1
- package/dist/esm/project-config/shared/minion-resource-access.validation.d.ts +4 -0
- package/dist/esm/project-config/shared/minion-resource-access.validation.d.ts.map +1 -1
- package/dist/esm/project-config/shared/minion-resource-access.validation.js +6 -2
- package/dist/esm/project-config/shared/minion-resource-access.validation.js.map +1 -1
- package/dist/esm/project-config/shared/platform-key-management.schemas.d.ts +250 -0
- package/dist/esm/project-config/shared/platform-key-management.schemas.d.ts.map +1 -0
- package/dist/esm/project-config/shared/platform-key-management.schemas.js +194 -0
- package/dist/esm/project-config/shared/platform-key-management.schemas.js.map +1 -0
- package/dist/esm/registry/index.d.ts +1 -0
- package/dist/esm/registry/index.d.ts.map +1 -1
- package/dist/esm/registry/index.js +1 -0
- package/dist/esm/registry/index.js.map +1 -1
- package/dist/esm/registry/local-checkout-source.d.ts +22 -2
- package/dist/esm/registry/local-checkout-source.d.ts.map +1 -1
- package/dist/esm/registry/local-checkout-source.js +66 -3
- package/dist/esm/registry/local-checkout-source.js.map +1 -1
- package/dist/esm/registry/lockfile-modules-section.schemas.d.ts +10 -0
- package/dist/esm/registry/lockfile-modules-section.schemas.d.ts.map +1 -1
- package/dist/esm/registry/module-artifact.schemas.d.ts +23 -0
- package/dist/esm/registry/module-artifact.schemas.d.ts.map +1 -1
- package/dist/esm/registry/module-manifest.schemas.d.ts +336 -18
- package/dist/esm/registry/module-manifest.schemas.d.ts.map +1 -1
- package/dist/esm/registry/module-manifest.schemas.js +245 -19
- package/dist/esm/registry/module-manifest.schemas.js.map +1 -1
- package/dist/esm/registry/module-search.schemas.d.ts +2 -0
- package/dist/esm/registry/module-search.schemas.d.ts.map +1 -1
- package/dist/esm/registry/module-search.schemas.js +14 -1
- package/dist/esm/registry/module-search.schemas.js.map +1 -1
- package/dist/esm/registry/registry-errors.d.ts +22 -2
- package/dist/esm/registry/registry-errors.d.ts.map +1 -1
- package/dist/esm/registry/registry-errors.js +28 -2
- package/dist/esm/registry/registry-errors.js.map +1 -1
- package/dist/esm/registry/registry-section-schemas.constants.d.ts +5 -0
- package/dist/esm/registry/registry-section-schemas.constants.d.ts.map +1 -1
- package/dist/esm/registry/registry-url-resolution.d.ts +72 -0
- package/dist/esm/registry/registry-url-resolution.d.ts.map +1 -0
- package/dist/esm/registry/registry-url-resolution.js +157 -0
- package/dist/esm/registry/registry-url-resolution.js.map +1 -0
- package/dist/esm/schemas/framework-secrets.schemas.d.ts +55 -0
- package/dist/esm/schemas/framework-secrets.schemas.d.ts.map +1 -1
- package/dist/esm/schemas/framework-secrets.schemas.js +53 -0
- package/dist/esm/schemas/framework-secrets.schemas.js.map +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/package.json +7 -7
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* # The platform's Vault custody contract (#2933)
|
|
3
|
+
*
|
|
4
|
+
* apps-manager signs through HashiCorp Vault (or OpenBao) with TWO tokens, and least privilege is a property of the
|
|
5
|
+
* policy each token holds. Those policies are stated here once, because three places need the same text: the
|
|
6
|
+
* self-hosted OpenBao the CLI renders (it writes them at its first start), the real-container test suite, and the
|
|
7
|
+
* runbook an operator follows to configure their own Vault. A copy in each would drift, and a drift here is either a
|
|
8
|
+
* provider that cannot do its job or a token that can do more than its job.
|
|
9
|
+
*
|
|
10
|
+
* - The SIGNER token signs, wraps and reads: `transit/sign/<k>`, `transit/encrypt/<k>` and `transit/decrypt/<k>` (data
|
|
11
|
+
* keys wrapped and unwrapped under a wrapping key, #2894), read on `transit/keys/<k>` (the public key and the
|
|
12
|
+
* attributes the attestation is computed from), and read on a KV key. It can never change a key's configuration, so it can never
|
|
13
|
+
* make a key exportable; Vault's deny-by-default already refuses that, and the explicit `deny` lines keep it refused
|
|
14
|
+
* if a broader grant is ever added beside these.
|
|
15
|
+
* - The OPERATOR token performs lifecycle acts (create, rotate, configure, delete; KV write, delete, destroy) and can
|
|
16
|
+
* neither sign, wrap, unwrap nor read key material, nor send `exportable` / `allow_plaintext_backup` (`denied_parameters`), so it
|
|
17
|
+
* cannot make a Transit key leave Vault either.
|
|
18
|
+
* - Both may renew THEMSELVES (`auth/token/renew-self`), because a periodic token that is not renewed expires; nothing
|
|
19
|
+
* else under `auth/` is granted.
|
|
20
|
+
*
|
|
21
|
+
* spec-cite: Vault "Policies" (path globs, `deny` precedence) https://developer.hashicorp.com/vault/docs/concepts/policies;
|
|
22
|
+
* Transit API https://developer.hashicorp.com/vault/api-docs/secret/transit; KV v2 API
|
|
23
|
+
* https://developer.hashicorp.com/vault/api-docs/secret/kv/kv-v2; token renew-self
|
|
24
|
+
* https://developer.hashicorp.com/vault/api-docs/auth/token#renew-a-token-self.
|
|
25
|
+
*/
|
|
26
|
+
/** @wildo_source:part:start platform.key-management.vault-custody facet:layer:platform facet:family:security facet:audience:app-developer */
|
|
27
|
+
/** The Transit mount the providers use when none is configured. */
|
|
28
|
+
export const VAULT_DEFAULT_TRANSIT_MOUNT = 'transit';
|
|
29
|
+
/** The KV v2 mount the providers use when none is configured (where a Vault dev server mounts it). */
|
|
30
|
+
export const VAULT_DEFAULT_KV_MOUNT = 'secret';
|
|
31
|
+
/** The prefix of every key name the providers create; the policies grant nothing outside it. */
|
|
32
|
+
export const VAULT_DEFAULT_KEY_NAME_PREFIX = 'wildo-';
|
|
33
|
+
/** The names the two policies are written under. */
|
|
34
|
+
export const VAULT_SIGNER_POLICY_NAME = 'wildo-key-signer';
|
|
35
|
+
export const VAULT_OPERATOR_POLICY_NAME = 'wildo-key-operator';
|
|
36
|
+
/** The layout with every default applied. */
|
|
37
|
+
export function vaultCustodyLayoutOf(layout = {}) {
|
|
38
|
+
return {
|
|
39
|
+
transitMount: layout.transitMount || VAULT_DEFAULT_TRANSIT_MOUNT,
|
|
40
|
+
kvMount: layout.kvMount || VAULT_DEFAULT_KV_MOUNT,
|
|
41
|
+
keyNamePrefix: layout.keyNamePrefix || VAULT_DEFAULT_KEY_NAME_PREFIX,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
const RENEW_SELF = 'path "auth/token/renew-self" { capabilities = ["update"] }';
|
|
45
|
+
/** The SIGNER token's policy, as Vault HCL. */
|
|
46
|
+
export function vaultSignerPolicy(layout = vaultCustodyLayoutOf()) {
|
|
47
|
+
const { transitMount: t, kvMount: kv, keyNamePrefix: p } = layout;
|
|
48
|
+
return [
|
|
49
|
+
`path "${t}/sign/${p}*" { capabilities = ["update"] }`,
|
|
50
|
+
`path "${t}/encrypt/${p}*" { capabilities = ["update"] }`,
|
|
51
|
+
`path "${t}/decrypt/${p}*" { capabilities = ["update"] }`,
|
|
52
|
+
`path "${t}/keys/${p}*" { capabilities = ["read"] }`,
|
|
53
|
+
`path "${kv}/data/${p}*" { capabilities = ["read"] }`,
|
|
54
|
+
`path "${kv}/metadata/${p}*" { capabilities = ["read"] }`,
|
|
55
|
+
`path "${t}/keys/+/config" { capabilities = ["deny"] }`,
|
|
56
|
+
`path "${t}/export/*" { capabilities = ["deny"] }`,
|
|
57
|
+
`path "${t}/backup/*" { capabilities = ["deny"] }`,
|
|
58
|
+
RENEW_SELF,
|
|
59
|
+
].join('\n');
|
|
60
|
+
}
|
|
61
|
+
/** The OPERATOR token's policy, as Vault HCL. */
|
|
62
|
+
export function vaultOperatorPolicy(layout = vaultCustodyLayoutOf()) {
|
|
63
|
+
const { transitMount: t, kvMount: kv, keyNamePrefix: p } = layout;
|
|
64
|
+
return [
|
|
65
|
+
// `exportable` and `allow_plaintext_backup` are one-way and turn a key into one that can leave Vault, so the
|
|
66
|
+
// operator may not send them at all, at creation or on `/config`: Vault refuses any request carrying a denied
|
|
67
|
+
// parameter, whatever its value.
|
|
68
|
+
`path "${t}/keys/${p}*" { capabilities = ["create", "update", "read", "delete"] denied_parameters = { "exportable" = [] "allow_plaintext_backup" = [] } }`,
|
|
69
|
+
`path "${kv}/data/${p}*" { capabilities = ["create", "update"] }`,
|
|
70
|
+
`path "${kv}/delete/${p}*" { capabilities = ["update"] }`,
|
|
71
|
+
`path "${kv}/destroy/${p}*" { capabilities = ["update"] }`,
|
|
72
|
+
`path "${kv}/metadata/${p}*" { capabilities = ["delete"] }`,
|
|
73
|
+
`path "${t}/sign/*" { capabilities = ["deny"] }`,
|
|
74
|
+
`path "${t}/encrypt/*" { capabilities = ["deny"] }`,
|
|
75
|
+
`path "${t}/decrypt/*" { capabilities = ["deny"] }`,
|
|
76
|
+
`path "${t}/export/*" { capabilities = ["deny"] }`,
|
|
77
|
+
`path "${t}/backup/*" { capabilities = ["deny"] }`,
|
|
78
|
+
RENEW_SELF,
|
|
79
|
+
].join('\n');
|
|
80
|
+
}
|
|
81
|
+
/** @wildo_source:part:end platform.key-management.vault-custody */
|
|
82
|
+
/**
|
|
83
|
+
* How long a token issued for the platform lives between renewals. apps-manager renews each token at half its lease
|
|
84
|
+
* (`VaultTokenRenewal`), so the period bounds how long a token that stops being renewed stays usable, not how long the
|
|
85
|
+
* platform runs.
|
|
86
|
+
*/
|
|
87
|
+
export const VAULT_TOKEN_PERIOD = '768h';
|
|
88
|
+
//# sourceMappingURL=vault-custody.contracts.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vault-custody.contracts.js","sourceRoot":"","sources":["../../../../src/key-management/vault-custody.contracts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,6IAA6I;AAC7I,mEAAmE;AACnE,MAAM,CAAC,MAAM,2BAA2B,GAAG,SAAS,CAAC;AACrD,sGAAsG;AACtG,MAAM,CAAC,MAAM,sBAAsB,GAAG,QAAQ,CAAC;AAC/C,gGAAgG;AAChG,MAAM,CAAC,MAAM,6BAA6B,GAAG,QAAQ,CAAC;AAEtD,oDAAoD;AACpD,MAAM,CAAC,MAAM,wBAAwB,GAAG,kBAAkB,CAAC;AAC3D,MAAM,CAAC,MAAM,0BAA0B,GAAG,oBAAoB,CAAC;AAS/D,6CAA6C;AAC7C,MAAM,UAAU,oBAAoB,CAAC,SAAsC,EAAE;IAC3E,OAAO;QACL,YAAY,EAAE,MAAM,CAAC,YAAY,IAAI,2BAA2B;QAChE,OAAO,EAAE,MAAM,CAAC,OAAO,IAAI,sBAAsB;QACjD,aAAa,EAAE,MAAM,CAAC,aAAa,IAAI,6BAA6B;KACrE,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,GAAG,4DAA4D,CAAC;AAEhF,+CAA+C;AAC/C,MAAM,UAAU,iBAAiB,CAAC,SAA6B,oBAAoB,EAAE;IACnF,MAAM,EAAE,YAAY,EAAE,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,aAAa,EAAE,CAAC,EAAE,GAAG,MAAM,CAAC;IAClE,OAAO;QACL,SAAS,CAAC,SAAS,CAAC,kCAAkC;QACtD,SAAS,CAAC,YAAY,CAAC,kCAAkC;QACzD,SAAS,CAAC,YAAY,CAAC,kCAAkC;QACzD,SAAS,CAAC,SAAS,CAAC,gCAAgC;QACpD,SAAS,EAAE,SAAS,CAAC,gCAAgC;QACrD,SAAS,EAAE,aAAa,CAAC,gCAAgC;QACzD,SAAS,CAAC,6CAA6C;QACvD,SAAS,CAAC,wCAAwC;QAClD,SAAS,CAAC,wCAAwC;QAClD,UAAU;KACX,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACf,CAAC;AAED,iDAAiD;AACjD,MAAM,UAAU,mBAAmB,CAAC,SAA6B,oBAAoB,EAAE;IACrF,MAAM,EAAE,YAAY,EAAE,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,aAAa,EAAE,CAAC,EAAE,GAAG,MAAM,CAAC;IAClE,OAAO;QACL,6GAA6G;QAC7G,8GAA8G;QAC9G,iCAAiC;QACjC,SAAS,CAAC,SAAS,CAAC,sIAAsI;QAC1J,SAAS,EAAE,SAAS,CAAC,4CAA4C;QACjE,SAAS,EAAE,WAAW,CAAC,kCAAkC;QACzD,SAAS,EAAE,YAAY,CAAC,kCAAkC;QAC1D,SAAS,EAAE,aAAa,CAAC,kCAAkC;QAC3D,SAAS,CAAC,sCAAsC;QAChD,SAAS,CAAC,yCAAyC;QACnD,SAAS,CAAC,yCAAyC;QACnD,SAAS,CAAC,wCAAwC;QAClD,SAAS,CAAC,wCAAwC;QAClD,UAAU;KACX,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACf,CAAC;AAED,mEAAmE;AAEnE;;;;GAIG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,MAAM,CAAC","sourcesContent":["/**\n * # The platform's Vault custody contract (#2933)\n *\n * apps-manager signs through HashiCorp Vault (or OpenBao) with TWO tokens, and least privilege is a property of the\n * policy each token holds. Those policies are stated here once, because three places need the same text: the\n * self-hosted OpenBao the CLI renders (it writes them at its first start), the real-container test suite, and the\n * runbook an operator follows to configure their own Vault. A copy in each would drift, and a drift here is either a\n * provider that cannot do its job or a token that can do more than its job.\n *\n * - The SIGNER token signs, wraps and reads: `transit/sign/<k>`, `transit/encrypt/<k>` and `transit/decrypt/<k>` (data\n * keys wrapped and unwrapped under a wrapping key, #2894), read on `transit/keys/<k>` (the public key and the\n * attributes the attestation is computed from), and read on a KV key. It can never change a key's configuration, so it can never\n * make a key exportable; Vault's deny-by-default already refuses that, and the explicit `deny` lines keep it refused\n * if a broader grant is ever added beside these.\n * - The OPERATOR token performs lifecycle acts (create, rotate, configure, delete; KV write, delete, destroy) and can\n * neither sign, wrap, unwrap nor read key material, nor send `exportable` / `allow_plaintext_backup` (`denied_parameters`), so it\n * cannot make a Transit key leave Vault either.\n * - Both may renew THEMSELVES (`auth/token/renew-self`), because a periodic token that is not renewed expires; nothing\n * else under `auth/` is granted.\n *\n * spec-cite: Vault \"Policies\" (path globs, `deny` precedence) https://developer.hashicorp.com/vault/docs/concepts/policies;\n * Transit API https://developer.hashicorp.com/vault/api-docs/secret/transit; KV v2 API\n * https://developer.hashicorp.com/vault/api-docs/secret/kv/kv-v2; token renew-self\n * https://developer.hashicorp.com/vault/api-docs/auth/token#renew-a-token-self.\n */\n\n/** @wildo_source:part:start platform.key-management.vault-custody facet:layer:platform facet:family:security facet:audience:app-developer */\n/** The Transit mount the providers use when none is configured. */\nexport const VAULT_DEFAULT_TRANSIT_MOUNT = 'transit';\n/** The KV v2 mount the providers use when none is configured (where a Vault dev server mounts it). */\nexport const VAULT_DEFAULT_KV_MOUNT = 'secret';\n/** The prefix of every key name the providers create; the policies grant nothing outside it. */\nexport const VAULT_DEFAULT_KEY_NAME_PREFIX = 'wildo-';\n\n/** The names the two policies are written under. */\nexport const VAULT_SIGNER_POLICY_NAME = 'wildo-key-signer';\nexport const VAULT_OPERATOR_POLICY_NAME = 'wildo-key-operator';\n\n/** Where the providers' keys live in one Vault. */\nexport interface VaultCustodyLayout {\n readonly transitMount: string;\n readonly kvMount: string;\n readonly keyNamePrefix: string;\n}\n\n/** The layout with every default applied. */\nexport function vaultCustodyLayoutOf(layout: Partial<VaultCustodyLayout> = {}): VaultCustodyLayout {\n return {\n transitMount: layout.transitMount || VAULT_DEFAULT_TRANSIT_MOUNT,\n kvMount: layout.kvMount || VAULT_DEFAULT_KV_MOUNT,\n keyNamePrefix: layout.keyNamePrefix || VAULT_DEFAULT_KEY_NAME_PREFIX,\n };\n}\n\nconst RENEW_SELF = 'path \"auth/token/renew-self\" { capabilities = [\"update\"] }';\n\n/** The SIGNER token's policy, as Vault HCL. */\nexport function vaultSignerPolicy(layout: VaultCustodyLayout = vaultCustodyLayoutOf()): string {\n const { transitMount: t, kvMount: kv, keyNamePrefix: p } = layout;\n return [\n `path \"${t}/sign/${p}*\" { capabilities = [\"update\"] }`,\n `path \"${t}/encrypt/${p}*\" { capabilities = [\"update\"] }`,\n `path \"${t}/decrypt/${p}*\" { capabilities = [\"update\"] }`,\n `path \"${t}/keys/${p}*\" { capabilities = [\"read\"] }`,\n `path \"${kv}/data/${p}*\" { capabilities = [\"read\"] }`,\n `path \"${kv}/metadata/${p}*\" { capabilities = [\"read\"] }`,\n `path \"${t}/keys/+/config\" { capabilities = [\"deny\"] }`,\n `path \"${t}/export/*\" { capabilities = [\"deny\"] }`,\n `path \"${t}/backup/*\" { capabilities = [\"deny\"] }`,\n RENEW_SELF,\n ].join('\\n');\n}\n\n/** The OPERATOR token's policy, as Vault HCL. */\nexport function vaultOperatorPolicy(layout: VaultCustodyLayout = vaultCustodyLayoutOf()): string {\n const { transitMount: t, kvMount: kv, keyNamePrefix: p } = layout;\n return [\n // `exportable` and `allow_plaintext_backup` are one-way and turn a key into one that can leave Vault, so the\n // operator may not send them at all, at creation or on `/config`: Vault refuses any request carrying a denied\n // parameter, whatever its value.\n `path \"${t}/keys/${p}*\" { capabilities = [\"create\", \"update\", \"read\", \"delete\"] denied_parameters = { \"exportable\" = [] \"allow_plaintext_backup\" = [] } }`,\n `path \"${kv}/data/${p}*\" { capabilities = [\"create\", \"update\"] }`,\n `path \"${kv}/delete/${p}*\" { capabilities = [\"update\"] }`,\n `path \"${kv}/destroy/${p}*\" { capabilities = [\"update\"] }`,\n `path \"${kv}/metadata/${p}*\" { capabilities = [\"delete\"] }`,\n `path \"${t}/sign/*\" { capabilities = [\"deny\"] }`,\n `path \"${t}/encrypt/*\" { capabilities = [\"deny\"] }`,\n `path \"${t}/decrypt/*\" { capabilities = [\"deny\"] }`,\n `path \"${t}/export/*\" { capabilities = [\"deny\"] }`,\n `path \"${t}/backup/*\" { capabilities = [\"deny\"] }`,\n RENEW_SELF,\n ].join('\\n');\n}\n\n/** @wildo_source:part:end platform.key-management.vault-custody */\n\n/**\n * How long a token issued for the platform lives between renewals. apps-manager renews each token at half its lease\n * (`VaultTokenRenewal`), so the period bounds how long a token that stops being renewed stays usable, not how long the\n * platform runs.\n */\nexport const VAULT_TOKEN_PERIOD = '768h';\n"]}
|
|
@@ -126,8 +126,9 @@ export interface LockfileMutateOptions {
|
|
|
126
126
|
*
|
|
127
127
|
* - Returns a fresh empty envelope if the file does not exist
|
|
128
128
|
* (and `createIfMissing` is not explicitly false).
|
|
129
|
-
* - Validates the canonical envelope shape (schemaVersion,
|
|
130
|
-
*
|
|
129
|
+
* - Validates the canonical envelope shape (schemaVersion, sections)
|
|
130
|
+
* against `SaasLockfileEnvelopeSchema`, after dropping the keys earlier
|
|
131
|
+
* envelopes carried (`withoutRetiredLockfileEnvelopeKeys`).
|
|
131
132
|
* - Applies caller-supplied `sectionSchemas` after the envelope
|
|
132
133
|
* shape passes — failures throw a `ZodError` so the caller knows
|
|
133
134
|
* exactly which section + field rejected.
|
|
@@ -145,13 +146,10 @@ export declare function readWildoSaasLock(options: Pick<LockfileMutateOptions, '
|
|
|
145
146
|
* re-validated against the envelope schema (and any caller-supplied
|
|
146
147
|
* `sectionSchemas`) before being atomically written.
|
|
147
148
|
*
|
|
148
|
-
*
|
|
149
|
-
*
|
|
150
|
-
*
|
|
151
|
-
*
|
|
152
|
-
* one diff, this field (#1765). The comparison is on BYTES rather than on the parsed sections so a
|
|
153
|
-
* no-op mutation still writes back what normalization changed (schema defaults, a missing trailing
|
|
154
|
-
* newline).
|
|
149
|
+
* Nothing is written when the bytes that would be written equal the bytes on disk, so a no-op
|
|
150
|
+
* mutation leaves the file, and its modification time, alone. The comparison is on BYTES rather than
|
|
151
|
+
* on the parsed sections so a no-op mutation still writes back what normalization changed (schema
|
|
152
|
+
* defaults, a missing trailing newline, a retired envelope key such as `generatedAt`).
|
|
155
153
|
*
|
|
156
154
|
* The library never inspects `sections.providers.runtimeScopes`,
|
|
157
155
|
* `sections.modules`, or `sections.i18n` — it only enforces the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lockfile-io.d.ts","sourceRoot":"","sources":["../../../../src/lockfile/lockfile-io.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAMH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,
|
|
1
|
+
{"version":3,"file":"lockfile-io.d.ts","sourceRoot":"","sources":["../../../../src/lockfile/lockfile-io.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAMH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAGL,KAAK,oBAAoB,EAE1B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAA2C,KAAK,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAE1G;;GAEG;AACH,eAAO,MAAM,6BAA6B,qCAAqC,CAAC;AAEhF;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAE7D;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,oBAAoB;;;;;;;;;CAIuB,CAAC;AAEzD;;;;;;;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40
|
-
import { SaasLockfileEnvelopeSchema, } from './wildo-saas-lock.shared.schemas.js';
|
|
40
|
+
import { SaasLockfileEnvelopeSchema, withoutRetiredLockfileEnvelopeKeys, } from './wildo-saas-lock.shared.schemas.js';
|
|
41
41
|
import { assertHeldFileLocksIntact, holdFileLock } from './file-lock-hold.js';
|
|
42
42
|
/**
|
|
43
43
|
* Canonical path of the saas-app lockfile, relative to the saas root.
|
|
@@ -98,8 +98,9 @@ override) {
|
|
|
98
98
|
*
|
|
99
99
|
* - Returns a fresh empty envelope if the file does not exist
|
|
100
100
|
* (and `createIfMissing` is not explicitly false).
|
|
101
|
-
* - Validates the canonical envelope shape (schemaVersion,
|
|
102
|
-
*
|
|
101
|
+
* - Validates the canonical envelope shape (schemaVersion, sections)
|
|
102
|
+
* against `SaasLockfileEnvelopeSchema`, after dropping the keys earlier
|
|
103
|
+
* envelopes carried (`withoutRetiredLockfileEnvelopeKeys`).
|
|
103
104
|
* - Applies caller-supplied `sectionSchemas` after the envelope
|
|
104
105
|
* shape passes — failures throw a `ZodError` so the caller knows
|
|
105
106
|
* exactly which section + field rejected.
|
|
@@ -117,14 +118,13 @@ export async function readWildoSaasLock(options) {
|
|
|
117
118
|
if (err.code === 'ENOENT' && options.createIfMissing !== false) {
|
|
118
119
|
return {
|
|
119
120
|
schemaVersion: 2,
|
|
120
|
-
generatedAt: new Date().toISOString(),
|
|
121
121
|
sections: {},
|
|
122
122
|
};
|
|
123
123
|
}
|
|
124
124
|
throw err;
|
|
125
125
|
}
|
|
126
126
|
const json = JSON.parse(raw);
|
|
127
|
-
const envelope = SaasLockfileEnvelopeSchema.parse(json);
|
|
127
|
+
const envelope = SaasLockfileEnvelopeSchema.parse(withoutRetiredLockfileEnvelopeKeys(json));
|
|
128
128
|
if (options.sectionSchemas) {
|
|
129
129
|
validateAndNormalizeSections(envelope.sections, options.sectionSchemas);
|
|
130
130
|
}
|
|
@@ -186,7 +186,6 @@ function serializeLockfile(envelope) {
|
|
|
186
186
|
function emptyEnvelope() {
|
|
187
187
|
return {
|
|
188
188
|
schemaVersion: 2,
|
|
189
|
-
generatedAt: new Date().toISOString(),
|
|
190
189
|
sections: {},
|
|
191
190
|
};
|
|
192
191
|
}
|
|
@@ -209,13 +208,10 @@ async function writeFileAtomicAsync(filePath, content) {
|
|
|
209
208
|
* re-validated against the envelope schema (and any caller-supplied
|
|
210
209
|
* `sectionSchemas`) before being atomically written.
|
|
211
210
|
*
|
|
212
|
-
*
|
|
213
|
-
*
|
|
214
|
-
*
|
|
215
|
-
*
|
|
216
|
-
* one diff, this field (#1765). The comparison is on BYTES rather than on the parsed sections so a
|
|
217
|
-
* no-op mutation still writes back what normalization changed (schema defaults, a missing trailing
|
|
218
|
-
* newline).
|
|
211
|
+
* Nothing is written when the bytes that would be written equal the bytes on disk, so a no-op
|
|
212
|
+
* mutation leaves the file, and its modification time, alone. The comparison is on BYTES rather than
|
|
213
|
+
* on the parsed sections so a no-op mutation still writes back what normalization changed (schema
|
|
214
|
+
* defaults, a missing trailing newline, a retired envelope key such as `generatedAt`).
|
|
219
215
|
*
|
|
220
216
|
* The library never inspects `sections.providers.runtimeScopes`,
|
|
221
217
|
* `sections.modules`, or `sections.i18n` — it only enforces the
|
|
@@ -234,20 +230,25 @@ export async function withLockfileMutate(options, mutator) {
|
|
|
234
230
|
const next = structuredClone(before);
|
|
235
231
|
await mutator(next);
|
|
236
232
|
// Re-validate AFTER mutation; the mutator may have introduced
|
|
237
|
-
// structurally-invalid input.
|
|
238
|
-
|
|
233
|
+
// structurally-invalid input. What is WRITTEN is the parsed value, not
|
|
234
|
+
// the mutator's object: the parse puts keys in the schema's order, and
|
|
235
|
+
// a reader always sees that order. Serializing the mutator's object
|
|
236
|
+
// instead wrote whatever order its producer built (the infra section
|
|
237
|
+
// in `BackingServiceKind` order, a newly added section last), so the
|
|
238
|
+
// provider sync and every other writer re-ordered each other's bytes
|
|
239
|
+
// forever and a no-op never stayed a no-op (#1765 review F1).
|
|
240
|
+
const normalized = SaasLockfileEnvelopeSchema.parse(next);
|
|
239
241
|
if (options.sectionSchemas) {
|
|
240
|
-
validateAndNormalizeSections(
|
|
242
|
+
validateAndNormalizeSections(normalized.sections, options.sectionSchemas);
|
|
241
243
|
}
|
|
242
244
|
const onDisk = await fs.readFile(filePath, 'utf8').catch(() => null);
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
next.generatedAt = new Date().toISOString();
|
|
245
|
+
const serialized = serializeLockfile(normalized);
|
|
246
|
+
if (onDisk === serialized)
|
|
247
|
+
return normalized;
|
|
247
248
|
// A writer that lost the lock mid-mutation would overwrite whoever took it (#2225).
|
|
248
249
|
assertHeldFileLocksIntact();
|
|
249
|
-
await writeFileAtomicAsync(filePath,
|
|
250
|
-
return
|
|
250
|
+
await writeFileAtomicAsync(filePath, serialized);
|
|
251
|
+
return normalized;
|
|
251
252
|
}, lockOptions);
|
|
252
253
|
}
|
|
253
254
|
export async function withDedicatedFileLock(lockTargetPath, fn, lockOptions) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lockfile-io.js","sourceRoot":"","sources":["../../../../src/lockfile/lockfile-io.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAElC,OAAO,eAAe,MAAM,mBAAmB,CAAC;AAEhD,OAAO,EACL,0BAA0B,GAG3B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,yBAAyB,EAAE,YAAY,EAAiC,MAAM,kBAAkB,CAAC;AAE1G;;GAEG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAG,kCAAkC,CAAC;AAEhF;;GAEG;AACH,MAAM,UAAU,oBAAoB,CAAC,QAAgB;IACnD,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,6BAA6B,CAA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QAC/C,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC,GAAG,UAAU,CAAC;IAC5C,CAAC,CACF,CAAC;IACF,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["/**\n * Shared `wildo-saas.lock.json` IO primitives.\n *\n * Phase 1 graduates the locking + atomic-write surface validated by\n * the Phase 0.B contention spike (`module-registry-analysis.md`)\n * into `platform-config-lib`. Both the dev companion's\n * `WildoSaasLockCompanionService` and the CLI-side\n * `RegistryLockfileService` consume this module so concurrent\n * writers — across processes (CLI + companion + minions) — never\n * lose updates and never observe a half-written envelope.\n *\n * Exposes two layers:\n *\n * 1. `withLockfileMutate(opts, mutator)` — full-envelope mutate\n * under `proper-lockfile` + `write-file-atomic`. The companion\n * uses this so it can preserve its full-envelope contract and\n * validate its companion-owned i18n schema in the same pass.\n *\n * 2. `withLockfileSectionMutate(opts, mutator)` — section-scoped\n * mutate. The CLI uses this so it can ONLY touch one section\n * (e.g. `sections.modules`) and never accidentally clobber a\n * sibling section.\n *\n * Both layers preserve unknown sections verbatim — every consumer\n * MUST round-trip every `sections.*` key it does not recognize.\n *\n * Hard contract (KD-4 / KD-15 / KD-18):\n * - The library NEVER writes provider runtime artifacts under\n * `.wildo-saas/generated/providers/*.runtime-providers.generated.json` or\n * `src/generated/wildo-provider-runtime.generated.ts`. Those are\n * produced by the provider materialization workflow alone.\n * - `sections.providers.runtimeScopes` is owned end-to-end by the\n * provider workstream; module-registry callers MUST NOT mutate it.\n * This module is unaware of the provider section beyond\n * preserving its bytes.\n */\n\nimport { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\nimport type lockfile from 'proper-lockfile';\nimport writeFileAtomic from 'write-file-atomic';\nimport { z } from 'zod';\nimport {\n SaasLockfileEnvelopeSchema,\n type SaasLockfileEnvelope,\n type SaasLockfileKnownSections,\n} from './wildo-saas-lock.shared.schemas';\nimport { assertHeldFileLocksIntact, holdFileLock, type FileLockCompromisedError } from './file-lock-hold';\n\n/**\n * Canonical path of the saas-app lockfile, relative to the saas root.\n */\nexport const WILDO_SAAS_LOCK_RELATIVE_PATH = '.wildo-saas/wildo-saas.lock.json';\n\n/**\n * Build the absolute lockfile path for a given saas root.\n */\nexport function getWildoSaasLockPath(saasRoot: string): string {\n return path.resolve(saasRoot, WILDO_SAAS_LOCK_RELATIVE_PATH);\n}\n\n/**\n * Default `proper-lockfile` options. The 5s `stale` window matches\n * the Phase 0.B spike (`module-registry-analysis.md` Phase 0.B\n * Findings): typical lock-hold time is < 50ms; 5s is generous enough\n * to absorb a CI pause without compromising legitimate locks. Tests\n * 4a-4d all passed under these settings.\n *\n * `realpath: false` is required when the saas root is symlinked\n * (common with pnpm `dependenciesMeta.injected: true` workspaces).\n */\nexport const DEFAULT_LOCK_OPTIONS = {\n retries: { retries: 200, minTimeout: 5, maxTimeout: 50, factor: 1.2 },\n stale: 5000,\n realpath: false,\n} as const satisfies Parameters<typeof lockfile.lock>[1];\n\n/**\n * The result of merging caller options over {@link DEFAULT_LOCK_OPTIONS}.\n *\n * Its leaves are WIDENED (`number` / `boolean`) and that is the point: the\n * defaults are `as const`, so `typeof DEFAULT_LOCK_OPTIONS` describes those exact\n * literals — `stale: 5000`, `realpath: false`. A merge that honours a caller\n * override cannot satisfy it, because an overridden `stale` is not `5000`.\n *\n * Annotating the merge as `typeof DEFAULT_LOCK_OPTIONS` claimed the result was\n * always the defaults, which is true only when nothing was overridden — i.e. in\n * the one case the function exists to avoid.\n */\nexport type ResolvedLockOptions = {\n /**\n * Either a retry POLICY or a bare attempt count — `proper-lockfile` accepts\n * both, and the merge passes a bare number straight through\n * (`overrideRetries ?? baseRetries`). Omitting `number` made the merge unable to\n * describe its own fallback branch.\n */\n readonly retries: number | { retries?: number; minTimeout?: number; maxTimeout?: number; factor?: number };\n readonly stale: number;\n readonly realpath: boolean;\n /** See {@link DedicatedFileLockOptions.onCompromised}. */\n readonly onCompromised?: (error: FileLockCompromisedError) => void;\n};\n\n/**\n * Deep-merge caller-supplied lock options on top of `DEFAULT_LOCK_OPTIONS`.\n *\n * Phase 1 review (M-2.1): a shallow merge replaced the entire\n * `retries` object whenever a caller passed a partial — so\n * `lockOptions: { retries: { retries: 5 } }` silently lost the\n * `minTimeout`/`maxTimeout`/`factor` defaults that Phase 0.B\n * validated. The deep merge keeps every default intact unless\n * the caller explicitly overrides each leaf.\n */\nfunction mergeLockOptions(\n // `DedicatedFileLockOptions`, NOT `Partial<typeof DEFAULT_LOCK_OPTIONS>`: that constant is\n // `as const`, so every leaf is a LITERAL type and `Partial` only reaches the top level — which\n // made the very call shape this merge exists to support (`{ retries: { retries: 5 } }`) a type\n // error, because `5` is not `200`. It also removes the cast the dedicated-lock caller needed.\n override?: DedicatedFileLockOptions,\n): ResolvedLockOptions {\n if (!override) return DEFAULT_LOCK_OPTIONS;\n const baseRetries = DEFAULT_LOCK_OPTIONS.retries;\n const overrideRetries = override.retries;\n const mergedRetries =\n typeof overrideRetries === 'object' && overrideRetries !== null\n ? { ...baseRetries, ...overrideRetries }\n : overrideRetries ?? baseRetries;\n return {\n ...DEFAULT_LOCK_OPTIONS,\n ...override,\n retries: mergedRetries,\n };\n}\n\nexport interface LockfileMutateOptions {\n /** Absolute path to the saas application root. */\n saasRoot: string;\n /**\n * Optional Zod schemas to validate sibling sections at parse time.\n * Companion-owned sections (e.g. `i18n`) are validated by passing\n * them here. CLI callers can pass\n * `DEFAULT_REGISTRY_SECTION_SCHEMAS` to validate `modules`.\n *\n * Sections not listed here are still PRESERVED on round-trip via\n * the envelope's `.catchall(z.unknown())` — they are simply not\n * type-narrowed.\n */\n sectionSchemas?: Record<string, z.ZodTypeAny>;\n /**\n * Override `proper-lockfile` options. Phase 0.B's measurements\n * suggest the defaults are fine for both CLI and companion\n * call patterns; this hook exists for tests + tuning.\n */\n lockOptions?: DedicatedFileLockOptions;\n /**\n * If true (default), the lockfile is created on first read with an\n * empty `sections` map. Set to false to fail with ENOENT.\n */\n createIfMissing?: boolean;\n}\n\n/**\n * Read the lockfile envelope, applying schema validation.\n *\n * - Returns a fresh empty envelope if the file does not exist\n * (and `createIfMissing` is not explicitly false).\n * - Validates the canonical envelope shape (schemaVersion, generatedAt,\n * sections) against `SaasLockfileEnvelopeSchema`.\n * - Applies caller-supplied `sectionSchemas` after the envelope\n * shape passes — failures throw a `ZodError` so the caller knows\n * exactly which section + field rejected.\n *\n * Does NOT acquire a lock; reads are unsynchronized. Callers that\n * need read-after-write coherence must read INSIDE `withLockfileMutate`.\n */\nexport async function readWildoSaasLock(\n options: Pick<LockfileMutateOptions, 'saasRoot' | 'sectionSchemas' | 'createIfMissing'>,\n): Promise<SaasLockfileEnvelope> {\n const filePath = getWildoSaasLockPath(options.saasRoot);\n let raw: string;\n try {\n raw = await fs.readFile(filePath, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT' && options.createIfMissing !== false) {\n return {\n schemaVersion: 2,\n generatedAt: new Date().toISOString(),\n sections: {},\n };\n }\n throw err;\n }\n const json = JSON.parse(raw) as unknown;\n const envelope = SaasLockfileEnvelopeSchema.parse(json);\n if (options.sectionSchemas) {\n validateAndNormalizeSections(envelope.sections, options.sectionSchemas);\n }\n return envelope;\n}\n\n/**\n * Validate every present `sections.<key>` against its caller-supplied\n * Zod schema AND write the parsed (default-expanded) value back so\n * defaults declared in those schemas actually persist on disk.\n *\n * Phase 1 review (H-2.1 / M-1.2): the prior implementation called\n * `.parse(value)` and discarded the result, which meant\n * `.default(...)` clauses in section schemas were only ever applied\n * during validation — never written. Schemas with shallow defaults\n * (e.g. `installed: z.record(...).default({})`) tolerated the bug\n * because mutators always set `installed` directly, but a future\n * schema with deep defaults would silently lose them.\n */\nfunction validateAndNormalizeSections(\n sections: SaasLockfileKnownSections,\n sectionSchemas: Record<string, z.ZodTypeAny>,\n): void {\n const mutable = sections as Record<string, unknown>;\n for (const [key, schema] of Object.entries(sectionSchemas)) {\n const value = mutable[key];\n if (value === undefined) continue;\n mutable[key] = schema.parse(value);\n }\n}\n\n/**\n * Acquire the OS-level lockfile lock, run `fn`, then release it.\n *\n * Wrapper around `holdFileLock` (`./file-lock-hold`) that:\n * - Creates the parent dir + an empty file if missing (proper-lockfile\n * refuses to lock a non-existent file).\n * - Forwards `realpath: false` so symlinked workspaces lock correctly.\n * - Always releases the lock, even on error.\n * - Inherits the live-holder reclaim guard and the compromise-as-error\n * handling (#2225).\n */\nasync function withLock<T>(\n filePath: string,\n fn: () => Promise<T>,\n // A MERGED value, not the defaults — see `ResolvedLockOptions`. Typing this as\n // `typeof DEFAULT_LOCK_OPTIONS` demanded the literal `200`/`5000`/`false`, so any\n // caller-overridden option was a type error at the point of USE rather than at\n // the point of override, which is why it read as a failure in the merge.\n lockOptions: ResolvedLockOptions,\n): Promise<T> {\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n // Ensure the file exists; `proper-lockfile.lock` refuses ENOENT.\n try {\n await fs.access(filePath);\n } catch {\n await writeFileAtomicAsync(filePath, JSON.stringify(emptyEnvelope(), null, 2));\n }\n return holdFileLock(filePath, fn, lockOptions);\n}\n\n/** The one on-disk form of the envelope: two-space JSON with a trailing newline. */\nfunction serializeLockfile(envelope: SaasLockfileEnvelope): string {\n return JSON.stringify(envelope, null, 2) + '\\n';\n}\n\nfunction emptyEnvelope(): SaasLockfileEnvelope {\n return {\n schemaVersion: 2,\n generatedAt: new Date().toISOString(),\n sections: {},\n };\n}\n\nasync function writeFileAtomicAsync(filePath: string, content: string): Promise<void> {\n await new Promise<void>((resolve, reject) => {\n writeFileAtomic(filePath, content, (err: Error | undefined) => {\n if (err) reject(err);\n else resolve();\n });\n });\n}\n\n/**\n * Read-modify-write a lockfile under an OS-level lock.\n *\n * The mutator receives a deep-cloned, schema-validated envelope —\n * any in-place mutation is safe and won't bleed back into the\n * pre-write copy. After the mutator returns, the result is\n * re-validated against the envelope schema (and any caller-supplied\n * `sectionSchemas`) before being atomically written.\n *\n * `generatedAt` is refreshed only when the mutation changes the file. When the bytes that would be\n * written — with the previous `generatedAt` — equal the bytes on disk, nothing is written and the\n * envelope is returned as it was. The lockfile is committed, and a timestamp that moved on every no-op\n * sync dirtied the tree with nothing in it: a `wildo registry add` + `remove` round trip left exactly\n * one diff, this field (#1765). The comparison is on BYTES rather than on the parsed sections so a\n * no-op mutation still writes back what normalization changed (schema defaults, a missing trailing\n * newline).\n *\n * The library never inspects `sections.providers.runtimeScopes`,\n * `sections.modules`, or `sections.i18n` — it only enforces the\n * envelope shape. Concrete section semantics live in their owning\n * subsystems.\n */\nexport async function withLockfileMutate(\n options: LockfileMutateOptions,\n mutator: (envelope: SaasLockfileEnvelope) => void | Promise<void>,\n): Promise<SaasLockfileEnvelope> {\n const filePath = getWildoSaasLockPath(options.saasRoot);\n const lockOptions = mergeLockOptions(options.lockOptions);\n return withLock(filePath, async () => {\n const before = await readWildoSaasLock({\n saasRoot: options.saasRoot,\n sectionSchemas: options.sectionSchemas,\n createIfMissing: true,\n });\n const next: SaasLockfileEnvelope = structuredClone(before);\n await mutator(next);\n // Re-validate AFTER mutation; the mutator may have introduced\n // structurally-invalid input.\n SaasLockfileEnvelopeSchema.parse(next);\n if (options.sectionSchemas) {\n validateAndNormalizeSections(next.sections, options.sectionSchemas);\n }\n const onDisk = await fs.readFile(filePath, 'utf8').catch(() => null);\n if (onDisk === serializeLockfile({ ...next, generatedAt: before.generatedAt })) {\n return { ...next, generatedAt: before.generatedAt };\n }\n next.generatedAt = new Date().toISOString();\n // A writer that lost the lock mid-mutation would overwrite whoever took it (#2225).\n assertHeldFileLocksIntact();\n await writeFileAtomicAsync(filePath, serializeLockfile(next));\n return next;\n }, lockOptions);\n}\n\n/**\n * Hold an OS-level `proper-lockfile` lock on an ARBITRARY dedicated lock\n * target while `fn` runs — the path-parameterized sibling of\n * `withLockfileMutate` for callers that need cross-process mutual\n * exclusion WITHOUT the `wildo-saas.lock.json` envelope semantics.\n *\n * Why this exists (meta-workflows P-20, 2026-07-03): the companion's\n * coding-agent dispatch lane serializes workspace mutations on a\n * dedicated target (`<saasRoot>/.wildo-saas/state/workspace-mutation.lock`)\n * held for the WHOLE agent run (minutes). Routing that through\n * `withLockfileMutate` would hold the shared saas lockfile hostage —\n * starving i18n/registry writers — and the envelope re-validation is\n * meaningless for a pure mutex. The primitive lives HERE (not\n * companion-local) so the CLI can adopt the SAME lock target with the\n * SAME semantics when its worktree-mutating commands learn to respect it.\n *\n * Semantics:\n * - Parent directory + an empty placeholder file are created if missing\n * (`proper-lockfile` refuses ENOENT targets). The file content is never\n * read or written by this helper — it is a pure lock anchor.\n * - `proper-lockfile` refreshes the lock mtime every `stale / 2` while the\n * holder is alive. That refresh can be LATE — an event-loop stall or a\n * saturated threadpool — and the mtime alone would then read as stale.\n * So a waiter's reclaim is refused while the recorded holder process is\n * alive on this host (`holdFileLock`, #2225); a CRASHED holder's lock is\n * still reclaimed after `stale`. Until #2225 this said long holds\n * \"survive the `stale` window\" unconditionally, and a 2026-10-01 build\n * wave showed they did not.\n * - Losing the lock while held never exits the process: the call rejects\n * with `FileLockCompromisedError` (`code: 'ECOMPROMISED'`) once `fn`\n * settles, and `assertHeldFileLocksIntact()` refuses inside `fn` from\n * the moment of the loss — call it before a commit or a write the lock\n * serializes.\n * - Lock options merge over {@link DEFAULT_LOCK_OPTIONS}. Callers that\n * want fail-fast contention (HTTP 409 instead of queueing) pass\n * `{ retries: { retries: 0 } }`.\n * - The lock is always released (or at least attempted) on completion,\n * including the error path.\n *\n * Contention surfaces as the `proper-lockfile` `ELOCKED` error\n * (`error.code === 'ELOCKED'`) — callers map it to their own conflict\n * vocabulary.\n */\nexport interface DedicatedFileLockOptions {\n /** `proper-lockfile` retry policy — `{ retries: { retries: 0 } }` = fail-fast contention. */\n retries?: { retries?: number; minTimeout?: number; maxTimeout?: number; factor?: number };\n /** Stale window in ms (lock mtime auto-refreshes while the holder lives). */\n stale?: number;\n /** Keep `false` for symlinked (pnpm-injected) workspaces. */\n realpath?: boolean;\n /**\n * Told once if the lock is lost while held, for the caller's own log. The section still fails with\n * `FileLockCompromisedError`. Omitted, one line goes to stderr.\n */\n onCompromised?: (error: FileLockCompromisedError) => void;\n}\n\nexport async function withDedicatedFileLock<T>(\n lockTargetPath: string,\n fn: () => Promise<T>,\n lockOptions?: DedicatedFileLockOptions,\n): Promise<T> {\n await fs.mkdir(path.dirname(lockTargetPath), { recursive: true });\n try {\n await fs.access(lockTargetPath);\n } catch {\n await writeFileAtomicAsync(lockTargetPath, '');\n }\n return holdFileLock(lockTargetPath, fn, mergeLockOptions(lockOptions));\n}\n\n/**\n * Canonical workspace-mutation lock target, app-root-relative. ONE constant\n * shared by every process that mutates the application worktree in a way\n * that must serialize against coding-agent dispatch runs (meta-workflows\n * P-20): the companion's dispatch lane holds it for the whole agent run;\n * CLI worktree-writers (e.g. `wildo config sync`) acquire it fail-fast\n * around their write phase. Deliberately NOT taken by human/parallel-session\n * edits (P-19b — per-file attribution compensates, never exclusion).\n * Keep companion and CLI on THIS constant — a hand-copied path is drift.\n */\nexport const WORKSPACE_MUTATION_LOCK_RELATIVE_PATH: string =\n '.wildo-saas/state/workspace-mutation.lock';\n\n/** Absolute workspace-mutation lock target for an application root. */\nexport function getWorkspaceMutationLockPath(saasRoot: string): string {\n return path.join(saasRoot, WORKSPACE_MUTATION_LOCK_RELATIVE_PATH);\n}\n\n/**\n * Section-scoped mutate. The mutator only sees one section's payload\n * (`sections.<sectionKey>`) and CANNOT reach sibling sections —\n * preventing accidental clobbers. Returns the mutated section.\n *\n * Use this from CLI callers (`RegistryLockfileService`) so cross-\n * section bugs are impossible by construction. Companion callers\n * that legitimately need full-envelope access keep using\n * `withLockfileMutate` directly.\n */\nexport async function withLockfileSectionMutate<S>(\n options: LockfileMutateOptions & {\n /** Section key under `sections` (e.g. `'modules'`, `'i18n'`). */\n sectionKey: string;\n /** Zod schema validating the section payload. Required. */\n sectionSchema: z.ZodType<S>;\n /** Initial value when the section does not yet exist. */\n initialSection: () => S;\n },\n mutator: (section: S) => S | void | Promise<S | void>,\n): Promise<S> {\n let mutatedOut!: S;\n await withLockfileMutate(\n {\n saasRoot: options.saasRoot,\n lockOptions: options.lockOptions,\n sectionSchemas: {\n ...options.sectionSchemas,\n [options.sectionKey]: options.sectionSchema,\n },\n },\n async (envelope) => {\n const sections = envelope.sections as Record<string, unknown>;\n const current = (sections[options.sectionKey] as S | undefined) ?? options.initialSection();\n const cloned = structuredClone(current);\n const ret = await mutator(cloned);\n const next = (ret ?? cloned) as S;\n // Per-section validation (also covers initial-default re-validation).\n mutatedOut = options.sectionSchema.parse(next);\n sections[options.sectionKey] = mutatedOut;\n },\n );\n return mutatedOut;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"lockfile-io.js","sourceRoot":"","sources":["../../../../src/lockfile/lockfile-io.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAElC,OAAO,eAAe,MAAM,mBAAmB,CAAC;AAEhD,OAAO,EACL,0BAA0B,EAC1B,kCAAkC,GAGnC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,yBAAyB,EAAE,YAAY,EAAiC,MAAM,kBAAkB,CAAC;AAE1G;;GAEG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAG,kCAAkC,CAAC;AAEhF;;GAEG;AACH,MAAM,UAAU,oBAAoB,CAAC,QAAgB;IACnD,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,6BAA6B,CAAC,CAAC;AAC/D,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,OAAO,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,UAAU,EAAE,CAAC,EAAE,UAAU,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE;IACrE,KAAK,EAAE,IAAI;IACX,QAAQ,EAAE,KAAK;CACuC,CAAC;AA4Bz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,CAAC;AACpE,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC7C,OAOC,EACD,OAAqD;IAErD,IAAI,UAAc,CAAC;IACnB,MAAM,kBAAkB,CACtB;QACE,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,cAAc,EAAE;YACd,GAAG,OAAO,CAAC,cAAc;YACzB,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,OAAO,CAAC,aAAa;SAC5C;KACF,EACD,KAAK,EAAE,QAAQ,EAAE,EAAE;QACjB,MAAM,QAAQ,GAAG,QAAQ,CAAC,QAAmC,CAAC;QAC9D,MAAM,OAAO,GAAI,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAmB,IAAI,OAAO,CAAC,cAAc,EAAE,CAAC;QAC5F,MAAM,MAAM,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;QACxC,MAAM,GAAG,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;QAClC,MAAM,IAAI,GAAG,CAAC,GAAG,IAAI,MAAM,CAAM,CAAC;QAClC,sEAAsE;QACtE,UAAU,GAAG,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC/C,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC,GAAG,UAAU,CAAC;IAC5C,CAAC,CACF,CAAC;IACF,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["/**\n * Shared `wildo-saas.lock.json` IO primitives.\n *\n * Phase 1 graduates the locking + atomic-write surface validated by\n * the Phase 0.B contention spike (`module-registry-analysis.md`)\n * into `platform-config-lib`. Both the dev companion's\n * `WildoSaasLockCompanionService` and the CLI-side\n * `RegistryLockfileService` consume this module so concurrent\n * writers — across processes (CLI + companion + minions) — never\n * lose updates and never observe a half-written envelope.\n *\n * Exposes two layers:\n *\n * 1. `withLockfileMutate(opts, mutator)` — full-envelope mutate\n * under `proper-lockfile` + `write-file-atomic`. The companion\n * uses this so it can preserve its full-envelope contract and\n * validate its companion-owned i18n schema in the same pass.\n *\n * 2. `withLockfileSectionMutate(opts, mutator)` — section-scoped\n * mutate. The CLI uses this so it can ONLY touch one section\n * (e.g. `sections.modules`) and never accidentally clobber a\n * sibling section.\n *\n * Both layers preserve unknown sections verbatim — every consumer\n * MUST round-trip every `sections.*` key it does not recognize.\n *\n * Hard contract (KD-4 / KD-15 / KD-18):\n * - The library NEVER writes provider runtime artifacts under\n * `.wildo-saas/generated/providers/*.runtime-providers.generated.json` or\n * `src/generated/wildo-provider-runtime.generated.ts`. Those are\n * produced by the provider materialization workflow alone.\n * - `sections.providers.runtimeScopes` is owned end-to-end by the\n * provider workstream; module-registry callers MUST NOT mutate it.\n * This module is unaware of the provider section beyond\n * preserving its bytes.\n */\n\nimport { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\nimport type lockfile from 'proper-lockfile';\nimport writeFileAtomic from 'write-file-atomic';\nimport { z } from 'zod';\nimport {\n SaasLockfileEnvelopeSchema,\n withoutRetiredLockfileEnvelopeKeys,\n type SaasLockfileEnvelope,\n type SaasLockfileKnownSections,\n} from './wildo-saas-lock.shared.schemas';\nimport { assertHeldFileLocksIntact, holdFileLock, type FileLockCompromisedError } from './file-lock-hold';\n\n/**\n * Canonical path of the saas-app lockfile, relative to the saas root.\n */\nexport const WILDO_SAAS_LOCK_RELATIVE_PATH = '.wildo-saas/wildo-saas.lock.json';\n\n/**\n * Build the absolute lockfile path for a given saas root.\n */\nexport function getWildoSaasLockPath(saasRoot: string): string {\n return path.resolve(saasRoot, WILDO_SAAS_LOCK_RELATIVE_PATH);\n}\n\n/**\n * Default `proper-lockfile` options. The 5s `stale` window matches\n * the Phase 0.B spike (`module-registry-analysis.md` Phase 0.B\n * Findings): typical lock-hold time is < 50ms; 5s is generous enough\n * to absorb a CI pause without compromising legitimate locks. Tests\n * 4a-4d all passed under these settings.\n *\n * `realpath: false` is required when the saas root is symlinked\n * (common with pnpm `dependenciesMeta.injected: true` workspaces).\n */\nexport const DEFAULT_LOCK_OPTIONS = {\n retries: { retries: 200, minTimeout: 5, maxTimeout: 50, factor: 1.2 },\n stale: 5000,\n realpath: false,\n} as const satisfies Parameters<typeof lockfile.lock>[1];\n\n/**\n * The result of merging caller options over {@link DEFAULT_LOCK_OPTIONS}.\n *\n * Its leaves are WIDENED (`number` / `boolean`) and that is the point: the\n * defaults are `as const`, so `typeof DEFAULT_LOCK_OPTIONS` describes those exact\n * literals — `stale: 5000`, `realpath: false`. A merge that honours a caller\n * override cannot satisfy it, because an overridden `stale` is not `5000`.\n *\n * Annotating the merge as `typeof DEFAULT_LOCK_OPTIONS` claimed the result was\n * always the defaults, which is true only when nothing was overridden — i.e. in\n * the one case the function exists to avoid.\n */\nexport type ResolvedLockOptions = {\n /**\n * Either a retry POLICY or a bare attempt count — `proper-lockfile` accepts\n * both, and the merge passes a bare number straight through\n * (`overrideRetries ?? baseRetries`). Omitting `number` made the merge unable to\n * describe its own fallback branch.\n */\n readonly retries: number | { retries?: number; minTimeout?: number; maxTimeout?: number; factor?: number };\n readonly stale: number;\n readonly realpath: boolean;\n /** See {@link DedicatedFileLockOptions.onCompromised}. */\n readonly onCompromised?: (error: FileLockCompromisedError) => void;\n};\n\n/**\n * Deep-merge caller-supplied lock options on top of `DEFAULT_LOCK_OPTIONS`.\n *\n * Phase 1 review (M-2.1): a shallow merge replaced the entire\n * `retries` object whenever a caller passed a partial — so\n * `lockOptions: { retries: { retries: 5 } }` silently lost the\n * `minTimeout`/`maxTimeout`/`factor` defaults that Phase 0.B\n * validated. The deep merge keeps every default intact unless\n * the caller explicitly overrides each leaf.\n */\nfunction mergeLockOptions(\n // `DedicatedFileLockOptions`, NOT `Partial<typeof DEFAULT_LOCK_OPTIONS>`: that constant is\n // `as const`, so every leaf is a LITERAL type and `Partial` only reaches the top level — which\n // made the very call shape this merge exists to support (`{ retries: { retries: 5 } }`) a type\n // error, because `5` is not `200`. It also removes the cast the dedicated-lock caller needed.\n override?: DedicatedFileLockOptions,\n): ResolvedLockOptions {\n if (!override) return DEFAULT_LOCK_OPTIONS;\n const baseRetries = DEFAULT_LOCK_OPTIONS.retries;\n const overrideRetries = override.retries;\n const mergedRetries =\n typeof overrideRetries === 'object' && overrideRetries !== null\n ? { ...baseRetries, ...overrideRetries }\n : overrideRetries ?? baseRetries;\n return {\n ...DEFAULT_LOCK_OPTIONS,\n ...override,\n retries: mergedRetries,\n };\n}\n\nexport interface LockfileMutateOptions {\n /** Absolute path to the saas application root. */\n saasRoot: string;\n /**\n * Optional Zod schemas to validate sibling sections at parse time.\n * Companion-owned sections (e.g. `i18n`) are validated by passing\n * them here. CLI callers can pass\n * `DEFAULT_REGISTRY_SECTION_SCHEMAS` to validate `modules`.\n *\n * Sections not listed here are still PRESERVED on round-trip via\n * the envelope's `.catchall(z.unknown())` — they are simply not\n * type-narrowed.\n */\n sectionSchemas?: Record<string, z.ZodTypeAny>;\n /**\n * Override `proper-lockfile` options. Phase 0.B's measurements\n * suggest the defaults are fine for both CLI and companion\n * call patterns; this hook exists for tests + tuning.\n */\n lockOptions?: DedicatedFileLockOptions;\n /**\n * If true (default), the lockfile is created on first read with an\n * empty `sections` map. Set to false to fail with ENOENT.\n */\n createIfMissing?: boolean;\n}\n\n/**\n * Read the lockfile envelope, applying schema validation.\n *\n * - Returns a fresh empty envelope if the file does not exist\n * (and `createIfMissing` is not explicitly false).\n * - Validates the canonical envelope shape (schemaVersion, sections)\n * against `SaasLockfileEnvelopeSchema`, after dropping the keys earlier\n * envelopes carried (`withoutRetiredLockfileEnvelopeKeys`).\n * - Applies caller-supplied `sectionSchemas` after the envelope\n * shape passes — failures throw a `ZodError` so the caller knows\n * exactly which section + field rejected.\n *\n * Does NOT acquire a lock; reads are unsynchronized. Callers that\n * need read-after-write coherence must read INSIDE `withLockfileMutate`.\n */\nexport async function readWildoSaasLock(\n options: Pick<LockfileMutateOptions, 'saasRoot' | 'sectionSchemas' | 'createIfMissing'>,\n): Promise<SaasLockfileEnvelope> {\n const filePath = getWildoSaasLockPath(options.saasRoot);\n let raw: string;\n try {\n raw = await fs.readFile(filePath, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT' && options.createIfMissing !== false) {\n return {\n schemaVersion: 2,\n sections: {},\n };\n }\n throw err;\n }\n const json = JSON.parse(raw) as unknown;\n const envelope = SaasLockfileEnvelopeSchema.parse(withoutRetiredLockfileEnvelopeKeys(json));\n if (options.sectionSchemas) {\n validateAndNormalizeSections(envelope.sections, options.sectionSchemas);\n }\n return envelope;\n}\n\n/**\n * Validate every present `sections.<key>` against its caller-supplied\n * Zod schema AND write the parsed (default-expanded) value back so\n * defaults declared in those schemas actually persist on disk.\n *\n * Phase 1 review (H-2.1 / M-1.2): the prior implementation called\n * `.parse(value)` and discarded the result, which meant\n * `.default(...)` clauses in section schemas were only ever applied\n * during validation — never written. Schemas with shallow defaults\n * (e.g. `installed: z.record(...).default({})`) tolerated the bug\n * because mutators always set `installed` directly, but a future\n * schema with deep defaults would silently lose them.\n */\nfunction validateAndNormalizeSections(\n sections: SaasLockfileKnownSections,\n sectionSchemas: Record<string, z.ZodTypeAny>,\n): void {\n const mutable = sections as Record<string, unknown>;\n for (const [key, schema] of Object.entries(sectionSchemas)) {\n const value = mutable[key];\n if (value === undefined) continue;\n mutable[key] = schema.parse(value);\n }\n}\n\n/**\n * Acquire the OS-level lockfile lock, run `fn`, then release it.\n *\n * Wrapper around `holdFileLock` (`./file-lock-hold`) that:\n * - Creates the parent dir + an empty file if missing (proper-lockfile\n * refuses to lock a non-existent file).\n * - Forwards `realpath: false` so symlinked workspaces lock correctly.\n * - Always releases the lock, even on error.\n * - Inherits the live-holder reclaim guard and the compromise-as-error\n * handling (#2225).\n */\nasync function withLock<T>(\n filePath: string,\n fn: () => Promise<T>,\n // A MERGED value, not the defaults — see `ResolvedLockOptions`. Typing this as\n // `typeof DEFAULT_LOCK_OPTIONS` demanded the literal `200`/`5000`/`false`, so any\n // caller-overridden option was a type error at the point of USE rather than at\n // the point of override, which is why it read as a failure in the merge.\n lockOptions: ResolvedLockOptions,\n): Promise<T> {\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n // Ensure the file exists; `proper-lockfile.lock` refuses ENOENT.\n try {\n await fs.access(filePath);\n } catch {\n await writeFileAtomicAsync(filePath, JSON.stringify(emptyEnvelope(), null, 2));\n }\n return holdFileLock(filePath, fn, lockOptions);\n}\n\n/** The one on-disk form of the envelope: two-space JSON with a trailing newline. */\nfunction serializeLockfile(envelope: SaasLockfileEnvelope): string {\n return JSON.stringify(envelope, null, 2) + '\\n';\n}\n\nfunction emptyEnvelope(): SaasLockfileEnvelope {\n return {\n schemaVersion: 2,\n sections: {},\n };\n}\n\nasync function writeFileAtomicAsync(filePath: string, content: string): Promise<void> {\n await new Promise<void>((resolve, reject) => {\n writeFileAtomic(filePath, content, (err: Error | undefined) => {\n if (err) reject(err);\n else resolve();\n });\n });\n}\n\n/**\n * Read-modify-write a lockfile under an OS-level lock.\n *\n * The mutator receives a deep-cloned, schema-validated envelope —\n * any in-place mutation is safe and won't bleed back into the\n * pre-write copy. After the mutator returns, the result is\n * re-validated against the envelope schema (and any caller-supplied\n * `sectionSchemas`) before being atomically written.\n *\n * Nothing is written when the bytes that would be written equal the bytes on disk, so a no-op\n * mutation leaves the file, and its modification time, alone. The comparison is on BYTES rather than\n * on the parsed sections so a no-op mutation still writes back what normalization changed (schema\n * defaults, a missing trailing newline, a retired envelope key such as `generatedAt`).\n *\n * The library never inspects `sections.providers.runtimeScopes`,\n * `sections.modules`, or `sections.i18n` — it only enforces the\n * envelope shape. Concrete section semantics live in their owning\n * subsystems.\n */\nexport async function withLockfileMutate(\n options: LockfileMutateOptions,\n mutator: (envelope: SaasLockfileEnvelope) => void | Promise<void>,\n): Promise<SaasLockfileEnvelope> {\n const filePath = getWildoSaasLockPath(options.saasRoot);\n const lockOptions = mergeLockOptions(options.lockOptions);\n return withLock(filePath, async () => {\n const before = await readWildoSaasLock({\n saasRoot: options.saasRoot,\n sectionSchemas: options.sectionSchemas,\n createIfMissing: true,\n });\n const next: SaasLockfileEnvelope = structuredClone(before);\n await mutator(next);\n // Re-validate AFTER mutation; the mutator may have introduced\n // structurally-invalid input. What is WRITTEN is the parsed value, not\n // the mutator's object: the parse puts keys in the schema's order, and\n // a reader always sees that order. Serializing the mutator's object\n // instead wrote whatever order its producer built (the infra section\n // in `BackingServiceKind` order, a newly added section last), so the\n // provider sync and every other writer re-ordered each other's bytes\n // forever and a no-op never stayed a no-op (#1765 review F1).\n const normalized = SaasLockfileEnvelopeSchema.parse(next);\n if (options.sectionSchemas) {\n validateAndNormalizeSections(normalized.sections, options.sectionSchemas);\n }\n const onDisk = await fs.readFile(filePath, 'utf8').catch(() => null);\n const serialized = serializeLockfile(normalized);\n if (onDisk === serialized) return normalized;\n // A writer that lost the lock mid-mutation would overwrite whoever took it (#2225).\n assertHeldFileLocksIntact();\n await writeFileAtomicAsync(filePath, serialized);\n return normalized;\n }, lockOptions);\n}\n\n/**\n * Hold an OS-level `proper-lockfile` lock on an ARBITRARY dedicated lock\n * target while `fn` runs — the path-parameterized sibling of\n * `withLockfileMutate` for callers that need cross-process mutual\n * exclusion WITHOUT the `wildo-saas.lock.json` envelope semantics.\n *\n * Why this exists (meta-workflows P-20, 2026-07-03): the companion's\n * coding-agent dispatch lane serializes workspace mutations on a\n * dedicated target (`<saasRoot>/.wildo-saas/state/workspace-mutation.lock`)\n * held for the WHOLE agent run (minutes). Routing that through\n * `withLockfileMutate` would hold the shared saas lockfile hostage —\n * starving i18n/registry writers — and the envelope re-validation is\n * meaningless for a pure mutex. The primitive lives HERE (not\n * companion-local) so the CLI can adopt the SAME lock target with the\n * SAME semantics when its worktree-mutating commands learn to respect it.\n *\n * Semantics:\n * - Parent directory + an empty placeholder file are created if missing\n * (`proper-lockfile` refuses ENOENT targets). The file content is never\n * read or written by this helper — it is a pure lock anchor.\n * - `proper-lockfile` refreshes the lock mtime every `stale / 2` while the\n * holder is alive. That refresh can be LATE — an event-loop stall or a\n * saturated threadpool — and the mtime alone would then read as stale.\n * So a waiter's reclaim is refused while the recorded holder process is\n * alive on this host (`holdFileLock`, #2225); a CRASHED holder's lock is\n * still reclaimed after `stale`. Until #2225 this said long holds\n * \"survive the `stale` window\" unconditionally, and a 2026-10-01 build\n * wave showed they did not.\n * - Losing the lock while held never exits the process: the call rejects\n * with `FileLockCompromisedError` (`code: 'ECOMPROMISED'`) once `fn`\n * settles, and `assertHeldFileLocksIntact()` refuses inside `fn` from\n * the moment of the loss — call it before a commit or a write the lock\n * serializes.\n * - Lock options merge over {@link DEFAULT_LOCK_OPTIONS}. Callers that\n * want fail-fast contention (HTTP 409 instead of queueing) pass\n * `{ retries: { retries: 0 } }`.\n * - The lock is always released (or at least attempted) on completion,\n * including the error path.\n *\n * Contention surfaces as the `proper-lockfile` `ELOCKED` error\n * (`error.code === 'ELOCKED'`) — callers map it to their own conflict\n * vocabulary.\n */\nexport interface DedicatedFileLockOptions {\n /** `proper-lockfile` retry policy — `{ retries: { retries: 0 } }` = fail-fast contention. */\n retries?: { retries?: number; minTimeout?: number; maxTimeout?: number; factor?: number };\n /** Stale window in ms (lock mtime auto-refreshes while the holder lives). */\n stale?: number;\n /** Keep `false` for symlinked (pnpm-injected) workspaces. */\n realpath?: boolean;\n /**\n * Told once if the lock is lost while held, for the caller's own log. The section still fails with\n * `FileLockCompromisedError`. Omitted, one line goes to stderr.\n */\n onCompromised?: (error: FileLockCompromisedError) => void;\n}\n\nexport async function withDedicatedFileLock<T>(\n lockTargetPath: string,\n fn: () => Promise<T>,\n lockOptions?: DedicatedFileLockOptions,\n): Promise<T> {\n await fs.mkdir(path.dirname(lockTargetPath), { recursive: true });\n try {\n await fs.access(lockTargetPath);\n } catch {\n await writeFileAtomicAsync(lockTargetPath, '');\n }\n return holdFileLock(lockTargetPath, fn, mergeLockOptions(lockOptions));\n}\n\n/**\n * Canonical workspace-mutation lock target, app-root-relative. ONE constant\n * shared by every process that mutates the application worktree in a way\n * that must serialize against coding-agent dispatch runs (meta-workflows\n * P-20): the companion's dispatch lane holds it for the whole agent run;\n * CLI worktree-writers (e.g. `wildo config sync`) acquire it fail-fast\n * around their write phase. Deliberately NOT taken by human/parallel-session\n * edits (P-19b — per-file attribution compensates, never exclusion).\n * Keep companion and CLI on THIS constant — a hand-copied path is drift.\n */\nexport const WORKSPACE_MUTATION_LOCK_RELATIVE_PATH: string =\n '.wildo-saas/state/workspace-mutation.lock';\n\n/** Absolute workspace-mutation lock target for an application root. */\nexport function getWorkspaceMutationLockPath(saasRoot: string): string {\n return path.join(saasRoot, WORKSPACE_MUTATION_LOCK_RELATIVE_PATH);\n}\n\n/**\n * Section-scoped mutate. The mutator only sees one section's payload\n * (`sections.<sectionKey>`) and CANNOT reach sibling sections —\n * preventing accidental clobbers. Returns the mutated section.\n *\n * Use this from CLI callers (`RegistryLockfileService`) so cross-\n * section bugs are impossible by construction. Companion callers\n * that legitimately need full-envelope access keep using\n * `withLockfileMutate` directly.\n */\nexport async function withLockfileSectionMutate<S>(\n options: LockfileMutateOptions & {\n /** Section key under `sections` (e.g. `'modules'`, `'i18n'`). */\n sectionKey: string;\n /** Zod schema validating the section payload. Required. */\n sectionSchema: z.ZodType<S>;\n /** Initial value when the section does not yet exist. */\n initialSection: () => S;\n },\n mutator: (section: S) => S | void | Promise<S | void>,\n): Promise<S> {\n let mutatedOut!: S;\n await withLockfileMutate(\n {\n saasRoot: options.saasRoot,\n lockOptions: options.lockOptions,\n sectionSchemas: {\n ...options.sectionSchemas,\n [options.sectionKey]: options.sectionSchema,\n },\n },\n async (envelope) => {\n const sections = envelope.sections as Record<string, unknown>;\n const current = (sections[options.sectionKey] as S | undefined) ?? options.initialSection();\n const cloned = structuredClone(current);\n const ret = await mutator(cloned);\n const next = (ret ?? cloned) as S;\n // Per-section validation (also covers initial-default re-validation).\n mutatedOut = options.sectionSchema.parse(next);\n sections[options.sectionKey] = mutatedOut;\n },\n );\n return mutatedOut;\n}\n"]}
|
|
@@ -56,13 +56,14 @@ export interface InfraEnvSelectionInput {
|
|
|
56
56
|
export interface MaterializeInfraSectionOptions {
|
|
57
57
|
envs: ReadonlyArray<InfraEnvSelectionInput>;
|
|
58
58
|
/**
|
|
59
|
-
* ISO-8601
|
|
60
|
-
* or CHANGED capabilities (see `previousSection` for
|
|
61
|
-
* rule). Caller controls it so multi-env writes share
|
|
62
|
-
* deterministic timestamp (matches the pattern from
|
|
63
|
-
* `materializeSaasProviderRuntimeArtifacts`).
|
|
59
|
+
* ISO-8601 instant of THIS materialization, used as the selection time
|
|
60
|
+
* for NEWLY-selected or CHANGED capabilities (see `previousSection` for
|
|
61
|
+
* the sticky-reuse rule). Caller controls it so multi-env writes share
|
|
62
|
+
* one deterministic timestamp (matches the pattern from
|
|
63
|
+
* `materializeSaasProviderRuntimeArtifacts`). It is not written anywhere
|
|
64
|
+
* else: the lockfile envelope carries no timestamp (#1765).
|
|
64
65
|
*/
|
|
65
|
-
|
|
66
|
+
materializedAt: string;
|
|
66
67
|
/**
|
|
67
68
|
* Optional `InfraProvider → InfraProviderModule` lookup. When
|
|
68
69
|
* present, each capability's `planContributionDigest` is computed
|
|
@@ -94,16 +95,18 @@ export interface MaterializeInfraSectionOptions {
|
|
|
94
95
|
* The previous lockfile's `sections.infra` (when present). Threaded
|
|
95
96
|
* so `providerSelectedAt` is STICKY: a capability whose resolved
|
|
96
97
|
* `provider` is unchanged retains its prior `providerSelectedAt`
|
|
97
|
-
* instead of being re-stamped with `
|
|
98
|
+
* instead of being re-stamped with `materializedAt`. Only a newly-
|
|
98
99
|
* selected capability or a provider CHANGE stamps a fresh
|
|
99
|
-
* `
|
|
100
|
+
* `materializedAt`.
|
|
100
101
|
*
|
|
101
|
-
* **Why this exists**: `
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
*
|
|
105
|
-
*
|
|
106
|
-
*
|
|
102
|
+
* **Why this exists**: `materializedAt` is a fresh clock reading on
|
|
103
|
+
* every run of `wildo config sync` and `wildo lock check`. Deriving
|
|
104
|
+
* `providerSelectedAt` directly from it made the field drift on every
|
|
105
|
+
* run, so the committed lockfile changed with no selection changing and
|
|
106
|
+
* `wildo lock check` reported phantom infra drift. (It was originally
|
|
107
|
+
* the lockfile envelope's own `generatedAt`, re-stamped by every write;
|
|
108
|
+
* that field is gone, the stickiness is still what keeps a re-run from
|
|
109
|
+
* changing the file.)
|
|
107
110
|
* Both callers — the `wildo config sync` writer and the
|
|
108
111
|
* `wildo lock check` drift-checker — MUST pass the same previous
|
|
109
112
|
* section so their projections agree.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"materialize-infra-section.d.ts","sourceRoot":"","sources":["../../../../src/lockfile/materialize-infra-section.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAEH,OAAO,EAKL,KAAK,wBAAwB,EAC9B,MAAM,mDAAmD,CAAC;AAE3D,OAAO,KAAK,EACV,aAAa,EACb,mBAAmB,EAEpB,MAAM,kDAAkD,CAAC;AAC1D,OAAO,KAAK,EAEV,wBAAwB,EACzB,MAAM,kCAAkC,CAAC;AAG1C;;;;;;GAMG;AACH,MAAM,WAAW,sBAAsB;IACrC,OAAO,EAAE,MAAM,CAAC;IAChB,eAAe,EAAE,wBAAwB,GAAG,SAAS,CAAC;CACvD;AAED,MAAM,WAAW,8BAA8B;IAC7C,IAAI,EAAE,aAAa,CAAC,sBAAsB,CAAC,CAAC;IAC5C
|
|
1
|
+
{"version":3,"file":"materialize-infra-section.d.ts","sourceRoot":"","sources":["../../../../src/lockfile/materialize-infra-section.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAEH,OAAO,EAKL,KAAK,wBAAwB,EAC9B,MAAM,mDAAmD,CAAC;AAE3D,OAAO,KAAK,EACV,aAAa,EACb,mBAAmB,EAEpB,MAAM,kDAAkD,CAAC;AAC1D,OAAO,KAAK,EAEV,wBAAwB,EACzB,MAAM,kCAAkC,CAAC;AAG1C;;;;;;GAMG;AACH,MAAM,WAAW,sBAAsB;IACrC,OAAO,EAAE,MAAM,CAAC;IAChB,eAAe,EAAE,wBAAwB,GAAG,SAAS,CAAC;CACvD;AAED,MAAM,WAAW,8BAA8B;IAC7C,IAAI,EAAE,aAAa,CAAC,sBAAsB,CAAC,CAAC;IAC5C;;;;;;;OAOG;IACH,cAAc,EAAE,MAAM,CAAC;IACvB;;;;;;;;;;;;;;;;OAgBG;IACH,SAAS,CAAC,EAAE,WAAW,CAAC,aAAa,EAAE,mBAAmB,CAAC,CAAC;IAC5D;;;;;;;OAOG;IACH,iBAAiB,EAAE,WAAW,CAAC,aAAa,CAAC,CAAC;IAC9C;;;;;;;;;;;;;;;;;;;OAmBG;IACH,eAAe,CAAC,EAAE,wBAAwB,CAAC;CAC5C;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,8BAA8B,GACtC,wBAAwB,GAAG,SAAS,CAuBtC"}
|
|
@@ -56,7 +56,7 @@ export function materializeInfraSection(options) {
|
|
|
56
56
|
const environments = {};
|
|
57
57
|
let recordedAny = false;
|
|
58
58
|
for (const env of options.envs) {
|
|
59
|
-
const capabilities = projectBackingServicesToCapabilities(env.backingServices, options.
|
|
59
|
+
const capabilities = projectBackingServicesToCapabilities(env.backingServices, options.materializedAt, env.envName, options.moduleMap, options.previousSection?.environments[env.envName]);
|
|
60
60
|
if (Object.keys(capabilities).length === 0)
|
|
61
61
|
continue;
|
|
62
62
|
environments[env.envName] = { capabilities };
|
|
@@ -64,7 +64,7 @@ export function materializeInfraSection(options) {
|
|
|
64
64
|
}
|
|
65
65
|
return recordedAny ? { environments } : undefined;
|
|
66
66
|
}
|
|
67
|
-
function projectBackingServicesToCapabilities(backingServices,
|
|
67
|
+
function projectBackingServicesToCapabilities(backingServices, materializedAt, envName, moduleMap, previousEnv) {
|
|
68
68
|
const capabilities = {};
|
|
69
69
|
if (!backingServices)
|
|
70
70
|
return capabilities;
|
|
@@ -95,18 +95,18 @@ function projectBackingServicesToCapabilities(backingServices, generatedAt, envN
|
|
|
95
95
|
// exposes a module for this provider. Falls back to the
|
|
96
96
|
// authored-entry digest only for a servable provider the catalogue
|
|
97
97
|
// serves without a module (the operator-credentialed exemptions).
|
|
98
|
-
const planContributionDigest = computeModulePlanDigest(provider, kind, entry,
|
|
98
|
+
const planContributionDigest = computeModulePlanDigest(provider, kind, entry, materializedAt, envName, moduleMap)
|
|
99
99
|
?? computeAuthoredEntryDigest(entry);
|
|
100
100
|
// `providerSelectedAt` is STICKY — only a provider's first
|
|
101
101
|
// selection (or re-selection after a change) is a meaningful moment.
|
|
102
102
|
// Reuse the prior timestamp when the resolved provider is unchanged
|
|
103
|
-
// so
|
|
104
|
-
//
|
|
105
|
-
//
|
|
103
|
+
// so a later run's clock never perturbs it (the root cause of
|
|
104
|
+
// phantom `wildo lock check` infra drift). A newly-added capability
|
|
105
|
+
// or a provider change stamps the fresh `materializedAt`.
|
|
106
106
|
const previousEntry = previousEnv?.capabilities[capability];
|
|
107
107
|
const providerSelectedAt = previousEntry && previousEntry.provider === provider
|
|
108
108
|
? previousEntry.providerSelectedAt
|
|
109
|
-
:
|
|
109
|
+
: materializedAt;
|
|
110
110
|
capabilities[capability] = {
|
|
111
111
|
provider,
|
|
112
112
|
providerSelectedAt,
|
|
@@ -142,13 +142,13 @@ function computeAuthoredEntryDigest(entry) {
|
|
|
142
142
|
* entry through `config` keeps the digest sensitive to authored
|
|
143
143
|
* drift even when the digest source is `module.plan()`.
|
|
144
144
|
*
|
|
145
|
-
* **Why ignore `
|
|
145
|
+
* **Why ignore `materializedAt` in the digest**: the timestamp feeds the
|
|
146
146
|
* `providerSelectedAt` field, NOT part of plan-contribution
|
|
147
147
|
* identity. Using it would make every `wildo lock` run produce a
|
|
148
148
|
* different digest — defeats drift detection. We don't pass it to
|
|
149
149
|
* `module.plan()`; we pass it through the surrounding shape only.
|
|
150
150
|
*/
|
|
151
|
-
function computeModulePlanDigest(provider, kind, entry,
|
|
151
|
+
function computeModulePlanDigest(provider, kind, entry, _materializedAt, envName, moduleMap) {
|
|
152
152
|
if (!moduleMap)
|
|
153
153
|
return undefined;
|
|
154
154
|
const module = moduleMap.get(provider);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"materialize-infra-section.js","sourceRoot":"","sources":["../../../../src/lockfile/materialize-infra-section.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAEH,OAAO,EACL,kBAAkB,EAClB,mCAAmC,EACnC,oBAAoB,GAGrB,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAAE,wCAAwC,EAAE,MAAM,sDAAsD,CAAC;AAUhH,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAwEtD;;;;;GAKG;AACH,MAAM,UAAU,uBAAuB,CACrC,OAAuC;IAEvC,IAAI,OAAO,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IAEhD,gGAAgG;IAChG,wCAAwC,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,iBAAiB,EAAE,OAAO,CAAC,iBAAiB,EAAE,CAAC,CAAC;IAE/G,MAAM,YAAY,GAA6C,EAAE,CAAC;IAClE,IAAI,WAAW,GAAG,KAAK,CAAC;IAExB,KAAK,MAAM,GAAG,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;QAC/B,MAAM,YAAY,GAAG,oCAAoC,CACvD,GAAG,CAAC,eAAe,EACnB,OAAO,CAAC,WAAW,EACnB,GAAG,CAAC,OAAO,EACX,OAAO,CAAC,SAAS,EACjB,OAAO,CAAC,eAAe,EAAE,YAAY,CAAC,GAAG,CAAC,OAAO,CAAC,CACnD,CAAC;QACF,IAAI,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,MAAM,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\n * `wildo.infra.<envName>.config.ts` files into the\n * `sections.infra` slice of `wildo-saas.lock.json` (Slice 2.5b of\n * `infra-provider-planner.md`).\n *\n * Lives in `platform-config-lib` (no runtime, no DI, no I/O — pure\n * projection). The CLI-side caller is responsible for loading the\n * authored configs from disk via\n * `loadInfraEnvConfig` (this package; the CLI's `loadAuthoredInfraEnvConfig` delegates to it) and passing\n * the parsed `backingServices` slice plus the env name.\n *\n * **Slice 2.5c-1 (2026-05-10)**: when the caller supplies an optional\n * `moduleMap` of `InfraProvider → InfraProviderModule`, the digest\n * is computed from `module.plan(planningContext)` instead of from\n * the authored entry. This captures **provider-version drift**\n * (e.g., a module change to plumbing port, secret env vars,\n * per-app blob paths) on top of authored-config drift. When the\n * map is omitted, behavior matches Slice 2.5b — backward-compatible.\n * When the map IS supplied but doesn't contain a module for the\n * resolved `InfraProvider`, the materializer falls back to the\n * authored-entry digest for that capability. After #1693 that can only\n * happen for a provider the catalogue declares servable WITHOUT a module\n * (`OPERATOR_CREDENTIALED_INFRA_PROVIDERS`, empty since #1696 gave\n * `IMMUDB_SELF` its module): every other module-less provider is refused\n * before any digest is computed.\n *\n * **#1693 (2026-09-26)**: the materializer REFUSES any declaration the\n * platform cannot serve — one that resolves to no `InfraProvider`, or to\n * one outside the `servableProviders` set the caller must supply. It used\n * to skip the first silently and hash the second, so the lockfile either\n * omitted a declared kind or recorded a selection nothing executes. Both\n * of its callers (`wildo config sync`, `wildo lock check`) reach the one\n * check here, so the two projections cannot disagree about what is\n * refused. See `backing-service-servability.ts`.\n *\n * **Slice 4.A.1 / H2 fix (2026-05-07)**: digest computation uses\n * `stableSha256Digest` (recursive sorted-keys serialization via\n * `canonical-json.ts`) so nested-object property reorders don't\n * spuriously trigger drift.\n */\n\nimport {\n BackingServiceKind,\n BackingServiceKindToInfraCapability,\n resolveInfraProvider,\n type BackingServiceEnvConfig,\n type BackingServicesEnvConfig,\n} from '../project-config/shared/backing-services.schemas';\nimport { assertBackingServiceDeclarationsServable } from '../project-config/shared/backing-service-servability';\nimport type {\n InfraProvider,\n InfraProviderModule,\n InfraProviderPlanningContext,\n} from '../project-config/shared/infra-providers.schemas';\nimport type {\n SaasLockfileInfraEnvironment,\n SaasLockfileInfraSection,\n} from './wildo-saas-lock.shared.schemas';\nimport { stableSha256Digest } from './canonical-json';\n\n/**\n * Per-env input for the materializer. The caller has already loaded\n * the authored `wildo.infra.<envName>.config.ts` and parsed it via\n * `defineInfraEnvConfig`; we only consume the `backingServices`\n * slice (the only authored surface that maps to `InfraCapability`\n * selections).\n */\nexport interface InfraEnvSelectionInput {\n envName: string;\n backingServices: BackingServicesEnvConfig | undefined;\n}\n\nexport interface MaterializeInfraSectionOptions {\n envs: ReadonlyArray<InfraEnvSelectionInput>;\n /**\n * ISO-8601 timestamp used as the selection time for NEWLY-selected\n * or CHANGED capabilities (see `previousSection` for the sticky-reuse\n * rule). Caller controls it so multi-env writes share one\n * deterministic timestamp (matches the pattern from\n * `materializeSaasProviderRuntimeArtifacts`).\n */\n generatedAt: string;\n /**\n * Optional `InfraProvider → InfraProviderModule` lookup. When\n * present, each capability's `planContributionDigest` is computed\n * from `module.plan(planningContext)` (richer — captures\n * provider-version drift) instead of from the authored entry\n * (Slice 2.5b). Slice 2.5c-1 of `infra-provider-planner.md`.\n *\n * The CLI-side caller in `provider-runtime-sync.service.ts`\n * builds this from `@wildo-ai/platform-infra-providers`'s\n * `buildInfraProviderModuleMap()`. Apps-manager-side callers\n * (none today) would do the same.\n *\n * **Module-less providers**: a resolved provider with no entry here\n * falls back to the authored-entry digest. Only a provider in\n * `servableProviders` can reach that point, so the fallback covers\n * exactly the catalogue's explicit module-less exemptions.\n */\n moduleMap?: ReadonlyMap<InfraProvider, InfraProviderModule>;\n /**\n * The providers the platform can actually SERVE — from\n * `collectServableInfraProviders()` in `@wildo-ai/platform-infra-providers`.\n * REQUIRED, not optional: a caller that could omit it would be a\n * projection that skips the refusal, and the whole point is that\n * `wildo config sync` and `wildo lock check` refuse the same\n * declarations (#1693).\n */\n servableProviders: ReadonlySet<InfraProvider>;\n /**\n * The previous lockfile's `sections.infra` (when present). Threaded\n * so `providerSelectedAt` is STICKY: a capability whose resolved\n * `provider` is unchanged retains its prior `providerSelectedAt`\n * instead of being re-stamped with `generatedAt`. Only a newly-\n * selected capability or a provider CHANGE stamps a fresh\n * `generatedAt`.\n *\n * **Why this exists**: `generatedAt` is the lockfile's volatile\n * generation timestamp — it is bumped by EVERY lockfile write,\n * including writes by unrelated subsystems via `withLockfileMutate`.\n * Deriving `providerSelectedAt` directly from it made the field\n * drift on every unrelated write, producing phantom\n * `wildo lock check` failures even when no infra selection changed.\n * Both callers — the `wildo config sync` writer and the\n * `wildo lock check` drift-checker — MUST pass the same previous\n * section so their projections agree.\n */\n previousSection?: SaasLockfileInfraSection;\n}\n\n/**\n * Project authored infra envs into the lockfile `sections.infra`\n * shape. Returns `undefined` when there are no envs to record (so\n * the lockfile writer can skip emitting the section entirely\n * instead of writing an empty `{ environments: {} }`).\n */\nexport function materializeInfraSection(\n options: MaterializeInfraSectionOptions,\n): SaasLockfileInfraSection | undefined {\n if (options.envs.length === 0) return undefined;\n\n // Refuse every unservable declaration, across every environment, before projecting any of them.\n assertBackingServiceDeclarationsServable({ envs: options.envs, servableProviders: options.servableProviders });\n\n const environments: SaasLockfileInfraSection['environments'] = {};\n let recordedAny = false;\n\n for (const env of options.envs) {\n const capabilities = projectBackingServicesToCapabilities(\n env.backingServices,\n options.generatedAt,\n env.envName,\n options.moduleMap,\n options.previousSection?.environments[env.envName],\n );\n if (Object.keys(capabilities).length === 0) continue;\n environments[env.envName] = { capabilities };\n recordedAny = true;\n }\n\n return recordedAny ? { environments } : undefined;\n}\n\nfunction projectBackingServicesToCapabilities(\n backingServices: BackingServicesEnvConfig | undefined,\n generatedAt: string,\n envName: string,\n moduleMap: ReadonlyMap<InfraProvider, InfraProviderModule> | undefined,\n previousEnv: SaasLockfileInfraEnvironment | undefined,\n): SaasLockfileInfraEnvironment['capabilities'] {\n const capabilities: SaasLockfileInfraEnvironment['capabilities'] = {};\n if (!backingServices) return capabilities;\n\n // Iterate via `Object.values(BackingServiceKind)` (Slice 4.A.2 / M7)\n // — avoids an unsafe `kindKey as BackingServiceKind` cast on\n // `Object.entries`'s string keys. `BackingServicesEnvConfigSchema`\n // is `.strict()` so unknown keys can't reach this code path; this\n // tightening just removes the dead defensive guard that came with\n // the cast.\n for (const kind of Object.values(BackingServiceKind)) {\n const entry = backingServices[kind];\n if (!entry) continue;\n const capability = BackingServiceKindToInfraCapability[kind];\n\n // Some kinds carry an additional `provider` brand (e.g. S3 = minio | aws);\n // others don't. The cast lifts to a permissive shape since\n // `BackingServiceEnvConfig` is a discriminated union and the brand only\n // exists on some variants.\n const providerBrand = (entry as BackingServiceEnvConfig & { provider?: string }).provider;\n const provider = resolveInfraProvider(kind, entry.source, providerBrand);\n if (!provider) {\n // Unreachable: `assertBackingServiceDeclarationsServable` has already refused every declaration\n // that resolves to no provider. Kept as a throw rather than a `continue`, because a silent skip\n // here is precisely the defect that assertion closed (#1693).\n throw new Error(`backingServices.${kind} in environment '${envName}' resolved to no provider after the servability check.`);\n }\n\n // Slice 2.5c-1: prefer module.plan() digest when the catalog\n // exposes a module for this provider. Falls back to the\n // authored-entry digest only for a servable provider the catalogue\n // serves without a module (the operator-credentialed exemptions).\n const planContributionDigest =\n computeModulePlanDigest(provider, kind, entry, generatedAt, envName, moduleMap)\n ?? computeAuthoredEntryDigest(entry);\n\n // `providerSelectedAt` is STICKY — only a provider's first\n // selection (or re-selection after a change) is a meaningful moment.\n // Reuse the prior timestamp when the resolved provider is unchanged\n // so an unrelated `generatedAt` bump never perturbs it (the root\n // cause of phantom `wildo lock check` infra drift). A newly-added\n // capability or a provider change stamps the fresh `generatedAt`.\n const previousEntry = previousEnv?.capabilities[capability];\n const providerSelectedAt =\n previousEntry && previousEntry.provider === provider\n ? previousEntry.providerSelectedAt\n : generatedAt;\n\n capabilities[capability] = {\n provider,\n providerSelectedAt,\n planContributionDigest,\n };\n }\n return capabilities;\n}\n\n/**\n * Stable digest of an authored `BackingServiceEnvConfig` entry.\n * Uses `stableJsonStringify` (recursive sorted-keys serialization)\n * via `stableSha256Digest` so the digest is insensitive to property-\n * order shuffles at ANY nesting level — not just top-level. This\n * matters for entries with nested objects like\n * `MongoBackingService.options: {retryWrites, w, authSource}` where\n * editor saves frequently reorder the nested keys.\n *\n * Slice 4.A.1 / H2 fix: previously this used `JSON.stringify(entry,\n * Object.keys(entry).sort())` which only sorted top-level keys.\n */\nfunction computeAuthoredEntryDigest(entry: BackingServiceEnvConfig): string {\n return stableSha256Digest(entry);\n}\n\n/**\n * Slice 2.5c-1: compute the digest by invoking the module's\n * `plan()` and hashing its contribution. Returns `undefined` when\n * the module map is missing OR doesn't cover the provider — caller\n * falls back to `computeAuthoredEntryDigest`.\n *\n * **Why include the authored entry IN the planning context**: the\n * module may use authored fields (e.g., a future opt-in flag in\n * `RabbitBackingService`) to vary its contribution. Threading the\n * entry through `config` keeps the digest sensitive to authored\n * drift even when the digest source is `module.plan()`.\n *\n * **Why ignore `generatedAt` in the digest**: the timestamp is the\n * `providerSelectedAt` field, NOT part of plan-contribution\n * identity. Using it would make every `wildo lock` run produce a\n * different digest — defeats drift detection. We don't pass it to\n * `module.plan()`; we pass it through the surrounding shape only.\n */\nfunction computeModulePlanDigest(\n provider: InfraProvider,\n kind: BackingServiceKind,\n entry: BackingServiceEnvConfig,\n _generatedAt: string,\n envName: string,\n moduleMap: ReadonlyMap<InfraProvider, InfraProviderModule> | undefined,\n): string | undefined {\n if (!moduleMap) return undefined;\n const module = moduleMap.get(provider);\n if (!module) return undefined;\n const planningContext: InfraProviderPlanningContext = {\n environment: envName,\n runtime: 'unknown', // Caller doesn't expose runtime per env at this layer.\n backingServiceKey: kind,\n config: entry,\n };\n const contribution = module.plan(planningContext);\n return stableSha256Digest(contribution);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"materialize-infra-section.js","sourceRoot":"","sources":["../../../../src/lockf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a,CAAC,QAAQ,KAAK,QAAQ;YAClD,CAAC,CAAC,aAAa,CAAC,kBAAkB;YAClC,CAAC,CAAC,cAAc,CAAC;QAErB,YAAY,CAAC,UAAU,CAAC,GAAG;YACzB,QAAQ;YACR,kBAAkB;YAClB,sBAAsB;SACvB,CAAC;IACJ,CAAC;IACD,OAAO,YAAY,CAAC;AACtB,CAAC;AAED;;;;;;;;;;;GAWG;AACH,SAAS,0BAA0B,CAAC,KAA8B;IAChE,OAAO,kBAAkB,CAAC,KAAK,CAAC,CAAC;AACnC,CAAC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,SAAS,uBAAuB,CAC9B,QAAuB,EACvB,IAAwB,EACxB,KAA8B,EAC9B,eAAuB,EACvB,OAAe,EACf,SAAsE;IAEtE,IAAI,CAAC,SAAS;QAAE,OAAO,SAAS,CAAC;IACjC,MAAM,MAAM,GAAG,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACvC,IAAI,CAAC,MAAM;QAAE,OAAO,SAAS,CAAC;IAC9B,MAAM,eAAe,GAAiC;QACpD,WAAW,EAAE,OAAO;QACpB,OAAO,EAAE,SAAS,EAAE,uDAAuD;QAC3E,iBAAiB,EAAE,IAAI;QACvB,MAAM,EAAE,KAAK;KACd,CAAC;IACF,MAAM,YAAY,GAAG,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;IAClD,OAAO,kBAAkB,CAAC,YAAY,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["/**\n * `materializeInfraSection` — pure function that projects authored\n * `wildo.infra.<envName>.config.ts` files into the\n * `sections.infra` slice of `wildo-saas.lock.json` (Slice 2.5b of\n * `infra-provider-planner.md`).\n *\n * Lives in `platform-config-lib` (no runtime, no DI, no I/O — pure\n * projection). The CLI-side caller is responsible for loading the\n * authored configs from disk via\n * `loadInfraEnvConfig` (this package; the CLI's `loadAuthoredInfraEnvConfig` delegates to it) and passing\n * the parsed `backingServices` slice plus the env name.\n *\n * **Slice 2.5c-1 (2026-05-10)**: when the caller supplies an optional\n * `moduleMap` of `InfraProvider → InfraProviderModule`, the digest\n * is computed from `module.plan(planningContext)` instead of from\n * the authored entry. This captures **provider-version drift**\n * (e.g., a module change to plumbing port, secret env vars,\n * per-app blob paths) on top of authored-config drift. When the\n * map is omitted, behavior matches Slice 2.5b — backward-compatible.\n * When the map IS supplied but doesn't contain a module for the\n * resolved `InfraProvider`, the materializer falls back to the\n * authored-entry digest for that capability. After #1693 that can only\n * happen for a provider the catalogue declares servable WITHOUT a module\n * (`OPERATOR_CREDENTIALED_INFRA_PROVIDERS`, empty since #1696 gave\n * `IMMUDB_SELF` its module): every other module-less provider is refused\n * before any digest is computed.\n *\n * **#1693 (2026-09-26)**: the materializer REFUSES any declaration the\n * platform cannot serve — one that resolves to no `InfraProvider`, or to\n * one outside the `servableProviders` set the caller must supply. It used\n * to skip the first silently and hash the second, so the lockfile either\n * omitted a declared kind or recorded a selection nothing executes. Both\n * of its callers (`wildo config sync`, `wildo lock check`) reach the one\n * check here, so the two projections cannot disagree about what is\n * refused. See `backing-service-servability.ts`.\n *\n * **Slice 4.A.1 / H2 fix (2026-05-07)**: digest computation uses\n * `stableSha256Digest` (recursive sorted-keys serialization via\n * `canonical-json.ts`) so nested-object property reorders don't\n * spuriously trigger drift.\n */\n\nimport {\n BackingServiceKind,\n BackingServiceKindToInfraCapability,\n resolveInfraProvider,\n type BackingServiceEnvConfig,\n type BackingServicesEnvConfig,\n} from '../project-config/shared/backing-services.schemas';\nimport { assertBackingServiceDeclarationsServable } from '../project-config/shared/backing-service-servability';\nimport type {\n InfraProvider,\n InfraProviderModule,\n InfraProviderPlanningContext,\n} from '../project-config/shared/infra-providers.schemas';\nimport type {\n SaasLockfileInfraEnvironment,\n SaasLockfileInfraSection,\n} from './wildo-saas-lock.shared.schemas';\nimport { stableSha256Digest } from './canonical-json';\n\n/**\n * Per-env input for the materializer. The caller has already loaded\n * the authored `wildo.infra.<envName>.config.ts` and parsed it via\n * `defineInfraEnvConfig`; we only consume the `backingServices`\n * slice (the only authored surface that maps to `InfraCapability`\n * selections).\n */\nexport interface InfraEnvSelectionInput {\n envName: string;\n backingServices: BackingServicesEnvConfig | undefined;\n}\n\nexport interface MaterializeInfraSectionOptions {\n envs: ReadonlyArray<InfraEnvSelectionInput>;\n /**\n * ISO-8601 instant of THIS materialization, used as the selection time\n * for NEWLY-selected or CHANGED capabilities (see `previousSection` for\n * the sticky-reuse rule). Caller controls it so multi-env writes share\n * one deterministic timestamp (matches the pattern from\n * `materializeSaasProviderRuntimeArtifacts`). It is not written anywhere\n * else: the lockfile envelope carries no timestamp (#1765).\n */\n materializedAt: string;\n /**\n * Optional `InfraProvider → InfraProviderModule` lookup. When\n * present, each capability's `planContributionDigest` is computed\n * from `module.plan(planningContext)` (richer — captures\n * provider-version drift) instead of from the authored entry\n * (Slice 2.5b). Slice 2.5c-1 of `infra-provider-planner.md`.\n *\n * The CLI-side caller in `provider-runtime-sync.service.ts`\n * builds this from `@wildo-ai/platform-infra-providers`'s\n * `buildInfraProviderModuleMap()`. Apps-manager-side callers\n * (none today) would do the same.\n *\n * **Module-less providers**: a resolved provider with no entry here\n * falls back to the authored-entry digest. Only a provider in\n * `servableProviders` can reach that point, so the fallback covers\n * exactly the catalogue's explicit module-less exemptions.\n */\n moduleMap?: ReadonlyMap<InfraProvider, InfraProviderModule>;\n /**\n * The providers the platform can actually SERVE — from\n * `collectServableInfraProviders()` in `@wildo-ai/platform-infra-providers`.\n * REQUIRED, not optional: a caller that could omit it would be a\n * projection that skips the refusal, and the whole point is that\n * `wildo config sync` and `wildo lock check` refuse the same\n * declarations (#1693).\n */\n servableProviders: ReadonlySet<InfraProvider>;\n /**\n * The previous lockfile's `sections.infra` (when present). Threaded\n * so `providerSelectedAt` is STICKY: a capability whose resolved\n * `provider` is unchanged retains its prior `providerSelectedAt`\n * instead of being re-stamped with `materializedAt`. Only a newly-\n * selected capability or a provider CHANGE stamps a fresh\n * `materializedAt`.\n *\n * **Why this exists**: `materializedAt` is a fresh clock reading on\n * every run of `wildo config sync` and `wildo lock check`. Deriving\n * `providerSelectedAt` directly from it made the field drift on every\n * run, so the committed lockfile changed with no selection changing and\n * `wildo lock check` reported phantom infra drift. (It was originally\n * the lockfile envelope's own `generatedAt`, re-stamped by every write;\n * that field is gone, the stickiness is still what keeps a re-run from\n * changing the file.)\n * Both callers — the `wildo config sync` writer and the\n * `wildo lock check` drift-checker — MUST pass the same previous\n * section so their projections agree.\n */\n previousSection?: SaasLockfileInfraSection;\n}\n\n/**\n * Project authored infra envs into the lockfile `sections.infra`\n * shape. Returns `undefined` when there are no envs to record (so\n * the lockfile writer can skip emitting the section entirely\n * instead of writing an empty `{ environments: {} }`).\n */\nexport function materializeInfraSection(\n options: MaterializeInfraSectionOptions,\n): SaasLockfileInfraSection | undefined {\n if (options.envs.length === 0) return undefined;\n\n // Refuse every unservable declaration, across every environment, before projecting any of them.\n assertBackingServiceDeclarationsServable({ envs: options.envs, servableProviders: options.servableProviders });\n\n const environments: SaasLockfileInfraSection['environments'] = {};\n let recordedAny = false;\n\n for (const env of options.envs) {\n const capabilities = projectBackingServicesToCapabilities(\n env.backingServices,\n options.materializedAt,\n env.envName,\n options.moduleMap,\n options.previousSection?.environments[env.envName],\n );\n if (Object.keys(capabilities).length === 0) continue;\n environments[env.envName] = { capabilities };\n recordedAny = true;\n }\n\n return recordedAny ? { environments } : undefined;\n}\n\nfunction projectBackingServicesToCapabilities(\n backingServices: BackingServicesEnvConfig | undefined,\n materializedAt: string,\n envName: string,\n moduleMap: ReadonlyMap<InfraProvider, InfraProviderModule> | undefined,\n previousEnv: SaasLockfileInfraEnvironment | undefined,\n): SaasLockfileInfraEnvironment['capabilities'] {\n const capabilities: SaasLockfileInfraEnvironment['capabilities'] = {};\n if (!backingServices) return capabilities;\n\n // Iterate via `Object.values(BackingServiceKind)` (Slice 4.A.2 / M7)\n // — avoids an unsafe `kindKey as BackingServiceKind` cast on\n // `Object.entries`'s string keys. `BackingServicesEnvConfigSchema`\n // is `.strict()` so unknown keys can't reach this code path; this\n // tightening just removes the dead defensive guard that came with\n // the cast.\n for (const kind of Object.values(BackingServiceKind)) {\n const entry = backingServices[kind];\n if (!entry) continue;\n const capability = BackingServiceKindToInfraCapability[kind];\n\n // Some kinds carry an additional `provider` brand (e.g. S3 = minio | aws);\n // others don't. The cast lifts to a permissive shape since\n // `BackingServiceEnvConfig` is a discriminated union and the brand only\n // exists on some variants.\n const providerBrand = (entry as BackingServiceEnvConfig & { provider?: string }).provider;\n const provider = resolveInfraProvider(kind, entry.source, providerBrand);\n if (!provider) {\n // Unreachable: `assertBackingServiceDeclarationsServable` has already refused every declaration\n // that resolves to no provider. Kept as a throw rather than a `continue`, because a silent skip\n // here is precisely the defect that assertion closed (#1693).\n throw new Error(`backingServices.${kind} in environment '${envName}' resolved to no provider after the servability check.`);\n }\n\n // Slice 2.5c-1: prefer module.plan() digest when the catalog\n // exposes a module for this provider. Falls back to the\n // authored-entry digest only for a servable provider the catalogue\n // serves without a module (the operator-credentialed exemptions).\n const planContributionDigest =\n computeModulePlanDigest(provider, kind, entry, materializedAt, envName, moduleMap)\n ?? computeAuthoredEntryDigest(entry);\n\n // `providerSelectedAt` is STICKY — only a provider's first\n // selection (or re-selection after a change) is a meaningful moment.\n // Reuse the prior timestamp when the resolved provider is unchanged\n // so a later run's clock never perturbs it (the root cause of\n // phantom `wildo lock check` infra drift). A newly-added capability\n // or a provider change stamps the fresh `materializedAt`.\n const previousEntry = previousEnv?.capabilities[capability];\n const providerSelectedAt =\n previousEntry && previousEntry.provider === provider\n ? previousEntry.providerSelectedAt\n : materializedAt;\n\n capabilities[capability] = {\n provider,\n providerSelectedAt,\n planContributionDigest,\n };\n }\n return capabilities;\n}\n\n/**\n * Stable digest of an authored `BackingServiceEnvConfig` entry.\n * Uses `stableJsonStringify` (recursive sorted-keys serialization)\n * via `stableSha256Digest` so the digest is insensitive to property-\n * order shuffles at ANY nesting level — not just top-level. This\n * matters for entries with nested objects like\n * `MongoBackingService.options: {retryWrites, w, authSource}` where\n * editor saves frequently reorder the nested keys.\n *\n * Slice 4.A.1 / H2 fix: previously this used `JSON.stringify(entry,\n * Object.keys(entry).sort())` which only sorted top-level keys.\n */\nfunction computeAuthoredEntryDigest(entry: BackingServiceEnvConfig): string {\n return stableSha256Digest(entry);\n}\n\n/**\n * Slice 2.5c-1: compute the digest by invoking the module's\n * `plan()` and hashing its contribution. Returns `undefined` when\n * the module map is missing OR doesn't cover the provider — caller\n * falls back to `computeAuthoredEntryDigest`.\n *\n * **Why include the authored entry IN the planning context**: the\n * module may use authored fields (e.g., a future opt-in flag in\n * `RabbitBackingService`) to vary its contribution. Threading the\n * entry through `config` keeps the digest sensitive to authored\n * drift even when the digest source is `module.plan()`.\n *\n * **Why ignore `materializedAt` in the digest**: the timestamp feeds the\n * `providerSelectedAt` field, NOT part of plan-contribution\n * identity. Using it would make every `wildo lock` run produce a\n * different digest — defeats drift detection. We don't pass it to\n * `module.plan()`; we pass it through the surrounding shape only.\n */\nfunction computeModulePlanDigest(\n provider: InfraProvider,\n kind: BackingServiceKind,\n entry: BackingServiceEnvConfig,\n _materializedAt: string,\n envName: string,\n moduleMap: ReadonlyMap<InfraProvider, InfraProviderModule> | undefined,\n): string | undefined {\n if (!moduleMap) return undefined;\n const module = moduleMap.get(provider);\n if (!module) return undefined;\n const planningContext: InfraProviderPlanningContext = {\n environment: envName,\n runtime: 'unknown', // Caller doesn't expose runtime per env at this layer.\n backingServiceKey: kind,\n config: entry,\n };\n const contribution = module.plan(planningContext);\n return stableSha256Digest(contribution);\n}\n"]}
|