@zabaca/zbc 0.24.0 → 0.26.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 (71) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/package.json +3 -2
  3. package/src/commands/add.ts +78 -5
  4. package/src/commands/init.ts +105 -10
  5. package/src/commands/list.ts +6 -3
  6. package/src/commands/update.ts +75 -6
  7. package/src/engine/destroy.ts +23 -2
  8. package/src/engine/resolve.ts +5 -0
  9. package/src/utils/detect-mode.ts +1 -1
  10. package/src/utils/host-workspaces.ts +57 -0
  11. package/src/utils/subtree.ts +78 -9
  12. package/src/utils/vendor-audit.ts +12 -8
  13. package/src/utils/vendor-stamp.ts +102 -1
  14. package/src/utils/vendored-app.ts +356 -0
  15. package/templates/CLAUDE.md +1 -1
  16. package/templates/apps/walgit/CONTEXT.md +45 -4
  17. package/templates/apps/walgit/README.md +394 -11
  18. package/templates/apps/walgit/shared/browse.ts +61 -0
  19. package/templates/apps/walgit/shared/capabilities.ts +26 -0
  20. package/templates/apps/walgit/shared/container-env.ts +12 -0
  21. package/templates/apps/walgit/shared/container-lifecycle.ts +1 -1
  22. package/templates/apps/walgit/shared/credentials.ts +4 -0
  23. package/templates/apps/walgit/shared/events.ts +35 -1
  24. package/templates/apps/walgit/shared/instructions.ts +4 -1
  25. package/templates/apps/walgit/shared/landing.ts +2 -1
  26. package/templates/apps/walgit/shared/llms.ts +73 -5
  27. package/templates/apps/walgit/shared/mcp.ts +19 -3
  28. package/templates/apps/walgit/shared/protocol.ts +40 -3
  29. package/templates/apps/walgit/shared/repo-list.ts +46 -6
  30. package/templates/apps/walgit/shared/scoped-token.ts +500 -0
  31. package/templates/apps/walgit/shared/token-revocation.ts +134 -0
  32. package/templates/apps/walgit/shared/wal-index.ts +19 -0
  33. package/templates/apps/walgit/shared/webhook.ts +281 -0
  34. package/templates/apps/walgit/src/admin.ts +510 -0
  35. package/templates/apps/walgit/src/announce-main.ts +17 -9
  36. package/templates/apps/walgit/src/announce.ts +86 -0
  37. package/templates/apps/walgit/src/browse.ts +255 -2
  38. package/templates/apps/walgit/src/cli.ts +140 -0
  39. package/templates/apps/walgit/src/expire.ts +5 -0
  40. package/templates/apps/walgit/src/git.ts +103 -0
  41. package/templates/apps/walgit/src/hook-main.ts +6 -3
  42. package/templates/apps/walgit/src/http.ts +563 -3
  43. package/templates/apps/walgit/src/limits.ts +3 -0
  44. package/templates/apps/walgit/src/merge.ts +525 -0
  45. package/templates/apps/walgit/src/rate-limit.ts +51 -14
  46. package/templates/apps/walgit/src/server.ts +65 -1
  47. package/templates/apps/walgit/worker/events-do.ts +218 -3
  48. package/templates/apps/walgit/worker/index.ts +134 -9
  49. package/templates/apps/walgit/worker/mcp.ts +18 -4
  50. package/templates/apps/warehouse/worker/router.ts +1 -2
  51. package/templates/apps/warehouse/worker/test-setup.ts +1 -2
  52. package/templates/infra/modules/cloudflare-access/index.ts +245 -28
  53. package/templates/infra/modules/cloudflare-access/registry.json +1 -1
  54. package/templates/infra/modules/d1/index.ts +133 -4
  55. package/templates/infra/modules/d1/registry.json +4 -1
  56. package/templates/infra/modules/queue/index.ts +313 -0
  57. package/templates/infra/modules/queue/registry.json +13 -0
  58. package/templates/infra/modules/r2/registry.json +1 -1
  59. package/templates/infra/src/define-module.ts +19 -2
  60. package/templates/infra/src/types.ts +24 -0
  61. package/templates/apps/inbox/package.json +0 -26
  62. package/templates/apps/inbox/public/index.html +0 -379
  63. package/templates/apps/inbox/registry.json +0 -9
  64. package/templates/apps/inbox/tsconfig.json +0 -19
  65. package/templates/apps/inbox/worker/api.ts +0 -197
  66. package/templates/apps/inbox/worker/commands.ts +0 -299
  67. package/templates/apps/inbox/worker/inbox-do.ts +0 -577
  68. package/templates/apps/inbox/worker/index.ts +0 -195
  69. package/templates/apps/inbox/worker/mcp.ts +0 -228
  70. package/templates/apps/inbox/worker/shared.ts +0 -117
  71. package/templates/apps/inbox/wrangler.jsonc +0 -48
package/CHANGELOG.md CHANGED
@@ -5,6 +5,51 @@ 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.26.0
9
+
10
+ ### `zbc init` no longer writes `.claude/settings.json` into an existing repo
11
+
12
+ The scaffolded settings grant Claude Code tool permissions (`bun`, `git`, `gh`,
13
+ …) and enable the `zbc` plugin. `init` used to write them in every mode; it now
14
+ writes them by default only for a greenfield project at the repo's top level. In
15
+ an existing Bun workspace, in a subfolder of another repo (`--dir`), or where
16
+ `.claude/` already exists, it skips them and says so. Pass `--claude` to get the
17
+ old behaviour, or `--no-claude` to skip them in any mode. A project already
18
+ scaffolded is untouched.
19
+
20
+ `init --dir <path>` is new: it puts the zbc project in a folder of its own, the
21
+ route for a repo that is not a Bun workspace. The subtree prefix is derived from
22
+ that folder (`deploy/zbc/vendor/zbc`); a project at the top level is vendored and
23
+ stamped exactly as before.
24
+
25
+ ## 0.25.0
26
+
27
+ ### The `inbox` app template is removed
28
+
29
+ `zbc add inbox` no longer resolves: the single-mailbox inbox Worker is gone from
30
+ the templates, with no alias left behind.
31
+
32
+ A project that already scaffolded it is untouched. `packages/inbox/` and its
33
+ three instance files are that project's own code, they keep deploying as they
34
+ did, and `zbc update` never looked at them. What ends is upstream: no fix to
35
+ that template will arrive.
36
+
37
+ What replaces it is `space`, below: a company's mail is one part of it. It is a
38
+ different application, not a newer inbox, so there is nothing to migrate
39
+ automatically.
40
+
41
+ ### `space` is pulled, not copied
42
+
43
+ `zbc add space` and `zbc update space` vendor a whole application (a small
44
+ company's mail, chat and calls, calendar, forms and signed documents, clients
45
+ and knowledge, in one Worker) as a git subtree of its own public repository at
46
+ `vendor/space/`, on its own version tags. It is not in this package.
47
+
48
+ `.zbc-vendor.json` gains an `apps` entry recording the repository, the ref and
49
+ the commit pulled. Commit it, as you do the engine's stamp. A project that has
50
+ no engine stamp gets a file holding only `apps`, which `zbc apply` reads exactly
51
+ as it read the missing file.
52
+
8
53
  ## 0.16.4
9
54
 
10
55
  ### The package no longer carries the publisher's `node_modules`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zabaca/zbc",
3
- "version": "0.24.0",
3
+ "version": "0.26.0",
4
4
  "description": "Zabaca stack CLI — scaffold and deploy infrastructure",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -23,7 +23,8 @@
23
23
  "!templates/**/node_modules",
24
24
  "!templates/**/*.test.ts",
25
25
  "!templates/**/.wrangler",
26
- "!templates/**/.DS_Store"
26
+ "!templates/**/.DS_Store",
27
+ "!templates/apps/space"
27
28
  ],
28
29
  "scripts": {
29
30
  "test": "bun test",
@@ -11,6 +11,7 @@ import {
11
11
  copyTemplateFile,
12
12
  } from '../utils/copy-template'
13
13
  import { isVendorMode, VENDOR_PREFIX } from '../utils/subtree'
14
+ import { addVendoredApp, VENDORED_APPS, type VendoredApp } from '../utils/vendored-app'
14
15
 
15
16
  interface RegistryFile {
16
17
  path: string
@@ -66,7 +67,7 @@ interface RegistryManifest {
66
67
  * packages/infra/modules/. 'library': code the modules beside it import and
67
68
  * that defines no module — same directory shape, same install path, but
68
69
  * nothing to write an instance file for. 'app': a full package scaffolded
69
- * into targetDir (e.g. packages/inbox). */
70
+ * into targetDir (e.g. packages/warehouse). */
70
71
  kind?: RegistryKind
71
72
  description?: string
72
73
  files?: RegistryFile[]
@@ -306,9 +307,8 @@ async function installApp(
306
307
  console.log(`zbc add: ${registry.name} (app)`)
307
308
 
308
309
  // 1. Auto-vendor the infra modules this app depends on. One seen-set across
309
- // the whole list: `inbox` names `cloudflare-email` and `r2`, and both of
310
- // those now name `cloudflare-api` — a fresh walk per entry would install
311
- // it twice.
310
+ // the whole list: two of an app's modules routinely name the same library
311
+ // (`cloudflare-api`), and a fresh walk per entry would install it twice.
312
312
  const seen = new Set<string>()
313
313
  for (const dep of registry.modules ?? []) {
314
314
  if (seen.has(dep)) continue
@@ -394,7 +394,7 @@ export const addCommand = defineCommand({
394
394
  module: {
395
395
  type: 'positional',
396
396
  description:
397
- 'Module or app name (e.g. turso, cloudflare, cloudflare-email, r2, inbox, secret-relay, warehouse)',
397
+ 'Module or app name (e.g. turso, cloudflare, cloudflare-email, r2, secret-relay, warehouse, space)',
398
398
  required: true,
399
399
  },
400
400
  'account-id': {
@@ -411,6 +411,14 @@ export const addCommand = defineCommand({
411
411
  description: 'Collect missing registry-declared secrets via a Secret Request (default: true)',
412
412
  default: true,
413
413
  },
414
+ ref: {
415
+ type: 'string',
416
+ description: 'Vendored apps (space): the ref to pull (default: the newest version tag)',
417
+ },
418
+ 'app-url': {
419
+ type: 'string',
420
+ description: 'Vendored apps (space): pull from this repository instead (a fork)',
421
+ },
414
422
  },
415
423
  async run({ args }) {
416
424
  const name = args.module
@@ -422,6 +430,18 @@ export const addCommand = defineCommand({
422
430
  process.exit(1)
423
431
  }
424
432
 
433
+ // A vendored app is not in this package: it is pulled from its own public
434
+ // copy, so it is looked for by name before the bundled registry is.
435
+ const vendoredApp = VENDORED_APPS[name]
436
+ if (vendoredApp) {
437
+ await addVendored(vendoredApp, projectRoot, infraDir, {
438
+ ref: args.ref,
439
+ url: args['app-url'],
440
+ env: args.env,
441
+ })
442
+ return
443
+ }
444
+
425
445
  const source = await resolveModuleSource(projectRoot, name)
426
446
  const registry = (await Bun.file(
427
447
  path.join(source.dir, 'registry.json'),
@@ -458,6 +478,59 @@ export const addCommand = defineCommand({
458
478
  },
459
479
  })
460
480
 
481
+ /**
482
+ * `zbc add <vendored app>`: pull the app's public copy into the project as a
483
+ * subtree, then install the zbc modules its deploy builds from. Files only, as
484
+ * every `add` is: nothing is deployed, and what the pull left in the working
485
+ * tree (the workspace entry, the starting files, the stamp) is the operator's
486
+ * to read and commit.
487
+ */
488
+ async function addVendored(
489
+ app: VendoredApp,
490
+ projectRoot: string,
491
+ infraDir: string,
492
+ opts: { ref?: string; url?: string; env: string },
493
+ ): Promise<void> {
494
+ console.log(`zbc add: ${app.name} (vendored app, pulled into ${app.prefix}/)`)
495
+ let result: Awaited<ReturnType<typeof addVendoredApp>>
496
+ try {
497
+ result = await addVendoredApp(projectRoot, app, opts)
498
+ } catch (err) {
499
+ console.error(`✗ ${(err as Error).message}`)
500
+ process.exit(1)
501
+ }
502
+ console.log(` pulled ${result.ref} (${result.commit.slice(0, 12)}) as one squashed commit`)
503
+ for (const pattern of result.workspacesAdded) console.log(` workspace: ${pattern}`)
504
+
505
+ // The modules the app's deploy builds its instances from. One seen-set, as an
506
+ // app template's dependencies get.
507
+ const seen = new Set<string>()
508
+ for (const dep of result.manifest.modules ?? []) {
509
+ if (seen.has(dep)) continue
510
+ const depRegistry = await installModule(dep, projectRoot, infraDir, {
511
+ quietSkip: true,
512
+ seen,
513
+ asDependency: true,
514
+ })
515
+ if (depRegistry) console.log(` ↳ module its deploy uses: ${dep}`)
516
+ }
517
+
518
+ await run(projectRoot, 'bun', ['install'])
519
+
520
+ console.log('')
521
+ console.log(`✓ ${app.name} is at ${app.prefix}/, recorded in .zbc-vendor.json`)
522
+ if (result.starter.written.length > 0) {
523
+ console.log(
524
+ ` Starting files for the "${opts.env}" environment were written; they are yours to edit.`,
525
+ )
526
+ }
527
+ console.log(` Read ${app.prefix}/docs/install.md for what to fill in before the first apply.`)
528
+ console.log(' Review what the pull left in the working tree, and commit it.')
529
+ console.log(
530
+ ` Later: \`zbc update ${app.name}\` pulls a newer copy over it and keeps your edits.`,
531
+ )
532
+ }
533
+
461
534
  /** Post-install: collect the registry's declared secrets via a Secret Request.
462
535
  * A missing relay downgrades to instructions — `add` itself still succeeds. */
463
536
  async function collectDeclaredSecrets(
@@ -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')
@@ -2,7 +2,7 @@ import * as path from 'node:path'
2
2
  import { defineCommand } from 'citty'
3
3
  import { listActions, type ListedAction } from '../engine/actions'
4
4
  import { discoverInstances } from '../engine/discover'
5
- import { isEphemeral, resolveOrder } from '../engine/resolve'
5
+ import { isEphemeral, isRetained, resolveOrder } from '../engine/resolve'
6
6
  import { findProjectRoot } from '../utils/find-project-root'
7
7
  import { loadConfig } from '../utils/load-config'
8
8
 
@@ -11,7 +11,9 @@ export interface ListedInstance {
11
11
  name: string
12
12
  module: string
13
13
  ephemeral: boolean
14
- /** Whether the module defines `destroy` — i.e. whether `zbc destroy` reaches it. */
14
+ /** Set `retain: true`: `zbc destroy` leaves it standing. See `InstanceOptions.retain`. */
15
+ retain: boolean
16
+ /** Whether `zbc destroy` reaches it: the module defines `destroy` and the instance is not retained. */
15
17
  destroyable: boolean
16
18
  imports: string[]
17
19
  /** Operator-invoked verbs the module declares — see `zbc run`. Usually empty. */
@@ -63,6 +65,7 @@ export const listCommand = defineCommand({
63
65
  name: instance.name,
64
66
  module: instance.moduleName,
65
67
  ephemeral: isEphemeral(instance),
68
+ retain: isRetained(instance),
66
69
  destroyable: instance._definition.destroy !== undefined,
67
70
  imports: instance.imports.map((dep) => dep.name),
68
71
  actions: listActions(instance),
@@ -82,7 +85,7 @@ export const listCommand = defineCommand({
82
85
  for (const instance of listed) {
83
86
  const notes = [
84
87
  instance.ephemeral ? 'ephemeral' : '',
85
- instance.destroyable ? 'destroyable' : 'no destroy',
88
+ instance.retain ? 'retain' : instance.destroyable ? 'destroyable' : 'no destroy',
86
89
  instance.imports.length > 0 ? `imports: ${instance.imports.join(', ')}` : '',
87
90
  instance.actions.length > 0
88
91
  ? `actions: ${instance.actions.map((action) => action.name).join(', ')}`
@@ -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,10 +9,13 @@ 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,
14
17
  } from '../utils/subtree'
18
+ import { describeAppAudit, updateVendoredApp, VENDORED_APPS } from '../utils/vendored-app'
15
19
  import pkg from '../../package.json' with { type: 'json' }
16
20
 
17
21
  export const updateCommand = defineCommand({
@@ -20,6 +24,20 @@ export const updateCommand = defineCommand({
20
24
  description: `Bring the vendored zbc engine + built-in modules up to this CLI's version`,
21
25
  },
22
26
  args: {
27
+ app: {
28
+ type: 'positional',
29
+ description: `A vendored app to update instead of the engine (${Object.keys(VENDORED_APPS).join(', ')})`,
30
+ required: false,
31
+ },
32
+ ref: {
33
+ type: 'string',
34
+ description:
35
+ 'With an app: the ref to pull (default: the newest version tag; a branch pulls the newest commit)',
36
+ },
37
+ 'app-url': {
38
+ type: 'string',
39
+ description: 'With an app: pull from this repository instead (a fork)',
40
+ },
23
41
  'core-url': {
24
42
  type: 'string',
25
43
  description: `zbc-core repository (default: ${DEFAULT_CORE_URL})`,
@@ -37,10 +55,50 @@ export const updateCommand = defineCommand({
37
55
  async run({ args }) {
38
56
  const projectRoot = await findProjectRoot()
39
57
 
58
+ // A vendored app is updated by name, and only it: the engine's vintage is a
59
+ // separate pull of a separate repository, on its own versions.
60
+ if (args.app !== undefined) {
61
+ const app = VENDORED_APPS[args.app]
62
+ if (!app) {
63
+ console.error(
64
+ `✗ "${args.app}" is not a vendored app. Available: ${Object.keys(VENDORED_APPS).join(', ')}. Run \`zbc update\` alone for the engine and modules.`,
65
+ )
66
+ process.exit(1)
67
+ }
68
+ console.log(`zbc update: ${app.name} → ${app.prefix}`)
69
+ let result: Awaited<ReturnType<typeof updateVendoredApp>>
70
+ try {
71
+ result = await updateVendoredApp(projectRoot, app, { ref: args.ref, url: args['app-url'] })
72
+ } catch (err) {
73
+ console.error(`✗ ${(err as Error).message}`)
74
+ process.exit(1)
75
+ }
76
+ console.log(`✓ ${app.prefix} is on ${result.ref} (${result.commit.slice(0, 12)})`)
77
+ for (const pattern of result.workspacesAdded) console.log(` workspace added: ${pattern}`)
78
+ for (const line of describeAppAudit(app, result.audit)) console.log(line)
79
+ console.log(
80
+ ' Review the squash merge commit, commit .zbc-vendor.json, and run `bun install`.',
81
+ )
82
+ return
83
+ }
84
+
40
85
  // Copy mode used to be a dead end here — the only way to receive an engine
41
86
  // fix was a hand diff, which is how consumers ended up reimplementing what
42
87
  // we ship. The CLI carries the templates, so it can re-lay them in place.
43
88
  const stamp = await readStamp(projectRoot)
89
+ // The subtree prefix as git sees it: `vendor/zbc` at the top level,
90
+ // `deploy/zbc/vendor/zbc` for a project in a subfolder. Always derived; the
91
+ // stamp's copy is information, and a stale one is said and then ignored.
92
+ const prefix = gitPrefix(projectRoot)
93
+ const recordedPrefix = stamp?.mode === 'subtree' ? (stamp.prefix ?? VENDOR_PREFIX) : prefix
94
+ if (recordedPrefix !== prefix) {
95
+ console.warn(
96
+ `⚠ ${STAMP_FILE} records the subtree at ${recordedPrefix}/, but this project's is ${prefix}/ (the folder moved?) — using ${prefix}/.`,
97
+ )
98
+ console.warn(
99
+ ` git's subtree history names ${recordedPrefix}/, so a pull at ${prefix}/ may be refused as never added; re-vendor at ${prefix}/ if it is.`,
100
+ )
101
+ }
44
102
 
45
103
  if (!(await isVendorMode(projectRoot))) {
46
104
  // A stamp saying `subtree` with no engine under the prefix is the varnick
@@ -49,10 +107,16 @@ export const updateCommand = defineCommand({
49
107
  // record that this is a subtree project — so say what is wrong instead.
50
108
  if (stamp?.mode === 'subtree') {
51
109
  console.error(
52
- `✗ ${STAMP_FILE} says this project vendors zbc as a subtree, but ${VENDOR_PREFIX}/src is missing — the subtree never landed, or was removed.`,
110
+ `✗ ${STAMP_FILE} says this project vendors zbc as a subtree, but ${prefix}/src is missing — the subtree never landed, or was removed.`,
53
111
  )
112
+ // git subtree runs only at the top level; say how to get there from here.
113
+ const top = gitTopLevel(projectRoot)
114
+ const fromTop =
115
+ top === null || prefix === VENDOR_PREFIX
116
+ ? ''
117
+ : `-C ${JSON.stringify(path.relative(process.cwd(), top) || '.')} `
54
118
  console.error(
55
- ` Re-vendor it: git subtree add --prefix=${VENDOR_PREFIX} ${DEFAULT_CORE_URL} ${stamp.coreRef ?? coreRefForVersion(pkg.version)} --squash`,
119
+ ` Re-vendor it: git ${fromTop}subtree add --prefix=${prefix} ${DEFAULT_CORE_URL} ${stamp.coreRef ?? coreRefForVersion(pkg.version)} --squash`,
56
120
  )
57
121
  process.exit(1)
58
122
  }
@@ -100,19 +164,24 @@ export const updateCommand = defineCommand({
100
164
 
101
165
  const url = args['core-url'] ?? DEFAULT_CORE_URL
102
166
  const ref = args['core-ref'] ?? coreRefForVersion(pkg.version)
103
- console.log(`zbc update: ${url} @ ${ref} → ${VENDOR_PREFIX}`)
167
+ console.log(`zbc update: ${url} @ ${ref} → ${prefix}`)
104
168
  try {
105
169
  subtreePull(projectRoot, { url, ref })
106
170
  } catch (err) {
107
171
  console.error(`✗ ${(err as Error).message}`)
108
172
  process.exit(1)
109
173
  }
110
- await writeStamp(projectRoot, { mode: 'subtree', cliVersion: pkg.version, coreRef: ref })
111
- console.log('✓ vendor/zbc updated — review the squash merge commit and push')
174
+ await writeStamp(projectRoot, {
175
+ mode: 'subtree',
176
+ cliVersion: pkg.version,
177
+ coreRef: ref,
178
+ prefix,
179
+ })
180
+ console.log(`✓ ${prefix} updated — review the squash merge commit and push`)
112
181
 
113
182
  // The push direction nobody watches: files written inside the prefix.
114
183
  const foreign = await foreignVendorFiles(projectRoot)
115
- for (const line of describeForeignFiles(foreign)) console.warn(line)
184
+ for (const line of describeForeignFiles(foreign, prefix)) console.warn(line)
116
185
  if (args.strict && foreign.length > 0) process.exit(1)
117
186
  },
118
187
  })
@@ -3,7 +3,7 @@ import type { InstanceRunOptions } from './apply'
3
3
  import { discoverInstances } from './discover'
4
4
  import { withOnDemandImports } from './on-demand'
5
5
  import { createReadinessGate } from './readiness'
6
- import { resolveOrder } from './resolve'
6
+ import { isRetained, resolveOrder } from './resolve'
7
7
  import { createSecretOutputRegistry, redactError } from './secret-outputs'
8
8
  import { loadSecrets } from './secrets'
9
9
 
@@ -37,6 +37,8 @@ export async function destroyInstances(
37
37
  reversed = [found]
38
38
  }
39
39
 
40
+ const retained = new Set(instances.filter(isRetained).map((i) => i.name))
41
+
40
42
  // Outputs of instances applied on demand, shared across the whole run: a
41
43
  // credential minted for one teardown is the same credential for the next.
42
44
  const outputs = new Map<string, unknown>()
@@ -51,6 +53,20 @@ export async function destroyInstances(
51
53
  }
52
54
 
53
55
  for (const instance of reversed) {
56
+ // Before the destroy lookup, because a retained instance has none: the
57
+ // operator is owed the reason, and a request to destroy THIS instance by
58
+ // name is refused rather than reported as a skip that reads like success.
59
+ if (isRetained(instance)) {
60
+ if (opts.target) {
61
+ throw new Error(
62
+ `Instance "${instance.name}" sets retain: zbc destroy never deletes it. Remove retain ` +
63
+ `in a reviewed change first, or delete the resource in the provider by hand.`,
64
+ )
65
+ }
66
+ console.log(`⊘ ${instance.moduleName}:${instance.name} is retained, left standing`)
67
+ continue
68
+ }
69
+
54
70
  const { destroy } = instance._definition
55
71
  if (!destroy) {
56
72
  console.log(`⊘ ${instance.moduleName}:${instance.name} has no destroy — skipping`)
@@ -80,8 +96,13 @@ export async function destroyInstances(
80
96
  `${field} references instance "${ref.from}", whose outputs a targeted destroy will not create. ` +
81
97
  `Run \`zbc destroy <env>\` for the whole environment, which applies "${ref.from}" only to tear ` +
82
98
  `it down again, or apply "${ref.from}" yourself first.`,
99
+ // A retained import is applied like any other (its apply adopts the
100
+ // live resource), but this run will not tear it down, so the line
101
+ // must not say it will.
83
102
  afterApply: (name) =>
84
- `✓ ${name} applied — this destroy created it; the run tears it down below`,
103
+ retained.has(name)
104
+ ? `✓ ${name} applied, because ${instance.name}'s destroy reads it; it is retained, so this run leaves it standing`
105
+ : `✓ ${name} applied — this destroy created it; the run tears it down below`,
85
106
  },
86
107
  (ctx) => destroy(validatedConfig, ctx),
87
108
  )
@@ -97,6 +97,11 @@ export function isEphemeral(instance: ModuleInstance): boolean {
97
97
  return declared ?? legacyConfigEphemeral(instance.moduleName, instance.config)
98
98
  }
99
99
 
100
+ /** Whether `zbc destroy` must leave this instance's resource standing. See `InstanceOptions.retain`. */
101
+ export function isRetained(instance: ModuleInstance): boolean {
102
+ return (instance as { retain?: boolean }).retain === true
103
+ }
104
+
100
105
  /**
101
106
  * An ephemeral instance of a module with no `destroy` is a contradiction, and
102
107
  * the engine refuses it before it applies anything — including the instances
@@ -39,7 +39,7 @@ export async function detectMode(cwd: string): Promise<InitMode> {
39
39
  return {
40
40
  kind: 'incompatible',
41
41
  reason:
42
- 'package.json exists but has no `workspaces` field. v1 only supports greenfield or existing Bun workspaces. Add `"workspaces": ["packages/*"]` and re-run.',
42
+ 'package.json exists but has no `workspaces` field, so this is not a Bun workspace (a pnpm repo, say). Put the zbc project in a folder of its own instead — `zbc init <name> --subtree --dir deploy/zbc`, or run init from inside that folder — which leaves this package.json, its lockfile and node_modules alone. Or, for a Bun repo, add `"workspaces": ["packages/*"]` and re-run.',
43
43
  }
44
44
  }
45
45