toolcrib 0.1.0 → 0.2.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
@@ -6,198 +6,249 @@ changed, and stages every addition/modification as a reviewable patch — it
6
6
  never writes to a pre-existing file directly. You (or your AI assistant)
7
7
  apply what you want with `toolcrib apply`.
8
8
 
9
+ This file covers the CLI itself, start to finish. It doesn't cover how to
10
+ use any individual component; for that, point your AI assistant at the
11
+ toolkit's `ai-docs/` folder, which `toolcrib init` vendors into your project
12
+ (see [What this guide doesn't cover](#what-this-guide-doesnt-cover)).
13
+
9
14
  ## Install
10
15
 
16
+ No install needed — run it directly:
17
+
18
+ ```bash
19
+ npx toolcrib <command>
20
+ ```
21
+
22
+ Or install it globally if you'll use it often:
23
+
11
24
  ```bash
12
25
  npm install -g toolcrib
26
+ toolcrib <command>
13
27
  ```
14
28
 
15
- Or run without installing, via `npx toolcrib <command>`.
29
+ Run every command from your project's root — the same directory as your
30
+ `package.json`.
16
31
 
17
- ## Commands
32
+ ## The lifecycle, at a glance
18
33
 
19
- | Command | What it does |
20
- |---|---|
21
- | `toolcrib init [--version <x.y.z>]` | Stage installation of the toolkit into the current project. Defaults to the latest release. |
22
- | `toolcrib merge [--version <x.y.z>]` | Stage an update from the currently installed version to another. |
23
- | `toolcrib apply` | Apply every staged patch in `./toolcrib-patches/`, then delete the folder regardless of outcome. |
24
- | `toolcrib doctor` | Read-only check for local drift and available updates. |
25
- | `toolcrib versions` | List available toolkit releases. |
34
+ ```
35
+ toolcrib init → review ./toolcrib-patches/ → toolcrib apply
36
+ │
37
+ (later, to check in on things) │
38
+ ▼
39
+ toolcrib doctor
40
+ │
41
+ (when a new version exists)
42
+ ▼
43
+ toolcrib merge → review ./toolcrib-patches/ → toolcrib apply
44
+ ```
26
45
 
27
- Nothing is ever written to an existing file outside of `toolcrib apply` —
28
- `init`/`merge` only ever produce patches for you to review first.
46
+ Two ideas make everything else make sense:
29
47
 
30
- ## Local development / running without publishing
48
+ 1. **Nothing is ever written to an existing file except by `toolcrib
49
+ apply`.** `init` and `merge` only ever compute a diff and save it as a
50
+ `.patch` file in `./toolcrib-patches/` — a folder you can open, read,
51
+ and delete without anything in your project changing. `apply` is the
52
+ only command that actually touches your files, and only for patches
53
+ sitting in that folder.
54
+ 2. **Every command is safe to run "just to see."** `init`/`merge` never
55
+ modify anything by themselves, and `doctor`/`versions` are read-only.
56
+ If you're ever unsure what a command will do, running it costs nothing
57
+ — the worst case is a `./toolcrib-patches/` folder you don't apply.
58
+
59
+ ## Commands
31
60
 
32
- Three ways to run this CLI against your own changes, in increasing order
33
- of fidelity to what a real published install behaves like.
61
+ ### `toolcrib init`
34
62
 
35
- ### 1. Run the file directly — fastest iteration
63
+ Stages the toolkit into your project for the first time.
36
64
 
37
65
  ```bash
38
- node src/index.js init
39
- node src/index.js apply
66
+ toolcrib init
67
+ toolcrib init --version 1.2.0 # a specific release instead of latest
68
+ toolcrib init --situation new # greenfield project, no existing UI
69
+ toolcrib init --situation refactor # adopting toolcrib into an existing app
40
70
  ```
41
71
 
42
- Good for quick iteration on logic. Skips the `bin`/shebang/executable-
43
- permission resolution path entirely, so it won't catch packaging issues.
72
+ What it does: downloads the requested release (`latest` by default),
73
+ computes what's new or different compared to what's already in `./toolcrib`
74
+ (nothing, the first time you run it), and writes every addition as a
75
+ numbered `.patch` file under `./toolcrib-patches/`. It also proposes
76
+ patches for `package.json` (adding the toolkit's dependencies and the
77
+ `#toolcrib` import alias), `.gitignore`, and an `AGENTS.md`/`CLAUDE.md`
78
+ block your AI assistant should read.
44
79
 
45
- ### 2. `npm link` — live global command, best for active development
80
+ `--situation` controls whether a **New Project** or **Refactor** guide gets
81
+ added to that instruction-file block, on top of the core rules that are
82
+ always included. Skip it and you'll get the core rules only, with a note
83
+ telling you to re-run with `--situation` (or add the missing block by hand)
84
+ when you're ready.
46
85
 
47
- ```bash
48
- cd cli
49
- npm link # once
50
- toolcrib init # now works from anywhere on your machine
51
- ```
86
+ One thing worth knowing up front: **`init` doesn't take a target folder
87
+ argument.** It always vendors into `./toolcrib` relative to wherever you
88
+ run it — there's no way to point it at, say, `./src/ui` instead. Run it
89
+ from your project root.
52
90
 
53
- This creates a real global symlink back to this folder — edits to `src/`
54
- take effect immediately, no relinking needed. Exercises the actual `bin`
55
- entry and shebang, unlike option 1.
91
+ Nothing is written to your project yet — see [Reviewing and applying
92
+ patches](#reviewing-and-applying-patches) below.
56
93
 
57
- ```bash
58
- npm unlink -g toolcrib # when done
59
- ```
94
+ ### `toolcrib apply`
60
95
 
61
- ### 3. `npm pack` + real global install — closest simulation of a real publish
96
+ Applies everything staged in `./toolcrib-patches/`.
62
97
 
63
98
  ```bash
64
- cd cli
65
- npm pack # produces toolcrib-<version>.tgz
66
- npm install -g ./toolcrib-<version>.tgz # a real install: real deps, real files[] whitelist applied
67
- toolcrib init # exactly what an end user would type
99
+ toolcrib apply
68
100
  ```
69
101
 
70
- This is the only option of the three that actually respects the `files`
71
- field in `package.json` (see below) — it's the real tarball a publish
72
- would produce, not a symlink to your live source tree. Worth running once
73
- before an actual `npm publish` as a final sanity check.
102
+ This is the command that actually creates/modifies files. It applies each
103
+ patch in order, reports how many succeeded, and **deletes the
104
+ `./toolcrib-patches/` folder afterward regardless of outcome** — a failed
105
+ patch isn't kept around to retry; if something fails, re-run `init` or
106
+ `merge` afterward to regenerate fresh patches against your project's
107
+ current state, which is more likely to apply cleanly than retrying a stale
108
+ one.
74
109
 
75
- ```bash
76
- npm uninstall -g toolcrib # when done
77
- ```
110
+ If your project isn't already a git repository, `apply` will offer to run
111
+ `git init` for you first (it uses `git apply` when possible, since that
112
+ gives you normal git tooling — `git diff`, `git checkout -- .` — to inspect
113
+ or undo what just landed). Say no and it falls back to a built-in patcher
114
+ that doesn't need git at all.
78
115
 
79
- ## Testing
116
+ ### `toolcrib doctor`
80
117
 
81
- ### Unit tests
118
+ Read-only. Never modifies anything.
82
119
 
83
120
  ```bash
84
- npm install
85
- npm test
121
+ toolcrib doctor
86
122
  ```
87
123
 
88
- Covers the pure-logic modules without any network access:
89
- - `test/patches.test.js` — `PendingChanges` (patch generation, idempotency,
90
- line-ending normalization, new-file vs. modification detection)
91
- - `test/deps.test.js` — semver-based dependency classification (add /
92
- compatible / conflict), including the `workspace:*`-style unrecognized-
93
- specifier case
94
- - `test/project.test.js` — `.gitignore` proposal idempotency, lock file
95
- read/write, and a regression test for a real bug (see below)
96
- - `test/github.test.js` — checksum verification (match / mismatch /
97
- missing-checksum-asset), version resolution, release listing — all with
98
- `fetch` mocked, no real network calls
99
-
100
- A `vitest.config.js` is present in this folder specifically so vitest
101
- doesn't walk up to the repo root's `vite.config.ts` (the toolkit's own dev
102
- app config, which needs `vite` — not installed here, since this is a
103
- separate Node CLI project).
104
-
105
- ### End-to-end integration test (real network-shaped, no GitHub release required)
106
-
107
- This exercises the full `init` → `apply` pipeline for real — real zip
108
- download, real sha256 verification, real extraction, real `git apply` —
109
- against a genuine `npm init`'d project, without needing a published
110
- GitHub release. It works by running a tiny local server
111
- (`integration-test/mock-github-server.js`) that serves a real release zip
112
- built from this repo's own toolkit source, shaped exactly like GitHub's
113
- API and release-asset URLs.
114
-
115
- **1. Build a real release from the toolkit source (repo root, not cli/)**
124
+ Run this any time you want to sanity-check your install without changing
125
+ anything. It reports:
126
+
127
+ - **Local drift** — files under `./toolcrib` that no longer match what the
128
+ installed version actually shipped (usually from hand-editing a vendored
129
+ file directly, which is supported — that's the whole point of vendoring
130
+ — but worth knowing about).
131
+ - **Stale instruction-file blocks** — if the `<!-- toolcrib:managed:... -->`
132
+ block in your `AGENTS.md`/`CLAUDE.md` was hand-edited instead of
133
+ regenerated, or is out of date with your installed version.
134
+ - **Whether a newer release is available.**
135
+ - **A `tsconfig.json` compatibility check** — if `moduleResolution` isn't
136
+ set to `"bundler"`, `"node16"`, or `"nodenext"`, `import { ... } from
137
+ '#toolcrib'` will run fine but your editor/`tsc` may falsely report
138
+ "Cannot find module." `doctor` tells you the exact setting to fix it.
139
+ - **Bundler-specific notes**, when relevant — for example, on a Next.js
140
+ project it'll remind you that any file rendering toolcrib components
141
+ needs a `'use client'` directive, since Next's App Router treats
142
+ components as server-only by default.
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:
116
148
 
117
149
  ```bash
118
- cd .. # repo root, alongside src/, ai-docs/, scripts/
119
- node scripts/build-release.js
120
- node scripts/package-release.js
150
+ toolcrib doctor --reprint-managed-block # every block found
151
+ toolcrib doctor --reprint-managed-block core # just one docId
121
152
  ```
122
153
 
123
- This produces `toolcrib.zip` and `toolcrib.zip.sha256` in the repo root.
154
+ ### `toolcrib merge`
124
155
 
125
- **2. Serve it locally**
156
+ Stages an upgrade from your currently installed version to another.
126
157
 
127
158
  ```bash
128
- cd cli
129
- mkdir -p integration-test/releases
130
- cp ../toolcrib.zip ../toolcrib.zip.sha256 integration-test/releases/
131
- node integration-test/mock-github-server.js
159
+ toolcrib merge # upgrade to latest
160
+ toolcrib merge --version 2.1.0 # upgrade to a specific version
132
161
  ```
133
162
 
134
- Leave this running in its own terminal — it listens on `localhost:9999`.
163
+ Works like `init`, but smarter: for every vendored file, it compares three
164
+ things — what you originally got, what's actually on disk now, and what
165
+ the new version ships — and sorts each file into one of three outcomes:
135
166
 
136
- **3. Run the real CLI against a real dummy project**
167
+ - **Safe update** — you never touched the file; the new version's copy is
168
+ staged as a patch.
169
+ - **Kept as-is** — you edited the file yourself and upstream didn't change
170
+ it; left alone, no patch generated.
171
+ - **Conflict** — you edited it *and* upstream changed it too. `merge` won't
172
+ guess which version wins. Instead it writes a `.upstream-diff` note
173
+ explaining what upstream changed, so you (or your AI assistant) can
174
+ reconcile it by hand.
137
175
 
138
- In another terminal — either via `node src/index.js` directly, or via
139
- `npm link` (see above) for the real `toolcrib` command:
176
+ As with `init`, nothing is written until you run `apply` afterward.
140
177
 
141
- ```bash
142
- mkdir /tmp/dummy-project && cd /tmp/dummy-project
143
- npm init -y
178
+ ### `toolcrib versions`
144
179
 
145
- TOOLCRIB_API_BASE=http://localhost:9999/api \
146
- TOOLCRIB_RELEASES_BASE=http://localhost:9999/releases \
147
- toolcrib init
180
+ Lists every published release.
148
181
 
149
- TOOLCRIB_API_BASE=http://localhost:9999/api \
150
- TOOLCRIB_RELEASES_BASE=http://localhost:9999/releases \
151
- toolcrib apply
182
+ ```bash
183
+ toolcrib versions
152
184
  ```
153
185
 
154
- Then inspect `/tmp/dummy-project` — `toolcrib/` should contain every
155
- vendored file, `package.json` should have the real peer dependencies
156
- added, `.gitignore` should have `/toolcrib-patches/`, and
157
- `toolcrib/.toolcrib-lock.json` should record the installed version.
158
-
159
- `TOOLCRIB_API_BASE` / `TOOLCRIB_RELEASES_BASE` are the only two overrides
160
- this CLI recognizes — unset, everything targets real GitHub. They exist
161
- specifically to make this kind of test possible without a published
162
- release or real network access.
163
-
164
- ### Bugs this integration test has already found
165
-
166
- Worth keeping this test around — it already found three real issues that
167
- unit tests, by construction, couldn't have caught:
168
-
169
- 1. **Hang on error** — a failed fetch left `@clack/prompts`' spinner
170
- interval alive, so the process never exited even after printing the
171
- error. Fixed by calling `process.exit(1)` explicitly in the CLI's
172
- top-level error handler rather than only setting `process.exitCode`.
173
- 2. **Crash in non-interactive environments** — `p.confirm()` throws a raw
174
- libuv TTY error (not a catchable message) when stdin/stdout aren't a
175
- real terminal (CI, scripts, sandboxes). Fixed by detecting
176
- `process.stdin.isTTY` and defaulting to "yes" for the (safe,
177
- recoverable) `git init` prompt when non-interactive.
178
- 3. **`git apply` rejected the lockfile patch** — its path was built with a
179
- leading `./`, which `git apply` treats as invalid even though every
180
- other file's path (built without the leading `./`) applied fine. Fixed
181
- by dropping the leading `./`; a regression test now locks this in.
182
-
183
- ## Publishing
186
+ Useful for picking an exact `--version` for `init` or `merge` instead of
187
+ always taking `latest`.
188
+
189
+ ## Reviewing and applying patches
190
+
191
+ After `init` or `merge`, you'll have a `./toolcrib-patches/` folder full of
192
+ numbered `.patch` files — plain unified diffs. Before running `apply`:
193
+
194
+ - Open a few and skim them. They're ordinary text; any editor or `git
195
+ diff`-style tool can show them.
196
+ - If you're not going to apply them, just delete the folder — nothing else
197
+ has changed yet.
198
+ - If everything looks right, run `toolcrib apply`.
199
+
200
+ ## Upgrading — a full example
184
201
 
185
202
  ```bash
186
- cd cli
187
- npm pack --dry-run # confirm exactly what would ship — should be
188
- # package.json + src/ only, ~15 files
189
- npm publish
203
+ toolcrib versions # see what's available
204
+ toolcrib merge --version 1.4.0 # stage the upgrade
205
+ # review ./toolcrib-patches/
206
+ toolcrib apply # actually upgrade
207
+ toolcrib doctor # confirm nothing's left drifted
190
208
  ```
191
209
 
192
- ### What the `files` field is for
193
-
194
- `package.json`'s `files` array is an explicit whitelist of what
195
- `npm publish`/`npm pack` include in the published package — everything
196
- else in this folder (tests, the integration-test mock server, this
197
- README, `package-lock.json`) is left out even though it's sitting right
198
- here in the repo. Without it, npm defaults to "include everything not
199
- gitignored," which would have shipped `test/`, `vitest.config.js`, and
200
- `package-lock.json` to every installer for no reason. `["src"]` was
201
- chosen by actually running `npm pack --dry-run` and confirming it's the
202
- complete, correct set — `package.json` and the `bin` entry are always
203
- included automatically regardless of what's listed.
210
+ ## Troubleshooting
211
+
212
+ **`toolcrib apply` says "No pending patches."**
213
+ There's nothing staged — run `init` (first install) or `merge` (upgrade)
214
+ first.
215
+
216
+ **`doctor` warns about `moduleResolution`.**
217
+ Set `"moduleResolution": "bundler"` (or `"node16"`/`"nodenext"`) in your
218
+ `tsconfig.json`'s `compilerOptions`. Your code still runs fine either way —
219
+ this only affects whether `tsc`/your editor understands the `#toolcrib`
220
+ import.
221
+
222
+ **`doctor` (or `merge`) flags a hand-edited instruction-file block.**
223
+ The `<!-- toolcrib:managed:... -->` block in `AGENTS.md`/`CLAUDE.md` is
224
+ meant to be regenerated by `toolcrib merge`, not edited by hand. Move any
225
+ notes of your own outside the fence, then run `merge` to restore it
226
+ cleanly.
227
+
228
+ **`merge` reports a conflict.**
229
+ You changed a vendored file yourself, and the new version changed it too.
230
+ Check the matching `.upstream-diff` file in `./toolcrib-patches/` for what
231
+ upstream did, and reconcile manually — or hand it to your AI assistant with
232
+ "reconcile my local changes to `<file>` with the upstream update."
233
+
234
+ **A bundler-specific note from `doctor`.**
235
+ `doctor` detects Next.js, Create React App, Vite, webpack, and Parcel from
236
+ files already in your project and calls out anything that specific
237
+ tool needs — for instance, Create React App's frozen webpack config
238
+ predating `package.json` "imports" support. If nothing's flagged for your
239
+ bundler, there's nothing to do.
240
+
241
+ ## What this guide doesn't cover
242
+
243
+ Everything about actually *using* the toolkit — which component to reach
244
+ for, how theming and the event bus work, first-run gotchas with providers
245
+ — lives in `ai-docs/`, vendored into your project the first time you run
246
+ `toolcrib init`. That folder is written for your AI assistant to read, not
247
+ for you to read directly: point your AI assistant at it and let it handle
248
+ the rest.
249
+
250
+ ## Contributing to the CLI itself
251
+
252
+ Working on this tool's own source (not just using it)? See
253
+ [CONTRIBUTING.md](CONTRIBUTING.md) for the local-dev workflow, test suite,
254
+ and publishing process.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "toolcrib",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Bootstrap the toolcrib UI toolkit into your project",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -92,14 +92,69 @@ export async function checkManagedBlocks(projectRoot, installedRelease) {
92
92
  return messages;
93
93
  }
94
94
 
95
+ /**
96
+ * Every managed block currently sitting in AGENTS.md/CLAUDE.md, available
97
+ * to reprint on demand — no network access, no lockfile requirement, just
98
+ * `listManagedBlocks` over whatever's already on disk. `docIdFilter`
99
+ * narrows to one docId; omitted, every block found across both files is
100
+ * returned. Doesn't validate `docIdFilter` against MANAGED_DOCS itself —
101
+ * an unrecognized filter here would just silently produce `[]`, the wrong
102
+ * failure mode for a typo'd docId, so that check lives in the caller.
103
+ */
104
+ export function listReprintableBlocks(projectRoot, docIdFilter) {
105
+ const results = [];
106
+ for (const targetFile of KNOWN_TARGET_FILES) {
107
+ const content = readTextIfExists(path.join(projectRoot, targetFile));
108
+ if (!content) continue;
109
+ for (const block of listManagedBlocks(content)) {
110
+ if (docIdFilter && block.docId !== docIdFilter) continue;
111
+ results.push({ targetFile, ...block });
112
+ }
113
+ }
114
+ return results;
115
+ }
116
+
95
117
  /**
96
118
  * Reports drift without staging any patches — a read-only diagnostic.
97
119
  * "No drift" here answers a different question than "are you on the
98
120
  * latest version," which is checked separately below; the two are
99
121
  * deliberately not conflated (see design notes).
100
122
  */
101
- export async function doctorCommand() {
123
+ export async function doctorCommand(options = {}) {
102
124
  const projectRoot = process.cwd();
125
+
126
+ // Reprint mode is a different question entirely from everything below —
127
+ // "what's the current managed-block content" rather than "has anything
128
+ // drifted" — so it branches before p.intro/readLock and skips both.
129
+ // Left entirely clack-free (no p.log, no intro/outro): the block content
130
+ // is meant to be re-fed into an agent's context, and clack's per-line
131
+ // `│` decoration would corrupt copy/paste of multi-line Markdown: kept
132
+ // the whole branch undecorated rather than just the payload lines, so
133
+ // there's no orphaned p.log message with no intro/outro frame around it.
134
+ if (options.reprintManagedBlock !== undefined) {
135
+ const docIdFilter = options.reprintManagedBlock === true ? undefined : options.reprintManagedBlock;
136
+ if (docIdFilter !== undefined && !MANAGED_DOCS[docIdFilter]) {
137
+ console.error(`Unknown docId "${docIdFilter}" — expected one of: ${Object.keys(MANAGED_DOCS).join(', ')}`);
138
+ process.exitCode = 1;
139
+ return;
140
+ }
141
+ const blocks = listReprintableBlocks(projectRoot, docIdFilter);
142
+ if (blocks.length === 0) {
143
+ console.warn(
144
+ docIdFilter
145
+ ? `No managed block "${docIdFilter}" found in AGENTS.md/CLAUDE.md.`
146
+ : 'No managed blocks found in AGENTS.md/CLAUDE.md — nothing to reprint.'
147
+ );
148
+ return;
149
+ }
150
+ for (const block of blocks) {
151
+ console.log(`--- ${block.targetFile}: managed block "${block.docId}" (v${block.version}) ---`);
152
+ console.log(block.content);
153
+ console.log('');
154
+ }
155
+ return;
156
+ }
157
+
103
158
  p.intro('toolcrib doctor');
104
159
 
105
160
  const lock = readLock(projectRoot);
@@ -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,15 +154,22 @@ 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
 
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` : '';
@@ -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
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
  }