toolcrib 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -79,6 +79,7 @@ toolcrib init
79
79
  toolcrib init --version 1.2.0 # a specific release instead of latest
80
80
  toolcrib init --situation new # greenfield project, no existing UI
81
81
  toolcrib init --situation refactor # adopting toolcrib into an existing app
82
+ toolcrib init --with-tests # also vendor the real component test suite
82
83
  ```
83
84
 
84
85
  What it does: downloads the requested release (`latest` by default),
@@ -100,6 +101,31 @@ argument.** It always vendors into `./toolcrib` relative to wherever you
100
101
  run it — there's no way to point it at, say, `./src/ui` instead. Run it
101
102
  from your project root.
102
103
 
104
+ #### `--with-tests`
105
+
106
+ toolcrib vendors component *source*, not an npm package — the real test
107
+ suite (Vitest + React Testing Library + jsdom) can't be vendored the same
108
+ unconditional way every other file is, since your project may not use
109
+ Vitest at all. `--with-tests` is opt-in: it stages the real test files
110
+ under `./toolcrib/__tests__/`, adds their peer dependencies (`vitest`,
111
+ `@testing-library/react`, etc.) to your `devDependencies`, and records that
112
+ this happened in `.toolcrib-lock.json` (`testsVersion`) so a later `toolcrib
113
+ merge` — no extra flag needed — keeps the vendored tests in sync
114
+ automatically alongside the core toolkit, once you've opted in.
115
+
116
+ If your project already uses Vitest, these run as-is. If it uses a
117
+ different test runner (Jest, etc.), **exclude `./toolcrib/__tests__/` from
118
+ that runner's own config before running your test suite** — a broad glob
119
+ could otherwise auto-discover these files and fail on missing Vitest
120
+ globals. Either way, they're real reference source: read them, run them, or
121
+ hand them to your AI assistant to adapt to whatever you actually use.
122
+
123
+ A `toolcrib/.toolcrib-tests-config.json` file is also vendored alongside
124
+ the lock file — it records the exact peer dependencies the test suite
125
+ declares, so a tool reading your project locally (e.g. a future
126
+ `toolcrib-mcp` capability) has something to check against without needing
127
+ network access. You shouldn't need to read or edit it directly.
128
+
103
129
  Nothing is written to your project yet — see [Reviewing and applying
104
130
  patches](#reviewing-and-applying-patches) below.
105
131
 
@@ -143,7 +169,7 @@ anything. It reports:
143
169
  - **Stale instruction-file blocks** — if the `<!-- toolcrib:managed:... -->`
144
170
  block in your `AGENTS.md`/`CLAUDE.md` was hand-edited instead of
145
171
  regenerated, or is out of date with your installed version.
146
- - **Whether a newer release is available.**
172
+ - **Whether a newer release is available** — and, when a known, fixed vulnerability affects your installed version specifically, its severity and a link to the fix (generated from real, fixed toolcrib CodeQL findings — see the project's own `AGENTS.md` for how).
147
173
  - **A `tsconfig.json` compatibility check** — if `moduleResolution` isn't
148
174
  set to `"bundler"`, `"node16"`, or `"nodenext"`, `import { ... } from
149
175
  '#toolcrib'` will run fine but your editor/`tsc` may falsely report
@@ -152,6 +178,9 @@ anything. It reports:
152
178
  project it'll remind you that any file rendering toolcrib components
153
179
  needs a `'use client'` directive, since Next's App Router treats
154
180
  components as server-only by default.
181
+ - **Vendored test-suite drift**, only if you've installed it via `--with-tests`
182
+ — reported separately from core drift, so the two never read as one
183
+ merged list.
155
184
 
156
185
  **`--reprint-managed-block [docId]`** re-prints the current managed block(s)
157
186
  to stdout instead of running the checks above — for re-injecting the
@@ -185,6 +214,10 @@ the new version ships — and sorts each file into one of three outcomes:
185
214
  explaining what upstream changed, so you (or your AI assistant) can
186
215
  reconcile it by hand.
187
216
 
217
+ If you installed the test suite via `toolcrib init --with-tests`, `merge`
218
+ keeps it in sync automatically — no separate flag needed here; it checks
219
+ `.toolcrib-lock.json` for you.
220
+
188
221
  As with `init`, nothing is written until you run `apply` afterward.
189
222
 
190
223
  ### `toolcrib versions`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "toolcrib",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "Bootstrap the toolcrib UI toolkit into your project",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -30,8 +30,8 @@
30
30
  "semver": "^7.6.0"
31
31
  },
32
32
  "devDependencies": {
33
- "@vitest/coverage-v8": "^4.1.10",
33
+ "@vitest/coverage-v8": "^5.0.0",
34
34
  "cross-spawn": "^7.0.6",
35
- "vitest": "^4.1.10"
35
+ "vitest": "^5.0.0"
36
36
  }
37
37
  }
@@ -1,9 +1,10 @@
1
1
  import path from 'node:path';
2
+ import semver from 'semver';
2
3
  import * as p from '@clack/prompts';
3
- import { fetchRelease } from '../lib/release.js';
4
+ import { fetchRelease, fetchTestsRelease } from '../lib/release.js';
4
5
  import { normalize } from '../lib/patches.js';
5
6
  import { readJsonIfExists, readLock, readTextIfExists, fileExists } from '../lib/project.js';
6
- import { fetchLatestVersion } from '../lib/github.js';
7
+ import { fetchLatestVersion, fetchSecurityAdvisories } from '../lib/github.js';
7
8
  import { MANAGED_DOCS, KNOWN_TARGET_FILES, listManagedBlocks } from '../lib/managedDocs.js';
8
9
  import { detectBundler } from '../lib/bundler.js';
9
10
  import { checkRootProviderWired } from '../lib/rootProvider.js';
@@ -53,6 +54,27 @@ export function checkTypeScriptAdopted(projectRoot) {
53
54
  return fileExists(path.join(projectRoot, 'tsconfig.json'));
54
55
  }
55
56
 
57
+ /**
58
+ * Which vendored files (under TOOLKIT_DIR) differ from what `release`
59
+ * actually shipped — shared by the core-toolkit drift check and the
60
+ * --with-tests drift check below, since both are the exact same
61
+ * "local vs. shipped, normalized" comparison over a different file set
62
+ * (test relPaths are already `__tests__/`-prefixed, same as init.js/
63
+ * merge.js's handling — see release.js's fetchTestsRelease).
64
+ */
65
+ function computeDrift(projectRoot, release) {
66
+ const drifted = [];
67
+ for (const relPath of release.allFiles()) {
68
+ const targetPath = path.join(projectRoot, TOOLKIT_DIR, relPath);
69
+ const local = readTextIfExists(targetPath);
70
+ const shipped = release.readFile(relPath);
71
+ if (normalize(local) !== normalize(shipped)) {
72
+ drifted.push(relPath);
73
+ }
74
+ }
75
+ return drifted;
76
+ }
77
+
56
78
  /**
57
79
  * Read-only drift check for managed <!-- toolcrib:managed:... --> blocks
58
80
  * inside AGENTS.md/CLAUDE.md — the same question the vendored-file drift
@@ -186,52 +208,121 @@ export async function doctorCommand(options = {}) {
186
208
 
187
209
  const spinner = p.spinner();
188
210
  spinner.start(`Checking against installed version v${lock.version}`);
189
- let release;
211
+ // Network-dependent section 1 of 2: drift check against the installed
212
+ // release. A failure here (rate limit, network down, bad release asset)
213
+ // should only skip *this* check, not abort bundler detection/root-provider
214
+ // check/etc. below — those are 100% local and would otherwise succeed.
215
+ // Also fetches the --with-tests artifact when lock.testsVersion is set —
216
+ // same "only skip this one check" failure isolation, independently of
217
+ // whether the core fetch itself succeeded.
218
+ let release = null;
219
+ let releaseFetchError = null;
220
+ let testsRelease = null;
221
+ let testsReleaseFetchError = null;
190
222
  try {
191
223
  release = await fetchRelease(lock.version);
192
224
  } catch (err) {
193
- spinner.stop('Failed to fetch release');
194
- throw err;
225
+ releaseFetchError = err;
195
226
  }
196
-
197
- const drifted = [];
198
- for (const relPath of release.allFiles()) {
199
- const targetPath = path.join(projectRoot, TOOLKIT_DIR, relPath);
200
- const local = readTextIfExists(targetPath);
201
- const shipped = release.readFile(relPath);
202
- if (normalize(local) !== normalize(shipped)) {
203
- drifted.push(relPath);
227
+ if (lock.testsVersion) {
228
+ try {
229
+ testsRelease = await fetchTestsRelease(lock.testsVersion);
230
+ } catch (err) {
231
+ testsReleaseFetchError = err;
204
232
  }
205
233
  }
206
- const managedBlockMessages = await checkManagedBlocks(projectRoot, release);
207
- await release.cleanup();
208
- spinner.stop('Drift check complete');
209
234
 
210
- if (drifted.length === 0) {
211
- p.log.success(`No local drift detected from v${lock.version}.`);
235
+ if (release) {
236
+ const drifted = computeDrift(projectRoot, release);
237
+ const managedBlockMessages = await checkManagedBlocks(projectRoot, release);
238
+ await release.cleanup();
239
+ spinner.stop('Drift check complete');
240
+
241
+ if (drifted.length === 0) {
242
+ p.log.success(`No local drift detected from v${lock.version}.`);
243
+ } else {
244
+ p.log.warn(
245
+ `${drifted.length} file(s) differ from the shipped v${lock.version}:\n` +
246
+ drifted.map((f) => ` ${f}`).join('\n')
247
+ );
248
+ }
249
+
250
+ if (managedBlockMessages.length === 0) {
251
+ p.log.success('No managed AGENTS.md/CLAUDE.md blocks found, or none have drifted.');
252
+ } else {
253
+ for (const message of managedBlockMessages) {
254
+ p.log[message.level](message.text);
255
+ }
256
+ }
212
257
  } else {
213
- p.log.warn(
214
- `${drifted.length} file(s) differ from the shipped v${lock.version}:\n` +
215
- drifted.map((f) => ` ${f}`).join('\n')
216
- );
258
+ spinner.stop('Drift check skipped');
259
+ p.log.warn(`Could not fetch v${lock.version} to check for drift: ${releaseFetchError.message}`);
217
260
  }
218
261
 
219
- if (managedBlockMessages.length === 0) {
220
- p.log.success('No managed AGENTS.md/CLAUDE.md blocks found, or none have drifted.');
221
- } else {
222
- for (const message of managedBlockMessages) {
223
- p.log[message.level](message.text);
262
+ // --with-tests drift check — only runs when lock.testsVersion is set
263
+ // (i.e. the test suite was ever vendored via `toolcrib init --with-tests`
264
+ // or kept in sync by a later `toolcrib merge`). Reported separately from
265
+ // the core-drift block above, worded distinctly, so a reader can't
266
+ // mistake test-source drift for core-toolkit drift or vice versa.
267
+ if (lock.testsVersion) {
268
+ if (testsRelease) {
269
+ const testsDrifted = computeDrift(projectRoot, testsRelease);
270
+ await testsRelease.cleanup();
271
+
272
+ if (testsDrifted.length === 0) {
273
+ p.log.success(`No local drift detected in the vendored test suite (v${lock.testsVersion}).`);
274
+ } else {
275
+ p.log.warn(
276
+ `${testsDrifted.length} test-suite file(s) differ from the shipped v${lock.testsVersion}:\n` +
277
+ testsDrifted.map((f) => ` ${f}`).join('\n')
278
+ );
279
+ }
280
+ } else {
281
+ p.log.warn(`Could not fetch test-suite v${lock.testsVersion} to check for drift: ${testsReleaseFetchError.message}`);
224
282
  }
225
283
  }
226
284
 
285
+ // Network-dependent section 2 of 2: "is a newer version available."
286
+ // Independent failure point from the drift check above (different
287
+ // GitHub endpoint, same rate limit) — same rule applies: a failure here
288
+ // shouldn't take out the local-only checks that follow.
227
289
  // fetchLatestVersion (GitHub's dedicated /releases/latest endpoint), not
228
290
  // listVersions — doctor only ever needs the single newest release to
229
291
  // compare against what's installed, not every release's full metadata.
230
- const newestVersion = await fetchLatestVersion();
231
- if (newestVersion !== lock.version) {
232
- p.log.info(`A newer version is available: v${newestVersion} (installed: v${lock.version}). Run 'toolcrib merge'.`);
233
- } else {
234
- p.log.info('You are on the latest release.');
292
+ try {
293
+ const newestVersion = await fetchLatestVersion();
294
+ if (newestVersion !== lock.version) {
295
+ p.log.info(`A newer version is available: v${newestVersion} (installed: v${lock.version}). Run 'toolcrib merge'.`);
296
+ } else {
297
+ p.log.info('You are on the latest release.');
298
+ }
299
+ } catch (err) {
300
+ p.log.warn(`Could not check for a newer release: ${err.message}`);
301
+ }
302
+
303
+ // Network-dependent section 3 of 3: security advisories, generated from
304
+ // real CodeQL findings (see scripts/generate-security-advisories.js).
305
+ // Independent failure point from the version check above -- this file
306
+ // always lives on the toolcrib repo's own main branch, never in a
307
+ // consumer's vendored copy (a frozen snapshot that structurally can't
308
+ // know about anything published after it), so it's fetched fresh on
309
+ // every run for the same reason fetchLatestVersion is. Enriches the
310
+ // version check above rather than replacing it: same underlying
311
+ // question ("is there a newer version worth getting"), this just says
312
+ // *why* when the answer is yes for a real, fixed vulnerability.
313
+ try {
314
+ const advisories = await fetchSecurityAdvisories();
315
+ const relevant = advisories
316
+ .filter((a) => semver.gt(a.fixedIn, lock.version))
317
+ .sort((a, b) => semver.compare(b.fixedIn, a.fixedIn));
318
+ for (const a of relevant) {
319
+ p.log.warn(
320
+ `Security: v${a.fixedIn} fixes a ${a.severity.toUpperCase()}-severity issue (installed: v${lock.version}) -- ` +
321
+ `${a.summary}\n ${a.url}\n Run 'toolcrib merge' to update.`
322
+ );
323
+ }
324
+ } catch (err) {
325
+ p.log.warn(`Could not check for security advisories: ${err.message}`);
235
326
  }
236
327
 
237
328
  if (!checkTypeScriptAdopted(projectRoot)) {
@@ -272,7 +363,7 @@ export async function doctorCommand(options = {}) {
272
363
  p.log.warn(
273
364
  "Root providers: couldn't find <ToolcribProvider> or a manual <ThemeProvider>/<ToastProvider>/<ToastContainer> " +
274
365
  'composition anywhere under src/. Every toolcrib component throws or silently no-ops without one of these ' +
275
- "wrapping your app root — see CORE.md §1. (Heuristic text scan — a false warning is possible if your root " +
366
+ "wrapping your app root — see CORE.md's Root Setup section. (Heuristic text scan — a false warning is possible if your root " +
276
367
  'setup uses an unusual file layout or a re-exported alias; verify directly if you believe it\'s already wired.)'
277
368
  );
278
369
  }
@@ -1,6 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import * as p from '@clack/prompts';
3
- import { fetchRelease } from '../lib/release.js';
3
+ import { fetchRelease, fetchTestsRelease } from '../lib/release.js';
4
+ import { resolveVersion } from '../lib/github.js';
4
5
  import { PendingChanges, joinPatchPath } from '../lib/patches.js';
5
6
  import { resolveDependencyDecisions, buildProposedPackageJson, mergeImportsField } from '../lib/deps.js';
6
7
  import { readJsonIfExists, readTextIfExists, fileExists, proposeGitignore, proposeLockUpdate } from '../lib/project.js';
@@ -40,11 +41,30 @@ export async function initCommand(options) {
40
41
 
41
42
  const spinner = p.spinner();
42
43
  spinner.start(`Resolving version "${options.version}"`);
43
- let release;
44
+ // Resolved once here, then passed as a concrete version string to both
45
+ // fetchRelease and (when --with-tests is set) fetchTestsRelease below —
46
+ // each independently resolving "latest" would risk a real, if narrow,
47
+ // race: a new release publishing between the two calls could pair a
48
+ // core zip from one version with a tests zip from another. Neither
49
+ // fetch function re-resolves once given an already-concrete version
50
+ // (see github.js's resolveVersion), so this costs no extra network call
51
+ // versus before.
52
+ let resolvedVersion, release, testsRelease;
44
53
  try {
45
- release = await fetchRelease(options.version);
54
+ resolvedVersion = await resolveVersion(options.version);
55
+ release = await fetchRelease(resolvedVersion);
56
+ if (options.withTests) {
57
+ testsRelease = await fetchTestsRelease(resolvedVersion);
58
+ }
46
59
  } catch (err) {
47
60
  spinner.stop(`Failed to resolve/download version "${options.version}"`);
61
+ // Real, found-by-review gap: if fetchRelease succeeded but
62
+ // fetchTestsRelease then threw, release's own temp directory was never
63
+ // cleaned up before this rethrow -- a real leak specifically on the
64
+ // --with-tests failure path. .catch(() => {}) on the cleanup itself:
65
+ // a cleanup failure here must never mask the original, more relevant
66
+ // error being thrown below it.
67
+ if (release) await release.cleanup().catch(() => {});
48
68
  throw err;
49
69
  }
50
70
  spinner.stop(`Resolved "${options.version}" → v${release.version}`);
@@ -64,6 +84,21 @@ export async function initCommand(options) {
64
84
  changes.propose(joinPatchPath(TOOLKIT_DIR, relPath), currentContent, proposedContent, relPath);
65
85
  }
66
86
 
87
+ // 1b. --with-tests: the optional test-suite artifact, staged the exact
88
+ // same way as core files above — every path testsRelease.allFiles()
89
+ // returns is already `__tests__/`-prefixed (see
90
+ // scripts/build-tests-release.js's own output layout), so proposing
91
+ // it into TOOLKIT_DIR lands it at ./toolcrib/__tests__/... alongside
92
+ // core source, one single vendored root rather than a second one.
93
+ if (testsRelease) {
94
+ for (const relPath of testsRelease.allFiles()) {
95
+ const proposedContent = testsRelease.readFile(relPath);
96
+ const targetPath = path.join(projectRoot, TOOLKIT_DIR, relPath);
97
+ const currentContent = readTextIfExists(targetPath);
98
+ changes.propose(joinPatchPath(TOOLKIT_DIR, relPath), currentContent, proposedContent, relPath);
99
+ }
100
+ }
101
+
67
102
  // 2. package.json — propose only the additions, never touch existing entries.
68
103
  const pkgPath = path.join(projectRoot, 'package.json');
69
104
  const userPkg = readJsonIfExists(pkgPath);
@@ -71,6 +106,7 @@ export async function initCommand(options) {
71
106
  p.log.error('No package.json found in the current directory. Run this from your project root.');
72
107
  process.exitCode = 1;
73
108
  await release.cleanup();
109
+ if (testsRelease) await testsRelease.cleanup();
74
110
  return;
75
111
  }
76
112
 
@@ -79,11 +115,24 @@ export async function initCommand(options) {
79
115
  ? buildProposedPackageJson(userPkg, depDecisions.toAdd)
80
116
  : userPkg;
81
117
 
118
+ // --with-tests: the test suite's own peerDependencies (vitest,
119
+ // testing-library, jsdom — see toolcrib-tests.config.json) go into
120
+ // devDependencies, not dependencies — dev tooling, not something a
121
+ // consumer's production bundle should carry. Applied on top of
122
+ // pkgWithDeps (core deps already merged), not a separate patch — see
123
+ // the "combined into one patch" note below.
124
+ const testsDepDecisions = testsRelease
125
+ ? resolveDependencyDecisions(pkgWithDeps, testsRelease.config.peerDependencies)
126
+ : null;
127
+ const pkgWithAllDeps = testsDepDecisions?.toAdd.length > 0
128
+ ? buildProposedPackageJson(pkgWithDeps, testsDepDecisions.toAdd, 'devDependencies')
129
+ : pkgWithDeps;
130
+
82
131
  // Combined into one patch against package.json — a second propose() call
83
132
  // for the same relPath would produce two independent diffs both based on
84
133
  // the original file, which can't both apply cleanly (see PendingChanges).
85
- const importsResult = mergeImportsField(pkgWithDeps, TOOLKIT_IMPORTS_ENTRY);
86
- if (depDecisions.toAdd.length > 0 || importsResult.changed) {
134
+ const importsResult = mergeImportsField(pkgWithAllDeps, TOOLKIT_IMPORTS_ENTRY);
135
+ if (depDecisions.toAdd.length > 0 || testsDepDecisions?.toAdd.length > 0 || importsResult.changed) {
87
136
  changes.propose(
88
137
  'package.json',
89
138
  readTextIfExists(pkgPath),
@@ -99,9 +148,40 @@ export async function initCommand(options) {
99
148
  }
100
149
 
101
150
  // 4. Version lockfile — the only piece of state persisted between runs.
102
- const lockChange = proposeLockUpdate(projectRoot, release.version);
151
+ // testsVersion is recorded alongside version only when --with-tests
152
+ // was actually passed — this is what lets merge later auto-detect
153
+ // "was the test suite installed" and keep it in sync without needing
154
+ // its own flag on every subsequent merge.
155
+ const lockChange = proposeLockUpdate(
156
+ projectRoot,
157
+ release.version,
158
+ testsRelease ? { testsVersion: testsRelease.version } : {}
159
+ );
103
160
  changes.propose(lockChange.relPath, lockChange.current, lockChange.proposed, '.toolcrib-lock.json');
104
161
 
162
+ // 4b. --with-tests: also vendor toolcrib-tests.config.json's own content
163
+ // (as .toolcrib-tests-config.json, alongside the lock file) -- not just
164
+ // the test files themselves. release.js's allFiles() deliberately
165
+ // excludes this filename from the file loop above (same reason
166
+ // fetchRelease's own allFiles() excludes toolcrib.config.json), since
167
+ // it's fetch-time metadata, not vendored source -- but its
168
+ // peerDependencies are the one piece of that metadata a later consumer
169
+ // (a toolcrib-mcp get_test_source tool, e.g.) has no other way to ever
170
+ // see, since toolcrib-mcp only ever reads what's already on disk in a
171
+ // vendored install, never a live fetch. Proposed unconditionally, like
172
+ // the lock file itself -- this is meta-configuration a consumer has no
173
+ // reason to hand-edit, not vendored source meant to be customized.
174
+ if (testsRelease) {
175
+ const testsConfigPath = 'toolcrib/.toolcrib-tests-config.json';
176
+ const proposedTestsConfig = JSON.stringify(testsRelease.config, null, 2) + '\n';
177
+ changes.propose(
178
+ testsConfigPath,
179
+ readTextIfExists(path.join(projectRoot, testsConfigPath)),
180
+ proposedTestsConfig,
181
+ '.toolcrib-tests-config.json'
182
+ );
183
+ }
184
+
105
185
  // 5. AI instruction file — always propose the "core" managed block. The
106
186
  // situational docs (new-app / refactor-app) need --situation since the
107
187
  // CLI can't infer which applies; without it, the outro just tells the
@@ -142,6 +222,7 @@ export async function initCommand(options) {
142
222
  }
143
223
 
144
224
  await release.cleanup();
225
+ if (testsRelease) await testsRelease.cleanup();
145
226
 
146
227
  if (changes.isEmpty()) {
147
228
  p.outro('Nothing to do — already up to date with this version.');
@@ -151,7 +232,7 @@ export async function initCommand(options) {
151
232
  const written = await changes.writeAll(projectRoot);
152
233
  p.log.success(`Staged ${changes.count()} change(s):\n${changes.summarize()}`);
153
234
 
154
- reportConflicts(depDecisions);
235
+ reportConflicts([...depDecisions.conflicts, ...(testsDepDecisions?.conflicts ?? [])]);
155
236
 
156
237
  const missingSituation = !situationDocId
157
238
  ? `\n\nThis staged a "core" block in ${targetFile}, but not a situational one — re-run with ` +
@@ -167,14 +248,27 @@ export async function initCommand(options) {
167
248
  `and everything else still applies cleanly.`
168
249
  : '';
169
250
 
251
+ // testsRelease is real, runnable Vitest + Testing Library source if this
252
+ // project already matches that stack (the low-friction default for a
253
+ // Vite-scaffolded project — see NEW_APP.md). If it doesn't — most
254
+ // commonly an existing Jest setup adopted via REFACTOR_APP.md — a broad
255
+ // test-runner glob could auto-discover these files and fail on missing
256
+ // Vitest globals; exclude ./toolcrib/__tests__/ from that config first.
257
+ const withTestsNote = testsRelease
258
+ ? `\n\nAlso staged the real component test suite under ./toolcrib/__tests__/ (Vitest + Testing Library). ` +
259
+ `If this project already uses Vitest, these run as-is. If it uses a different test runner (e.g. Jest), ` +
260
+ `exclude ./toolcrib/__tests__/ from that runner's own config before running your test suite, or it may ` +
261
+ `try to auto-discover these files and fail on missing Vitest globals — then adapt what you need by hand.`
262
+ : '';
263
+
170
264
  p.outro(
171
265
  `Review the patches in ./toolcrib-patches/, then run:\n` +
172
- ` toolcrib apply${missingSituation}${claudeStubNote}`
266
+ ` toolcrib apply${missingSituation}${claudeStubNote}${withTestsNote}`
173
267
  );
174
268
  }
175
269
 
176
- function reportConflicts(depDecisions) {
177
- if (depDecisions.conflicts.length === 0) return;
270
+ function reportConflicts(conflicts) {
271
+ if (conflicts.length === 0) return;
178
272
  // Matches doctor.js/merge.js: both set process.exitCode = 1 for their own
179
273
  // "needs a human/AI decision" states. init.js previously didn't, which
180
274
  // meant a real dependency conflict (e.g. a React major outside toolcrib's
@@ -184,8 +278,8 @@ function reportConflicts(depDecisions) {
184
278
  // enough if nothing downstream ever inspects stdout for it.
185
279
  process.exitCode = 1;
186
280
  p.log.warn(
187
- `${depDecisions.conflicts.length} dependency conflict(s) — not staged, needs your decision:\n` +
188
- depDecisions.conflicts
281
+ `${conflicts.length} dependency conflict(s) — not staged, needs your decision:\n` +
282
+ conflicts
189
283
  .map((c) => ` ${c.name}: you have ${c.userRange}, toolcrib needs ${c.requiredRange} (${c.reason})`)
190
284
  .join('\n')
191
285
  );
@@ -1,6 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import * as p from '@clack/prompts';
3
- import { fetchRelease } from '../lib/release.js';
3
+ import { fetchRelease, fetchTestsRelease } from '../lib/release.js';
4
+ import { resolveVersion } from '../lib/github.js';
4
5
  import { PendingChanges, normalize, joinPatchPath } from '../lib/patches.js';
5
6
  import { mergeImportsField } from '../lib/deps.js';
6
7
  import { fileExists, readJsonIfExists, readLock, readTextIfExists, proposeLockUpdate } from '../lib/project.js';
@@ -30,6 +31,105 @@ function classify(original, local, updated) {
30
31
  return 'conflict';
31
32
  }
32
33
 
34
+ /**
35
+ * The full four-way diff, applied per-file across one (oldRelease,
36
+ * newRelease) pair — extracted so both the core toolkit files and (when
37
+ * --with-tests was used) the vendored test-suite files run through the
38
+ * exact same logic rather than a second copy-pasted loop. Both file sets
39
+ * land under the same TOOLKIT_DIR: core relPaths have no prefix, test
40
+ * relPaths are already `__tests__/`-prefixed (see
41
+ * scripts/build-tests-release.js), so no separate target-directory
42
+ * parameter is needed here.
43
+ *
44
+ * Mutates `changes`/`conflicts` in place (matching this file's existing
45
+ * call-site style below) and returns per-call counts for the caller to
46
+ * fold into its own running totals.
47
+ */
48
+ function diffReleaseFiles(projectRoot, oldRelease, newRelease, changes, conflicts) {
49
+ let updatedCount = 0;
50
+ let keptCount = 0;
51
+ let deletedCount = 0;
52
+
53
+ // Found by review: allFiles() re-walks its temp directory recursively on
54
+ // every call (listFilesRecursive is not cached), so calling
55
+ // oldRelease.allFiles().includes(relPath)/newRelease.allFiles().includes(relPath)
56
+ // inside these loops' own bodies (below) re-did that full filesystem walk
57
+ // once per file — real O(n²) filesystem I/O for a release with hundreds
58
+ // of files, made worse now that --with-tests doubles how often this
59
+ // function runs per merge. Computed once, up front, as Sets for O(1)
60
+ // membership checks instead.
61
+ const oldFiles = new Set(oldRelease.allFiles());
62
+ const newFiles = new Set(newRelease.allFiles());
63
+
64
+ for (const relPath of newFiles) {
65
+ const targetPath = path.join(projectRoot, TOOLKIT_DIR, relPath);
66
+ const local = readTextIfExists(targetPath);
67
+ const updated = newRelease.readFile(relPath);
68
+ // A file that's new in this release won't exist in oldRelease — treat as empty original.
69
+ const original = oldFiles.has(relPath) ? oldRelease.readFile(relPath) : '';
70
+
71
+ const status = classify(original, local, updated);
72
+
73
+ switch (status) {
74
+ case 'unchanged':
75
+ case 'safe-update':
76
+ changes.propose(joinPatchPath(TOOLKIT_DIR, relPath), local, updated, relPath);
77
+ updatedCount++;
78
+ break;
79
+ case 'keep-local':
80
+ keptCount++;
81
+ break;
82
+ case 'conflict':
83
+ conflicts.push({ relPath, patchPath: joinPatchPath(TOOLKIT_DIR, relPath), original, local, updated });
84
+ break;
85
+ }
86
+ }
87
+
88
+ // A file present in oldRelease but absent from newRelease was removed
89
+ // upstream — e.g. useAnimatedMount.ts when Drawer moved to Radix
90
+ // Presence in v0.10.0. Without this pass, a vendored copy of a file
91
+ // upstream no longer ships just sits there forever, unreferenced but
92
+ // never cleaned up, since the loop above only ever visits paths that
93
+ // still exist in the *new* release. classify(original, local, '')
94
+ // reuses the same four-way logic as the update loop, treating "removed
95
+ // upstream" as updated content of '': local unmodified from original ->
96
+ // safe to delete; local modified -> a real conflict (don't silently
97
+ // discard someone's customization just because upstream dropped the
98
+ // file), same as any other conflicting edit.
99
+ for (const relPath of oldFiles) {
100
+ if (newFiles.has(relPath)) continue;
101
+
102
+ const targetPath = path.join(projectRoot, TOOLKIT_DIR, relPath);
103
+ if (!fileExists(targetPath)) continue; // already absent locally — nothing to propose
104
+ const local = readTextIfExists(targetPath);
105
+
106
+ const original = oldRelease.readFile(relPath);
107
+ const status = classify(original, local, '');
108
+
109
+ switch (status) {
110
+ case 'safe-update':
111
+ changes.propose(joinPatchPath(TOOLKIT_DIR, relPath), local, '', relPath);
112
+ deletedCount++;
113
+ break;
114
+ case 'conflict':
115
+ conflicts.push({
116
+ relPath,
117
+ patchPath: joinPatchPath(TOOLKIT_DIR, relPath),
118
+ original,
119
+ local,
120
+ updated: '',
121
+ removedUpstream: true,
122
+ });
123
+ break;
124
+ // 'unchanged'/'keep-local' can't occur here: original is always
125
+ // non-empty (relPath came from oldRelease.allFiles()) and updated is
126
+ // always '', so upstreamChanged is unconditionally true.
127
+ }
128
+ }
129
+
130
+ return { updatedCount, keptCount, deletedCount };
131
+ }
132
+
33
133
  /**
34
134
  * Same classify()-based logic as the vendored-files loop below, applied to
35
135
  * managed <!-- toolcrib:managed:... --> blocks inside AGENTS.md/CLAUDE.md
@@ -133,101 +233,77 @@ export async function mergeCommand(options) {
133
233
 
134
234
  const spinner = p.spinner();
135
235
  spinner.start(`Fetching current (v${lock.version}) and target (${options.version}) releases`);
136
- let oldRelease, newRelease;
236
+ // Resolved once, then reused as a concrete version for every fetch below
237
+ // that targets the "new" side — the same real, if narrow, race init.js
238
+ // guards against: two independent 'latest' resolutions could otherwise
239
+ // pair a core zip from one version with a tests zip from another if a
240
+ // new release publishes in between.
241
+ let resolvedVersion, oldRelease, newRelease, oldTestsRelease, newTestsRelease;
137
242
  try {
138
- [oldRelease, newRelease] = await Promise.all([
139
- fetchRelease(lock.version),
140
- fetchRelease(options.version),
141
- ]);
243
+ resolvedVersion = await resolveVersion(options.version);
244
+ const fetches = [fetchRelease(lock.version), fetchRelease(resolvedVersion)];
245
+ // Auto-continue: no --with-tests flag on merge itself — whether the
246
+ // test suite was ever installed is read straight from the lock file,
247
+ // so it stays in sync automatically once opted into via init, with no
248
+ // separate flag to remember on every later merge.
249
+ if (lock.testsVersion) {
250
+ fetches.push(fetchTestsRelease(lock.testsVersion), fetchTestsRelease(resolvedVersion));
251
+ }
252
+ // Promise.allSettled, not Promise.all — a real, found-by-review gap:
253
+ // Promise.all rejects and abandons immediately on the first failure,
254
+ // so any OTHER fetch among these 2-4 that had already resolved by then
255
+ // (its own real temp directory already on disk) was never cleaned up,
256
+ // permanently leaking it. allSettled waits for every fetch to finish
257
+ // one way or the other, so every successfully-resolved release can
258
+ // still be cleaned up before this function throws.
259
+ const settled = await Promise.allSettled(fetches);
260
+ const firstRejection = settled.find((r) => r.status === 'rejected');
261
+ if (firstRejection) {
262
+ await Promise.all(
263
+ settled.filter((r) => r.status === 'fulfilled').map((r) => r.value.cleanup().catch(() => {}))
264
+ );
265
+ throw firstRejection.reason;
266
+ }
267
+ const results = settled.map((r) => r.value);
268
+ [oldRelease, newRelease] = results;
269
+ if (lock.testsVersion) {
270
+ [oldTestsRelease, newTestsRelease] = results.slice(2);
271
+ }
142
272
  } catch (err) {
143
273
  spinner.stop('Failed to fetch releases');
144
274
  throw err;
145
275
  }
146
276
  spinner.stop(`Comparing v${oldRelease.version} → v${newRelease.version}`);
147
277
 
278
+ const cleanupAll = () =>
279
+ Promise.all([oldRelease.cleanup(), newRelease.cleanup(), oldTestsRelease?.cleanup(), newTestsRelease?.cleanup()].filter(Boolean));
280
+
148
281
  if (oldRelease.version === newRelease.version) {
149
282
  p.outro('Already on this version. Run `toolcrib doctor` to check for local drift instead.');
150
- await Promise.all([oldRelease.cleanup(), newRelease.cleanup()]);
283
+ await cleanupAll();
151
284
  return;
152
285
  }
153
286
 
154
287
  const changes = new PendingChanges();
155
288
  const conflicts = [];
156
- let updatedCount = 0;
157
- let keptCount = 0;
158
- let deletedCount = 0;
159
-
160
- for (const relPath of newRelease.allFiles()) {
161
- const targetPath = path.join(projectRoot, TOOLKIT_DIR, relPath);
162
- const local = readTextIfExists(targetPath);
163
- const updated = newRelease.readFile(relPath);
164
- // A file that's new in this release won't exist in oldRelease — treat as empty original.
165
- const original = oldRelease.allFiles().includes(relPath) ? oldRelease.readFile(relPath) : '';
166
289
 
167
- const status = classify(original, local, updated);
290
+ const coreDiff = diffReleaseFiles(projectRoot, oldRelease, newRelease, changes, conflicts);
291
+ let updatedCount = coreDiff.updatedCount;
292
+ let keptCount = coreDiff.keptCount;
293
+ let deletedCount = coreDiff.deletedCount;
168
294
 
169
- switch (status) {
170
- case 'unchanged':
171
- case 'safe-update':
172
- changes.propose(joinPatchPath(TOOLKIT_DIR, relPath), local, updated, relPath);
173
- updatedCount++;
174
- break;
175
- case 'keep-local':
176
- keptCount++;
177
- break;
178
- case 'conflict':
179
- conflicts.push({ relPath, patchPath: joinPatchPath(TOOLKIT_DIR, relPath), original, local, updated });
180
- break;
181
- }
182
- }
183
-
184
- // A file present in oldRelease but absent from newRelease was removed
185
- // upstream — e.g. useAnimatedMount.ts when Drawer moved to Radix
186
- // Presence in v0.10.0. Without this pass, a vendored copy of a file
187
- // upstream no longer ships just sits there forever, unreferenced but
188
- // never cleaned up, since the loop above only ever visits paths that
189
- // still exist in the *new* release. classify(original, local, '')
190
- // reuses the same four-way logic as the update loop, treating "removed
191
- // upstream" as updated content of '': local unmodified from original ->
192
- // safe to delete; local modified -> a real conflict (don't silently
193
- // discard someone's customization just because upstream dropped the
194
- // file), same as any other conflicting edit.
195
- for (const relPath of oldRelease.allFiles()) {
196
- if (newRelease.allFiles().includes(relPath)) continue;
197
-
198
- const targetPath = path.join(projectRoot, TOOLKIT_DIR, relPath);
199
- if (!fileExists(targetPath)) continue; // already absent locally — nothing to propose
200
- const local = readTextIfExists(targetPath);
201
-
202
- const original = oldRelease.readFile(relPath);
203
- const status = classify(original, local, '');
204
-
205
- switch (status) {
206
- case 'safe-update':
207
- changes.propose(joinPatchPath(TOOLKIT_DIR, relPath), local, '', relPath);
208
- deletedCount++;
209
- break;
210
- case 'conflict':
211
- conflicts.push({
212
- relPath,
213
- patchPath: joinPatchPath(TOOLKIT_DIR, relPath),
214
- original,
215
- local,
216
- updated: '',
217
- removedUpstream: true,
218
- });
219
- break;
220
- // 'unchanged'/'keep-local' can't occur here: original is always
221
- // non-empty (relPath came from oldRelease.allFiles()) and updated is
222
- // always '', so upstreamChanged is unconditionally true.
223
- }
295
+ if (oldTestsRelease && newTestsRelease) {
296
+ const testsDiff = diffReleaseFiles(projectRoot, oldTestsRelease, newTestsRelease, changes, conflicts);
297
+ updatedCount += testsDiff.updatedCount;
298
+ keptCount += testsDiff.keptCount;
299
+ deletedCount += testsDiff.deletedCount;
224
300
  }
225
301
 
226
302
  const managedBlockCounts = await mergeManagedBlocks(projectRoot, oldRelease, newRelease, changes, conflicts);
227
303
  updatedCount += managedBlockCounts.updatedCount;
228
304
  keptCount += managedBlockCounts.keptCount;
229
305
 
230
- await Promise.all([oldRelease.cleanup(), newRelease.cleanup()]);
306
+ await cleanupAll();
231
307
 
232
308
  // Installs from before the "imports" subpath entry existed won't have it —
233
309
  // propose adding it here too, not just on a fresh `init`.
@@ -254,9 +330,28 @@ export async function mergeCommand(options) {
254
330
  // installed, and a later `merge` would diff from the wrong baseline,
255
331
  // misclassifying every file that legitimately changed in this merge as
256
332
  // a local edit — and flagging false conflicts against it next time.
257
- const lockChange = proposeLockUpdate(projectRoot, newRelease.version);
333
+ const lockChange = proposeLockUpdate(
334
+ projectRoot,
335
+ newRelease.version,
336
+ lock.testsVersion ? { testsVersion: newRelease.version } : {}
337
+ );
258
338
  changes.propose(lockChange.relPath, lockChange.current, lockChange.proposed, '.toolcrib-lock.json');
259
339
 
340
+ // Keeps .toolcrib-tests-config.json in sync too, same reasoning and same
341
+ // unconditional-overwrite treatment as init.js's own step 4b — this is
342
+ // meta-configuration (peerDependencies) a tool like toolcrib-mcp reads
343
+ // directly off disk, not vendored source meant to be hand-customized.
344
+ if (newTestsRelease) {
345
+ const testsConfigPath = 'toolcrib/.toolcrib-tests-config.json';
346
+ const proposedTestsConfig = JSON.stringify(newTestsRelease.config, null, 2) + '\n';
347
+ changes.propose(
348
+ testsConfigPath,
349
+ readTextIfExists(path.join(projectRoot, testsConfigPath)),
350
+ proposedTestsConfig,
351
+ '.toolcrib-tests-config.json'
352
+ );
353
+ }
354
+
260
355
  // Conflicts get their own patch showing the *upstream* diff (local vs.
261
356
  // untouched), so the human/AI can see exactly what upstream changed
262
357
  // without it silently overwriting local customizations.
package/src/index.js CHANGED
@@ -55,6 +55,10 @@ program
55
55
  '--situation <situation>',
56
56
  'also stage the matching AGENTS.md/CLAUDE.md doc block: "new" (greenfield project) or "refactor" (adopting into an existing app)'
57
57
  )
58
+ .option(
59
+ '--with-tests',
60
+ 'also vendor the real component test suite (Vitest + Testing Library) into ./toolcrib/__tests__/ — see README for what this does and its test-runner-collision caveat'
61
+ )
58
62
  .action(async (options) => {
59
63
  await initCommand(options).catch(fail);
60
64
  });
package/src/lib/deps.js CHANGED
@@ -44,12 +44,19 @@ export function resolveDependencyDecisions(userPkg, requiredDeps) {
44
44
  return decisions;
45
45
  }
46
46
 
47
- /** Produce the proposed package.json content (as an object) reflecting toAdd only. */
48
- export function buildProposedPackageJson(userPkg, toAdd) {
47
+ /**
48
+ * Produce the proposed package.json content (as an object) reflecting
49
+ * toAdd only. `depsField` defaults to "dependencies" (core toolkit
50
+ * peerDependencies); init.js's --with-tests path passes "devDependencies"
51
+ * instead, since the test suite's own peer deps (vitest, testing-library,
52
+ * jsdom — see toolcrib-tests.config.json) are dev tooling, not something a
53
+ * consumer's production bundle should carry.
54
+ */
55
+ export function buildProposedPackageJson(userPkg, toAdd, depsField = 'dependencies') {
49
56
  const proposed = structuredClone(userPkg);
50
- proposed.dependencies ??= {};
57
+ proposed[depsField] ??= {};
51
58
  for (const { name, range } of toAdd) {
52
- proposed.dependencies[name] = range;
59
+ proposed[depsField][name] = range;
53
60
  }
54
61
  return proposed;
55
62
  }
package/src/lib/github.js CHANGED
@@ -2,7 +2,13 @@ import crypto from 'node:crypto';
2
2
 
3
3
  const REPO = 'escape-llc/toolcrib';
4
4
  const ASSET_NAME = 'toolcrib.zip';
5
- const CHECKSUM_ASSET_NAME = 'toolcrib.zip.sha256';
5
+
6
+ // Exported so release.js's fetchTestsRelease can request it by name without
7
+ // restringing 'toolcrib-tests.zip' a second time — the optional test-suite
8
+ // artifact scripts/build-tests-release.js/package-tests-release.js already
9
+ // build and release.yml already publishes on every release (see
10
+ // toolcrib init --with-tests).
11
+ export const TESTS_ASSET_NAME = 'toolcrib-tests.zip';
6
12
 
7
13
  // Optional overrides for tests/mirrors — unset in normal use, everything
8
14
  // targets real GitHub. Integration tests point these at a local server
@@ -88,6 +94,36 @@ export async function fetchLatestVersion() {
88
94
  return release.tag_name.replace(/^v/, '');
89
95
  }
90
96
 
97
+ /**
98
+ * Fetch security-advisories.json fresh from the toolcrib repo's own
99
+ * `main` branch -- never from a consumer's vendored copy, which is a
100
+ * frozen snapshot from whatever version they installed and structurally
101
+ * can't know about anything published after that (see
102
+ * scripts/generate-security-advisories.js for how the file itself is
103
+ * generated, from real CodeQL alert state, never hand-authored).
104
+ *
105
+ * Uses the Contents API's raw media type to get the file's bytes
106
+ * directly rather than base64-decoding the default JSON-wrapped
107
+ * response. A missing file (a fresh main with nothing published yet, or
108
+ * before this file's first commit) is treated as "no advisories," not an
109
+ * error -- unlike every other call in this file, absence here is the
110
+ * normal, expected starting state, not a failure.
111
+ *
112
+ * Public, unauthenticated read (unlike the generator script, which needs
113
+ * a token to read the code-scanning alerts API this file is derived
114
+ * from) -- a consumer's `doctor` run never needs credentials for this.
115
+ */
116
+ export async function fetchSecurityAdvisories() {
117
+ const res = await fetch(`${API_BASE}/repos/${REPO}/contents/security-advisories.json?ref=main`, {
118
+ headers: { Accept: 'application/vnd.github.raw+json' },
119
+ });
120
+
121
+ if (res.status === 404) return [];
122
+ if (!res.ok) throwGitHubApiError(res, 'security-advisories.json');
123
+
124
+ return JSON.parse(await res.text());
125
+ }
126
+
91
127
  function assetUrl(version, assetName) {
92
128
  return version === 'latest'
93
129
  ? `${RELEASES_BASE}/latest/download/${assetName}`
@@ -131,16 +167,23 @@ function sha256(buffer) {
131
167
  * mechanism was introduced — a failed fetch of it (missing, network
132
168
  * error, or an on-path actor blocking just that request) is treated
133
169
  * as an integrity failure, not tolerated as an older-release gap.
170
+ *
171
+ * `assetName` defaults to the core toolkit zip; release.js's
172
+ * fetchTestsRelease passes TESTS_ASSET_NAME to fetch the optional
173
+ * test-suite artifact via this exact same verified-download path instead
174
+ * of a parallel one — the checksum sibling is always `${assetName}.sha256`,
175
+ * the one naming convention both assets already share.
134
176
  */
135
- export async function downloadReleaseZip(version) {
136
- const zipUrl = assetUrl(version, ASSET_NAME);
137
- const checksumUrl = assetUrl(version, CHECKSUM_ASSET_NAME);
177
+ export async function downloadReleaseZip(version, assetName = ASSET_NAME) {
178
+ const checksumAssetName = `${assetName}.sha256`;
179
+ const zipUrl = assetUrl(version, assetName);
180
+ const checksumUrl = assetUrl(version, checksumAssetName);
138
181
 
139
182
  const [zipBuffer, checksumText] = await Promise.all([
140
183
  fetchBuffer(zipUrl),
141
184
  fetchText(checksumUrl).catch((err) => {
142
185
  throw new Error(
143
- `Failed to fetch checksum for ${ASSET_NAME} (${err.message}). ` +
186
+ `Failed to fetch checksum for ${assetName} (${err.message}). ` +
144
187
  `Refusing to install an unverified download.`
145
188
  );
146
189
  }),
@@ -150,7 +193,7 @@ export async function downloadReleaseZip(version) {
150
193
  const actual = sha256(zipBuffer);
151
194
  if (actual !== expected) {
152
195
  throw new Error(
153
- `Checksum mismatch for ${ASSET_NAME} (expected ${expected}, got ${actual}). ` +
196
+ `Checksum mismatch for ${assetName} (expected ${expected}, got ${actual}). ` +
154
197
  `The download may be corrupted or incomplete — try again.`
155
198
  );
156
199
  }
@@ -57,19 +57,34 @@ export function fileExists(filePath) {
57
57
 
58
58
  /**
59
59
  * The ONLY thing persisted locally between CLI runs is the installed
60
- * version string — no cached hashes, no file-by-file state. Everything
61
- * else is recomputed on demand against the immutable release artifacts,
62
- * which is what keeps merge/doctor correct regardless of local
63
- * environment quirks (line-ending drift, etc.) — see design notes.
60
+ * version string (plus, optionally, testsVersion — see below) — no cached
61
+ * hashes, no file-by-file state. Everything else is recomputed on demand
62
+ * against the immutable release artifacts, which is what keeps
63
+ * merge/doctor correct regardless of local environment quirks (line-ending
64
+ * drift, etc.) — see design notes.
64
65
  */
65
66
  export function readLock(projectRoot) {
66
67
  return readJsonIfExists(path.join(projectRoot, LOCK_PATH));
67
68
  }
68
69
 
69
- export function proposeLockUpdate(projectRoot, version) {
70
+ /**
71
+ * `extra` is merged into the written lock JSON alongside `version` —
72
+ * today, used only for `testsVersion` (recorded when `toolcrib init
73
+ * --with-tests` vendors the optional test-suite artifact, see
74
+ * lib/release.js's fetchTestsRelease). Omitted (the default), the output
75
+ * is exactly `{ version }`, unchanged from before this existed.
76
+ *
77
+ * Deliberately no implicit "preserve testsVersion unless told otherwise"
78
+ * behavior in here — a caller that wants to carry an existing testsVersion
79
+ * forward reads the current lock itself and passes it through explicitly
80
+ * via `extra`, keeping that decision visible at each call site rather than
81
+ * hidden inside this function, matching this file's own "recomputed on
82
+ * demand, nothing cached implicitly" design principle above.
83
+ */
84
+ export function proposeLockUpdate(projectRoot, version, extra = {}) {
70
85
  const lockPath = path.join(projectRoot, LOCK_PATH);
71
86
  const current = readTextIfExists(lockPath);
72
- const proposed = JSON.stringify({ version }, null, 2) + '\n';
87
+ const proposed = JSON.stringify({ version, ...extra }, null, 2) + '\n';
73
88
  return { relPath: LOCK_PATH, current, proposed };
74
89
  }
75
90
 
@@ -2,7 +2,7 @@ import fs from 'node:fs';
2
2
  import fsp from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import os from 'node:os';
5
- import { downloadReleaseZip, resolveVersion } from './github.js';
5
+ import { downloadReleaseZip, resolveVersion, TESTS_ASSET_NAME } from './github.js';
6
6
  import { extractZip, listFilesRecursive } from './zip.js';
7
7
 
8
8
  // See the matching stripBOM in lib/project.js for why this exists — Node's
@@ -26,10 +26,20 @@ export async function fetchRelease(version) {
26
26
  const zipBuffer = await downloadReleaseZip(resolvedVersion);
27
27
 
28
28
  const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'toolcrib-release-'));
29
- await extractZip(zipBuffer, tempDir);
30
29
 
31
- const configPath = path.join(tempDir, 'toolcrib.config.json');
32
- const config = JSON.parse(stripBOM(fs.readFileSync(configPath, 'utf-8')));
30
+ // Same real, found-by-review leak as fetchTestsRelease below (identical
31
+ // shape, pre-dating it): mkdtemp already created tempDir at this point --
32
+ // clean it up if extraction or config parsing fails, rather than leaking
33
+ // it every time this specific failure path is hit.
34
+ let config;
35
+ try {
36
+ await extractZip(zipBuffer, tempDir);
37
+ const configPath = path.join(tempDir, 'toolcrib.config.json');
38
+ config = JSON.parse(stripBOM(fs.readFileSync(configPath, 'utf-8')));
39
+ } catch (err) {
40
+ await fsp.rm(tempDir, { recursive: true, force: true }).catch(() => {});
41
+ throw err;
42
+ }
33
43
 
34
44
  return {
35
45
  version: resolvedVersion,
@@ -40,3 +50,56 @@ export async function fetchRelease(version) {
40
50
  cleanup: () => fsp.rm(tempDir, { recursive: true, force: true }),
41
51
  };
42
52
  }
53
+
54
+ /**
55
+ * Same shape as fetchRelease, pointed at the optional test-suite artifact
56
+ * (toolcrib-tests.zip / toolcrib-tests.config.json) instead of the core
57
+ * toolkit one — kept as its own function rather than a mode flag on
58
+ * fetchRelease, mirroring scripts/package-tests-release.js's own stated
59
+ * reasoning ("the two artifacts have independent failure modes worth
60
+ * seeing separately"). Every file this returns via allFiles()/readFile()
61
+ * is already `__tests__/`-prefixed, per build-tests-release.js's own
62
+ * output layout — callers propose them straight into TOOLKIT_DIR the same
63
+ * way core files are, landing at ./toolcrib/__tests__/...
64
+ *
65
+ * `version` must already be a concrete version string, not 'latest' —
66
+ * callers that need both a core and a tests release for the same install
67
+ * (init --with-tests, merge) must resolve 'latest' exactly once
68
+ * themselves (see github.js's resolveVersion) and pass the same resolved
69
+ * string to both fetchRelease and this function. Calling resolveVersion
70
+ * independently a second time here would re-hit GitHub's /releases/latest
71
+ * endpoint a moment later — a real, if narrow, race: a new release
72
+ * publishing in between could pair a core zip from one version with a
73
+ * tests zip from another.
74
+ */
75
+ export async function fetchTestsRelease(version) {
76
+ const zipBuffer = await downloadReleaseZip(version, TESTS_ASSET_NAME);
77
+
78
+ const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'toolcrib-tests-release-'));
79
+
80
+ // Real, found-by-review gap: mkdtemp already created tempDir on disk at
81
+ // this point -- if extractZip or the config parse below throws, the
82
+ // function would previously propagate that error before ever returning
83
+ // the object holding cleanup(), permanently leaking the temp directory.
84
+ // Clean up on that specific failure path, then rethrow the original error
85
+ // unchanged (the caller's own error message/handling is what matters,
86
+ // not this cleanup step).
87
+ let config;
88
+ try {
89
+ await extractZip(zipBuffer, tempDir);
90
+ const configPath = path.join(tempDir, 'toolcrib-tests.config.json');
91
+ config = JSON.parse(stripBOM(fs.readFileSync(configPath, 'utf-8')));
92
+ } catch (err) {
93
+ await fsp.rm(tempDir, { recursive: true, force: true }).catch(() => {});
94
+ throw err;
95
+ }
96
+
97
+ return {
98
+ version,
99
+ config,
100
+ tempDir,
101
+ readFile: (relPath) => stripBOM(fs.readFileSync(path.join(tempDir, relPath), 'utf-8')),
102
+ allFiles: () => listFilesRecursive(tempDir).filter((f) => f !== 'toolcrib-tests.config.json'),
103
+ cleanup: () => fsp.rm(tempDir, { recursive: true, force: true }),
104
+ };
105
+ }
@@ -41,7 +41,7 @@ function listCandidateFiles(rootDir) {
41
41
  * Read-only heuristic: does this project's own source wire up toolcrib's
42
42
  * root providers, via `<ToolcribProvider>` or the equivalent manual
43
43
  * `<ThemeProvider>` + `<ToastProvider>` + `<ToastContainer>` composition?
44
- * Both are legitimate per `CORE.md` §1 -- this doesn't prefer one, it just
44
+ * Both are legitimate per `CORE.md`'s Root Setup section -- this doesn't prefer one, it just
45
45
  * confirms *something* is wired, since every toolcrib component throws or
46
46
  * silently no-ops without it, and that failure mode gives no clue back to
47
47
  * "you forgot the root setup."