toolcrib 0.1.1 → 0.3.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
@@ -141,6 +141,16 @@ anything. It reports:
141
141
  needs a `'use client'` directive, since Next's App Router treats
142
142
  components as server-only by default.
143
143
 
144
+ **`--reprint-managed-block [docId]`** re-prints the current managed block(s)
145
+ to stdout instead of running the checks above — for re-injecting the
146
+ primer into an agent session that's lost it to context compaction,
147
+ without starting a new session:
148
+
149
+ ```bash
150
+ toolcrib doctor --reprint-managed-block # every block found
151
+ toolcrib doctor --reprint-managed-block core # just one docId
152
+ ```
153
+
144
154
  ### `toolcrib merge`
145
155
 
146
156
  Stages an upgrade from your currently installed version to another.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "toolcrib",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "Bootstrap the toolcrib UI toolkit into your project",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -2,10 +2,11 @@ import path from 'node:path';
2
2
  import * as p from '@clack/prompts';
3
3
  import { fetchRelease } from '../lib/release.js';
4
4
  import { normalize } from '../lib/patches.js';
5
- import { readJsonIfExists, readLock, readTextIfExists } from '../lib/project.js';
5
+ import { readJsonIfExists, readLock, readTextIfExists, fileExists } from '../lib/project.js';
6
6
  import { listVersions } from '../lib/github.js';
7
7
  import { MANAGED_DOCS, KNOWN_TARGET_FILES, listManagedBlocks } from '../lib/managedDocs.js';
8
8
  import { detectBundler } from '../lib/bundler.js';
9
+ import { checkRootProviderWired } from '../lib/rootProvider.js';
9
10
 
10
11
  const TOOLKIT_DIR = './toolcrib';
11
12
 
@@ -33,6 +34,25 @@ export function checkImportsCompatibility(projectRoot) {
33
34
  return moduleResolution;
34
35
  }
35
36
 
37
+ /**
38
+ * Read-only heuristic: does this project appear to be a TypeScript project
39
+ * at all? Absence of `tsconfig.json` is the same signal
40
+ * `checkImportsCompatibility` already treats as "nothing to check here,
41
+ * e.g. a plain JS project" — this check exists specifically to make that
42
+ * case non-silent instead. toolcrib's own components are fully typed so
43
+ * that an invalid prop value (a typo'd `variant`, a misspelled event name,
44
+ * a prop that doesn't exist on that component) fails at compile time —
45
+ * a `.jsx`/`.js` consumer gets none of that, since `tsc` doesn't
46
+ * type-check plain JS by default. Confirmed as a real failure mode, not
47
+ * hypothetical: a real consumer app passed `variant="solid"` — not a
48
+ * value any toolcrib `Button` variant accepts — and it shipped invisibly
49
+ * for the life of the project until it happened to visually collide with
50
+ * an unrelated layout change and got noticed by eye.
51
+ */
52
+ export function checkTypeScriptAdopted(projectRoot) {
53
+ return fileExists(path.join(projectRoot, 'tsconfig.json'));
54
+ }
55
+
36
56
  /**
37
57
  * Read-only drift check for managed <!-- toolcrib:managed:... --> blocks
38
58
  * inside AGENTS.md/CLAUDE.md — the same question the vendored-file drift
@@ -92,14 +112,69 @@ export async function checkManagedBlocks(projectRoot, installedRelease) {
92
112
  return messages;
93
113
  }
94
114
 
115
+ /**
116
+ * Every managed block currently sitting in AGENTS.md/CLAUDE.md, available
117
+ * to reprint on demand — no network access, no lockfile requirement, just
118
+ * `listManagedBlocks` over whatever's already on disk. `docIdFilter`
119
+ * narrows to one docId; omitted, every block found across both files is
120
+ * returned. Doesn't validate `docIdFilter` against MANAGED_DOCS itself —
121
+ * an unrecognized filter here would just silently produce `[]`, the wrong
122
+ * failure mode for a typo'd docId, so that check lives in the caller.
123
+ */
124
+ export function listReprintableBlocks(projectRoot, docIdFilter) {
125
+ const results = [];
126
+ for (const targetFile of KNOWN_TARGET_FILES) {
127
+ const content = readTextIfExists(path.join(projectRoot, targetFile));
128
+ if (!content) continue;
129
+ for (const block of listManagedBlocks(content)) {
130
+ if (docIdFilter && block.docId !== docIdFilter) continue;
131
+ results.push({ targetFile, ...block });
132
+ }
133
+ }
134
+ return results;
135
+ }
136
+
95
137
  /**
96
138
  * Reports drift without staging any patches — a read-only diagnostic.
97
139
  * "No drift" here answers a different question than "are you on the
98
140
  * latest version," which is checked separately below; the two are
99
141
  * deliberately not conflated (see design notes).
100
142
  */
101
- export async function doctorCommand() {
143
+ export async function doctorCommand(options = {}) {
102
144
  const projectRoot = process.cwd();
145
+
146
+ // Reprint mode is a different question entirely from everything below —
147
+ // "what's the current managed-block content" rather than "has anything
148
+ // drifted" — so it branches before p.intro/readLock and skips both.
149
+ // Left entirely clack-free (no p.log, no intro/outro): the block content
150
+ // is meant to be re-fed into an agent's context, and clack's per-line
151
+ // `│` decoration would corrupt copy/paste of multi-line Markdown: kept
152
+ // the whole branch undecorated rather than just the payload lines, so
153
+ // there's no orphaned p.log message with no intro/outro frame around it.
154
+ if (options.reprintManagedBlock !== undefined) {
155
+ const docIdFilter = options.reprintManagedBlock === true ? undefined : options.reprintManagedBlock;
156
+ if (docIdFilter !== undefined && !MANAGED_DOCS[docIdFilter]) {
157
+ console.error(`Unknown docId "${docIdFilter}" — expected one of: ${Object.keys(MANAGED_DOCS).join(', ')}`);
158
+ process.exitCode = 1;
159
+ return;
160
+ }
161
+ const blocks = listReprintableBlocks(projectRoot, docIdFilter);
162
+ if (blocks.length === 0) {
163
+ console.warn(
164
+ docIdFilter
165
+ ? `No managed block "${docIdFilter}" found in AGENTS.md/CLAUDE.md.`
166
+ : 'No managed blocks found in AGENTS.md/CLAUDE.md — nothing to reprint.'
167
+ );
168
+ return;
169
+ }
170
+ for (const block of blocks) {
171
+ console.log(`--- ${block.targetFile}: managed block "${block.docId}" (v${block.version}) ---`);
172
+ console.log(block.content);
173
+ console.log('');
174
+ }
175
+ return;
176
+ }
177
+
103
178
  p.intro('toolcrib doctor');
104
179
 
105
180
  const lock = readLock(projectRoot);
@@ -157,6 +232,16 @@ export async function doctorCommand() {
157
232
  p.log.info('You are on the latest release.');
158
233
  }
159
234
 
235
+ if (!checkTypeScriptAdopted(projectRoot)) {
236
+ p.log.warn(
237
+ 'No tsconfig.json found — this project doesn\'t appear to be using TypeScript. ' +
238
+ 'Every toolcrib component ships a full, exact prop type specifically so an invalid value ' +
239
+ '(a typo\'d variant, a misspelled event name, a prop that doesn\'t exist) fails at compile ' +
240
+ 'time instead of shipping silently — a plain JS/JSX project gets none of that protection. ' +
241
+ 'See NEW_APP.md\'s "Already started in JavaScript?" section to convert.'
242
+ );
243
+ }
244
+
160
245
  const badModuleResolution = checkImportsCompatibility(projectRoot);
161
246
  if (badModuleResolution !== null) {
162
247
  p.log.warn(
@@ -174,5 +259,21 @@ export async function doctorCommand() {
174
259
  p.log.info(`Detected ${bundler.label} — ${bundler.note}`);
175
260
  }
176
261
 
262
+ const rootProvider = checkRootProviderWired(projectRoot);
263
+ if (rootProvider.found) {
264
+ p.log.success(
265
+ rootProvider.via === 'ToolcribProvider'
266
+ ? 'Root providers: <ToolcribProvider> found.'
267
+ : 'Root providers: manual <ThemeProvider>/<ToastProvider>/<ToastContainer> composition found.'
268
+ );
269
+ } else {
270
+ p.log.warn(
271
+ "Root providers: couldn't find <ToolcribProvider> or a manual <ThemeProvider>/<ToastProvider>/<ToastContainer> " +
272
+ 'composition anywhere under src/. Every toolcrib component throws or silently no-ops without one of these ' +
273
+ "wrapping your app root — see CORE.md §1. (Heuristic text scan — a false warning is possible if your root " +
274
+ 'setup uses an unusual file layout or a re-exported alias; verify directly if you believe it\'s already wired.)'
275
+ );
276
+ }
277
+
177
278
  p.outro('Done.');
178
279
  }
@@ -3,8 +3,8 @@ import * as p from '@clack/prompts';
3
3
  import { fetchRelease } from '../lib/release.js';
4
4
  import { PendingChanges, joinPatchPath } from '../lib/patches.js';
5
5
  import { resolveDependencyDecisions, buildProposedPackageJson, mergeImportsField } from '../lib/deps.js';
6
- import { readJsonIfExists, readTextIfExists, proposeGitignore, proposeLockUpdate } from '../lib/project.js';
7
- import { MANAGED_DOCS, DEFAULT_TARGET_FILE, upsertManagedBlock } from '../lib/managedDocs.js';
6
+ import { readJsonIfExists, readTextIfExists, fileExists, proposeGitignore, proposeLockUpdate } from '../lib/project.js';
7
+ import { MANAGED_DOCS, DEFAULT_TARGET_FILE, KNOWN_TARGET_FILES, upsertManagedBlock } from '../lib/managedDocs.js';
8
8
 
9
9
  const TOOLKIT_DIR = './toolcrib';
10
10
  // The subpath-imports entry that gives consumer code a stable, file-location-
@@ -16,6 +16,23 @@ const TOOLKIT_IMPORTS_ENTRY = { '#toolcrib': './toolcrib/index.ts' };
16
16
  // docIds always written, plus the situational one --situation selects.
17
17
  const SITUATION_TO_DOC_ID = { new: 'new-app', refactor: 'refactor-app' };
18
18
 
19
+ /**
20
+ * Which instruction file to write the managed block into. Mirrors what
21
+ * doctor/merge already scan (KNOWN_TARGET_FILES) rather than always
22
+ * defaulting to AGENTS.md — a project that already has a CLAUDE.md (e.g.
23
+ * an existing Claude Code setup) and no AGENTS.md would otherwise get a
24
+ * brand-new AGENTS.md sitting unused next to the file its own assistant
25
+ * actually reads, while merge/doctor go on dutifully tracking blocks in
26
+ * both. First existing file wins; DEFAULT_TARGET_FILE only applies when
27
+ * neither is present yet.
28
+ */
29
+ function resolveTargetFile(projectRoot) {
30
+ for (const file of KNOWN_TARGET_FILES) {
31
+ if (readTextIfExists(path.join(projectRoot, file))) return file;
32
+ }
33
+ return DEFAULT_TARGET_FILE;
34
+ }
35
+
19
36
  export async function initCommand(options) {
20
37
  const projectRoot = process.cwd();
21
38
 
@@ -93,7 +110,11 @@ export async function initCommand(options) {
93
110
  const situationDocId = SITUATION_TO_DOC_ID[options.situation];
94
111
  const docIdsToWrite = situationDocId ? ['core', situationDocId] : ['core'];
95
112
 
96
- const agentsPath = path.join(projectRoot, DEFAULT_TARGET_FILE);
113
+ const agentsFileExisted = fileExists(path.join(projectRoot, 'AGENTS.md'));
114
+ const claudeFileExisted = fileExists(path.join(projectRoot, 'CLAUDE.md'));
115
+
116
+ const targetFile = resolveTargetFile(projectRoot);
117
+ const agentsPath = path.join(projectRoot, targetFile);
97
118
  const originalAgentsContent = readTextIfExists(agentsPath);
98
119
  let proposedAgentsContent = originalAgentsContent;
99
120
  for (const docId of docIdsToWrite) {
@@ -101,7 +122,23 @@ export async function initCommand(options) {
101
122
  proposedAgentsContent = upsertManagedBlock(proposedAgentsContent, docId, release.version, docContent);
102
123
  }
103
124
  if (proposedAgentsContent !== originalAgentsContent) {
104
- changes.propose(DEFAULT_TARGET_FILE, originalAgentsContent, proposedAgentsContent, DEFAULT_TARGET_FILE);
125
+ changes.propose(targetFile, originalAgentsContent, proposedAgentsContent, targetFile);
126
+ }
127
+
128
+ // 5b. Claude Code discovery: Claude Code reads CLAUDE.md by default, not
129
+ // AGENTS.md (this repo's own root CLAUDE.md is a one-line `@AGENTS.md`
130
+ // import for exactly that reason). resolveTargetFile() only falls back to
131
+ // AGENTS.md when NEITHER file existed yet — in that specific case, a
132
+ // Claude Code user would otherwise get instructions their own tool never
133
+ // discovers. Scoped strictly to that case: an existing AGENTS.md-only
134
+ // setup (even without a CLAUDE.md) reflects a choice already made and
135
+ // shouldn't be second-guessed uninvited. Staged as its own independent
136
+ // patch (see PendingChanges.propose), so a non-Claude-Code user can just
137
+ // delete that one patch file before `toolcrib apply` and keep everything
138
+ // else.
139
+ const claudeStubProposed = !agentsFileExisted && !claudeFileExisted && targetFile === 'AGENTS.md';
140
+ if (claudeStubProposed) {
141
+ changes.propose('CLAUDE.md', '', '@AGENTS.md\n', 'CLAUDE.md');
105
142
  }
106
143
 
107
144
  await release.cleanup();
@@ -117,20 +154,35 @@ export async function initCommand(options) {
117
154
  reportConflicts(depDecisions);
118
155
 
119
156
  const missingSituation = !situationDocId
120
- ? `\n\nThis staged a "core" block in ${DEFAULT_TARGET_FILE}, but not a situational one — re-run with ` +
157
+ ? `\n\nThis staged a "core" block in ${targetFile}, but not a situational one — re-run with ` +
121
158
  `--situation new (greenfield project) or --situation refactor (adopting into an existing app) to add it, ` +
122
159
  `or add it by hand wrapped in the same <!-- toolcrib:managed:... --> fence so 'toolcrib merge' can still ` +
123
160
  `track it. See ./toolcrib/ai-docs/NEW_APP.md / REFACTOR_APP.md.`
124
161
  : '';
125
162
 
163
+ const claudeStubNote = claudeStubProposed
164
+ ? `\n\nAlso staged a minimal CLAUDE.md (\`@AGENTS.md\`) since neither file existed yet — Claude Code reads ` +
165
+ `CLAUDE.md by default, not AGENTS.md, so this is what makes the staged instructions visible to it. Not ` +
166
+ `using Claude Code? Delete the CLAUDE.md patch under ./toolcrib-patches/ before running 'toolcrib apply' ` +
167
+ `and everything else still applies cleanly.`
168
+ : '';
169
+
126
170
  p.outro(
127
171
  `Review the patches in ./toolcrib-patches/, then run:\n` +
128
- ` toolcrib apply${missingSituation}`
172
+ ` toolcrib apply${missingSituation}${claudeStubNote}`
129
173
  );
130
174
  }
131
175
 
132
176
  function reportConflicts(depDecisions) {
133
177
  if (depDecisions.conflicts.length === 0) return;
178
+ // Matches doctor.js/merge.js: both set process.exitCode = 1 for their own
179
+ // "needs a human/AI decision" states. init.js previously didn't, which
180
+ // meant a real dependency conflict (e.g. a React major outside toolcrib's
181
+ // supported range) and a fully clean init were indistinguishable to
182
+ // anything checking the exit code — a script, CI step, or an agent
183
+ // deciding whether to proceed unattended. The warning text alone isn't
184
+ // enough if nothing downstream ever inspects stdout for it.
185
+ process.exitCode = 1;
134
186
  p.log.warn(
135
187
  `${depDecisions.conflicts.length} dependency conflict(s) — not staged, needs your decision:\n` +
136
188
  depDecisions.conflicts
package/src/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { readFileSync } from 'node:fs';
2
3
  import { Command } from 'commander';
3
4
  import { initCommand } from './commands/init.js';
4
5
  import { mergeCommand } from './commands/merge.js';
@@ -6,6 +7,14 @@ import { applyCommand } from './commands/apply.js';
6
7
  import { doctorCommand } from './commands/doctor.js';
7
8
  import { versionsCommand } from './commands/versions.js';
8
9
 
10
+ // Read at runtime instead of a JSON import assertion: `assert { type: 'json' }`
11
+ // vs `with { type: 'json' }` differs across the Node 18-22 range this CLI's
12
+ // `engines.node >= 18` promises to support, so plain fs avoids picking a
13
+ // syntax that breaks on some of those versions.
14
+ const packageJson = JSON.parse(
15
+ readFileSync(new URL('../package.json', import.meta.url), 'utf8')
16
+ );
17
+
9
18
  const program = new Command();
10
19
 
11
20
  // Without this, commander resolves `--version` anywhere in argv against the
@@ -20,7 +29,7 @@ program.enablePositionalOptions();
20
29
  program
21
30
  .name('toolcrib')
22
31
  .description('Bootstrap and maintain the toolcrib UI toolkit in your project')
23
- .version('1.0.0');
32
+ .version(packageJson.version);
24
33
 
25
34
  program
26
35
  .command('init')
@@ -52,8 +61,12 @@ program
52
61
  program
53
62
  .command('doctor')
54
63
  .description('Check installed files for local drift and available updates (read-only)')
55
- .action(async () => {
56
- await doctorCommand().catch(fail);
64
+ .option(
65
+ '--reprint-managed-block [docId]',
66
+ 're-print the current managed block(s) to stdout, for re-injecting into an agent session that lost the primer to context compaction; optionally scope to one docId (core/new-app/refactor-app)'
67
+ )
68
+ .action(async (options) => {
69
+ await doctorCommand(options).catch(fail);
57
70
  });
58
71
 
59
72
  program
package/src/lib/fences.js CHANGED
@@ -35,6 +35,10 @@ function bannerFor(style) {
35
35
  return style === 'markdown' ? `<!-- ${text} -->` : style === 'hash' ? `# ${text}` : `// ${text}`;
36
36
  }
37
37
 
38
+ function escapeRegExp(text) {
39
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
40
+ }
41
+
38
42
  export const FENCE_STYLES = {
39
43
  // Markdown / HTML-comment files: AGENTS.md, CLAUDE.md.
40
44
  markdown: {
@@ -50,18 +54,31 @@ export const FENCE_STYLES = {
50
54
  // content run through normalize() by their callers (doctor.js,
51
55
  // merge.js) so a pure line-ending difference is never itself reported
52
56
  // as drift — this is about matching the fence at all.
53
- pattern: (id) =>
54
- new RegExp(
55
- `<!-- toolcrib:managed:${id}:start version=(\\S+) -->\\r?\\n([\\s\\S]*?)<!-- toolcrib:managed:${id}:end -->\\r?\\n?`
56
- ),
57
+ //
58
+ // `id` is escaped before interpolation into the RegExp source — every
59
+ // `id` this CLI actually passes today is a fixed internal constant
60
+ // ('gitignore', 'core', 'new-app', 'refactor-app'), never attacker- or
61
+ // even user-controlled, so this has never been reachable in practice.
62
+ // Escaping anyway costs nothing and means that stays true by
63
+ // construction rather than by every future caller happening to keep
64
+ // passing safe ids — the same reasoning as escaping the version string,
65
+ // just not yet applied here consistently.
66
+ pattern: (id) => {
67
+ const safeId = escapeRegExp(id);
68
+ return new RegExp(
69
+ `<!-- toolcrib:managed:${safeId}:start version=(\\S+) -->\\r?\\n([\\s\\S]*?)<!-- toolcrib:managed:${safeId}:end -->\\r?\\n?`
70
+ );
71
+ },
57
72
  },
58
73
  // #-comment files: .gitignore, .env, YAML, shell scripts.
59
74
  hash: {
60
75
  start: (id, version) => `# toolcrib:managed:${id}:start version=${version}`,
61
76
  banner: () => bannerFor('hash'),
62
77
  end: (id) => `# toolcrib:managed:${id}:end`,
63
- pattern: (id) =>
64
- new RegExp(`# toolcrib:managed:${id}:start version=(\\S+)\\r?\\n([\\s\\S]*?)# toolcrib:managed:${id}:end\\r?\\n?`),
78
+ pattern: (id) => {
79
+ const safeId = escapeRegExp(id);
80
+ return new RegExp(`# toolcrib:managed:${safeId}:start version=(\\S+)\\r?\\n([\\s\\S]*?)# toolcrib:managed:${safeId}:end\\r?\\n?`);
81
+ },
65
82
  },
66
83
  // JS/TS/JSX/TSX source files. Not used by any current CLI feature — no
67
84
  // command patches user source code yet — but defined here so a future
@@ -72,8 +89,10 @@ export const FENCE_STYLES = {
72
89
  start: (id, version) => `// toolcrib:managed:${id}:start version=${version}`,
73
90
  banner: () => bannerFor('js'),
74
91
  end: (id) => `// toolcrib:managed:${id}:end`,
75
- pattern: (id) =>
76
- new RegExp(`// toolcrib:managed:${id}:start version=(\\S+)\\r?\\n([\\s\\S]*?)// toolcrib:managed:${id}:end\\r?\\n?`),
92
+ pattern: (id) => {
93
+ const safeId = escapeRegExp(id);
94
+ return new RegExp(`// toolcrib:managed:${safeId}:start version=(\\S+)\\r?\\n([\\s\\S]*?)// toolcrib:managed:${safeId}:end\\r?\\n?`);
95
+ },
77
96
  },
78
97
  };
79
98
 
@@ -83,10 +102,6 @@ export const FENCE_STYLES = {
83
102
  // dependency/imports key names (see lib/deps.js), not by an inline marker.
84
103
  export const NO_FENCE_ASSET_TYPES = ['json'];
85
104
 
86
- function escapeRegExp(text) {
87
- return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
88
- }
89
-
90
105
  /** Build a complete fenced block (start marker, banner, content, end marker) in the given style. */
91
106
  export function buildFence(style, id, version, content) {
92
107
  const banner = style.banner ? `${style.banner()}\n` : '';
package/src/lib/github.js CHANGED
@@ -22,6 +22,27 @@ export async function listVersions() {
22
22
  });
23
23
 
24
24
  if (!res.ok) {
25
+ // GitHub's unauthenticated rate limit (60/hr, shared across every caller
26
+ // on the same IP — e.g. a shared CI runner or sandbox) surfaces as a
27
+ // plain 403, indistinguishable from a real auth/network failure unless
28
+ // the response headers are inspected. Left as a generic error, this
29
+ // sends whoever/whatever hits it down a diagnostic path (checking
30
+ // headers, retrying with curl, poking at User-Agent) to rediscover a
31
+ // fix (`toolcrib init --version <x.y.z>`) that already exists and is
32
+ // documented — see CLI README. Checked here so the message states the
33
+ // real cause and the real fix directly, instead of a bare status code.
34
+ const remaining = res.status === 403 ? res.headers?.get?.('x-ratelimit-remaining') : null;
35
+ if (res.status === 403 && remaining === '0') {
36
+ const resetHeader = res.headers?.get?.('x-ratelimit-reset');
37
+ const resetAt = resetHeader ? new Date(Number(resetHeader) * 1000).toLocaleTimeString() : 'unknown';
38
+ throw new Error(
39
+ `GitHub's unauthenticated API rate limit (60 requests/hour, shared by IP) is exhausted — ` +
40
+ `resets around ${resetAt}. This only affects version *discovery* ("latest" resolution); it ` +
41
+ `does not affect release downloads themselves. Fix: run \`toolcrib init --version <x.y.z>\` ` +
42
+ `(or \`apply\`/\`merge\` with an explicit version) with a version you already know, which skips ` +
43
+ `this call entirely.`
44
+ );
45
+ }
25
46
  throw new Error(`Failed to fetch release list: ${res.status} ${res.statusText}`);
26
47
  }
27
48
 
@@ -16,6 +16,21 @@ export function applyPatchFallback(patchPath, projectRoot) {
16
16
  const targetRelPath = parsed.newFileName.replace(/^b\//, '');
17
17
  const targetPath = path.join(projectRoot, targetRelPath);
18
18
 
19
+ // Defense in depth: every relPath this CLI itself writes into a patch
20
+ // header comes from its own vendored file list or fixed strings
21
+ // (package.json, .gitignore, ...), never from anything an attacker
22
+ // controls directly — but nothing enforced that at the point a patch is
23
+ // actually applied. Rejecting a resolved target outside projectRoot here
24
+ // means a corrupted, hand-edited, or (in a worse scenario) tampered
25
+ // patch file can't be used to write outside the project regardless of
26
+ // how it got that path, rather than relying solely on every upstream
27
+ // producer of a patch file staying honest.
28
+ const resolvedRoot = path.resolve(projectRoot);
29
+ const resolvedTarget = path.resolve(targetPath);
30
+ if (resolvedTarget !== resolvedRoot && !resolvedTarget.startsWith(resolvedRoot + path.sep)) {
31
+ return { success: false, error: `Refusing to apply patch: target path "${targetRelPath}" resolves outside the project root.` };
32
+ }
33
+
19
34
  const isNewFile = parsed.oldFileName === '/dev/null';
20
35
  const currentContent = isNewFile ? '' : fs.readFileSync(targetPath, 'utf-8');
21
36
 
@@ -32,6 +32,17 @@ export function readTextIfExists(filePath) {
32
32
  return fs.existsSync(filePath) ? stripBOM(fs.readFileSync(filePath, 'utf-8')) : '';
33
33
  }
34
34
 
35
+ /**
36
+ * True existence check, distinct from readTextIfExists's '' return value --
37
+ * that '' can't tell "the file doesn't exist" apart from "the file exists
38
+ * and is empty." Callers that specifically need the former (e.g. deciding
39
+ * whether to propose a brand-new file vs. one that just happens to be
40
+ * blank) should use this instead of `readTextIfExists(...) !== ''`.
41
+ */
42
+ export function fileExists(filePath) {
43
+ return fs.existsSync(filePath);
44
+ }
45
+
35
46
  /**
36
47
  * The ONLY thing persisted locally between CLI runs is the installed
37
48
  * version string — no cached hashes, no file-by-file state. Everything
@@ -0,0 +1,88 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ // Directories never worth descending into for this scan: dependency trees,
5
+ // VCS internals, build output, and the vendored toolkit itself (its own
6
+ // source legitimately contains `<ThemeProvider>`/`<ToastProvider>` --
7
+ // scanning it would produce a false "found it" even for a consumer who
8
+ // never wired their own root).
9
+ const EXCLUDED_DIR_NAMES = new Set(['node_modules', '.git', 'dist', 'build', '.next', 'toolcrib']);
10
+ const SOURCE_FILE_PATTERN = /\.(tsx|jsx|ts|js)$/;
11
+ // A generous but bounded walk -- this is a best-effort heuristic diagnostic
12
+ // (grep for a JSX pattern), not the byte-exact vendored-file drift check
13
+ // elsewhere in this tool, so it deliberately stops rather than walking an
14
+ // unbounded tree on a pathological repo layout.
15
+ const MAX_FILES_SCANNED = 2000;
16
+
17
+ function listCandidateFiles(rootDir) {
18
+ const results = [];
19
+ const stack = [rootDir];
20
+ while (stack.length > 0 && results.length < MAX_FILES_SCANNED) {
21
+ const dir = stack.pop();
22
+ let entries;
23
+ try {
24
+ entries = fs.readdirSync(dir, { withFileTypes: true });
25
+ } catch {
26
+ continue; // unreadable directory (permissions, symlink loop) -- skip, not fatal to the scan
27
+ }
28
+ for (const entry of entries) {
29
+ if (entry.isDirectory()) {
30
+ if (EXCLUDED_DIR_NAMES.has(entry.name) || entry.name.startsWith('.')) continue;
31
+ stack.push(path.join(dir, entry.name));
32
+ } else if (SOURCE_FILE_PATTERN.test(entry.name)) {
33
+ results.push(path.join(dir, entry.name));
34
+ }
35
+ }
36
+ }
37
+ return results;
38
+ }
39
+
40
+ /**
41
+ * Read-only heuristic: does this project's own source wire up toolcrib's
42
+ * root providers, via `<ToolcribProvider>` or the equivalent manual
43
+ * `<ThemeProvider>` + `<ToastProvider>` + `<ToastContainer>` composition?
44
+ * Both are legitimate per `CORE.md` §1 -- this doesn't prefer one, it just
45
+ * confirms *something* is wired, since every toolcrib component throws or
46
+ * silently no-ops without it, and that failure mode gives no clue back to
47
+ * "you forgot the root setup."
48
+ *
49
+ * Necessarily a grep-style heuristic, not a real JSX/AST check (unlike the
50
+ * byte-exact vendored-file drift check elsewhere in this tool) -- a false
51
+ * positive (e.g. these strings appearing only in a comment) is judged the
52
+ * safer failure mode than a false "not found" nagging a project that's
53
+ * actually wired correctly, just not in a way this scan happens to expect
54
+ * (e.g. `ThemeProvider` re-exported under a local alias).
55
+ *
56
+ * Scans from `<projectRoot>/src` if present (the near-universal convention
57
+ * for a React app's own source), falling back to `projectRoot` itself for
58
+ * a project with no `src/` directory. Returns `{ found: boolean, via:
59
+ * 'ToolcribProvider' | 'manual' | null }`.
60
+ */
61
+ export function checkRootProviderWired(projectRoot) {
62
+ const scanRoot = fs.existsSync(path.join(projectRoot, 'src')) ? path.join(projectRoot, 'src') : projectRoot;
63
+ if (!fs.existsSync(scanRoot)) return { found: false, via: null };
64
+
65
+ let sawThemeProvider = false;
66
+ let sawToastProvider = false;
67
+ let sawToastContainer = false;
68
+
69
+ for (const filePath of listCandidateFiles(scanRoot)) {
70
+ let text;
71
+ try {
72
+ text = fs.readFileSync(filePath, 'utf-8');
73
+ } catch {
74
+ continue;
75
+ }
76
+ if (text.includes('<ToolcribProvider')) {
77
+ return { found: true, via: 'ToolcribProvider' };
78
+ }
79
+ if (text.includes('<ThemeProvider')) sawThemeProvider = true;
80
+ if (text.includes('<ToastProvider')) sawToastProvider = true;
81
+ if (text.includes('<ToastContainer')) sawToastContainer = true;
82
+ }
83
+
84
+ if (sawThemeProvider && sawToastProvider && sawToastContainer) {
85
+ return { found: true, via: 'manual' };
86
+ }
87
+ return { found: false, via: null };
88
+ }
package/src/lib/zip.js CHANGED
@@ -19,6 +19,16 @@ const execFileAsync = promisify(execFile);
19
19
  * If you'd rather have zero external-binary reliance, swap this for the
20
20
  * `unzipper` or `yauzl` npm package — either is fine for CLI-only code.
21
21
  */
22
+ /**
23
+ * Escape a value for embedding inside a PowerShell single-quoted string
24
+ * literal. PowerShell's escape rule for a single quote inside a
25
+ * single-quoted string is to double it (`''`), not backslash-escape it —
26
+ * this is PowerShell's own rule, unrelated to Node/shell escaping.
27
+ */
28
+ export function powerShellQuote(value) {
29
+ return `'${value.replace(/'/g, "''")}'`;
30
+ }
31
+
22
32
  export async function extractZip(zipBuffer, targetDir) {
23
33
  await fsp.mkdir(targetDir, { recursive: true });
24
34
 
@@ -28,11 +38,24 @@ export async function extractZip(zipBuffer, targetDir) {
28
38
  try {
29
39
  if (process.platform === 'win32') {
30
40
  // PowerShell's Expand-Archive ships on all modern Windows installs.
31
- await execFileAsync('powershell', [
32
- '-NoProfile',
33
- '-Command',
34
- `Expand-Archive -Path '${tmpZipPath}' -DestinationPath '${targetDir}' -Force`,
35
- ]);
41
+ //
42
+ // The script text is passed via -EncodedCommand (a base64-encoded
43
+ // UTF-16LE string) rather than as a plain -Command string built by
44
+ // interpolating paths directly into single-quoted PowerShell literals.
45
+ // execFile doesn't invoke a shell, so Node itself never reinterprets
46
+ // these arguments — but powershell.exe's own argument handling for a
47
+ // multi-token -Command re-joins everything after it into one script
48
+ // line, which put the actual escaping burden on this string being
49
+ // built correctly to begin with. -EncodedCommand takes exactly one
50
+ // argument (the encoded blob) with nothing left for powershell.exe's
51
+ // own parser to re-split or reinterpret, and powerShellQuote() above
52
+ // still applies PowerShell's real single-quote escaping rule to each
53
+ // value, so a path containing a literal `'` (however unlikely from
54
+ // os.tmpdir()/mkdtemp() in practice) is handled correctly rather than
55
+ // relying on that never happening.
56
+ const script = `Expand-Archive -Path ${powerShellQuote(tmpZipPath)} -DestinationPath ${powerShellQuote(targetDir)} -Force`;
57
+ const encodedScript = Buffer.from(script, 'utf16le').toString('base64');
58
+ await execFileAsync('powershell', ['-NoProfile', '-EncodedCommand', encodedScript]);
36
59
  } else {
37
60
  await execFileAsync('unzip', ['-o', '-q', tmpZipPath, '-d', targetDir]);
38
61
  }