@maverickcer/env-cap 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/ADOPTION.md +144 -0
  2. package/AGENTS.md +146 -0
  3. package/CHANGELOG.md +438 -0
  4. package/CODE_OF_CONDUCT.md +124 -0
  5. package/CODE_REVIEW.md +200 -0
  6. package/CONTRIBUTING.md +131 -0
  7. package/GUIDE.md +1214 -0
  8. package/PROMPT.md +89 -0
  9. package/README.md +92 -200
  10. package/RELEASING.md +160 -0
  11. package/SECURITY.md +270 -0
  12. package/SUPPORT.md +76 -0
  13. package/VERSIONING.md +118 -0
  14. package/benchmarks/READING-BENCHMARKS.md +197 -0
  15. package/benchmarks/README.md +126 -0
  16. package/benchmarks/WRITING-BENCHMARKS.md +252 -0
  17. package/benchmarks/performance-buildtime/BENCHMARKS.md +889 -0
  18. package/benchmarks/performance-runtime/BENCHMARKS.md +1988 -0
  19. package/dist/.dts/_ipc/build-fs.d.ts +53 -0
  20. package/dist/.dts/_ipc/build-fs.d.ts.map +1 -0
  21. package/dist/.dts/_ipc/compiler-api.d.ts +17 -0
  22. package/dist/.dts/_ipc/compiler-api.d.ts.map +1 -0
  23. package/dist/.dts/_ipc/display-path.d.ts +27 -0
  24. package/dist/.dts/_ipc/display-path.d.ts.map +1 -0
  25. package/dist/.dts/_ipc/generated-banner.d.ts +58 -0
  26. package/dist/.dts/_ipc/generated-banner.d.ts.map +1 -0
  27. package/dist/.dts/_ipc/glob.d.ts +22 -0
  28. package/dist/.dts/_ipc/glob.d.ts.map +1 -0
  29. package/dist/.dts/_ipc/no-node-fs.d.ts +34 -0
  30. package/dist/.dts/_ipc/no-node-fs.d.ts.map +1 -0
  31. package/dist/.dts/_ipc/resolve-tsconfig-paths.d.ts +134 -0
  32. package/dist/.dts/_ipc/resolve-tsconfig-paths.d.ts.map +1 -0
  33. package/dist/.dts/_ipc/typescript.d.ts +20 -0
  34. package/dist/.dts/_ipc/typescript.d.ts.map +1 -0
  35. package/dist/.dts/build/compatibility.d.ts.map +1 -1
  36. package/dist/.dts/build/compiler-api.d.ts +3 -6
  37. package/dist/.dts/build/compiler-api.d.ts.map +1 -1
  38. package/dist/.dts/build/display-path.d.ts +3 -21
  39. package/dist/.dts/build/display-path.d.ts.map +1 -1
  40. package/dist/.dts/build/generated-banner.d.ts +21 -42
  41. package/dist/.dts/build/generated-banner.d.ts.map +1 -1
  42. package/dist/.dts/build/glob.d.ts +3 -15
  43. package/dist/.dts/build/glob.d.ts.map +1 -1
  44. package/dist/.dts/build/link.d.ts.map +1 -1
  45. package/dist/.dts/build/merge-documentation.d.ts +35 -0
  46. package/dist/.dts/build/merge-documentation.d.ts.map +1 -0
  47. package/dist/.dts/build/resolution/resolve-tsconfig-paths.d.ts +11 -112
  48. package/dist/.dts/build/resolution/resolve-tsconfig-paths.d.ts.map +1 -1
  49. package/dist/.dts/build/types.d.ts +4 -53
  50. package/dist/.dts/build/types.d.ts.map +1 -1
  51. package/dist/.dts/build/typescript.d.ts +3 -17
  52. package/dist/.dts/build/typescript.d.ts.map +1 -1
  53. package/dist/.dts/eslint-plugin/glob.d.ts +4 -15
  54. package/dist/.dts/eslint-plugin/glob.d.ts.map +1 -1
  55. package/dist/.dts/eslint-plugin/index.d.ts +1 -1
  56. package/dist/.dts/eslint-plugin/no-node-fs.d.ts +8 -18
  57. package/dist/.dts/eslint-plugin/no-node-fs.d.ts.map +1 -1
  58. package/dist/.dts/eslint-plugin/no-raw-process-env.d.ts.map +1 -1
  59. package/dist/{build-H4KFV44Z.js → build-WKDIAWF7.js} +198 -60
  60. package/dist/build-WKDIAWF7.js.map +1 -0
  61. package/dist/build.cjs +194 -56
  62. package/dist/build.cjs.map +1 -1
  63. package/dist/build.js +194 -56
  64. package/dist/build.js.map +1 -1
  65. package/dist/{chunk-7GVPOHDU.js → chunk-KEGYUHBU.js} +2 -2
  66. package/dist/cli/index.js +36 -29
  67. package/dist/cli/index.js.map +1 -1
  68. package/dist/eslint-plugin/index.cjs +84 -54
  69. package/dist/eslint-plugin/index.cjs.map +1 -1
  70. package/dist/eslint-plugin/index.js +83 -53
  71. package/dist/eslint-plugin/index.js.map +1 -1
  72. package/examples/README.md +95 -0
  73. package/package.json +48 -14
  74. package/skills/env-cap/SKILL.md +91 -0
  75. package/skills/env-cap/references/api.md +220 -0
  76. package/specs/architecture.md +634 -0
  77. package/specs/decisions/0001-runtime-documentation-separation.md +197 -0
  78. package/specs/decisions/0002-static-analysis-never-execution.md +233 -0
  79. package/specs/decisions/0003-no-global-env-object.md +172 -0
  80. package/specs/decisions/0004-no-client-server-package-split.md +116 -0
  81. package/specs/decisions/0005-warn-not-throw-by-default.md +93 -0
  82. package/specs/decisions/0006-self-redacting-contracts.md +124 -0
  83. package/specs/decisions/0007-processor-not-transformer.md +109 -0
  84. package/specs/decisions/0008-gzip-size-budget.md +173 -0
  85. package/specs/decisions/0009-exclusive-groups-are-always-errors.md +139 -0
  86. package/specs/decisions/0010-dependency-ownership-engine-scope-boundary.md +100 -0
  87. package/specs/decisions/0011-shared-discovery-compute-atomic-write-non-atomic.md +104 -0
  88. package/specs/decisions/0012-live-expiration-overrides-not-ast-functions.md +145 -0
  89. package/specs/decisions/0013-json-output-is-a-versioned-mirror.md +136 -0
  90. package/specs/decisions/0014-cross-package-schema-discovery.md +206 -0
  91. package/specs/decisions/0015-security-backport-window.md +60 -0
  92. package/specs/decisions/0016-check-mode-compute-before-compare-never-partial-write.md +113 -0
  93. package/specs/decisions/0017-eslint-plugin-entry-point.md +113 -0
  94. package/specs/decisions/0018-rotation-alert-issue-on-non-pr-runs.md +104 -0
  95. package/specs/decisions/0019-published-json-schema-generated-from-types.md +100 -0
  96. package/specs/decisions/0020-declaration-maps-via-separate-tsc-pass.md +101 -0
  97. package/specs/decisions/0021-manifest-change-report-persisted-snapshot.md +177 -0
  98. package/specs/decisions/0022-validation-contexts.md +267 -0
  99. package/specs/decisions/0023-tsconfig-path-alias-resolution.md +182 -0
  100. package/specs/decisions/0024-fact-model-architecture.md +144 -0
  101. package/specs/decisions/0025-contract-model-json-projection.md +105 -0
  102. package/specs/decisions/0026-finding-model-unifies-four-families.md +109 -0
  103. package/specs/decisions/0027-dependency-model-fact-shape-not-engine-access.md +98 -0
  104. package/specs/decisions/0028-ownership-model-shared-effective-owner.md +85 -0
  105. package/specs/decisions/0029-lifecycle-model-deprecation-rename-fields.md +98 -0
  106. package/specs/decisions/0030-change-model-wraps-manifest-change-report.md +97 -0
  107. package/specs/decisions/0031-evidence-entry-point.md +85 -0
  108. package/specs/decisions/0032-evidence-projection-provenance-mechanism.md +120 -0
  109. package/specs/decisions/0033-reference-projections-live-in-examples.md +81 -0
  110. package/specs/decisions/0034-three-tier-examples-restructuring.md +85 -0
  111. package/specs/decisions/0035-documentenv-metadata-generalization-and-compliance-fields.md +85 -0
  112. package/specs/decisions/0036-exact-source-position-evidence.md +122 -0
  113. package/specs/decisions/0037-developer-declared-dynamic-access-citations.md +114 -0
  114. package/specs/decisions/0038-always-computed-evidence-model-backs-generate-check-docs.md +244 -0
  115. package/specs/decisions/0039-scanner-local-dataflow-boundary.md +160 -0
  116. package/specs/decisions/0040-library-surfaces-do-not-acquire-node-fs.md +156 -0
  117. package/specs/decisions/0041-dual-package-hazard-checked-documented.md +75 -0
  118. package/specs/decisions/0042-init-cli-subcommand-scaffolds-only.md +95 -0
  119. package/specs/decisions/0043-env-cap-resolver-relocated-and-duplicated.md +71 -0
  120. package/specs/decisions/0044-strict-escalates-every-warning-family.md +88 -0
  121. package/specs/decisions/0045-promote-experimental-surfaces-to-stable.md +103 -0
  122. package/specs/decisions/0046-cli-restricted-to-runtime-and-evidence-output.md +177 -0
  123. package/specs/decisions/0047-supported-toolchain-node-22-and-typescript-5-6.md +30 -0
  124. package/specs/decisions/0048-eslint-plugin-does-not-vendor-typescript-eslint.md +25 -0
  125. package/specs/decisions/0049-typescript-7-scanner-uses-a-bundled-typescript-6.md +87 -0
  126. package/specs/decisions/0050-a-variable-declared-twice-is-documented-once.md +55 -0
  127. package/specs/generated-artifacts.md +104 -0
  128. package/specs/migrations/README.md +30 -0
  129. package/specs/migrations/from-centralized-schema.md +503 -0
  130. package/specs/migrations/from-dotenv.md +352 -0
  131. package/specs/migrations/from-envalid.md +482 -0
  132. package/specs/migrations/from-process-env.md +398 -0
  133. package/specs/migrations/from-t3-env.md +416 -0
  134. package/specs/migrations/from-zod.md +303 -0
  135. package/dist/build-H4KFV44Z.js.map +0 -1
  136. /package/dist/{chunk-7GVPOHDU.js.map → chunk-KEGYUHBU.js.map} +0 -0
@@ -0,0 +1,139 @@
1
+ # 0009: Exclusive-group violations are always hard errors, never subject to `onIncompatibility`
2
+
3
+ ## Status
4
+
5
+ Accepted. Implemented in `src/build/exclusive-group.ts`
6
+ (`detectExclusiveGroupIssues`), called unconditionally from
7
+ `src/build/generate-manifest.ts`'s `computeManifest()` alongside
8
+ `detectCompatibilityIssues` (0005).
9
+
10
+ ## Context
11
+
12
+ `documentEnv()` accepts an optional `exclusiveGroup: string` (`src/build/parse.ts`,
13
+ `src/runtime/document.ts`) an author uses to mark two or more contracts as
14
+ interchangeable alternatives -- e.g. two database backends, only one of which
15
+ should ever be wired into a given deployment. It works together with
16
+ `active` (also on `documentEnv()`, defaulting to `true`): a contract can ship
17
+ in the repository while `active: false` keeps it out of the contract,
18
+ `.env.example`, and (per this decision) exclusive-group checking entirely.
19
+ `examples/team-service` is built around exactly this pair --
20
+ `postgres` and `mongodb` both declare `exclusiveGroup: "database"`, only
21
+ `postgres` is active by default, and mongodb ships fully documented but
22
+ dormant.
23
+
24
+ 0005 established the general policy for build-time findings that
25
+ `generateEnvManifest()` cannot execute code to verify: static analysis can
26
+ _prove_ some things (e.g. two contracts give explicit, conflicting return-type
27
+ annotations for the same variable) and can only _suspect_ others (e.g. two
28
+ contracts have differently-shaped processor source with no annotation to
29
+ compare). Proven findings get `severity: "error"` and always block
30
+ generation; suspected findings get `severity: "warning"` and only block
31
+ generation if a project opts in via `onIncompatibility: "throw"`. Both
32
+ severities share the same `CompatibilityIssue` shape and are produced by the
33
+ same family of checks (`detectCompatibilityIssues`), so it would be
34
+ reasonable to assume `onIncompatibility` governs every finding that shape can
35
+ represent.
36
+
37
+ `detectExclusiveGroupIssues` returns `CompatibilityIssue[]` too, and
38
+ `computeManifest()` concatenates its output directly into the same
39
+ `compatibilityIssues` array before applying the `onIncompatibility` split
40
+ (`src/build/generate-manifest.ts`). But it never assigns `severity: "warning"` --
41
+ every issue it produces is `"error"`, unconditionally. Right now, that's
42
+ explained only in a comment on the function itself ("this is never a
43
+ heuristic warning ... regardless of `onIncompatibility`"), not as a decision
44
+ -- so the asymmetry with 0005's general policy has no record of _why_ it's
45
+ correct, only a note that it's intentional.
46
+
47
+ ## Decision
48
+
49
+ An exclusive-group violation is always represented as a `CompatibilityIssue`
50
+ with `severity: "error"`, and per 0005, `severity: "error"` findings always
51
+ block generation regardless of the `onIncompatibility` value a project
52
+ passes. There is no option, and none is planned, that downgrades an
53
+ exclusive-group violation to a warning or otherwise lets generation succeed
54
+ while one is present.
55
+
56
+ This is not a special case bolted onto the blocking logic in
57
+ `generate-manifest.ts` -- `detectExclusiveGroupIssues` simply never emits anything but
58
+ `"error"`. The reason is that 0005's error/warning split tracks _provability_,
59
+ and exclusive-group membership is never a matter of degree the way duplicate-
60
+ variable compatibility is. Two active contracts either declare the identical
61
+ `exclusiveGroup` string or they don't; there is no differently-shaped-source,
62
+ can't-prove-it-either-way middle case for a plain string comparison the way
63
+ there is for comparing processor implementations. And unlike a duplicate
64
+ variable name -- which two capabilities could plausibly share by coincidence and
65
+ still be compatible -- `exclusiveGroup` only exists because an author
66
+ deliberately opted a contract into it. A violation isn't the tool inferring a
67
+ _possible_ problem from incomplete information; it's the tool checking an
68
+ explicit, author-authored constraint and finding it broken. 0005's warning
69
+ tier exists for the former case. This check never produces the former case,
70
+ so it never has a reason to reach for that tier.
71
+
72
+ Inactive contracts are filtered out before this check ever runs
73
+ (`computeManifest()` in `generate-manifest.ts` only passes `activeContracts` to both
74
+ `detectCompatibilityIssues` and `detectExclusiveGroupIssues`) -- shipping a
75
+ dormant alternative in the same exclusive group as the active one is never a
76
+ violation, regardless of this decision. Only two _active_ contracts sharing a
77
+ group is.
78
+
79
+ ## Consequences
80
+
81
+ - **The composable-boilerplates pattern is actually safe, not just
82
+ documented as safe.** The entire pitch of shipping every backend option
83
+ dormant (0001-adjacent: keep build-time metadata out of the runtime, but
84
+ keep it real enough to enforce) depends on "two of them active at once" being
85
+ something the build can't let through silently. If this were a
86
+ `onIncompatibility`-gated warning like duplicate-variable mismatches, a
87
+ project using the (0005) default `"warn"` setting could flip `mongodb` to
88
+ `active: true` without flipping `postgres` to `false`, and generation would
89
+ succeed -- the violation would sit in `result.warnings` and in generated
90
+ docs, which 0005 itself already flags as easy for a team to never review.
91
+ `examples/team-service`'s README demonstrates the actual
92
+ behavior: attempting that flip fails `generate:env` immediately, with both
93
+ contract names and files named in the error.
94
+
95
+ - **No knob exists to relax this, on purpose.** A team migrating between two
96
+ exclusive-group members must actually set the old one's `active: false`
97
+ before the new one's `active: true` takes effect cleanly -- there is no
98
+ transitional "both active, just warn about it" state. That friction is the
99
+ intended behavior, not a gap: the same tradeoff 0008 makes for the size
100
+ budget (a check with no escape hatch stays meaningful) applies here for the
101
+ same reason.
102
+
103
+ - **`onIncompatibility`'s scope is narrower than its placement in the type
104
+ system suggests.** Because exclusive-group issues share `CompatibilityIssue`
105
+ and flow through the same array as duplicate-variable issues, reading the
106
+ option's doc comment or `GenerateEnvManifestResult["warnings"]"`'s type in
107
+ isolation could suggest it controls all compatibility-shaped findings. This
108
+ ADR is the place that correction now lives, instead of only the docstring
109
+ on `detectExclusiveGroupIssues`.
110
+
111
+ ## Alternatives considered
112
+
113
+ - **Gate exclusive-group violations behind `onIncompatibility`, same as
114
+ heuristic duplicate-variable warnings.**
115
+ Rejected. There is no legitimate "maybe" reading of two active contracts
116
+ sharing an author-declared exclusive group -- unlike differently-shaped
117
+ processor source, which might still produce equivalent output, exclusivity
118
+ is the entire and only meaning of the field. Warning by default would also
119
+ make the composable-boilerplates safety story false for any project that
120
+ hasn't opted into `--strict`: exactly the scenario the field exists to
121
+ prevent would pass silently under the framework's own default settings.
122
+
123
+ - **A dedicated `onExclusiveGroupViolation` option, separate from
124
+ `onIncompatibility`, defaulting to `"throw"` but overridable.**
125
+ Considered, not added. No real use case has asked for a way to temporarily
126
+ tolerate two active members of the same exclusive group, and adding a
127
+ configuration point for a policy nobody has needed to relax risks the same
128
+ problem 0008 warns against for size budgets -- an unused knob is a knob
129
+ nobody remembers the reason for. If a genuine transitional need surfaces
130
+ (e.g. a deliberate, temporary dual-active state during a live migration), a
131
+ distinctly-named option is the right future shape; folding it into
132
+ `onIncompatibility` would blur the proven/heuristic distinction 0005
133
+ established it to express.
134
+
135
+ - **Represent exclusive-group violations as `severity: "warning"` like the
136
+ heuristic duplicate-variable cases.**
137
+ Rejected. That would misrepresent something fully provable by a plain
138
+ string comparison as something requiring human judgment, undermining the
139
+ distinction 0005 draws between the two severities in the first place.
@@ -0,0 +1,100 @@
1
+ # 0010: The Dependency-Ownership Engine's Scope Is Fixed and Its Internals Are Not a Public API
2
+
3
+ ## Status
4
+
5
+ Accepted. Implemented in `src/build/scan-dependencies.ts` and
6
+ `src/build/dependency-graph.ts`, orchestrated by `generateUsageReport()`
7
+ (`src/build/generate-usage.ts`). Referenced, but not previously written down
8
+ as its own decision, by comments in both files and in `src/build/index.ts`.
9
+ Backfilled by this ADR.
10
+
11
+ ## Context
12
+
13
+ `generateUsageReport()` answers a different question than
14
+ `generateEnvManifest()`/`generateDocumentation()`: not "what contracts
15
+ exist," but "who actually imports and reads each one, and what would break if
16
+ it changed or disappeared." Answering that requires a second static-analysis
17
+ pass, structurally similar to schema discovery but broader in what it scans
18
+ and different in what it's allowed to conclude:
19
+
20
+ - **What it scans is deliberately not configurable.** `SCAN_INCLUDE =
21
+ ["**/*.ts", "**/*.tsx"]` (`generate-usage.ts`) is a fixed constant, not an
22
+ option a caller can override, unlike `include`/`exclude` for schema
23
+ discovery. Usage can occur in any source file in the project, so there is
24
+ no meaningful narrower default to offer, and letting a project quietly scope
25
+ this down (e.g. to exclude a directory) would silently produce false
26
+ "abandoned" findings for contracts only consumed from the excluded area --
27
+ exactly the false-positive risk this feature exists to avoid.
28
+ - **What it's allowed to conclude is deliberately conservative.**
29
+ `dependency-graph.ts`'s two-pass design distinguishes contracts that are
30
+ never imported (`abandoned`) from contracts reachable only through an
31
+ unresolved barrel/wildcard re-export (`unresolvedConsumers`) -- see
32
+ `deriveOwnershipFindings`'s doc comment. A barrel chain
33
+ (`export * from "./somewhere"`) is recorded as ambiguous
34
+ (`hasWildcardReExport`) but never traced to find out what it actually
35
+ forwards. Tracing it would mean resolving an unbounded chain of re-exports
36
+ across files this engine doesn't already know are schema-relevant --
37
+ scope creep with no natural stopping point, for a feature whose entire
38
+ value proposition is that its findings are provable, not heuristic.
39
+ - **Its internals are not exported from `@maverickcer/env-cap/build`.** `scan-dependencies.ts`'s
40
+ AST-access-site vocabulary (`AccessSite`, `FileScanResult`) and
41
+ `dependency-graph.ts`'s graph-building machinery
42
+ (`buildDependencyGraph`, `deriveOwnershipFindings`) are used only by
43
+ `generateUsageReport()` internally. `src/build/index.ts`'s public surface
44
+ stops at the ownership-framed result types
45
+ (`OwnershipDependencyEntry`, `AbandonedContractFinding`, etc.) that
46
+ `generate-usage.ts` maps the raw graph into.
47
+
48
+ ## Decision
49
+
50
+ 1. `SCAN_INCLUDE` stays a fixed, non-configurable constant. A project that
51
+ needs different scanning boundaries is a signal the engine's convention
52
+ doesn't fit that project's layout, not a signal to add a configuration
53
+ point.
54
+ 2. Barrel/wildcard re-export chains are recorded as ambiguous and reported
55
+ as `unresolvedConsumers`, never traced further and never used to promote
56
+ a contract to `abandoned` or to silently assume it's consumed.
57
+ 3. The AST-level scanning/graph-building internals
58
+ (`scan-dependencies.ts`, `dependency-graph.ts`) are not exported from
59
+ `@maverickcer/env-cap/build`. Only the ownership-framed result of
60
+ `generateUsageReport()` is public.
61
+
62
+ ## Consequences
63
+
64
+ - `generateUsageReport()`'s findings stay trustworthy enough to gate CI on
65
+ (`onOwnershipIssue: "throw"`) precisely because they're never the product
66
+ of an unbounded or configurable search -- a false "abandoned" finding
67
+ blocking a release would erode the one property (provable, not
68
+ heuristic) that makes this check worth having.
69
+ - A project with an unusual layout that defeats `SCAN_INCLUDE` in practice
70
+ (e.g. TypeScript source outside `.ts`/`.tsx` extensions) simply won't get
71
+ useful ownership findings for that area -- there's no escape hatch, by
72
+ design, matching the same "no knob nobody's asked for yet" reasoning as
73
+ 0009's exclusive-group check.
74
+ - `env-cap` answers ownership/visibility questions about the contracts it
75
+ already knows about; it does not ship a general-purpose static-analysis
76
+ toolkit for arbitrary AST queries. A tool wanting the latter should use
77
+ the TypeScript compiler API directly, not treat `scan-dependencies.ts` as
78
+ a stable dependency.
79
+
80
+ ## Alternatives considered
81
+
82
+ - **Make `SCAN_INCLUDE` configurable, mirroring `include`/`exclude`.**
83
+ Rejected. Unlike schema discovery -- where a project genuinely might want
84
+ to narrow which directories are searched for `env.schema.ts` files --
85
+ narrowing usage-scanning has no safe default: any exclusion risks hiding a
86
+ real consumer and manufacturing a false "abandoned" finding. If a real
87
+ need for this surfaces, it should be a distinctly-named, clearly-scoped
88
+ option, not a blanket reuse of the schema-discovery pattern.
89
+ - **Trace barrel/wildcard re-export chains to resolve ambiguous consumers.**
90
+ Rejected as scope creep with no natural bound -- see Context. A future,
91
+ separately-justified decision could revisit this if a bounded, provably
92
+ terminating resolution strategy is found, but none has been proposed.
93
+ - **Export `scan-dependencies.ts`/`dependency-graph.ts` for custom tooling,
94
+ the same way lower-level build primitives (`discoverSchemaFiles`,
95
+ `linkFiles`) are exported.** Rejected for now. Those primitives are
96
+ exported because real external use (custom CI scripts, bundler plugins)
97
+ already justifies the commitment to keep their shape stable. No comparable
98
+ external use case for the raw ownership-graph internals has come up; if
99
+ one does, exporting a stable subset of this vocabulary is a future
100
+ decision, not a retroactive justification for exporting it today.
@@ -0,0 +1,104 @@
1
+ # 0011: `generateEnvArtifacts()` Shares One Discovery Pass and Guarantees Compute-Phase Atomicity, Not Write-Phase Atomicity
2
+
3
+ ## Status
4
+
5
+ Accepted. Implemented in `src/build/generate-env-artifacts.ts`. Referenced,
6
+ but not previously written down as its own decision, by comments in
7
+ `generate-manifest.ts`, `generate-documentation.ts`, `scan-dependencies.ts`,
8
+ and `src/build/index.ts`. Backfilled by this ADR.
9
+
10
+ ## Context
11
+
12
+ `generateEnvManifest()`, `generateDocumentation()`, and
13
+ `generateUsageReport()` are each fully self-sufficient -- every one of them
14
+ runs its own discovery and linking pass when called standalone. A project
15
+ that wants all three (the common case, and the CLI's default mode with
16
+ `--location`/`--docs`/`--ownership` all supplied) calling them separately
17
+ would parse and link the same schema files three times over, once per
18
+ function.
19
+
20
+ `generateEnvArtifacts()` exists to avoid that, but composing three
21
+ independent generators into one orchestrator raises two distinct questions
22
+ that are easy to conflate into a single "is it atomic?" question, when they
23
+ actually have different answers:
24
+
25
+ 1. Should a blocking finding in one pass (e.g. an undocumented contract with
26
+ `onUndocumented: "throw"`) prevent a different pass (e.g. the manifest)
27
+ from writing anything, even though the manifest pass itself found nothing
28
+ wrong?
29
+ 2. If every pass's blocking checks succeed, and this function then writes
30
+ three separate files, and the second `fs.writeFile` fails (disk full,
31
+ permissions changed mid-run) -- is the first file's write rolled back?
32
+
33
+ ## Decision
34
+
35
+ **Discovery and linking run exactly once**, shared across every requested
36
+ pass via one `discoverSchemaFiles()` + `linkFiles()` call (plus one more
37
+ `discoverSchemaFiles()` call with `SCAN_INCLUDE` when a usage pass is
38
+ requested, since it scans a superset of files). A shared `fileCache` Map
39
+ ensures a file matched by more than one pass's glob (a schema file is also
40
+ matched by the usage pass's broader `SCAN_INCLUDE`) is read from disk only
41
+ once.
42
+
43
+ **Compute-phase atomicity is guaranteed.** Every requested pass's blocking
44
+ findings (manifest compatibility/exclusive-group issues, undocumented
45
+ contracts when `onUndocumented: "throw"`, abandoned/unconsumed ownership
46
+ issues when `onOwnershipIssue: "throw"`) are collected into one array before
47
+ any pass writes anything. If any of them is blocking, `EnvProjectGenerationError`
48
+ is thrown with the full aggregated list, and **nothing from any pass is
49
+ written** -- not even the passes that individually found nothing wrong. Output
50
+ path validation (`resolveWithinRoot()` for each requested `location`) is
51
+ checked in this same fail-fast phase, before discovery even runs.
52
+
53
+ **Write-phase atomicity is explicitly not attempted.** Once every pass's
54
+ compute phase has succeeded and writes begin, each `fs.writeFile` call is
55
+ independent. A real I/O failure partway through (disk full, permissions
56
+ revoked between the manifest write and the docs write) can leave some
57
+ artifacts on disk and not others. This failure mode is not wrapped in
58
+ `EnvProjectGenerationError` -- it propagates as whatever `fs.writeFile` (or
59
+ `fs.mkdir`) itself throws, since by that point the caller needs to know a
60
+ real I/O error occurred, not a compatibility finding.
61
+
62
+ ## Consequences
63
+
64
+ - A project that requests all three artifacts gets exactly the same
65
+ contract graph, computed once, feeding all three outputs -- there is no
66
+ possibility of the manifest and docs disagreeing about what was discovered
67
+ because they ran against subtly different filesystem states (e.g. a file
68
+ changing between two separate CLI invocations).
69
+ - A blocking finding anywhere genuinely blocks everything, which is the
70
+ behavior the CLI's `--strict`/`--strict-docs`/`--strict-ownership` flags
71
+ and the GitHub Action's PR-annotation flow depend on: a CI run either
72
+ produces a fully consistent set of artifacts or produces none, never a
73
+ partially-updated set that could silently drift from what the code
74
+ actually declares.
75
+ - The lack of write-phase atomicity is a real, accepted gap for the rare
76
+ case of an I/O failure mid-write, not an oversight. A team relying on
77
+ generated artifacts always being fully in sync with disk should treat a
78
+ thrown error from `generateEnvArtifacts()`/the CLI as "verify what's on
79
+ disk before trusting it," the same posture already required for any
80
+ interrupted multi-file write.
81
+
82
+ ## Alternatives considered
83
+
84
+ - **Transactional (temp-file + atomic rename) writes across all three
85
+ artifacts.** Considered, rejected as disproportionate machinery for a
86
+ rare failure mode. It would require every write to go through a
87
+ write-to-temp-then-rename dance (and reasoning about rename semantics
88
+ across filesystems/OSes), for a scenario -- an I/O error occurring between
89
+ two writes that already passed every compute-phase check -- that is both
90
+ rare and, when it does happen, immediately visible as a thrown error
91
+ rather than a silent inconsistency.
92
+ - **Run each pass's discovery independently, accepting the duplicate
93
+ parsing cost.** Rejected as the reason `generateEnvArtifacts()` exists in
94
+ the first place -- it would reintroduce exactly the "parse the same files
95
+ three times" cost this orchestrator is meant to eliminate, and would risk
96
+ the three passes seeing different filesystem states if anything changed
97
+ between their independent discovery calls.
98
+ - **Make write-phase atomicity a caller-opt-in flag.** Considered, not
99
+ added. No real use case has asked for it, and adding a configuration
100
+ point for a guarantee nobody has needed risks the same "unused knob"
101
+ problem 0008 and 0009 both warn against. If a genuine need surfaces, a
102
+ distinctly-scoped mechanism (e.g. writing to a temp directory and letting
103
+ the caller move it into place) is the right shape, not a boolean bolted
104
+ onto this function.
@@ -0,0 +1,145 @@
1
+ # 0012: Live Expiration Overrides Are a JS-Level Callback, Not an AST-Discoverable Function
2
+
3
+ ## Status
4
+
5
+ Accepted.
6
+
7
+ Implemented in:
8
+
9
+ - `src/build/live-expirations.ts`
10
+ - `src/build/generate-documentation.ts`
11
+ - `src/build/generate-env-artifacts.ts`
12
+
13
+ ## Considered and Denied: Add Async Function Support to `expiresAt`
14
+
15
+ The first shape considered for "let `expiresAt` come from somewhere dynamic" was to
16
+ widen the type schema authors write directly inside `documentEnv()`:
17
+
18
+ ```ts
19
+ documentEnv(paypalSchema, {
20
+ variables: {
21
+ PAYPAL_CLIENT_SECRET: {
22
+ expiresAt: async () => fetchRotationDateFromVault(),
23
+ },
24
+ },
25
+ })
26
+ ```
27
+
28
+ **Denied.**
29
+
30
+ This is why: `expiresAt` (and everything else `documentEnv()` carries) is read entirely
31
+ by static analysis (ADR 0002, "Build Tooling Parses Schema Files as AST; It Never
32
+ Imports or Executes Them"). `src/build/parse.ts` never `import()`s or `require()`s a
33
+ discovered schema file -- it hands the file's source text to
34
+ `ts.createSourceFile()` and walks the resulting syntax tree. The one place a value is
35
+ actually _computed_ out of that tree is `evaluateLiteral()`
36
+ (`src/build/literal-eval.ts`), which structurally resolves string/number/boolean/
37
+ `null`/array/object literal nodes into real JS values -- and nothing else. It has no
38
+ case for a function or arrow-function expression, by design: evaluating one would mean
39
+ calling it, and calling anything found in a schema file's source text is exactly the
40
+ "discovery becomes code execution" outcome ADR 0002 exists to rule out.
41
+
42
+ Concretely, an `expiresAt: async () => ...` written in a schema file could never be
43
+ resolved by the generator. At best, the parser could notice a function expression sits
44
+ there and skip it with a warning -- which is precisely what a half-built, dead branch
45
+ in this codebase attempted before this decision: `parse.ts`/`link.ts`/`docs.ts` all
46
+ carried a `string | (() => Promise<string>)` union for `expiresAt`, with an
47
+ `evaluated.value instanceof Function` check that could never be true, since
48
+ `evaluateLiteral()` can never produce a `Function` value in the first place. That dead
49
+ scaffolding was removed as part of this decision (see the "Simplify expiration
50
+ metadata" changeset).
51
+
52
+ There is no version of "a function embedded in the AST, invoked by the generator" that
53
+ doesn't collapse into "the generator executes arbitrary code found in a schema file."
54
+ Widening `expiresAt`'s type without widening what the parser is allowed to do would
55
+ just leave the type promising something the implementation can never deliver.
56
+
57
+ ## Decision: `liveExpirationDates`, a Post-Discovery, Orchestration-Layer Callback
58
+
59
+ Approved instead: expiration metadata from a live source is supplied as a plain
60
+ JavaScript value passed to `generateEnvArtifacts()`/`generateDocumentation()` as a normal
61
+ function argument -- never written inside, or parsed out of, a schema file.
62
+
63
+ ```ts
64
+ liveExpirationDates?: (
65
+ variableNames: readonly string[],
66
+ ) => Promise<Readonly<Record<string, string>>>;
67
+ ```
68
+
69
+ The callback is invoked by the orchestration layer (`generateDocumentation()`,
70
+ `generateEnvArtifacts()`), never by anything in the AST discovery/linking path
71
+ (`discoverSchemaFiles()`/`parseSchemaFile()`/`linkFiles()`), and only after those steps
72
+ have already produced a fully-linked `DiscoveredContract[]`:
73
+
74
+ 1. Discovery and linking run exactly as before -- 100% static, unchanged.
75
+ 2. `collectVariableNames()` collects the unique variable keys across every linked
76
+ contract's `variables`.
77
+ 3. If `liveExpirationDates` was provided (and, in `generateEnvArtifacts()`, only if a `docs`
78
+ pass was actually requested -- no point fetching metadata nothing will render), it
79
+ is invoked exactly once with those names.
80
+ 4. `applyLiveExpirationOverrides()` -- a pure function operating on already-discovered
81
+ data, not on source text -- rebuilds the contracts array with each variable's
82
+ `expiresAt` replaced by a valid override where one was returned, and left as the
83
+ static `documentEnv()` value everywhere else.
84
+ 5. Only this rebuilt array is handed to `computeDocumentation()`/`renderDocs()`.
85
+
86
+ This keeps the two concerns -- "what does the codebase statically declare" and "what
87
+ does a live system currently say" -- separated by _when_ and _how_ they run, not
88
+ blurred together in one type. AST discovery never becomes aware that live overrides
89
+ exist at all.
90
+
91
+ Two narrower choices made while implementing this:
92
+
93
+ - **`variableNames: readonly string[]`, not a wider context object.** A broader shape
94
+ (e.g. passing the full `DiscoveredContract[]` alongside the names) was considered so
95
+ a future callback could see contract/ownership context, not just bare variable
96
+ names. Deferred, not adopted: this package is pre-1.0 (`0.1.0`, no published
97
+ consumers), so widening the callback's parameter later is a free, non-breaking
98
+ addition, while shipping a wider shape now and narrowing it later would not be.
99
+ - **`Readonly<Record<string, string>>`, not `Readonly<Record<string, string | undefined>>`.**
100
+ An absent key and an explicit `{ KEY: undefined }` entry always produce the
101
+ identical outcome ("preserve the static value") -- there is no behavior the
102
+ `| undefined` state adds. Dropping it removes a redundant state from the contract
103
+ entirely: a key is either present with a valid override, or it isn't. A returned
104
+ value is additionally validated with the same ISO-8601 `parseIsoDate()` rule the
105
+ static path already uses (exported from `docs.ts` for reuse) before being applied;
106
+ an invalid value is treated exactly like an absent key rather than corrupting
107
+ rendered output, matching this codebase's existing "warn/skip, never guess" policy.
108
+
109
+ ## Consequences
110
+
111
+ ### The callback boundary is the only place dynamic expiration data can enter
112
+
113
+ Every other stage of `expiresAt` handling -- discovery, linking, static
114
+ `documentEnv()` values, rendering -- remains provably pure and synchronous, since the
115
+ function-typed scaffolding that would have made parts of it asynchronous was removed
116
+ alongside this decision. `resolveLiveExpirationDates()` in `live-expirations.ts` is the
117
+ single, explicit, orchestration-only seam where a generation run can do anything other
118
+ than read already-discovered data.
119
+
120
+ ### Contract-level `expiresAt` cannot be overridden this way
121
+
122
+ Because the callback is keyed by variable name, only `DiscoveredVariable.expiresAt`
123
+ is ever replaced by `applyLiveExpirationOverrides()`; a contract-level `expiresAt`
124
+ (the whole-feature sunset date set via `documentEnv()`'s own `expiresAt`, distinct
125
+ from a per-variable one) always stays static. This is a direct, intentional
126
+ consequence of the chosen callback shape, not an oversight.
127
+
128
+ ### The returned override data is defensively isolated
129
+
130
+ `applyLiveExpirationOverrides()` rebuilds every contract and variable (and their
131
+ `metadata`/`extra` records) into new objects rather than reusing references from the
132
+ input, and `resolveLiveExpirationDates()` deep-freezes the result before returning it.
133
+ Nothing about mutating the docs-pass-specific contracts array can leak back into the
134
+ un-overridden `linkResult.contracts` that the manifest/usage passes in the same
135
+ `generateEnvArtifacts()` run also read.
136
+
137
+ ## Summary
138
+
139
+ Static discovery answers "what does the code declare"; `liveExpirationDates` answers
140
+ "what does a live system currently say" -- and the two are kept apart by running at
141
+ different times through different mechanisms, not by widening what the AST layer is
142
+ asked to evaluate. A function written inside a schema file can never be executed by
143
+ this generator, by design (ADR 0002); a function passed as a normal JS argument to
144
+ `generateEnvArtifacts()` always could be, safely, because invoking it was never in tension
145
+ with "never execute a discovered schema file" in the first place.
@@ -0,0 +1,136 @@
1
+ # 0013: `--json` Is a Versioned Mirror of `GenerateEnvArtifactsResult`, Not a New Derived Shape
2
+
3
+ ## Status
4
+
5
+ Accepted.
6
+
7
+ Implemented in:
8
+
9
+ - `src/build/docs.ts` (`buildCatalog()`, `CatalogVariable`/`CatalogContract`)
10
+ - `src/build/generate-documentation.ts` (`GenerateDocumentationResult.catalog`)
11
+ - `src/cli/json.ts`
12
+ - `src/cli/index.ts`
13
+ - `action.yml`
14
+ - `scripts/github-action/report.mjs`
15
+
16
+ ## Context
17
+
18
+ `generateEnvArtifacts()` already computes a fully structured result -- undocumented
19
+ variables, expiring secrets, ownership/blast-radius data, exclusive-group violations --
20
+ but the CLI (`src/cli/index.ts`) only ever rendered it as hand-formatted
21
+ `process.stdout.write(...)` text. A platform team wanting this data in CI checks, PR
22
+ annotations, or a fleet-wide dashboard had to scrape human-readable output. `--json`
23
+ closes that gap. A first-party GitHub Action was added alongside it as the concrete
24
+ "platform team" consumer this data now serves.
25
+
26
+ While designing `--json`, a second gap surfaced: `GenerateDocumentationResult` carried
27
+ _findings about_ the documentation (undocumented/stale/expiring) but never the
28
+ documentation itself. `renderDocs()` builds the rich Markdown Catalog from the full
29
+ `DiscoveredContract[]`/`DiscoveredVariable[]` graph, but that graph was discarded after
30
+ rendering -- `contracts` was only a `DiscoveredContractSummary[]` (file/exportName/
31
+ contractName/variableCount/active/documented, no per-variable metadata). `--json` as
32
+ originally scoped would have given a platform team every _problem_ but none of the
33
+ actual _catalog_. `docs.catalog` (Part 1) closes that gap first.
34
+
35
+ ## Decisions
36
+
37
+ 1. **`--json` mirrors `GenerateEnvArtifactsResult`/a thrown error's `.issues` inside a
38
+ thin `{ schemaVersion, kind, toolVersion, ok }` envelope.** No new, richer, or
39
+ derived shape is invented -- notably, no stored `blastRadius` field (see decision 3).
40
+ Serialization lives in its own module, `src/cli/json.ts`
41
+ (`serializeSuccess`/`serializeFailure`/`writeJson`), not inlined in `main()`, so the
42
+ contract has one canonical owner, is unit/snapshot-testable without stdout spying,
43
+ and the CLI's control-flow function doesn't become the de facto owner of a public
44
+ contract.
45
+
46
+ 2. **The GitHub Action's exit code is always exactly the CLI's own exit code.**
47
+ `--json` only changes formatting; pass/fail is still governed entirely by
48
+ `--strict`/`--strict-docs`/`--strict-ownership` and the always-hard-error
49
+ exclusive-group check. `action.yml`'s final step is a bare `exit
50
+ ${{ steps.run.outputs.exit-code }}` -- the Action must never introduce a second,
51
+ independent pass/fail policy of its own.
52
+
53
+ 3. **Presentation concerns belong in the Action's renderer, not in the CLI or
54
+ `src/build`.** Severity-level mapping for annotations (error/warning/notice),
55
+ Markdown rendering, and blast-radius arithmetic all live in
56
+ `scripts/github-action/report.mjs`. `consumers.length` is computed there on demand,
57
+ consistent with `usage-report.ts`'s existing Markdown renderer doing the same thing
58
+ (`src/build/usage-report.ts`'s `renderDependencyOwnershipTable()`) -- no new field is
59
+ added to `OwnershipDependencyEntry` to store it redundantly. The CLI's job is to expose data;
60
+ the Action's job is to decide how GitHub should present it.
61
+
62
+ 4. **Field/key ordering in the JSON output is not part of the contract.** Consumers
63
+ must not rely on it. Ordering _within_ an array (e.g. `manifest.contracts`,
64
+ `docs.documentation.undocumentedVariables`) is inherited from
65
+ `generateEnvArtifacts()`'s own already-deterministic computation --
66
+ `discoverSchemaFiles()` sorts discovered files alphabetically, and downstream lists
67
+ are built by iterating that order. The JSON layer does no additional sorting of its
68
+ own; a nondeterministic list is a `src/build` discovery/computation fix, never
69
+ something to patch in the CLI's serialization or the Action's rendering.
70
+
71
+ 5. **`schemaVersion` increments only on a breaking change** -- an existing field's type
72
+ or meaning changes, or a field is removed. Never for a purely additive field.
73
+ Consumers must ignore unknown top-level and nested properties, at any version, so
74
+ the payload can grow without a version bump. `toolVersion` (the installed package's
75
+ own `package.json#version`, resolved once via `import.meta.url` so it reflects the
76
+ real installed package regardless of `npx`/local devDependency/global install) is a
77
+ separate field answering a separate question: `schemaVersion` says "can I safely
78
+ parse this," `toolVersion` says "which release produced it" -- e.g. three apps in
79
+ the same org on different `env-cap` patch/minor versions can all emit
80
+ `schemaVersion: 1` while `toolVersion` still lets a consumer identify a known
81
+ per-release quirk or drive an upgrade recommendation.
82
+
83
+ 6. **Streaming/incremental output (JSON Lines, `--watch`) is explicitly out of scope.**
84
+ `--json` always emits exactly one atomic report per invocation, matching
85
+ `generateEnvArtifacts()`'s own atomic compute/write guarantee. A future streaming
86
+ mode, if ever justified, should be a distinct flag/format, not a variant of this one.
87
+
88
+ 7. **Exporting `src/cli/json.ts`'s payload/error TypeScript types as a public API was
89
+ considered and deliberately deferred.** `src/cli` isn't one of the package's three
90
+ public entry points (`.`, `./build`, `./helpers`), and no real external consumer
91
+ need has been demonstrated yet. The JSON _shape_ is documented and stable regardless
92
+ of whether TS types for it are exported -- the JSON payload itself is the canonical,
93
+ stable contract. If types are exported later, they must mirror the documented JSON
94
+ shape, not the other way around; a TS interface is never the source of truth for
95
+ what's on the wire.
96
+
97
+ 8. **`GenerateDocumentationResult.catalog` is keyed by variable name within each
98
+ contract, but the top-level list of contracts is an array, not a map keyed by
99
+ `contractName`.** A variable key is guaranteed unique within one contract (a schema
100
+ object-literal property name); `contractName` is not guaranteed unique across files
101
+ -- two unrelated contracts can legitimately share a name, and a
102
+ `Record<contractName, CatalogContract>` would let the second silently clobber the
103
+ first. Arbitrary author-supplied `documentEnv()` metadata (`CatalogVariable.extra`,
104
+ `CatalogContract.metadata`) is always its own nested property, never spread onto the
105
+ same object as reserved fields -- structurally, not by naming convention, so a
106
+ user's own field name (e.g. an extra key literally called `documented` or
107
+ `required`) can never silently override a reserved one. Any future field added to
108
+ `CatalogVariable`/`CatalogContract` must preserve this: extend the object with a new
109
+ named field, never widen what gets merged from `extra`/`metadata`.
110
+
111
+ 9. **`catalog` lives on `GenerateDocumentationResult` itself, not a new standalone pass
112
+ or type.** Considered and rejected as a false separation: `catalog` is unavoidably
113
+ built from `docsContracts`, the live-expiration-resolved graph that
114
+ `generate-env-artifacts.ts` only computes when a `docs` pass is actually requested
115
+ (see ADR 0012). A standalone `generateEnvCatalog()` would either duplicate that
116
+ resolution step or still secretly depend on `docsOptions` to be correct -- moving the
117
+ field elsewhere wouldn't remove the coupling, only hide it. `catalog` also isn't a
118
+ new category of data bolted onto a findings-only type; `contracts:
119
+ DiscoveredContractSummary[]` already _is_ a catalog, just a truncated one --
120
+ `catalog` completes it at full per-variable detail, the same way
121
+ `generateDocumentation()`'s own doc comment already describes its job as writing the
122
+ rich Markdown "Catalog".
123
+
124
+ ## Consequences
125
+
126
+ - A consumer parsing `--json` output must branch on `ok` and otherwise treat the
127
+ payload defensively: read only known fields, tolerate additional ones, and never
128
+ assume key order.
129
+ - Any change to `GenerateEnvArtifactsResult` (or the types it's built from) is
130
+ simultaneously a change to a public, versioned wire contract -- not just an internal
131
+ refactor. Whether it needs a `schemaVersion` bump per decision 5 is part of making
132
+ that change, not an afterthought.
133
+ - The GitHub Action's `report.mjs` and the JSON contract are coupled by convention, not
134
+ by a shared type (`report.mjs` is plain JS, no dependency on `src/cli/json.ts`'s
135
+ types per decision 7) -- keeping the two in sync across a payload change is a manual
136
+ discipline, called out in `skills/env-cap/SKILL.md`'s Maintainer Notes.