@zabaca/zbc 0.25.0 → 0.27.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 (74) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/package.json +1 -1
  3. package/src/commands/init.ts +105 -10
  4. package/src/commands/secret.ts +1 -66
  5. package/src/commands/update.ts +77 -7
  6. package/src/engine/actions.ts +35 -3
  7. package/src/engine/on-demand.ts +9 -1
  8. package/src/engine/secret-outputs.ts +15 -0
  9. package/src/engine/secrets.ts +81 -1
  10. package/src/utils/copy-refresh.ts +124 -19
  11. package/src/utils/detect-mode.ts +1 -1
  12. package/src/utils/host-workspaces.ts +57 -0
  13. package/src/utils/subtree.ts +54 -15
  14. package/src/utils/template-history.ts +66 -0
  15. package/src/utils/vendor-audit.ts +12 -8
  16. package/src/utils/vendor-stamp.ts +10 -0
  17. package/src/utils/vendored-app.ts +3 -0
  18. package/templates/apps/walgit/CONTEXT.md +45 -4
  19. package/templates/apps/walgit/README.md +394 -11
  20. package/templates/apps/walgit/shared/browse.ts +61 -0
  21. package/templates/apps/walgit/shared/capabilities.ts +26 -0
  22. package/templates/apps/walgit/shared/container-env.ts +12 -0
  23. package/templates/apps/walgit/shared/container-lifecycle.ts +1 -1
  24. package/templates/apps/walgit/shared/credentials.ts +4 -0
  25. package/templates/apps/walgit/shared/events.ts +35 -1
  26. package/templates/apps/walgit/shared/instructions.ts +4 -1
  27. package/templates/apps/walgit/shared/landing.ts +2 -1
  28. package/templates/apps/walgit/shared/llms.ts +73 -5
  29. package/templates/apps/walgit/shared/mcp.ts +19 -3
  30. package/templates/apps/walgit/shared/protocol.ts +40 -3
  31. package/templates/apps/walgit/shared/repo-list.ts +46 -6
  32. package/templates/apps/walgit/shared/scoped-token.ts +500 -0
  33. package/templates/apps/walgit/shared/token-revocation.ts +134 -0
  34. package/templates/apps/walgit/shared/wal-index.ts +19 -0
  35. package/templates/apps/walgit/shared/webhook.ts +281 -0
  36. package/templates/apps/walgit/src/admin.ts +510 -0
  37. package/templates/apps/walgit/src/announce-main.ts +17 -9
  38. package/templates/apps/walgit/src/announce.ts +86 -0
  39. package/templates/apps/walgit/src/browse.ts +255 -2
  40. package/templates/apps/walgit/src/cli.ts +140 -0
  41. package/templates/apps/walgit/src/expire.ts +5 -0
  42. package/templates/apps/walgit/src/git.ts +103 -0
  43. package/templates/apps/walgit/src/hook-main.ts +6 -3
  44. package/templates/apps/walgit/src/http.ts +563 -3
  45. package/templates/apps/walgit/src/limits.ts +3 -0
  46. package/templates/apps/walgit/src/merge.ts +525 -0
  47. package/templates/apps/walgit/src/rate-limit.ts +51 -14
  48. package/templates/apps/walgit/src/server.ts +65 -1
  49. package/templates/apps/walgit/worker/events-do.ts +218 -3
  50. package/templates/apps/walgit/worker/index.ts +134 -9
  51. package/templates/apps/walgit/worker/mcp.ts +17 -2
  52. package/templates/history.json +1 -0
  53. package/templates/infra/modules/cloudflare/index.ts +140 -1
  54. package/templates/infra/modules/cloudflare-access/index.ts +176 -65
  55. package/templates/infra/modules/cloudflare-access/registry.json +1 -1
  56. package/templates/infra/modules/cloudflare-api/index.ts +56 -0
  57. package/templates/infra/modules/cloudflare-email/index.ts +44 -17
  58. package/templates/infra/modules/cloudflare-email/registry.json +1 -1
  59. package/templates/infra/modules/cloudflare-stored-token/index.ts +343 -0
  60. package/templates/infra/modules/cloudflare-stored-token/registry.json +12 -0
  61. package/templates/infra/modules/cloudflare-token/index.ts +46 -17
  62. package/templates/infra/modules/cloudflare-token/registry.json +1 -1
  63. package/templates/infra/modules/cloudflare-tunnel/index.ts +63 -8
  64. package/templates/infra/modules/cloudflare-tunnel/registry.json +1 -1
  65. package/templates/infra/modules/d1/index.ts +37 -35
  66. package/templates/infra/modules/d1/registry.json +1 -1
  67. package/templates/infra/modules/docker-compose-stack/index.ts +3 -1
  68. package/templates/infra/modules/queue/index.ts +28 -18
  69. package/templates/infra/modules/queue/registry.json +1 -1
  70. package/templates/infra/modules/r2/index.ts +20 -11
  71. package/templates/infra/modules/r2/registry.json +1 -1
  72. package/templates/infra/src/context.ts +41 -0
  73. package/templates/infra/src/testing.ts +19 -1
  74. package/templates/infra/src/types.ts +23 -0
package/CHANGELOG.md CHANGED
@@ -5,6 +5,120 @@ only add or fix things are described by their `release(cli): @zabaca/zbc <x.y.z>
5
5
  commit message and the PRs it names; this file exists for the ones a consumer
6
6
  has to read before upgrading.
7
7
 
8
+ ## 0.27.0
9
+
10
+ ### `cloudflare-access`: a service token is minted by an action, and its secret is stored, not printed
11
+
12
+ **Every instance that declares `serviceTokenName` must change before it applies again.**
13
+
14
+ An apply used to create the service token and print its client id and secret
15
+ once, for you to capture. It no longer creates the token, rotates it, or prints
16
+ or emits a secret. The `clientSecret` output is gone.
17
+
18
+ What to do, per instance with `serviceTokenName`:
19
+
20
+ 1. Add `serviceTokenSecret: '<KEY>'`: the key in that environment's
21
+ `secrets.yaml` under which the token's client secret is kept. Without it the
22
+ instance is refused.
23
+ 2. Make sure the secret is under that key:
24
+ - **The token exists and you hold its secret:** put it there
25
+ (`sops set`), or name the key it is already under.
26
+ - **The token exists and nobody holds the secret:**
27
+ `zbc run <env> <instance> rotate --yes`. The old secret stops working at
28
+ once, so whatever uses the door needs the new one in the same sitting.
29
+ - **A new token:** `zbc run <env> <instance> mint`.
30
+ Commit `secrets.yaml` after `mint` or `rotate`.
31
+ 3. Remove `rotate: true` if you have it; it is refused. `rotate: false` is
32
+ still accepted and does nothing.
33
+ 4. Replace anything that read the secret from the apply log or from
34
+ `zbc apply --json` with a read of the key:
35
+ `zbc secret get <env> <KEY>`. A Worker in the same environment names the key
36
+ in `workerSecrets`.
37
+
38
+ An apply of an instance whose token does not exist stops and says to run
39
+ `mint`. An apply whose key is missing from `secrets.yaml` stops before calling
40
+ Cloudflare. `clientId` is still an output.
41
+
42
+ The space kit follows: each machine door in the install file
43
+ (`access.agent`, `telegram`, `texts`, `clients`, `leads`) needs a `secret`
44
+ beside `application` and `token`, the name its token's secret is held under.
45
+ An install with a door turned on is refused until it has one.
46
+
47
+ ### `cloudflare-tunnel`: the run token is a declared secret
48
+
49
+ `runToken` was a plain output, written verbatim into `zbc apply --json`. It is
50
+ now a secret output: `[redacted]` in that file and in anything the engine
51
+ prints. An instance that imports it still receives the real value in memory.
52
+
53
+ - If you read `runToken` out of `--json`, set `runTokenSecret: '<KEY>'` on the
54
+ instance, run `zbc run <env> <instance> store-run-token`, commit
55
+ `secrets.yaml`, and read the key with `zbc secret get`.
56
+ - An `ephemeral: true` tunnel is refused before anything applies: recreating
57
+ the tunnel changes its token under a cloudflared no apply reaches.
58
+
59
+ ### An action can store a secret (`ctx.storeSecret`)
60
+
61
+ New, for module authors: an action may write one key of the environment's
62
+ `secrets.yaml` through sops. An apply cannot. See ADR-0023.
63
+
64
+ ### Copy-mode `zbc update` no longer replaces or deletes what the project wrote
65
+
66
+ `zbc update` in a copy-mode project chose what to refresh by directory name. A
67
+ module the project wrote under a built-in's name (`d1`, before zbc had one), or
68
+ a built-in it had edited, was overwritten with zbc's, and every file in
69
+ `packages/infra/src/` that zbc does not ship was deleted, all with exit 0.
70
+
71
+ It now replaces or removes a file only when some version of zbc shipped it,
72
+ formatting and comments aside:
73
+
74
+ - A built-in-named module with a file no version of zbc shipped is kept whole
75
+ and printed as `keep`. If you relied on `update` to reset such a module, pass
76
+ `--overwrite-edits`.
77
+ - An edited file in `packages/infra/src/` stops the update before anything is
78
+ written. Move the edit out, or pass `--overwrite-engine-edits`.
79
+ - Your own files beside zbc's are left in place and listed.
80
+ - A library a refreshed module imports that the project does not have is named
81
+ with the `zbc add` that brings it.
82
+
83
+ A kept module stays at the vintage it was copied at while the engine under it
84
+ moves, so read the `keep` lines and check those modules still load.
85
+
86
+ ### `cloudflare-api` gains exports the Cloudflare modules now import
87
+
88
+ `r2`, `queue`, `d1`, `cloudflare-email` and `cloudflare-tunnel` import
89
+ `apiTokenFor`, `apiTokenSchema` and `tokenScopeHint` from `../cloudflare-api`.
90
+ A subtree project gets the library with the modules. A copy-mode project gets
91
+ it from `zbc update` as long as its copy of `cloudflare-api` is unedited; if
92
+ you edited it, `update` keeps yours and the refreshed modules will not load
93
+ until you add the three exports or pass `--overwrite-edits`.
94
+
95
+ No instance needs changing: `apiToken` is optional on `r2`, `queue`, `d1` and
96
+ `cloudflare-email`, and every form accepted before still is.
97
+
98
+ ### `cloudflare` can prove a deploy is what answers
99
+
100
+ Nothing to change in an existing instance. If you poll a health path after
101
+ `zbc apply` to see the new commit, `deployCheck: { path }` beside `deployIdVar`
102
+ now does it inside the apply and fails the apply when the Worker never names
103
+ the deploy. The module also emits `deployId`.
104
+
105
+ ## 0.26.0
106
+
107
+ ### `zbc init` no longer writes `.claude/settings.json` into an existing repo
108
+
109
+ The scaffolded settings grant Claude Code tool permissions (`bun`, `git`, `gh`,
110
+ …) and enable the `zbc` plugin. `init` used to write them in every mode; it now
111
+ writes them by default only for a greenfield project at the repo's top level. In
112
+ an existing Bun workspace, in a subfolder of another repo (`--dir`), or where
113
+ `.claude/` already exists, it skips them and says so. Pass `--claude` to get the
114
+ old behaviour, or `--no-claude` to skip them in any mode. A project already
115
+ scaffolded is untouched.
116
+
117
+ `init --dir <path>` is new: it puts the zbc project in a folder of its own, the
118
+ route for a repo that is not a Bun workspace. The subtree prefix is derived from
119
+ that folder (`deploy/zbc/vendor/zbc`); a project at the top level is vendored and
120
+ stamped exactly as before.
121
+
8
122
  ## 0.25.0
9
123
 
10
124
  ### The `inbox` app template is removed
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zabaca/zbc",
3
- "version": "0.25.0",
3
+ "version": "0.27.0",
4
4
  "description": "Zabaca stack CLI — scaffold and deploy infrastructure",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -3,7 +3,16 @@ import * as fs from 'node:fs/promises'
3
3
  import { defineCommand } from 'citty'
4
4
  import { detectMode } from '../utils/detect-mode'
5
5
  import { copyTemplateDir, copyTemplateFile, templatesRoot } from '../utils/copy-template'
6
- import { coreRefForVersion, DEFAULT_CORE_URL, subtreeAdd, VENDOR_PREFIX } from '../utils/subtree'
6
+ import {
7
+ coreRefForVersion,
8
+ DEFAULT_CORE_URL,
9
+ gitPrefix,
10
+ gitTopLevel,
11
+ projectSubdir,
12
+ subtreeAdd,
13
+ VENDOR_PREFIX,
14
+ } from '../utils/subtree'
15
+ import { hostWorkspaceGlobsCovering } from '../utils/host-workspaces'
7
16
  import { STAMP_FILE, writeStamp } from '../utils/vendor-stamp'
8
17
  import pkg from '../../package.json' with { type: 'json' }
9
18
 
@@ -22,6 +31,34 @@ async function writeIfMissing(filePath: string, body: string): Promise<void> {
22
31
  console.log(` write ${path.relative(process.cwd(), filePath)}`)
23
32
  }
24
33
 
34
+ /**
35
+ * Lay the CI workflows. A project at the repository's top level gets them
36
+ * verbatim. One in a subfolder gets them at the TOP level's `.github/workflows/`
37
+ * — GitHub reads no other — with every `run` step defaulted into the project
38
+ * folder, so the same `bun install` / `bunx @zabaca/zbc apply` run in it.
39
+ */
40
+ async function layWorkflows(tplRoot: string, repoTop: string, subdir: string): Promise<void> {
41
+ const wfSrc = path.join(tplRoot, 'workflows')
42
+ const wfDest = path.join(repoTop, '.github/workflows')
43
+ if (subdir === '') {
44
+ await copyTemplateDir(wfSrc, wfDest)
45
+ return
46
+ }
47
+ for (const name of await fs.readdir(wfSrc)) {
48
+ const body = await Bun.file(path.join(wfSrc, name)).text()
49
+ // JSON-quoted: a double-quoted YAML scalar, whatever the folder is called.
50
+ const defaults = `defaults:\n run:\n working-directory: ${JSON.stringify(subdir)}\n\njobs:`
51
+ const dest = path.join(wfDest, name)
52
+ if (await Bun.file(dest).exists()) {
53
+ console.warn(
54
+ ` warn: ${path.relative(process.cwd(), dest)} already exists (the host's own?) — zbc's ${name} was not written; merge it in by hand with working-directory: ${subdir}`,
55
+ )
56
+ continue
57
+ }
58
+ await writeIfMissing(dest, body.replace(/^jobs:/m, defaults))
59
+ }
60
+ }
61
+
25
62
  export const initCommand = defineCommand({
26
63
  meta: {
27
64
  name: 'init',
@@ -30,9 +67,20 @@ export const initCommand = defineCommand({
30
67
  args: {
31
68
  project: {
32
69
  type: 'positional',
33
- description: 'Project name (defaults to current directory name)',
70
+ description: 'Project name (defaults to the project directory name)',
71
+ required: false,
72
+ },
73
+ dir: {
74
+ type: 'string',
75
+ description:
76
+ 'Scaffold the project into this folder (created if missing), as if run from inside it — e.g. deploy/zbc in a non-Bun repo',
34
77
  required: false,
35
78
  },
79
+ claude: {
80
+ type: 'boolean',
81
+ description:
82
+ 'Write .claude/settings.json (default: only for a greenfield init at the repo top level; --no-claude never writes it)',
83
+ },
36
84
  ci: {
37
85
  type: 'string',
38
86
  description: 'CI provider to scaffold (e.g. "github")',
@@ -64,12 +112,29 @@ export const initCommand = defineCommand({
64
112
  },
65
113
  },
66
114
  async run({ args }) {
67
- const cwd = process.cwd()
115
+ // The project root. Everything below is written relative to it, exactly as
116
+ // if `init` had been run from inside it; only the CI workflows go to the
117
+ // repository's top level, the one place GitHub reads them from.
118
+ const cwd = args.dir ? path.resolve(process.cwd(), args.dir) : process.cwd()
119
+ await ensureDir(cwd)
68
120
  const projectName = args.project ?? path.basename(cwd)
69
121
  const tplRoot = templatesRoot()
122
+ // The host: the git top level, or — for `--dir` outside any git work tree
123
+ // (copy mode needs no git) — the folder init was run from, so the folder
124
+ // is still treated as a subfolder of the repo that holds it.
125
+ let repoTop = gitTopLevel(cwd)
126
+ let subdir = projectSubdir(cwd)
127
+ if (repoTop === null && args.dir) {
128
+ const rel = path.relative(process.cwd(), cwd)
129
+ if (rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel)) {
130
+ repoTop = process.cwd()
131
+ subdir = rel.split(path.sep).join('/')
132
+ }
133
+ }
70
134
 
71
135
  console.log(`zbc init: ${projectName}`)
72
136
  console.log(` cwd: ${cwd}`)
137
+ if (subdir !== '') console.log(` repo: ${repoTop} (project in ${subdir}/)`)
73
138
 
74
139
  const mode = await detectMode(cwd)
75
140
  if (mode.kind === 'incompatible') {
@@ -78,6 +143,22 @@ export const initCommand = defineCommand({
78
143
  }
79
144
  console.log(` mode: ${mode.kind}${args.subtree ? ' (subtree)' : ''}`)
80
145
 
146
+ // A project folder the host's own workspace globs cover is one the host's
147
+ // package manager will try to install and link too.
148
+ if (repoTop !== null && subdir !== '') {
149
+ const covering = await hostWorkspaceGlobsCovering(repoTop, subdir)
150
+ if (covering.length > 0) {
151
+ console.warn(
152
+ ` warn: ${subdir}/ falls under the host repo's workspace globs (${covering.join(', ')}) — its package manager will try to manage this project too. Prefer a folder outside them (e.g. deploy/zbc).`,
153
+ )
154
+ }
155
+ }
156
+ const prefix = gitPrefix(cwd)
157
+ const hadClaudeDir = await fs
158
+ .stat(path.join(cwd, '.claude'))
159
+ .then((st) => st.isDirectory())
160
+ .catch(() => false)
161
+
81
162
  // 0. Subtree mode: vendor zbc-core FIRST — `git subtree add` demands a
82
163
  // clean tree, so it must run before any scaffold file is written.
83
164
  let vendoredRef: string | undefined
@@ -85,7 +166,7 @@ export const initCommand = defineCommand({
85
166
  const url = args['core-url'] ?? DEFAULT_CORE_URL
86
167
  const ref = args['core-ref'] ?? coreRefForVersion(pkg.version)
87
168
  vendoredRef = ref
88
- console.log(` vendoring: ${url} @ ${ref} → ${VENDOR_PREFIX}`)
169
+ console.log(` vendoring: ${url} @ ${ref} → ${prefix}`)
89
170
  try {
90
171
  subtreeAdd(cwd, { url, ref })
91
172
  } catch (err) {
@@ -165,24 +246,36 @@ export const initCommand = defineCommand({
165
246
 
166
247
  // 6. CI workflows
167
248
  if (args.ci === 'github') {
168
- const wfDest = path.join(cwd, '.github/workflows')
169
- await copyTemplateDir(path.join(tplRoot, 'workflows'), wfDest)
249
+ await layWorkflows(tplRoot, repoTop ?? cwd, subdir)
170
250
  } else if (args.ci) {
171
251
  console.warn(` warn: unknown --ci=${args.ci} (only "github" supported)`)
172
252
  }
173
253
 
174
- // 7. Claude Code scaffolding (skip-if-exists, safe in either mode)
254
+ // 7. Claude Code scaffolding. CLAUDE.md is skip-if-exists in any mode. The
255
+ // settings grant tool permissions and enable a plugin, which is not
256
+ // init's to decide for a repository that already exists: only a
257
+ // greenfield project at the top level gets them unasked.
175
258
  await copyTemplateFile(path.join(tplRoot, 'CLAUDE.md'), path.join(cwd, 'CLAUDE.md'), {
176
259
  vars,
177
260
  })
178
- await copyTemplateDir(path.join(tplRoot, 'claude'), path.join(cwd, '.claude'))
261
+ const existingRepo = mode.kind === 'monorepo' || subdir !== '' || hadClaudeDir
262
+ const writeClaude = args.claude ?? !existingRepo
263
+ if (writeClaude) {
264
+ await copyTemplateDir(path.join(tplRoot, 'claude'), path.join(cwd, '.claude'))
265
+ } else {
266
+ console.log(
267
+ args.claude === false
268
+ ? ' skip .claude/settings.json (--no-claude)'
269
+ : ' skip .claude/settings.json (existing repo — pass --claude to write it)',
270
+ )
271
+ }
179
272
 
180
273
  // 8. Vintage stamp — which engine this project is running, recorded at the
181
274
  // project root so `git subtree push` can never carry it upstream.
182
275
  await writeStamp(cwd, {
183
276
  mode: args.subtree ? 'subtree' : 'copy',
184
277
  cliVersion: pkg.version,
185
- ...(vendoredRef ? { coreRef: vendoredRef } : {}),
278
+ ...(vendoredRef ? { coreRef: vendoredRef, prefix } : {}),
186
279
  })
187
280
  console.log(` write ${STAMP_FILE}`)
188
281
 
@@ -190,10 +283,12 @@ export const initCommand = defineCommand({
190
283
  console.log('✓ init done')
191
284
  if (args.subtree) {
192
285
  console.log(
193
- ` engine + modules vendored at ${VENDOR_PREFIX}/ — commit the scaffold, then never mix ${VENDOR_PREFIX}/ and other paths in one commit (subtree push sends prefix-touching commits upstream)`,
286
+ ` engine + modules vendored at ${prefix}/ — commit the scaffold, then never mix ${prefix}/ and other paths in one commit (subtree push sends prefix-touching commits upstream)`,
194
287
  )
195
288
  }
196
289
  console.log('')
290
+ if (args.dir)
291
+ console.log(`Run the next steps from ${path.relative(process.cwd(), cwd) || '.'}/.`)
197
292
  if (mode.kind === 'greenfield') {
198
293
  console.log('Next steps:')
199
294
  console.log(' 1. bun install')
@@ -1,6 +1,5 @@
1
1
  import * as path from 'node:path'
2
2
  import { defineCommand } from 'citty'
3
- import { parse as parseYaml, stringify as stringifyYaml } from 'yaml'
4
3
  import {
5
4
  decryptSubmission,
6
5
  decryptWithDocumentKey,
@@ -14,7 +13,7 @@ import {
14
13
  import { resolveSecret } from '../../templates/infra/src/context'
15
14
  import { applyEnvironment } from '../engine/apply'
16
15
  import { discoverInstances } from '../engine/discover'
17
- import { loadSecrets } from '../engine/secrets'
16
+ import { loadSecrets, writeSecrets } from '../engine/secrets'
18
17
  import { findProjectRoot } from '../utils/find-project-root'
19
18
  import { loadConfig } from '../utils/load-config'
20
19
 
@@ -40,70 +39,6 @@ function sleep(ms: number): Promise<void> {
40
39
  return new Promise((resolve) => setTimeout(resolve, ms))
41
40
  }
42
41
 
43
- /**
44
- * Merge `values` into the environment's secrets.yaml. With a `.sops.yaml` at
45
- * the project root, writes go through sops so plaintext never lands on disk:
46
- * `sops set` per key into an existing encrypted file, or a stdin-piped
47
- * `sops -e` (with --filename-override so creation rules match) to create one.
48
- * Without `.sops.yaml`, falls back to plain YAML (development mode, mirroring
49
- * loadSecrets).
50
- */
51
- async function writeSecrets(
52
- projectRoot: string,
53
- envDir: string,
54
- values: Record<string, string>,
55
- ): Promise<void> {
56
- const secretsPath = path.join(envDir, 'secrets.yaml')
57
- const file = Bun.file(secretsPath)
58
- const exists = await file.exists()
59
- const hasSopsConfig = await Bun.file(path.join(projectRoot, '.sops.yaml')).exists()
60
-
61
- if (!hasSopsConfig) {
62
- const existing = exists ? (parseYaml(await file.text()) ?? {}) : {}
63
- await Bun.write(secretsPath, stringifyYaml({ ...existing, ...values }))
64
- return
65
- }
66
-
67
- const alreadyEncrypted = exists && parseYaml(await file.text())?.sops
68
- if (alreadyEncrypted) {
69
- for (const [key, value] of Object.entries(values)) {
70
- const proc = Bun.spawnSync(
71
- ['sops', 'set', secretsPath, `["${key}"]`, JSON.stringify(value)],
72
- { cwd: projectRoot, stderr: 'pipe' },
73
- )
74
- if (proc.exitCode !== 0) {
75
- throw new Error(`sops set failed for ${key}: ${proc.stderr.toString()}`)
76
- }
77
- }
78
- return
79
- }
80
-
81
- // Missing (or plain, pre-sops) file: merge in memory, encrypt via stdin so
82
- // plaintext never touches the filesystem.
83
- const existing = exists ? (parseYaml(await file.text()) ?? {}) : {}
84
- const plaintext = stringifyYaml({ ...existing, ...values })
85
- const proc = Bun.spawnSync(
86
- [
87
- 'sops',
88
- '--config',
89
- path.join(projectRoot, '.sops.yaml'),
90
- '--filename-override',
91
- secretsPath,
92
- '-e',
93
- '--input-type',
94
- 'yaml',
95
- '--output-type',
96
- 'yaml',
97
- '/dev/stdin',
98
- ],
99
- { cwd: projectRoot, stdin: new TextEncoder().encode(plaintext), stderr: 'pipe' },
100
- )
101
- if (proc.exitCode !== 0) {
102
- throw new Error(`sops encrypt failed: ${proc.stderr.toString()}`)
103
- }
104
- await Bun.write(secretsPath, proc.stdout)
105
- }
106
-
107
42
  /**
108
43
  * Find the project's Secret Relay and converge it through the normal apply
109
44
  * graph (outputs are per-run, not persisted — ADR-0003), returning its
@@ -1,3 +1,4 @@
1
+ import * as path from 'node:path'
1
2
  import { defineCommand } from 'citty'
2
3
  import { findProjectRoot } from '../utils/find-project-root'
3
4
  import { refreshCopiedTemplates } from '../utils/copy-refresh'
@@ -8,6 +9,8 @@ import {
8
9
  coreRefForVersion,
9
10
  DEFAULT_CORE_URL,
10
11
  ensureCleanGitTree,
12
+ gitPrefix,
13
+ gitTopLevel,
11
14
  isVendorMode,
12
15
  subtreePull,
13
16
  VENDOR_PREFIX,
@@ -43,6 +46,17 @@ export const updateCommand = defineCommand({
43
46
  type: 'string',
44
47
  description: 'zbc-core ref to pull (default: the tag matching this CLI version)',
45
48
  },
49
+ 'overwrite-engine-edits': {
50
+ type: 'boolean',
51
+ description: "Copy mode: replace engine files the project edited with this CLI's",
52
+ default: false,
53
+ },
54
+ 'overwrite-edits': {
55
+ type: 'boolean',
56
+ description:
57
+ "Copy mode: replace edited engine files and edited or own built-in-named modules with this CLI's",
58
+ default: false,
59
+ },
46
60
  strict: {
47
61
  type: 'boolean',
48
62
  description: `Exit non-zero if ${VENDOR_PREFIX}/ holds files zbc-core does not ship`,
@@ -83,6 +97,19 @@ export const updateCommand = defineCommand({
83
97
  // fix was a hand diff, which is how consumers ended up reimplementing what
84
98
  // we ship. The CLI carries the templates, so it can re-lay them in place.
85
99
  const stamp = await readStamp(projectRoot)
100
+ // The subtree prefix as git sees it: `vendor/zbc` at the top level,
101
+ // `deploy/zbc/vendor/zbc` for a project in a subfolder. Always derived; the
102
+ // stamp's copy is information, and a stale one is said and then ignored.
103
+ const prefix = gitPrefix(projectRoot)
104
+ const recordedPrefix = stamp?.mode === 'subtree' ? (stamp.prefix ?? VENDOR_PREFIX) : prefix
105
+ if (recordedPrefix !== prefix) {
106
+ console.warn(
107
+ `⚠ ${STAMP_FILE} records the subtree at ${recordedPrefix}/, but this project's is ${prefix}/ (the folder moved?) — using ${prefix}/.`,
108
+ )
109
+ console.warn(
110
+ ` git's subtree history names ${recordedPrefix}/, so a pull at ${prefix}/ may be refused as never added; re-vendor at ${prefix}/ if it is.`,
111
+ )
112
+ }
86
113
 
87
114
  if (!(await isVendorMode(projectRoot))) {
88
115
  // A stamp saying `subtree` with no engine under the prefix is the varnick
@@ -91,10 +118,16 @@ export const updateCommand = defineCommand({
91
118
  // record that this is a subtree project — so say what is wrong instead.
92
119
  if (stamp?.mode === 'subtree') {
93
120
  console.error(
94
- `✗ ${STAMP_FILE} says this project vendors zbc as a subtree, but ${VENDOR_PREFIX}/src is missing — the subtree never landed, or was removed.`,
121
+ `✗ ${STAMP_FILE} says this project vendors zbc as a subtree, but ${prefix}/src is missing — the subtree never landed, or was removed.`,
95
122
  )
123
+ // git subtree runs only at the top level; say how to get there from here.
124
+ const top = gitTopLevel(projectRoot)
125
+ const fromTop =
126
+ top === null || prefix === VENDOR_PREFIX
127
+ ? ''
128
+ : `-C ${JSON.stringify(path.relative(process.cwd(), top) || '.')} `
96
129
  console.error(
97
- ` Re-vendor it: git subtree add --prefix=${VENDOR_PREFIX} ${DEFAULT_CORE_URL} ${stamp.coreRef ?? coreRefForVersion(pkg.version)} --squash`,
130
+ ` Re-vendor it: git ${fromTop}subtree add --prefix=${prefix} ${DEFAULT_CORE_URL} ${stamp.coreRef ?? coreRefForVersion(pkg.version)} --squash`,
98
131
  )
99
132
  process.exit(1)
100
133
  }
@@ -116,9 +149,36 @@ export const updateCommand = defineCommand({
116
149
  console.error(`✗ ${(err as Error).message}`)
117
150
  process.exit(1)
118
151
  }
119
- const result = await refreshCopiedTemplates(projectRoot)
152
+ const result = await refreshCopiedTemplates(projectRoot, {
153
+ overwriteEngine: args['overwrite-engine-edits'] || args['overwrite-edits'],
154
+ overwriteModules: args['overwrite-edits'],
155
+ })
156
+ if (result.editedEngine.length > 0) {
157
+ console.error("✗ The engine in packages/infra/src has edits of this project's own:")
158
+ for (const file of result.editedEngine) console.error(` ${file}`)
159
+ console.error(
160
+ ' No version of zbc shipped these files as they read here, and the engine cannot be\n' +
161
+ ' refreshed in part. Nothing was changed. Move the edits out of packages/infra/src,\n' +
162
+ " or run `zbc update --overwrite-engine-edits` to replace them with this CLI's files.",
163
+ )
164
+ process.exit(1)
165
+ }
120
166
  for (const skip of result.skipped) console.log(` skip ${skip.path} (${skip.reason})`)
121
167
  for (const gone of result.removed) console.log(` remove ${gone} (no longer shipped)`)
168
+ for (const kept of result.kept) {
169
+ console.log(
170
+ ` keep ${kept.path} (${kept.files.join(', ')} ${kept.files.length === 1 ? 'matches' : 'match'} no version zbc shipped)`,
171
+ )
172
+ }
173
+ for (const file of result.own) console.log(` yours, left in place: ${file}`)
174
+ if (result.kept.length > 0) {
175
+ console.log('')
176
+ console.log(
177
+ " Kept modules are this project's own or edited copies. They stay at their vintage,\n" +
178
+ ' so check they still load against the refreshed engine.\n' +
179
+ ' `zbc update --overwrite-edits` replaces them with the built-ins.',
180
+ )
181
+ }
122
182
  if (result.refreshed.length === 0) {
123
183
  console.log(' nothing to refresh (no copied engine or built-in modules found)')
124
184
  }
@@ -130,6 +190,11 @@ export const updateCommand = defineCommand({
130
190
  ` cd packages/infra && bun add ${missing.map(([n, v]) => `${n}@${v}`).join(' ')}`,
131
191
  )
132
192
  }
193
+ if (result.missingModules.length > 0) {
194
+ console.log('')
195
+ console.log(' Refreshed modules import libraries this project does not have:')
196
+ for (const name of result.missingModules) console.log(` zbc add ${name}`)
197
+ }
133
198
  await writeStamp(projectRoot, { mode: 'copy', cliVersion: pkg.version })
134
199
  console.log(
135
200
  `✓ refreshed ${result.refreshed.length} path(s) — review the diff before committing.`,
@@ -142,19 +207,24 @@ export const updateCommand = defineCommand({
142
207
 
143
208
  const url = args['core-url'] ?? DEFAULT_CORE_URL
144
209
  const ref = args['core-ref'] ?? coreRefForVersion(pkg.version)
145
- console.log(`zbc update: ${url} @ ${ref} → ${VENDOR_PREFIX}`)
210
+ console.log(`zbc update: ${url} @ ${ref} → ${prefix}`)
146
211
  try {
147
212
  subtreePull(projectRoot, { url, ref })
148
213
  } catch (err) {
149
214
  console.error(`✗ ${(err as Error).message}`)
150
215
  process.exit(1)
151
216
  }
152
- await writeStamp(projectRoot, { mode: 'subtree', cliVersion: pkg.version, coreRef: ref })
153
- console.log('✓ vendor/zbc updated — review the squash merge commit and push')
217
+ await writeStamp(projectRoot, {
218
+ mode: 'subtree',
219
+ cliVersion: pkg.version,
220
+ coreRef: ref,
221
+ prefix,
222
+ })
223
+ console.log(`✓ ${prefix} updated — review the squash merge commit and push`)
154
224
 
155
225
  // The push direction nobody watches: files written inside the prefix.
156
226
  const foreign = await foreignVendorFiles(projectRoot)
157
- for (const line of describeForeignFiles(foreign)) console.warn(line)
227
+ for (const line of describeForeignFiles(foreign, prefix)) console.warn(line)
158
228
  if (args.strict && foreign.length > 0) process.exit(1)
159
229
  },
160
230
  })
@@ -7,6 +7,7 @@
7
7
  // by a test asserting it stays unimported — which is also outside the graph,
8
8
  // the decrypted secrets, and the imports edge that the act needs.
9
9
 
10
+ import * as path from 'node:path'
10
11
  import type { ApplyContext, ModuleInstance } from '../../templates/infra/src/types'
11
12
  import type { InstanceRunOptions } from './apply'
12
13
  import { discoverInstances } from './discover'
@@ -14,7 +15,7 @@ import { applyImportsEagerly, withOnDemandImports } from './on-demand'
14
15
  import { createReadinessGate } from './readiness'
15
16
  import { resolveOrder } from './resolve'
16
17
  import { createSecretOutputRegistry, redactError } from './secret-outputs'
17
- import { loadSecrets } from './secrets'
18
+ import { loadSecrets, writeSecrets } from './secrets'
18
19
 
19
20
  export interface RunActionOptions extends InstanceRunOptions {
20
21
  /** The instance to act on. Required — an action is never fanned out. */
@@ -25,6 +26,12 @@ export interface RunActionOptions extends InstanceRunOptions {
25
26
  confirmed?: boolean
26
27
  /** Where the instances came from, for error messages. */
27
28
  envLabel?: string
29
+ /**
30
+ * Writes one key of the environment's secrets.yaml. With it, the action's
31
+ * body may call `ctx.storeSecret`; without it, that call throws as it does in
32
+ * an apply (ADR-0023).
33
+ */
34
+ storeSecret?: (key: string, value: string) => Promise<void>
28
35
  }
29
36
 
30
37
  /** One action as `zbc run` and `zbc list` report it. */
@@ -134,7 +141,20 @@ export async function runAction(
134
141
  instance,
135
142
  runOpts,
136
143
  outputs,
137
- { onDemand: true, asker },
144
+ {
145
+ onDemand: true,
146
+ asker,
147
+ ...(opts.storeSecret
148
+ ? {
149
+ storeSecret: async (key: string, value: string) => {
150
+ // Before the write: a value that fails to store is as much a
151
+ // credential in the error that says so as one that did not.
152
+ registry.recordValue(`secrets.yaml ${key}`, value)
153
+ await opts.storeSecret?.(key, value)
154
+ },
155
+ }
156
+ : {}),
157
+ },
138
158
  (ctx: ApplyContext) => action.run(validatedConfig, ctx),
139
159
  )
140
160
  } catch (err) {
@@ -151,7 +171,19 @@ export async function runEnvironmentAction(
151
171
  ): Promise<void> {
152
172
  const instances = await discoverInstances(envDir)
153
173
  const secrets = await loadSecrets(envDir)
154
- await runAction(instances, { ...opts, secrets, projectRoot, envLabel: envDir })
174
+ const file = path.relative(projectRoot, path.join(envDir, 'secrets.yaml'))
175
+ await runAction(instances, {
176
+ ...opts,
177
+ secrets,
178
+ projectRoot,
179
+ envLabel: envDir,
180
+ async storeSecret(key, value) {
181
+ await writeSecrets(projectRoot, envDir, { [key]: value }, { valueViaStdin: true })
182
+ // The one thing the operator has to do next, said where they will see it:
183
+ // a stored secret that is not committed is lost with this checkout.
184
+ console.log(` Stored ${key} in ${file}. Commit that file.`)
185
+ },
186
+ })
155
187
  }
156
188
 
157
189
  /** The I/O half of "what can this instance do": no secrets, no provider, no run. */
@@ -57,6 +57,11 @@ interface OnDemandCommon {
57
57
  asker: string
58
58
  /** An extra line after an on-demand apply — a destroy says it will tear it down again. */
59
59
  afterApply?: (name: string) => string
60
+ /**
61
+ * The writer behind `ctx.storeSecret` for THIS body. Set for an action and
62
+ * for nothing else; never handed on to the imports the body causes to apply.
63
+ */
64
+ storeSecret?: (key: string, value: string) => Promise<void>
60
65
  }
61
66
 
62
67
  /**
@@ -150,6 +155,9 @@ function onDemandContext(
150
155
  secrets: opts.secrets,
151
156
  imports: importOutputs,
152
157
  projectRoot: opts.projectRoot,
158
+ // Only what `mode` carries: an action's body. The imports this context
159
+ // applies on demand are applies, built elsewhere, and get no writer.
160
+ ...(mode.storeSecret ? { storeSecret: mode.storeSecret } : {}),
153
161
  })
154
162
 
155
163
  /** Both spellings of the edge go through here before reaching `base`. */
@@ -184,7 +192,7 @@ function onDemandContext(
184
192
  if (!dep) throw new Error(`Cannot apply "${name}": it is not among ${instance.name}'s imports`)
185
193
  if (name in importOutputs) throw new Error(`Import "${name}" was already applied`)
186
194
 
187
- await ensureApplied(dep, mode.asker, opts, outputs, mode)
195
+ await ensureApplied(dep, mode.asker, opts, outputs, { ...mode, storeSecret: undefined })
188
196
  // THE EDGE, again: the value this body is about to read is held until the
189
197
  // module that minted it says it is usable.
190
198
  await opts.gate?.ensureReady(name)