toolcrib 0.1.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/LICENSE +21 -0
- package/README.md +203 -0
- package/package.json +34 -0
- package/src/commands/apply.js +91 -0
- package/src/commands/doctor.js +178 -0
- package/src/commands/init.js +140 -0
- package/src/commands/merge.js +251 -0
- package/src/commands/versions.js +18 -0
- package/src/index.js +87 -0
- package/src/lib/bundler.js +87 -0
- package/src/lib/deps.js +74 -0
- package/src/lib/fences.js +129 -0
- package/src/lib/git.js +79 -0
- package/src/lib/github.js +102 -0
- package/src/lib/managedDocs.js +51 -0
- package/src/lib/patchFallback.js +30 -0
- package/src/lib/patches.js +120 -0
- package/src/lib/project.js +80 -0
- package/src/lib/release.js +42 -0
- package/src/lib/zip.js +65 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 escape-llc
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
# toolcrib (CLI)
|
|
2
|
+
|
|
3
|
+
Bootstraps and maintains the [toolcrib](https://github.com/escape-llc/toolcrib)
|
|
4
|
+
UI toolkit inside your own project. Downloads a release, computes what's
|
|
5
|
+
changed, and stages every addition/modification as a reviewable patch — it
|
|
6
|
+
never writes to a pre-existing file directly. You (or your AI assistant)
|
|
7
|
+
apply what you want with `toolcrib apply`.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install -g toolcrib
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Or run without installing, via `npx toolcrib <command>`.
|
|
16
|
+
|
|
17
|
+
## Commands
|
|
18
|
+
|
|
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. |
|
|
26
|
+
|
|
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.
|
|
29
|
+
|
|
30
|
+
## Local development / running without publishing
|
|
31
|
+
|
|
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.
|
|
34
|
+
|
|
35
|
+
### 1. Run the file directly — fastest iteration
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
node src/index.js init
|
|
39
|
+
node src/index.js apply
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Good for quick iteration on logic. Skips the `bin`/shebang/executable-
|
|
43
|
+
permission resolution path entirely, so it won't catch packaging issues.
|
|
44
|
+
|
|
45
|
+
### 2. `npm link` — live global command, best for active development
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
cd cli
|
|
49
|
+
npm link # once
|
|
50
|
+
toolcrib init # now works from anywhere on your machine
|
|
51
|
+
```
|
|
52
|
+
|
|
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.
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
npm unlink -g toolcrib # when done
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### 3. `npm pack` + real global install — closest simulation of a real publish
|
|
62
|
+
|
|
63
|
+
```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
|
|
68
|
+
```
|
|
69
|
+
|
|
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.
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
npm uninstall -g toolcrib # when done
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Testing
|
|
80
|
+
|
|
81
|
+
### Unit tests
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
npm install
|
|
85
|
+
npm test
|
|
86
|
+
```
|
|
87
|
+
|
|
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/)**
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
cd .. # repo root, alongside src/, ai-docs/, scripts/
|
|
119
|
+
node scripts/build-release.js
|
|
120
|
+
node scripts/package-release.js
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
This produces `toolcrib.zip` and `toolcrib.zip.sha256` in the repo root.
|
|
124
|
+
|
|
125
|
+
**2. Serve it locally**
|
|
126
|
+
|
|
127
|
+
```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
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Leave this running in its own terminal — it listens on `localhost:9999`.
|
|
135
|
+
|
|
136
|
+
**3. Run the real CLI against a real dummy project**
|
|
137
|
+
|
|
138
|
+
In another terminal — either via `node src/index.js` directly, or via
|
|
139
|
+
`npm link` (see above) for the real `toolcrib` command:
|
|
140
|
+
|
|
141
|
+
```bash
|
|
142
|
+
mkdir /tmp/dummy-project && cd /tmp/dummy-project
|
|
143
|
+
npm init -y
|
|
144
|
+
|
|
145
|
+
TOOLCRIB_API_BASE=http://localhost:9999/api \
|
|
146
|
+
TOOLCRIB_RELEASES_BASE=http://localhost:9999/releases \
|
|
147
|
+
toolcrib init
|
|
148
|
+
|
|
149
|
+
TOOLCRIB_API_BASE=http://localhost:9999/api \
|
|
150
|
+
TOOLCRIB_RELEASES_BASE=http://localhost:9999/releases \
|
|
151
|
+
toolcrib apply
|
|
152
|
+
```
|
|
153
|
+
|
|
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
|
|
184
|
+
|
|
185
|
+
```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
|
|
190
|
+
```
|
|
191
|
+
|
|
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.
|
package/package.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "toolcrib",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Bootstrap the toolcrib UI toolkit into your project",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/escape-llc/toolcrib.git",
|
|
10
|
+
"directory": "cli"
|
|
11
|
+
},
|
|
12
|
+
"bin": {
|
|
13
|
+
"toolcrib": "src/index.js"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"src"
|
|
17
|
+
],
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=18"
|
|
20
|
+
},
|
|
21
|
+
"scripts": {
|
|
22
|
+
"test": "vitest run",
|
|
23
|
+
"test:watch": "vitest"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"@clack/prompts": "^1.7.0",
|
|
27
|
+
"commander": "^15.0.0",
|
|
28
|
+
"diff": "^9.0.0",
|
|
29
|
+
"semver": "^7.6.0"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"vitest": "^4.1.10"
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import * as p from '@clack/prompts';
|
|
4
|
+
import { PATCH_DIR } from '../lib/patches.js';
|
|
5
|
+
import { isGitInstalled, ensureGitRepo, gitApplyStreaming } from '../lib/git.js';
|
|
6
|
+
import { applyPatchFallback } from '../lib/patchFallback.js';
|
|
7
|
+
|
|
8
|
+
export async function applyCommand() {
|
|
9
|
+
const projectRoot = process.cwd();
|
|
10
|
+
const patchDir = path.join(projectRoot, PATCH_DIR);
|
|
11
|
+
|
|
12
|
+
p.intro('toolcrib apply');
|
|
13
|
+
|
|
14
|
+
if (!fs.existsSync(patchDir)) {
|
|
15
|
+
p.outro('No pending patches. Run `toolcrib init` or `toolcrib merge` first.');
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const patchFiles = fs
|
|
20
|
+
.readdirSync(patchDir)
|
|
21
|
+
.filter((f) => f.endsWith('.patch'))
|
|
22
|
+
.sort() // numbered filenames give a stable, predictable apply order
|
|
23
|
+
.map((f) => path.join(patchDir, f));
|
|
24
|
+
|
|
25
|
+
if (patchFiles.length === 0) {
|
|
26
|
+
p.outro('No pending patches.');
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// p.confirm() requires a real interactive TTY — it throws a raw libuv
|
|
31
|
+
// error (not a catchable "no TTY" message) when stdin isn't one, which
|
|
32
|
+
// happens in CI, scripted usage, and various sandboxed environments.
|
|
33
|
+
// In that case, default to "yes" for git init specifically: it's a safe,
|
|
34
|
+
// recoverable, expected action (see ensureGitRepo), not a destructive one,
|
|
35
|
+
// so silently proceeding is preferable to crashing on a routine setup step.
|
|
36
|
+
const isInteractive = process.stdin.isTTY && process.stdout.isTTY;
|
|
37
|
+
const confirmFn = async (message) => {
|
|
38
|
+
if (!isInteractive) {
|
|
39
|
+
p.log.info(`${message} (no interactive terminal detected — proceeding automatically)`);
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
const result = await p.confirm({ message });
|
|
43
|
+
return result === true;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const gitAvailable = await isGitInstalled();
|
|
47
|
+
const repoReady = gitAvailable && (await ensureGitRepo(projectRoot, { confirmFn }));
|
|
48
|
+
|
|
49
|
+
const succeeded = [];
|
|
50
|
+
const failed = [];
|
|
51
|
+
|
|
52
|
+
for (const patchFile of patchFiles) {
|
|
53
|
+
p.log.step(`Applying ${path.basename(patchFile)}`);
|
|
54
|
+
|
|
55
|
+
const result = repoReady
|
|
56
|
+
? await gitApplyStreaming(patchFile, projectRoot)
|
|
57
|
+
: applyPatchFallback(patchFile, projectRoot);
|
|
58
|
+
|
|
59
|
+
if (result.success) {
|
|
60
|
+
succeeded.push(patchFile);
|
|
61
|
+
} else {
|
|
62
|
+
failed.push({ patchFile, error: result.error });
|
|
63
|
+
p.log.error(` ${result.error || 'unknown error'}`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Delete the entire staging directory unconditionally, whether patches
|
|
68
|
+
// succeeded or failed — no stale state persists between runs. A failed
|
|
69
|
+
// patch isn't "saved for later"; the next init/merge recomputes the
|
|
70
|
+
// diff fresh against current reality, which is more likely to produce
|
|
71
|
+
// something applicable than retrying an identical stale patch.
|
|
72
|
+
fs.rmSync(patchDir, { recursive: true, force: true });
|
|
73
|
+
|
|
74
|
+
p.log.success(`Applied ${succeeded.length} of ${patchFiles.length} patch(es).`);
|
|
75
|
+
if (failed.length > 0) {
|
|
76
|
+
p.log.warn(
|
|
77
|
+
`${failed.length} patch(es) failed and were discarded.\n` +
|
|
78
|
+
`Re-run 'toolcrib init' or 'toolcrib merge' to regenerate them against current state.`
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (!repoReady) {
|
|
83
|
+
p.log.info(
|
|
84
|
+
gitAvailable
|
|
85
|
+
? 'Applied using the built-in fallback (no git repository).'
|
|
86
|
+
: 'git was not found — applied using the built-in fallback.'
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
p.outro('Done.');
|
|
91
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import * as p from '@clack/prompts';
|
|
3
|
+
import { fetchRelease } from '../lib/release.js';
|
|
4
|
+
import { normalize } from '../lib/patches.js';
|
|
5
|
+
import { readJsonIfExists, readLock, readTextIfExists } from '../lib/project.js';
|
|
6
|
+
import { listVersions } from '../lib/github.js';
|
|
7
|
+
import { MANAGED_DOCS, KNOWN_TARGET_FILES, listManagedBlocks } from '../lib/managedDocs.js';
|
|
8
|
+
import { detectBundler } from '../lib/bundler.js';
|
|
9
|
+
|
|
10
|
+
const TOOLKIT_DIR = './toolcrib';
|
|
11
|
+
|
|
12
|
+
// moduleResolution modes under which TypeScript actually reads package.json
|
|
13
|
+
// "imports" subpaths (what makes `import { Card } from '#toolcrib'`
|
|
14
|
+
// type-check, not just run). Anything else — including TS's own default —
|
|
15
|
+
// resolves the import at runtime via bundler/Node but reports a false
|
|
16
|
+
// "Cannot find module" in the editor and tsc.
|
|
17
|
+
const IMPORTS_COMPATIBLE_MODULE_RESOLUTIONS = new Set(['bundler', 'node16', 'nodenext']);
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Read-only check: will `import ... from '#toolcrib'` type-check under this
|
|
21
|
+
* project's tsconfig? Returns null when there's nothing to warn about (no
|
|
22
|
+
* tsconfig.json — e.g. a plain JS project — or an already-compatible
|
|
23
|
+
* moduleResolution). Otherwise returns the offending value for the warning
|
|
24
|
+
* message ('' meaning unset/default).
|
|
25
|
+
*/
|
|
26
|
+
export function checkImportsCompatibility(projectRoot) {
|
|
27
|
+
const tsconfig = readJsonIfExists(path.join(projectRoot, 'tsconfig.json'));
|
|
28
|
+
if (!tsconfig) return null;
|
|
29
|
+
|
|
30
|
+
const moduleResolution = (tsconfig.compilerOptions?.moduleResolution || '').toLowerCase();
|
|
31
|
+
if (IMPORTS_COMPATIBLE_MODULE_RESOLUTIONS.has(moduleResolution)) return null;
|
|
32
|
+
|
|
33
|
+
return moduleResolution;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Read-only drift check for managed <!-- toolcrib:managed:... --> blocks
|
|
38
|
+
* inside AGENTS.md/CLAUDE.md — the same question the vendored-file drift
|
|
39
|
+
* check above answers, but for content merged into files the CLI doesn't
|
|
40
|
+
* otherwise own. `installedRelease` (already fetched for the vendored-file
|
|
41
|
+
* check) is reused when a block's own recorded version matches the
|
|
42
|
+
* installed one — the common case — rather than re-fetching.
|
|
43
|
+
*/
|
|
44
|
+
export async function checkManagedBlocks(projectRoot, installedRelease) {
|
|
45
|
+
const messages = [];
|
|
46
|
+
|
|
47
|
+
for (const targetFile of KNOWN_TARGET_FILES) {
|
|
48
|
+
const content = readTextIfExists(path.join(projectRoot, targetFile));
|
|
49
|
+
if (!content) continue;
|
|
50
|
+
|
|
51
|
+
for (const block of listManagedBlocks(content)) {
|
|
52
|
+
const docFile = MANAGED_DOCS[block.docId];
|
|
53
|
+
|
|
54
|
+
let originalDocContent;
|
|
55
|
+
try {
|
|
56
|
+
if (block.version === installedRelease.version) {
|
|
57
|
+
originalDocContent = installedRelease.readFile(`ai-docs/${docFile}`);
|
|
58
|
+
} else {
|
|
59
|
+
const atVersionRelease = await fetchRelease(block.version);
|
|
60
|
+
originalDocContent = atVersionRelease.readFile(`ai-docs/${docFile}`);
|
|
61
|
+
await atVersionRelease.cleanup();
|
|
62
|
+
}
|
|
63
|
+
} catch {
|
|
64
|
+
messages.push({
|
|
65
|
+
level: 'warn',
|
|
66
|
+
text: `${targetFile}: managed block "${block.docId}" claims version ${block.version}, which no longer resolves to a release — can't verify drift.`,
|
|
67
|
+
});
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// block.content was already trimEnd()'d at extraction (see
|
|
72
|
+
// extractFence) — originalDocContent is a raw file read and still has
|
|
73
|
+
// its trailing newline, so it must be trimmed the same way before
|
|
74
|
+
// comparing, or every block would falsely register as drifted purely
|
|
75
|
+
// from that trailing newline (confirmed via a real end-to-end run:
|
|
76
|
+
// this fired for every managed block, not just hand-edited ones).
|
|
77
|
+
if (normalize(block.content) !== normalize(originalDocContent).trimEnd()) {
|
|
78
|
+
messages.push({
|
|
79
|
+
level: 'warn',
|
|
80
|
+
text: `${targetFile}: managed block "${block.docId}" (v${block.version}) was edited by hand — it's meant to be regenerated by 'toolcrib merge', not edited directly. Move your own notes outside the fence, then run 'toolcrib merge' to restore it.`,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
if (block.version !== installedRelease.version) {
|
|
84
|
+
messages.push({
|
|
85
|
+
level: 'info',
|
|
86
|
+
text: `${targetFile}: managed block "${block.docId}" is at v${block.version}, installed toolkit is v${installedRelease.version} — run 'toolcrib merge' to update it too.`,
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return messages;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Reports drift without staging any patches — a read-only diagnostic.
|
|
97
|
+
* "No drift" here answers a different question than "are you on the
|
|
98
|
+
* latest version," which is checked separately below; the two are
|
|
99
|
+
* deliberately not conflated (see design notes).
|
|
100
|
+
*/
|
|
101
|
+
export async function doctorCommand() {
|
|
102
|
+
const projectRoot = process.cwd();
|
|
103
|
+
p.intro('toolcrib doctor');
|
|
104
|
+
|
|
105
|
+
const lock = readLock(projectRoot);
|
|
106
|
+
if (!lock) {
|
|
107
|
+
p.log.error('No toolcrib install found. Run `toolcrib init` first.');
|
|
108
|
+
process.exitCode = 1;
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const spinner = p.spinner();
|
|
113
|
+
spinner.start(`Checking against installed version v${lock.version}`);
|
|
114
|
+
let release;
|
|
115
|
+
try {
|
|
116
|
+
release = await fetchRelease(lock.version);
|
|
117
|
+
} catch (err) {
|
|
118
|
+
spinner.stop('Failed to fetch release');
|
|
119
|
+
throw err;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const drifted = [];
|
|
123
|
+
for (const relPath of release.allFiles()) {
|
|
124
|
+
const targetPath = path.join(projectRoot, TOOLKIT_DIR, relPath);
|
|
125
|
+
const local = readTextIfExists(targetPath);
|
|
126
|
+
const shipped = release.readFile(relPath);
|
|
127
|
+
if (normalize(local) !== normalize(shipped)) {
|
|
128
|
+
drifted.push(relPath);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
const managedBlockMessages = await checkManagedBlocks(projectRoot, release);
|
|
132
|
+
await release.cleanup();
|
|
133
|
+
spinner.stop('Drift check complete');
|
|
134
|
+
|
|
135
|
+
if (drifted.length === 0) {
|
|
136
|
+
p.log.success(`No local drift detected from v${lock.version}.`);
|
|
137
|
+
} else {
|
|
138
|
+
p.log.warn(
|
|
139
|
+
`${drifted.length} file(s) differ from the shipped v${lock.version}:\n` +
|
|
140
|
+
drifted.map((f) => ` ${f}`).join('\n')
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (managedBlockMessages.length === 0) {
|
|
145
|
+
p.log.success('No managed AGENTS.md/CLAUDE.md blocks found, or none have drifted.');
|
|
146
|
+
} else {
|
|
147
|
+
for (const message of managedBlockMessages) {
|
|
148
|
+
p.log[message.level](message.text);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const versions = await listVersions();
|
|
153
|
+
const newest = versions.find((v) => !v.prerelease);
|
|
154
|
+
if (newest && newest.version !== lock.version) {
|
|
155
|
+
p.log.info(`A newer version is available: v${newest.version} (installed: v${lock.version}). Run 'toolcrib merge'.`);
|
|
156
|
+
} else {
|
|
157
|
+
p.log.info('You are on the latest release.');
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const badModuleResolution = checkImportsCompatibility(projectRoot);
|
|
161
|
+
if (badModuleResolution !== null) {
|
|
162
|
+
p.log.warn(
|
|
163
|
+
`tsconfig.json's "moduleResolution" is ${badModuleResolution ? `"${badModuleResolution}"` : 'unset (defaulting to a legacy mode)'}, ` +
|
|
164
|
+
`which doesn't type-check package.json "imports" subpaths. The toolkit's ` +
|
|
165
|
+
`\`import { ... } from '#toolcrib'\` will still run correctly (bundlers and Node resolve it fine), ` +
|
|
166
|
+
`but tsc/your editor may report "Cannot find module '#toolcrib'". ` +
|
|
167
|
+
`Set "moduleResolution": "bundler" (or "node16"/"nodenext") in compilerOptions to fix the false error.`
|
|
168
|
+
);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const pkg = readJsonIfExists(path.join(projectRoot, 'package.json'));
|
|
172
|
+
const bundler = detectBundler(projectRoot, pkg);
|
|
173
|
+
if (bundler?.note) {
|
|
174
|
+
p.log.info(`Detected ${bundler.label} — ${bundler.note}`);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
p.outro('Done.');
|
|
178
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import * as p from '@clack/prompts';
|
|
3
|
+
import { fetchRelease } from '../lib/release.js';
|
|
4
|
+
import { PendingChanges, joinPatchPath } from '../lib/patches.js';
|
|
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';
|
|
8
|
+
|
|
9
|
+
const TOOLKIT_DIR = './toolcrib';
|
|
10
|
+
// The subpath-imports entry that gives consumer code a stable, file-location-
|
|
11
|
+
// independent way to import the toolkit (`import { Card } from '#toolcrib'`),
|
|
12
|
+
// bundler-agnostic per Node's package.json "imports" resolution. Must match
|
|
13
|
+
// TOOLKIT_DIR — see build-release.js's INDEX_FILE for the vendored entry point.
|
|
14
|
+
const TOOLKIT_IMPORTS_ENTRY = { '#toolcrib': './toolcrib/index.ts' };
|
|
15
|
+
|
|
16
|
+
// docIds always written, plus the situational one --situation selects.
|
|
17
|
+
const SITUATION_TO_DOC_ID = { new: 'new-app', refactor: 'refactor-app' };
|
|
18
|
+
|
|
19
|
+
export async function initCommand(options) {
|
|
20
|
+
const projectRoot = process.cwd();
|
|
21
|
+
|
|
22
|
+
p.intro('toolcrib init');
|
|
23
|
+
|
|
24
|
+
const spinner = p.spinner();
|
|
25
|
+
spinner.start(`Resolving version "${options.version}"`);
|
|
26
|
+
let release;
|
|
27
|
+
try {
|
|
28
|
+
release = await fetchRelease(options.version);
|
|
29
|
+
} catch (err) {
|
|
30
|
+
spinner.stop(`Failed to resolve/download version "${options.version}"`);
|
|
31
|
+
throw err;
|
|
32
|
+
}
|
|
33
|
+
spinner.stop(`Resolved "${options.version}" → v${release.version}`);
|
|
34
|
+
|
|
35
|
+
const changes = new PendingChanges();
|
|
36
|
+
|
|
37
|
+
// 1. Every vendored file becomes a propose() call — new-file and
|
|
38
|
+
// modified-file cases are handled identically (see PendingChanges),
|
|
39
|
+
// so init and merge share this exact loop shape.
|
|
40
|
+
for (const relPath of release.allFiles()) {
|
|
41
|
+
const proposedContent = release.readFile(relPath);
|
|
42
|
+
const targetPath = path.join(projectRoot, TOOLKIT_DIR, relPath);
|
|
43
|
+
const currentContent = readTextIfExists(targetPath);
|
|
44
|
+
// targetPath above is a real filesystem path (correctly OS-native);
|
|
45
|
+
// this one becomes a patch header and must stay forward-slash — see
|
|
46
|
+
// joinPatchPath's docstring.
|
|
47
|
+
changes.propose(joinPatchPath(TOOLKIT_DIR, relPath), currentContent, proposedContent, relPath);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// 2. package.json — propose only the additions, never touch existing entries.
|
|
51
|
+
const pkgPath = path.join(projectRoot, 'package.json');
|
|
52
|
+
const userPkg = readJsonIfExists(pkgPath);
|
|
53
|
+
if (!userPkg) {
|
|
54
|
+
p.log.error('No package.json found in the current directory. Run this from your project root.');
|
|
55
|
+
process.exitCode = 1;
|
|
56
|
+
await release.cleanup();
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const depDecisions = resolveDependencyDecisions(userPkg, release.config.peerDependencies);
|
|
61
|
+
const pkgWithDeps = depDecisions.toAdd.length > 0
|
|
62
|
+
? buildProposedPackageJson(userPkg, depDecisions.toAdd)
|
|
63
|
+
: userPkg;
|
|
64
|
+
|
|
65
|
+
// Combined into one patch against package.json — a second propose() call
|
|
66
|
+
// for the same relPath would produce two independent diffs both based on
|
|
67
|
+
// the original file, which can't both apply cleanly (see PendingChanges).
|
|
68
|
+
const importsResult = mergeImportsField(pkgWithDeps, TOOLKIT_IMPORTS_ENTRY);
|
|
69
|
+
if (depDecisions.toAdd.length > 0 || importsResult.changed) {
|
|
70
|
+
changes.propose(
|
|
71
|
+
'package.json',
|
|
72
|
+
readTextIfExists(pkgPath),
|
|
73
|
+
JSON.stringify(importsResult.pkg, null, 2) + '\n',
|
|
74
|
+
'package.json'
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// 3. .gitignore — same propose() mechanism, no special-casing required.
|
|
79
|
+
const gitignoreChange = proposeGitignore(projectRoot, release.version);
|
|
80
|
+
if (gitignoreChange) {
|
|
81
|
+
changes.propose(gitignoreChange.relPath, gitignoreChange.current, gitignoreChange.proposed, '.gitignore');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// 4. Version lockfile — the only piece of state persisted between runs.
|
|
85
|
+
const lockChange = proposeLockUpdate(projectRoot, release.version);
|
|
86
|
+
changes.propose(lockChange.relPath, lockChange.current, lockChange.proposed, '.toolcrib-lock.json');
|
|
87
|
+
|
|
88
|
+
// 5. AI instruction file — always propose the "core" managed block. The
|
|
89
|
+
// situational docs (new-app / refactor-app) need --situation since the
|
|
90
|
+
// CLI can't infer which applies; without it, the outro just tells the
|
|
91
|
+
// user which flag to re-run with (or to add the block manually,
|
|
92
|
+
// wrapped in the same fence, for `doctor`/`merge` to still track it).
|
|
93
|
+
const situationDocId = SITUATION_TO_DOC_ID[options.situation];
|
|
94
|
+
const docIdsToWrite = situationDocId ? ['core', situationDocId] : ['core'];
|
|
95
|
+
|
|
96
|
+
const agentsPath = path.join(projectRoot, DEFAULT_TARGET_FILE);
|
|
97
|
+
const originalAgentsContent = readTextIfExists(agentsPath);
|
|
98
|
+
let proposedAgentsContent = originalAgentsContent;
|
|
99
|
+
for (const docId of docIdsToWrite) {
|
|
100
|
+
const docContent = release.readFile(`ai-docs/${MANAGED_DOCS[docId]}`);
|
|
101
|
+
proposedAgentsContent = upsertManagedBlock(proposedAgentsContent, docId, release.version, docContent);
|
|
102
|
+
}
|
|
103
|
+
if (proposedAgentsContent !== originalAgentsContent) {
|
|
104
|
+
changes.propose(DEFAULT_TARGET_FILE, originalAgentsContent, proposedAgentsContent, DEFAULT_TARGET_FILE);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
await release.cleanup();
|
|
108
|
+
|
|
109
|
+
if (changes.isEmpty()) {
|
|
110
|
+
p.outro('Nothing to do — already up to date with this version.');
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const written = await changes.writeAll(projectRoot);
|
|
115
|
+
p.log.success(`Staged ${changes.count()} change(s):\n${changes.summarize()}`);
|
|
116
|
+
|
|
117
|
+
reportConflicts(depDecisions);
|
|
118
|
+
|
|
119
|
+
const missingSituation = !situationDocId
|
|
120
|
+
? `\n\nThis staged a "core" block in ${DEFAULT_TARGET_FILE}, but not a situational one — re-run with ` +
|
|
121
|
+
`--situation new (greenfield project) or --situation refactor (adopting into an existing app) to add it, ` +
|
|
122
|
+
`or add it by hand wrapped in the same <!-- toolcrib:managed:... --> fence so 'toolcrib merge' can still ` +
|
|
123
|
+
`track it. See ./toolcrib/ai-docs/NEW_APP.md / REFACTOR_APP.md.`
|
|
124
|
+
: '';
|
|
125
|
+
|
|
126
|
+
p.outro(
|
|
127
|
+
`Review the patches in ./toolcrib-patches/, then run:\n` +
|
|
128
|
+
` toolcrib apply${missingSituation}`
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function reportConflicts(depDecisions) {
|
|
133
|
+
if (depDecisions.conflicts.length === 0) return;
|
|
134
|
+
p.log.warn(
|
|
135
|
+
`${depDecisions.conflicts.length} dependency conflict(s) — not staged, needs your decision:\n` +
|
|
136
|
+
depDecisions.conflicts
|
|
137
|
+
.map((c) => ` ${c.name}: you have ${c.userRange}, toolcrib needs ${c.requiredRange} (${c.reason})`)
|
|
138
|
+
.join('\n')
|
|
139
|
+
);
|
|
140
|
+
}
|