@zabaca/zbc 0.25.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 (44) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/package.json +1 -1
  3. package/src/commands/init.ts +105 -10
  4. package/src/commands/update.ts +33 -6
  5. package/src/utils/detect-mode.ts +1 -1
  6. package/src/utils/host-workspaces.ts +57 -0
  7. package/src/utils/subtree.ts +54 -15
  8. package/src/utils/vendor-audit.ts +12 -8
  9. package/src/utils/vendor-stamp.ts +10 -0
  10. package/src/utils/vendored-app.ts +3 -0
  11. package/templates/apps/walgit/CONTEXT.md +45 -4
  12. package/templates/apps/walgit/README.md +394 -11
  13. package/templates/apps/walgit/shared/browse.ts +61 -0
  14. package/templates/apps/walgit/shared/capabilities.ts +26 -0
  15. package/templates/apps/walgit/shared/container-env.ts +12 -0
  16. package/templates/apps/walgit/shared/container-lifecycle.ts +1 -1
  17. package/templates/apps/walgit/shared/credentials.ts +4 -0
  18. package/templates/apps/walgit/shared/events.ts +35 -1
  19. package/templates/apps/walgit/shared/instructions.ts +4 -1
  20. package/templates/apps/walgit/shared/landing.ts +2 -1
  21. package/templates/apps/walgit/shared/llms.ts +73 -5
  22. package/templates/apps/walgit/shared/mcp.ts +19 -3
  23. package/templates/apps/walgit/shared/protocol.ts +40 -3
  24. package/templates/apps/walgit/shared/repo-list.ts +46 -6
  25. package/templates/apps/walgit/shared/scoped-token.ts +500 -0
  26. package/templates/apps/walgit/shared/token-revocation.ts +134 -0
  27. package/templates/apps/walgit/shared/wal-index.ts +19 -0
  28. package/templates/apps/walgit/shared/webhook.ts +281 -0
  29. package/templates/apps/walgit/src/admin.ts +510 -0
  30. package/templates/apps/walgit/src/announce-main.ts +17 -9
  31. package/templates/apps/walgit/src/announce.ts +86 -0
  32. package/templates/apps/walgit/src/browse.ts +255 -2
  33. package/templates/apps/walgit/src/cli.ts +140 -0
  34. package/templates/apps/walgit/src/expire.ts +5 -0
  35. package/templates/apps/walgit/src/git.ts +103 -0
  36. package/templates/apps/walgit/src/hook-main.ts +6 -3
  37. package/templates/apps/walgit/src/http.ts +563 -3
  38. package/templates/apps/walgit/src/limits.ts +3 -0
  39. package/templates/apps/walgit/src/merge.ts +525 -0
  40. package/templates/apps/walgit/src/rate-limit.ts +51 -14
  41. package/templates/apps/walgit/src/server.ts +65 -1
  42. package/templates/apps/walgit/worker/events-do.ts +218 -3
  43. package/templates/apps/walgit/worker/index.ts +134 -9
  44. package/templates/apps/walgit/worker/mcp.ts +17 -2
package/CHANGELOG.md CHANGED
@@ -5,6 +5,23 @@ 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
+
8
25
  ## 0.25.0
9
26
 
10
27
  ### 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.26.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,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,
@@ -83,6 +86,19 @@ export const updateCommand = defineCommand({
83
86
  // fix was a hand diff, which is how consumers ended up reimplementing what
84
87
  // we ship. The CLI carries the templates, so it can re-lay them in place.
85
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
+ }
86
102
 
87
103
  if (!(await isVendorMode(projectRoot))) {
88
104
  // A stamp saying `subtree` with no engine under the prefix is the varnick
@@ -91,10 +107,16 @@ export const updateCommand = defineCommand({
91
107
  // record that this is a subtree project — so say what is wrong instead.
92
108
  if (stamp?.mode === 'subtree') {
93
109
  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.`,
110
+ `✗ ${STAMP_FILE} says this project vendors zbc as a subtree, but ${prefix}/src is missing — the subtree never landed, or was removed.`,
95
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) || '.')} `
96
118
  console.error(
97
- ` 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`,
98
120
  )
99
121
  process.exit(1)
100
122
  }
@@ -142,19 +164,24 @@ export const updateCommand = defineCommand({
142
164
 
143
165
  const url = args['core-url'] ?? DEFAULT_CORE_URL
144
166
  const ref = args['core-ref'] ?? coreRefForVersion(pkg.version)
145
- console.log(`zbc update: ${url} @ ${ref} → ${VENDOR_PREFIX}`)
167
+ console.log(`zbc update: ${url} @ ${ref} → ${prefix}`)
146
168
  try {
147
169
  subtreePull(projectRoot, { url, ref })
148
170
  } catch (err) {
149
171
  console.error(`✗ ${(err as Error).message}`)
150
172
  process.exit(1)
151
173
  }
152
- await writeStamp(projectRoot, { mode: 'subtree', cliVersion: pkg.version, coreRef: ref })
153
- 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`)
154
181
 
155
182
  // The push direction nobody watches: files written inside the prefix.
156
183
  const foreign = await foreignVendorFiles(projectRoot)
157
- for (const line of describeForeignFiles(foreign)) console.warn(line)
184
+ for (const line of describeForeignFiles(foreign, prefix)) console.warn(line)
158
185
  if (args.strict && foreign.length > 0) process.exit(1)
159
186
  },
160
187
  })
@@ -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
 
@@ -0,0 +1,57 @@
1
+ import * as path from 'node:path'
2
+ import { parse as parseYaml } from 'yaml'
3
+
4
+ /**
5
+ * The workspace globs a repository's own package manager reads: the root
6
+ * `package.json` `workspaces` (npm, Yarn, Bun) and `pnpm-workspace.yaml`
7
+ * `packages` (pnpm). A missing or unreadable file contributes none.
8
+ */
9
+ export async function hostWorkspaceGlobs(repoTop: string): Promise<string[]> {
10
+ const globs: string[] = []
11
+ const pkgFile = Bun.file(path.join(repoTop, 'package.json'))
12
+ if (await pkgFile.exists()) {
13
+ try {
14
+ const pkg = (await pkgFile.json()) as { workspaces?: string[] | { packages?: string[] } }
15
+ const ws = Array.isArray(pkg.workspaces) ? pkg.workspaces : (pkg.workspaces?.packages ?? [])
16
+ globs.push(...ws.filter((g): g is string => typeof g === 'string'))
17
+ } catch {
18
+ // Not ours to diagnose: detect-mode reports an unreadable manifest.
19
+ }
20
+ }
21
+ const pnpmFile = Bun.file(path.join(repoTop, 'pnpm-workspace.yaml'))
22
+ if (await pnpmFile.exists()) {
23
+ try {
24
+ const doc = parseYaml(await pnpmFile.text()) as { packages?: unknown } | null
25
+ if (Array.isArray(doc?.packages)) {
26
+ globs.push(...doc.packages.filter((g): g is string => typeof g === 'string'))
27
+ }
28
+ } catch {
29
+ // An unparseable pnpm-workspace.yaml is pnpm's to complain about.
30
+ }
31
+ }
32
+ return globs
33
+ }
34
+
35
+ // `./apps/*/` and `apps/*` are the same glob to a package manager.
36
+ const strip = (glob: string) => glob.replace(/^\.\//, '').replace(/\/+$/, '')
37
+
38
+ /**
39
+ * The host globs that cover the zbc project folder (`subdir`, top-level
40
+ * relative) or the `packages/infra` package inside it — either one is a
41
+ * package the host's package manager would try to install and link. A `!`
42
+ * glob that excludes the path wins, as it does for pnpm and Yarn.
43
+ */
44
+ export async function hostWorkspaceGlobsCovering(
45
+ repoTop: string,
46
+ subdir: string,
47
+ ): Promise<string[]> {
48
+ const globs = await hostWorkspaceGlobs(repoTop)
49
+ const includes = globs.filter((g) => !g.startsWith('!')).map(strip)
50
+ const excludes = globs.filter((g) => g.startsWith('!')).map((g) => strip(g.slice(1)))
51
+ const candidates = [subdir, `${subdir}/packages/infra`]
52
+ return includes.filter((glob) =>
53
+ candidates.some(
54
+ (dir) => new Bun.Glob(glob).match(dir) && !excludes.some((ex) => new Bun.Glob(ex).match(dir)),
55
+ ),
56
+ )
57
+ }
@@ -1,4 +1,5 @@
1
1
  import { spawnSync } from 'node:child_process'
2
+ import * as fs from 'node:fs'
2
3
  import * as path from 'node:path'
3
4
 
4
5
  /**
@@ -45,9 +46,43 @@ export function ensureCleanGitTree(cwd: string): void {
45
46
  }
46
47
 
47
48
  /**
48
- * Where a subtree lands. The engine's is `vendor/zbc`, the default; a vendored
49
- * app names its own (`vendor/space`), so one project can hold several subtrees
50
- * and each pull only ever touches its own prefix.
49
+ * The repository's top level, or null outside a git work tree. A zbc project
50
+ * may be a subfolder of a larger repository (a pnpm monorepo adopting zbc in
51
+ * `deploy/zbc/`), and git's own paths are the top level's, not the project's.
52
+ */
53
+ export function gitTopLevel(cwd: string): string | null {
54
+ const res = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8' })
55
+ if (res.status !== 0 || res.error) return null
56
+ return res.stdout.trim() || null
57
+ }
58
+
59
+ /** The project root relative to the top level, posix-style; '' at the top level or outside git. */
60
+ export function projectSubdir(projectRoot: string): string {
61
+ const top = gitTopLevel(projectRoot)
62
+ if (top === null) return ''
63
+ // Both sides through realpath: git reports the resolved top level, and a
64
+ // project reached through a symlink (macOS's /tmp) would otherwise climb out.
65
+ const rel = path.relative(fs.realpathSync(top), fs.realpathSync(projectRoot))
66
+ return rel.split(path.sep).join('/')
67
+ }
68
+
69
+ /**
70
+ * Where git sees a project-relative path: `vendor/zbc` in a project at the top
71
+ * level, `deploy/zbc/vendor/zbc` in one at `deploy/zbc/`. Derived on every
72
+ * call, never stored, so a project folder that moves keeps working. Outside a
73
+ * git work tree it is the project-relative path unchanged.
74
+ */
75
+ export function gitPrefix(projectRoot: string, prefix: string = VENDOR_PREFIX): string {
76
+ const sub = projectSubdir(projectRoot)
77
+ return sub === '' ? prefix : path.posix.join(sub, prefix)
78
+ }
79
+
80
+ /**
81
+ * Where a subtree lands, relative to the project root. The engine's is
82
+ * `vendor/zbc`, the default; a vendored app names its own (`vendor/space`), so
83
+ * one project can hold several subtrees and each pull only ever touches its own
84
+ * prefix. `git subtree` refuses to run anywhere but the top level, so these
85
+ * resolve the top level and the prefix as git sees it themselves.
51
86
  */
52
87
  interface SubtreeOptions {
53
88
  url: string
@@ -55,31 +90,35 @@ interface SubtreeOptions {
55
90
  prefix?: string
56
91
  }
57
92
 
93
+ function subtree(projectRoot: string, verb: 'add' | 'pull', opts: SubtreeOptions): void {
94
+ ensureCleanGitTree(projectRoot)
95
+ const top = gitTopLevel(projectRoot) ?? projectRoot
96
+ const prefix = gitPrefix(projectRoot, opts.prefix ?? VENDOR_PREFIX)
97
+ git(top, ['subtree', verb, `--prefix=${prefix}`, opts.url, opts.ref, '--squash'])
98
+ }
99
+
58
100
  /** Vendor a repository at the prefix (squashed). One commit, reversible via git. */
59
- export function subtreeAdd(cwd: string, opts: SubtreeOptions): void {
60
- ensureCleanGitTree(cwd)
61
- const prefix = opts.prefix ?? VENDOR_PREFIX
62
- git(cwd, ['subtree', 'add', `--prefix=${prefix}`, opts.url, opts.ref, '--squash'])
101
+ export function subtreeAdd(projectRoot: string, opts: SubtreeOptions): void {
102
+ subtree(projectRoot, 'add', opts)
63
103
  }
64
104
 
65
105
  /** Pull a newer ref into the prefix (squashed merge). */
66
- export function subtreePull(cwd: string, opts: SubtreeOptions): void {
67
- ensureCleanGitTree(cwd)
68
- const prefix = opts.prefix ?? VENDOR_PREFIX
69
- git(cwd, ['subtree', 'pull', `--prefix=${prefix}`, opts.url, opts.ref, '--squash'])
106
+ export function subtreePull(projectRoot: string, opts: SubtreeOptions): void {
107
+ subtree(projectRoot, 'pull', opts)
70
108
  }
71
109
 
72
110
  /**
73
111
  * The upstream commit a prefix was last pulled at, read from git's own record:
74
112
  * every squashed `subtree add` and `subtree pull` writes a commit whose message
75
113
  * carries `git-subtree-dir` and `git-subtree-split`. Null when the prefix was
76
- * never vendored as a subtree in this history.
114
+ * never vendored as a subtree in this history. `prefix` is project-relative;
115
+ * git recorded the top-level-relative one.
77
116
  */
78
- export function subtreeSplitCommit(cwd: string, prefix: string): string | null {
79
- const escaped = prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
117
+ export function subtreeSplitCommit(projectRoot: string, prefix: string): string | null {
118
+ const escaped = gitPrefix(projectRoot, prefix).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
80
119
  let body: string
81
120
  try {
82
- body = git(cwd, ['log', '-1', `--grep=^git-subtree-dir: ${escaped}/*$`, '--format=%B'])
121
+ body = git(projectRoot, ['log', '-1', `--grep=^git-subtree-dir: ${escaped}/*$`, '--format=%B'])
83
122
  } catch {
84
123
  return null
85
124
  }
@@ -3,7 +3,7 @@ import type { Dirent } from 'node:fs'
3
3
  import * as fs from 'node:fs/promises'
4
4
  import * as path from 'node:path'
5
5
  import { templatesRoot } from './copy-template'
6
- import { VENDOR_PREFIX } from './subtree'
6
+ import { gitPrefix, gitTopLevel, VENDOR_PREFIX } from './subtree'
7
7
 
8
8
  /**
9
9
  * The reverse drift hazard: files a consumer wrote *inside* `vendor/zbc/`.
@@ -23,15 +23,18 @@ import { VENDOR_PREFIX } from './subtree'
23
23
  * vendor/zbc cannot, and must not be reported as consumer-authored.
24
24
  */
25
25
  function trackedVendorFiles(projectRoot: string): string[] {
26
- const res = spawnSync('git', ['ls-files', '-z', '--', VENDOR_PREFIX], {
27
- cwd: projectRoot,
26
+ // Asked at the top level with the prefix as git sees it, so the listing is
27
+ // the same whether the project is the repository or a subfolder of one.
28
+ const prefix = gitPrefix(projectRoot)
29
+ const res = spawnSync('git', ['ls-files', '-z', '--', prefix], {
30
+ cwd: gitTopLevel(projectRoot) ?? projectRoot,
28
31
  encoding: 'utf8',
29
32
  })
30
33
  if (res.status !== 0 || res.error) return []
31
34
  return res.stdout
32
35
  .split('\0')
33
36
  .filter((line) => line.length > 0)
34
- .map((line) => path.posix.relative(VENDOR_PREFIX, line))
37
+ .map((line) => path.posix.relative(prefix, line))
35
38
  }
36
39
 
37
40
  async function walk(root: string, base = ''): Promise<string[]> {
@@ -62,11 +65,12 @@ export async function foreignVendorFiles(projectRoot: string): Promise<string[]>
62
65
  return vendored.filter((rel) => !rel.endsWith('.test.ts') && !upstream.has(rel)).toSorted()
63
66
  }
64
67
 
65
- export function describeForeignFiles(files: string[]): string[] {
68
+ /** `prefix` is the one to name: the top-level-relative prefix when the project is a subfolder. */
69
+ export function describeForeignFiles(files: string[], prefix: string = VENDOR_PREFIX): string[] {
66
70
  if (files.length === 0) return []
67
71
  return [
68
- `⚠ ${files.length} file(s) under ${VENDOR_PREFIX}/ are not shipped by zbc-core at that path:`,
69
- ...files.map((f) => ` ${VENDOR_PREFIX}/${f}`),
70
- ` ${VENDOR_PREFIX}/ is upstream's — \`git subtree push\` would carry these into zbc-core. Move consumer-authored files outside the prefix (e.g. docs/ or packages/infra/).`,
72
+ `⚠ ${files.length} file(s) under ${prefix}/ are not shipped by zbc-core at that path:`,
73
+ ...files.map((f) => ` ${prefix}/${f}`),
74
+ ` ${prefix}/ is upstream's — \`git subtree push\` would carry these into zbc-core. Move consumer-authored files outside the prefix (e.g. docs/ or packages/infra/).`,
71
75
  ]
72
76
  }
@@ -27,6 +27,13 @@ export interface VendorStamp {
27
27
  cliVersion: string
28
28
  /** zbc-core ref pulled, for subtree mode. */
29
29
  coreRef?: string
30
+ /**
31
+ * The subtree prefix as git saw it, recorded for information only when the
32
+ * project is a subfolder of its repository (`deploy/zbc/vendor/zbc`); absent
33
+ * means `vendor/zbc`. The commands always derive it again, and `zbc update`
34
+ * warns when the two disagree (the folder was moved).
35
+ */
36
+ prefix?: string
30
37
  /** ISO timestamp of the vendoring. */
31
38
  vendoredAt: string
32
39
  }
@@ -47,6 +54,7 @@ export async function readStamp(projectRoot: string): Promise<VendorStamp | null
47
54
  mode: raw.mode,
48
55
  cliVersion: raw.cliVersion,
49
56
  coreRef: typeof raw.coreRef === 'string' ? raw.coreRef : undefined,
57
+ prefix: typeof raw.prefix === 'string' ? raw.prefix : undefined,
50
58
  vendoredAt: typeof raw.vendoredAt === 'string' ? raw.vendoredAt : '',
51
59
  }
52
60
  } catch {
@@ -62,6 +70,8 @@ export async function writeStamp(
62
70
  mode: stamp.mode,
63
71
  cliVersion: stamp.cliVersion,
64
72
  ...(stamp.coreRef ? { coreRef: stamp.coreRef } : {}),
73
+ // A project at the top level writes exactly the stamp it always did.
74
+ ...(stamp.prefix && stamp.prefix !== VENDOR_PREFIX ? { prefix: stamp.prefix } : {}),
65
75
  vendoredAt: stamp.vendoredAt ?? new Date().toISOString(),
66
76
  }
67
77
  // The engine's stamp and the vendored apps' share the file, and each writer
@@ -223,6 +223,9 @@ export function auditVendoredApp(
223
223
  return map
224
224
  }
225
225
  const upstream = blobs(upstreamListing, '')
226
+ // Asked from the project root, where git takes and prints paths relative to
227
+ // that folder: `vendor/space` holds whether the project is the repository or
228
+ // a subfolder of one.
226
229
  const local = blobs(git(projectRoot, ['ls-files', '-s', '-z', '--', app.prefix]), app.prefix)
227
230
  const own = [...local.keys()].filter((file) => !upstream.has(file)).toSorted()
228
231
  const edited = [...local.keys()]