toolcrib 0.10.0 → 0.11.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
@@ -138,12 +138,21 @@ toolcrib apply
138
138
  ```
139
139
 
140
140
  This is the command that actually creates/modifies files. It applies each
141
- patch in order, reports how many succeeded, and **deletes the
142
- `./toolcrib-patches/` folder afterward regardless of outcome** — a failed
143
- patch isn't kept around to retry; if something fails, re-run `init` or
144
- `merge` afterward to regenerate fresh patches against your project's
145
- current state, which is more likely to apply cleanly than retrying a stale
146
- one.
141
+ patch in order and reports how many succeeded. Staged work is never thrown
142
+ away:
143
+
144
+ - A patch that applied is removed from `./toolcrib-patches/`.
145
+ - **If any patch fails, nothing else is deleted.** The failed patches stay in
146
+ the folder and are listed, so you can fix the cause and re-run `apply`
147
+ (or delete the folder and run `merge` again).
148
+ - Conflict notes and upstream copies from `merge` (under
149
+ `./toolcrib-patches/conflicts/`) are not patches, so `apply` never writes
150
+ them into `./toolcrib/`. They stay in the folder, and `apply` lists them,
151
+ until you delete the folder.
152
+ - The folder itself is removed only when everything in it has been dealt with.
153
+
154
+ `init` and `merge` refuse to start while `./toolcrib-patches/` exists and is
155
+ not empty, and tell you to run `toolcrib apply` or delete the folder.
147
156
 
148
157
  If your project isn't already a git repository, `apply` will offer to run
149
158
  `git init` for you first (it uses `git apply` when possible, since that
@@ -203,16 +212,45 @@ toolcrib merge --version 2.1.0 # upgrade to a specific version
203
212
 
204
213
  Works like `init`, but smarter: for every vendored file, it compares three
205
214
  things — what you originally got, what's actually on disk now, and what
206
- the new version ships — and sorts each file into one of three outcomes:
215
+ the new version ships — and sorts each file into one of these outcomes:
207
216
 
208
- - **Safe update** — you never touched the file; the new version's copy is
217
+ - **Updated** — you never touched the file; the new version's copy is
209
218
  staged as a patch.
210
- - **Kept as-is** — you edited the file yourself and upstream didn't change
219
+ - **Kept local** — you edited the file yourself and upstream didn't change
211
220
  it; left alone, no patch generated.
212
- - **Conflict** — you edited it *and* upstream changed it too. `merge` won't
213
- guess which version wins. Instead it writes a `.upstream-diff` note
214
- explaining what upstream changed, so you (or your AI assistant) can
215
- reconcile it by hand.
221
+ - **Merged** — you edited it *and* upstream changed it, but in different
222
+ places. `merge` does a line-level three-way merge (your copy, the version
223
+ you installed, the new version) and stages the merged file as an ordinary
224
+ patch. It uses `git merge-file` when git is installed and a built-in
225
+ merge otherwise. Line endings are normalized for the merge and your
226
+ file's own style (CRLF or LF, and a leading BOM) is kept in the result.
227
+ - **Absorbed upstream** — the new release already contains your change (it
228
+ merges to exactly the new version's file, or your file already equals it).
229
+ Reported separately so you can see your patch landed upstream.
230
+ - **Conflict** — the edits overlap. The file is staged *with conflict
231
+ markers* (`<<<<<<< local` / `=======` / `>>>>>>> vX.Y.Z`) as a normal
232
+ patch, and listed by path in the summary. A file you edited that upstream
233
+ removed, or one you deleted that upstream changed, can't be merged: your
234
+ file is left untouched and only a note is written.
235
+ - **Binary conflict** — a file that isn't valid UTF-8 text (or contains a NUL
236
+ byte) is never line-merged. Your copy is untouched; the upstream copy is
237
+ staged whole, next to a note, in the staging folder.
238
+ - **Project-added** — a file under `./toolcrib/` that neither the installed nor
239
+ the new release ships (your own component, say). Listed as kept and never
240
+ touched. (`__tests__/` is only considered when you installed the test suite.)
241
+ - **Collision** — you added a file at a path the new release now ships. It is
242
+ three-way merged against an empty base: identical content is absorbed,
243
+ anything else is staged with conflict markers and reported as a collision.
244
+
245
+ Conflict notes and binary upstream copies are written under
246
+ `./toolcrib-patches/conflicts/` as plain files (`<path>.md`, `<path>.upstream`).
247
+ They are never written into `./toolcrib/`, because `apply` only applies
248
+ `.patch` files. When it finishes, `merge` prints a count for each outcome
249
+ above, then the conflicting paths and where their notes are.
250
+
251
+ Limitation: only files in conflict are checked for binary content. A binary
252
+ file that only upstream changed still goes through the ordinary text-patch
253
+ path, as before; the toolkit ships text source only.
216
254
 
217
255
  If you installed the test suite via `toolcrib init --with-tests`, `merge`
218
256
  keeps it in sync automatically — no separate flag needed here; it checks
@@ -302,10 +340,19 @@ notes of your own outside the fence, then run `merge` to restore it
302
340
  cleanly.
303
341
 
304
342
  **`merge` reports a conflict.**
305
- You changed a vendored file yourself, and the new version changed it too.
306
- Check the matching `.upstream-diff` file in `./toolcrib-patches/` for what
307
- upstream did, and reconcile manually — or hand it to your AI assistant with
308
- "reconcile my local changes to `<file>` with the upstream update."
343
+ You changed a vendored file yourself, and the new version changed it in an
344
+ overlapping place. For a text file, `apply` writes it with conflict markers:
345
+ resolve each `<<<<<<< local` ... `>>>>>>> vX.Y.Z` block in place. The note at
346
+ `./toolcrib-patches/conflicts/<file>.md` shows what upstream changed. For
347
+ removed, deleted and binary files nothing is written to your file; read the
348
+ note (and the staged `.upstream` copy for binary files). Or hand it to your AI
349
+ assistant with "reconcile my local changes to `<file>` with the upstream
350
+ update." Delete `./toolcrib-patches/` when you're done; `merge` and `init`
351
+ won't run while it's there.
352
+
353
+ **`merge` or `init` says `./toolcrib-patches/` already holds staged work.**
354
+ They refuse to overwrite unapplied patches or conflict notes. Run `toolcrib
355
+ apply`, or delete the folder if you're finished with it.
309
356
 
310
357
  **A bundler-specific note from `doctor`.**
311
358
  `doctor` detects Next.js, Create React App, Vite, webpack, and Parcel from
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "toolcrib",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Bootstrap the toolcrib UI toolkit into your project",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -4,6 +4,12 @@ import * as p from '@clack/prompts';
4
4
  import { PATCH_DIR } from '../lib/patches.js';
5
5
  import { isGitInstalled, ensureGitRepo, gitApplyStreaming } from '../lib/git.js';
6
6
  import { applyPatchFallback } from '../lib/patchFallback.js';
7
+ import { listFilesRecursive } from '../lib/zip.js';
8
+
9
+ /** Every file left under the staging folder, forward-slash, relative to it. */
10
+ function listStaged(dir) {
11
+ return listFilesRecursive(dir);
12
+ }
7
13
 
8
14
  export async function applyCommand() {
9
15
  const projectRoot = process.cwd();
@@ -23,7 +29,14 @@ export async function applyCommand() {
23
29
  .map((f) => path.join(patchDir, f));
24
30
 
25
31
  if (patchFiles.length === 0) {
26
- p.outro('No pending patches.');
32
+ const staged = listStaged(patchDir);
33
+ // Only empty folders left (every note resolved and deleted): clear them.
34
+ if (staged.length === 0) fs.rmSync(patchDir, { recursive: true, force: true });
35
+ p.outro(
36
+ staged.length > 0
37
+ ? `No pending patches. ./toolcrib-patches/ still holds ${staged.length} note/upstream-copy file(s) from a merge; resolve them, then delete the folder.`
38
+ : 'No pending patches.'
39
+ );
27
40
  return;
28
41
  }
29
42
 
@@ -64,18 +77,30 @@ export async function applyCommand() {
64
77
  }
65
78
  }
66
79
 
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 });
80
+ // Staging safety: nothing that hasn't been dealt with is ever deleted.
81
+ // Patches that applied are done, so they're removed (re-running apply
82
+ // would only fail on them). A failed patch stays, and so does everything
83
+ // else staged beside the patches (conflict notes, binary upstream copies):
84
+ // those are the user's work-in-progress, and `merge`/`init` refuse to run
85
+ // over a non-empty folder precisely so they can't be lost.
86
+ for (const patchFile of succeeded) fs.rmSync(patchFile, { force: true });
87
+ const remaining = listStaged(patchDir);
88
+ if (remaining.length === 0) fs.rmSync(patchDir, { recursive: true, force: true });
73
89
 
74
90
  p.log.success(`Applied ${succeeded.length} of ${patchFiles.length} patch(es).`);
75
91
  if (failed.length > 0) {
76
92
  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.`
93
+ `${failed.length} patch(es) failed and were kept in ./toolcrib-patches/ (nothing was deleted):\n` +
94
+ failed.map((f) => ` ${path.basename(f.patchFile)}${f.error ? ` — ${f.error.split('\n')[0]}` : ''}`).join('\n') +
95
+ `\nFix the cause and re-run 'toolcrib apply', or delete the folder and run 'toolcrib merge' again to regenerate them.`
96
+ );
97
+ }
98
+ const notes = remaining.filter((f) => !f.endsWith('.patch'));
99
+ if (notes.length > 0) {
100
+ p.log.info(
101
+ `${notes.length} staged file(s) were not applied (they are notes and upstream copies, never written into ./toolcrib/):\n` +
102
+ notes.map((f) => ` ./toolcrib-patches/${f}`).join('\n') +
103
+ `\nResolve what they describe, then delete ./toolcrib-patches/. 'toolcrib merge' will not run until it's gone.`
79
104
  );
80
105
  }
81
106
 
@@ -2,7 +2,7 @@ import path from 'node:path';
2
2
  import * as p from '@clack/prompts';
3
3
  import { fetchRelease, fetchTestsRelease } from '../lib/release.js';
4
4
  import { resolveVersion } from '../lib/github.js';
5
- import { PendingChanges, joinPatchPath } from '../lib/patches.js';
5
+ import { PendingChanges, joinPatchPath, hasStagedWork, STAGED_WORK_MESSAGE } from '../lib/patches.js';
6
6
  import { resolveDependencyDecisions, buildProposedPackageJson, mergeImportsField } from '../lib/deps.js';
7
7
  import { readJsonIfExists, readTextIfExists, fileExists, proposeGitignore, proposeLockUpdate } from '../lib/project.js';
8
8
  import { MANAGED_DOCS, DEFAULT_TARGET_FILE, KNOWN_TARGET_FILES, upsertManagedBlock } from '../lib/managedDocs.js';
@@ -39,6 +39,12 @@ export async function initCommand(options) {
39
39
 
40
40
  p.intro('toolcrib init');
41
41
 
42
+ if (hasStagedWork(projectRoot)) {
43
+ p.log.error(STAGED_WORK_MESSAGE);
44
+ process.exitCode = 1;
45
+ return;
46
+ }
47
+
42
48
  const spinner = p.spinner();
43
49
  spinner.start(`Resolving version "${options.version}"`);
44
50
  // Resolved once here, then passed as a concrete version string to both
@@ -1,8 +1,13 @@
1
+ import fs from 'node:fs';
1
2
  import path from 'node:path';
2
3
  import * as p from '@clack/prompts';
4
+ import { createTwoFilesPatch } from 'diff';
3
5
  import { fetchRelease, fetchTestsRelease } from '../lib/release.js';
4
6
  import { resolveVersion } from '../lib/github.js';
5
- import { PendingChanges, normalize, joinPatchPath } from '../lib/patches.js';
7
+ import { isGitInstalled } from '../lib/git.js';
8
+ import { listFilesRecursive } from '../lib/zip.js';
9
+ import { isBinaryBuffer, detectEol, toEol, mergeThreeWay } from '../lib/lineMerge.js';
10
+ import { PendingChanges, normalize, joinPatchPath, hasStagedWork, STAGED_WORK_MESSAGE } from '../lib/patches.js';
6
11
  import { resolveDependencyDecisions, buildProposedPackageJson, mergeImportsField } from '../lib/deps.js';
7
12
  import { fileExists, readJsonIfExists, readLock, readTextIfExists, proposeLockUpdate } from '../lib/project.js';
8
13
  import { MANAGED_DOCS, KNOWN_TARGET_FILES, listManagedBlocks, upsertManagedBlock } from '../lib/managedDocs.js';
@@ -11,6 +16,12 @@ const TOOLKIT_DIR = './toolcrib';
11
16
  // See init.js for why this exists — installs predating this entry need it
12
17
  // added on `merge` too, not just on a fresh `init`.
13
18
  const TOOLKIT_IMPORTS_ENTRY = { '#toolcrib': './toolcrib/index.ts' };
19
+ // Conflict notes and binary upstream copies are staged here, under the
20
+ // staging folder (never under ./toolcrib/, and never as `.patch` files, so
21
+ // `apply` cannot write them into the kit).
22
+ const NOTES_DIR = 'conflicts';
23
+ // Meta files inside ./toolcrib/ that the CLI itself owns; never "project-added".
24
+ const KIT_META_FILES = new Set(['.toolcrib-lock.json', '.toolcrib-tests-config.json']);
14
25
 
15
26
  /**
16
27
  * Four-way classification per vendored file, comparing:
@@ -23,6 +34,8 @@ const TOOLKIT_IMPORTS_ENTRY = { '#toolcrib': './toolcrib/index.ts' };
23
34
  *
24
35
  * Returns one of five outcomes: 'unchanged', 'safe-update', 'keep-local',
25
36
  * 'conflict', or 'converged' (both sides changed to identical content).
37
+ * 'conflict' means both sides changed differently; the caller then tries a
38
+ * line-level three-way merge before reporting anything as a conflict.
26
39
  */
27
40
  function classify(original, local, updated) {
28
41
  const localModified = normalize(local) !== normalize(original);
@@ -37,6 +50,117 @@ function classify(original, local, updated) {
37
50
  return 'conflict';
38
51
  }
39
52
 
53
+ /** Raw bytes of a release file; test fakes without readBuffer fall back to their text. */
54
+ function readBytes(release, relPath) {
55
+ return release.readBuffer ? release.readBuffer(relPath) : Buffer.from(release.readFile(relPath), 'utf8');
56
+ }
57
+
58
+ function newResults() {
59
+ return {
60
+ updated: 0, // clean update patches proposed
61
+ merged: [], // both sides changed, line merge was clean
62
+ absorbed: [], // local change is already contained in the new release
63
+ kept: 0, // local edit, upstream untouched
64
+ deleted: 0, // removed upstream, proposed for deletion
65
+ projectAdded: [], // in ./toolcrib/ but in neither release
66
+ conflicts: [], // { relPath, displayPath, kind, collision, notePath }
67
+ };
68
+ }
69
+
70
+ const fenced = (text) => `~~~~diff\n${text.trimEnd()}\n~~~~\n`;
71
+
72
+ /**
73
+ * Stage a conflict's note (and, for a binary file, the untouched upstream
74
+ * copy) in the staging folder and record it for the summary. `noteName` is
75
+ * the toolkit-relative path the note is filed under.
76
+ */
77
+ function recordConflict(ctx, { relPath, noteName = relPath, displayPath, kind, collision = false, body, upstreamBytes }) {
78
+ const notePath = `${NOTES_DIR}/${noteName}.md`;
79
+ const copyPath = upstreamBytes ? `${NOTES_DIR}/${noteName}.upstream` : null;
80
+ const heading = collision ? `Add/add collision: ${displayPath}` : `Conflict: ${displayPath}`;
81
+ const copyLine = copyPath ? `\nThe untouched upstream copy (v${ctx.newVersion}) is staged beside this note as \`${path.posix.basename(copyPath)}\`.\n` : '';
82
+ ctx.changes.addStagedFile(notePath, `# ${heading}\n\n${body}\n${copyLine}`);
83
+ if (copyPath) ctx.changes.addStagedFile(copyPath, upstreamBytes);
84
+ ctx.results.conflicts.push({ relPath, displayPath, kind, collision, notePath: `./toolcrib-patches/${notePath}` });
85
+ }
86
+
87
+ function upstreamDiff(ctx, relPath, original, updated) {
88
+ return (
89
+ `## What upstream changed (v${ctx.oldVersion} to v${ctx.newVersion})\n\n` +
90
+ fenced(createTwoFilesPatch(`a/${relPath}`, `b/${relPath}`, normalize(original), normalize(updated)))
91
+ );
92
+ }
93
+
94
+ /**
95
+ * The file changed on both sides, differently: try a line-level three-way
96
+ * merge (original = base, local = ours, updated = theirs). A clean merge is
97
+ * proposed as an ordinary patch; overlapping edits are proposed with conflict
98
+ * markers and reported; anything that can't be line-merged (binary, deleted
99
+ * locally) gets a note in the staging folder and the local file is untouched.
100
+ */
101
+ async function resolveBothChanged(ctx, { relPath, targetPath, hasOriginal, oldRelease, newRelease, original, updated, collision }) {
102
+ const patchPath = joinPatchPath(TOOLKIT_DIR, relPath);
103
+ const displayPath = patchPath;
104
+ const base = { relPath, displayPath, collision };
105
+
106
+ if (!fileExists(targetPath)) {
107
+ // In the old release, deleted from the project, changed upstream: nothing to merge into.
108
+ recordConflict(ctx, {
109
+ ...base,
110
+ kind: 'deleted-locally',
111
+ body:
112
+ `This file was deleted from the project, but upstream changed it in v${ctx.newVersion}.\n` +
113
+ `It was not recreated. Decide whether to restore it (take the upstream version below) or keep it deleted.\n\n` +
114
+ upstreamDiff(ctx, relPath, original, updated),
115
+ });
116
+ return;
117
+ }
118
+
119
+ const localBytes = fs.readFileSync(targetPath);
120
+ const originalBytes = hasOriginal ? readBytes(oldRelease, relPath) : Buffer.alloc(0);
121
+ const updatedBytes = readBytes(newRelease, relPath);
122
+
123
+ if (isBinaryBuffer(localBytes) || isBinaryBuffer(originalBytes) || isBinaryBuffer(updatedBytes)) {
124
+ recordConflict(ctx, {
125
+ ...base,
126
+ kind: 'binary',
127
+ body:
128
+ `This is a binary file (not valid UTF-8 text), so it was not line-merged. ` +
129
+ `Both your project and upstream changed it${collision ? '' : ` since v${ctx.oldVersion}`}.\n` +
130
+ `Your copy in ./toolcrib/ is untouched. Pick one, or reconcile them with a tool that understands the format.`,
131
+ upstreamBytes: updatedBytes,
132
+ });
133
+ return;
134
+ }
135
+
136
+ const localRaw = localBytes.toString('utf8'); // exact disk content (BOM and CRLF intact): what the patch must match
137
+ const hasBom = localRaw.charCodeAt(0) === 0xfeff;
138
+ const eol = detectEol(localRaw);
139
+ const ours = normalize(hasBom ? localRaw.slice(1) : localRaw);
140
+ const theirs = normalize(updated);
141
+ const result = await mergeThreeWay({ base: normalize(original), ours, theirs }, { engine: ctx.engine, newLabel: `v${ctx.newVersion}` });
142
+
143
+ const proposed = (hasBom ? '' : '') + toEol(result.merged, eol);
144
+
145
+ if (result.conflicts === 0) {
146
+ if (result.merged === theirs) ctx.results.absorbed.push(displayPath);
147
+ else ctx.results.merged.push(displayPath);
148
+ ctx.changes.propose(patchPath, localRaw, proposed, relPath);
149
+ return;
150
+ }
151
+
152
+ ctx.changes.propose(patchPath, localRaw, proposed, `${relPath} (conflict markers)`);
153
+ recordConflict(ctx, {
154
+ ...base,
155
+ kind: 'markers',
156
+ body:
157
+ `${collision ? 'The project added this file and the new release now ships one at the same path. ' : 'Both your project and upstream changed this file. '}` +
158
+ `${result.conflicts} region(s) overlap. The patch for ${displayPath} writes the merged file with ` +
159
+ `\`<<<<<<< local\` / \`=======\` / \`>>>>>>> v${ctx.newVersion}\` markers; resolve each one in place and delete the markers.\n\n` +
160
+ (collision ? '' : upstreamDiff(ctx, relPath, original, updated)),
161
+ });
162
+ }
163
+
40
164
  /**
41
165
  * The full four-way diff, applied per-file across one (oldRelease,
42
166
  * newRelease) pair — extracted so both the core toolkit files and (when
@@ -47,14 +171,11 @@ function classify(original, local, updated) {
47
171
  * scripts/build-tests-release.js), so no separate target-directory
48
172
  * parameter is needed here.
49
173
  *
50
- * Mutates `changes`/`conflicts` in place (matching this file's existing
51
- * call-site style below) and returns per-call counts for the caller to
52
- * fold into its own running totals.
174
+ * Records everything in `ctx` (`changes` for patches/notes, `results` for the
175
+ * summary).
53
176
  */
54
- function diffReleaseFiles(projectRoot, oldRelease, newRelease, changes, conflicts) {
55
- let updatedCount = 0;
56
- let keptCount = 0;
57
- let deletedCount = 0;
177
+ async function diffReleaseFiles(projectRoot, oldRelease, newRelease, ctx) {
178
+ const { changes, results } = ctx;
58
179
 
59
180
  // Found by review: allFiles() re-walks its temp directory recursively on
60
181
  // every call (listFilesRecursive is not cached), so calling
@@ -71,8 +192,12 @@ function diffReleaseFiles(projectRoot, oldRelease, newRelease, changes, conflict
71
192
  const targetPath = path.join(projectRoot, TOOLKIT_DIR, relPath);
72
193
  const local = readTextIfExists(targetPath);
73
194
  const updated = newRelease.readFile(relPath);
74
- // A file that's new in this release won't exist in oldRelease — treat as empty original.
75
- const original = oldFiles.has(relPath) ? oldRelease.readFile(relPath) : '';
195
+ const hasOriginal = oldFiles.has(relPath);
196
+ // A file that's new in this release won't exist in oldRelease — treat as
197
+ // an empty original. If the project already has a file at that path it is
198
+ // an add/add collision: the same three-way merge, with an empty base.
199
+ const original = hasOriginal ? oldRelease.readFile(relPath) : '';
200
+ const collision = !hasOriginal && fileExists(targetPath);
76
201
 
77
202
  const status = classify(original, local, updated);
78
203
 
@@ -80,18 +205,18 @@ function diffReleaseFiles(projectRoot, oldRelease, newRelease, changes, conflict
80
205
  case 'unchanged':
81
206
  case 'safe-update':
82
207
  changes.propose(joinPatchPath(TOOLKIT_DIR, relPath), local, updated, relPath);
83
- updatedCount++;
208
+ results.updated++;
84
209
  break;
85
210
  case 'converged':
86
211
  // Local already matches the new release, so there's nothing to
87
- // propose; it still counts as updated, not as a conflict.
88
- updatedCount++;
212
+ // propose: the change was absorbed upstream.
213
+ results.absorbed.push(joinPatchPath(TOOLKIT_DIR, relPath));
89
214
  break;
90
215
  case 'keep-local':
91
- keptCount++;
216
+ results.kept++;
92
217
  break;
93
218
  case 'conflict':
94
- conflicts.push({ relPath, patchPath: joinPatchPath(TOOLKIT_DIR, relPath), original, local, updated });
219
+ await resolveBothChanged(ctx, { relPath, targetPath, hasOriginal, oldRelease, newRelease, original, updated, collision });
95
220
  break;
96
221
  }
97
222
  }
@@ -106,7 +231,8 @@ function diffReleaseFiles(projectRoot, oldRelease, newRelease, changes, conflict
106
231
  // upstream" as updated content of '': local unmodified from original ->
107
232
  // safe to delete; local modified -> a real conflict (don't silently
108
233
  // discard someone's customization just because upstream dropped the
109
- // file), same as any other conflicting edit.
234
+ // file), same as any other conflicting edit. No merge is possible here, so
235
+ // it's a note in the staging folder.
110
236
  for (const relPath of oldFiles) {
111
237
  if (newFiles.has(relPath)) continue;
112
238
 
@@ -120,16 +246,17 @@ function diffReleaseFiles(projectRoot, oldRelease, newRelease, changes, conflict
120
246
  switch (status) {
121
247
  case 'safe-update':
122
248
  changes.propose(joinPatchPath(TOOLKIT_DIR, relPath), local, '', relPath);
123
- deletedCount++;
249
+ results.deleted++;
124
250
  break;
125
251
  case 'conflict':
126
- conflicts.push({
252
+ recordConflict(ctx, {
127
253
  relPath,
128
- patchPath: joinPatchPath(TOOLKIT_DIR, relPath),
129
- original,
130
- local,
131
- updated: '',
132
- removedUpstream: true,
254
+ displayPath: joinPatchPath(TOOLKIT_DIR, relPath),
255
+ kind: 'removed-upstream',
256
+ body:
257
+ `This file was modified locally, but removed upstream in v${ctx.newVersion}.\n` +
258
+ `Automatic deletion was skipped and your copy is untouched. Review it, or ask your AI assistant:\n` +
259
+ `"reconcile my local changes to ${relPath}, which was removed upstream"\n`,
133
260
  });
134
261
  break;
135
262
  // 'unchanged'/'keep-local' can't occur here: original is always
@@ -140,8 +267,24 @@ function diffReleaseFiles(projectRoot, oldRelease, newRelease, changes, conflict
140
267
  // proposed, so the empty file is left on disk as-is.
141
268
  }
142
269
  }
270
+ }
143
271
 
144
- return { updatedCount, keptCount, deletedCount };
272
+ /**
273
+ * Files under ./toolcrib/ that neither the old nor the new release ships:
274
+ * the project's own additions. Reported, never touched. `known` is every
275
+ * release-relative path of every release involved; `testsInstalled` decides
276
+ * whether `__tests__/` is the kit's (and so already covered by `known`) or
277
+ * is simply not looked at.
278
+ */
279
+ function findProjectAdded(projectRoot, known, testsInstalled) {
280
+ const toolkitRoot = path.join(projectRoot, TOOLKIT_DIR);
281
+ if (!fs.existsSync(toolkitRoot)) return [];
282
+ return listFilesRecursive(toolkitRoot)
283
+ .filter((relPath) => !KIT_META_FILES.has(relPath))
284
+ .filter((relPath) => testsInstalled || !relPath.startsWith('__tests__/'))
285
+ .filter((relPath) => !known.has(relPath))
286
+ .map((relPath) => joinPatchPath(TOOLKIT_DIR, relPath))
287
+ .sort();
145
288
  }
146
289
 
147
290
  /**
@@ -156,9 +299,8 @@ function diffReleaseFiles(projectRoot, oldRelease, newRelease, changes, conflict
156
299
  * the block may be older or newer than the currently-installed toolkit
157
300
  * version if it was hand-edited or added out of band.
158
301
  */
159
- async function mergeManagedBlocks(projectRoot, oldRelease, newRelease, changes, conflicts) {
160
- let updatedCount = 0;
161
- let keptCount = 0;
302
+ async function mergeManagedBlocks(projectRoot, oldRelease, newRelease, ctx) {
303
+ const { changes, results } = ctx;
162
304
 
163
305
  for (const targetFile of KNOWN_TARGET_FILES) {
164
306
  const targetPath = path.join(projectRoot, targetFile);
@@ -211,23 +353,28 @@ async function mergeManagedBlocks(projectRoot, oldRelease, newRelease, changes,
211
353
  // the "original" and misclassifies this block.
212
354
  proposedFileContent = upsertManagedBlock(proposedFileContent, block.docId, newRelease.version, updatedDocContent);
213
355
  fileChanged = fileChanged || status !== 'unchanged';
214
- updatedCount++;
356
+ if (status === 'converged') results.absorbed.push(`${targetFile} (managed block "${block.docId}")`);
357
+ else results.updated++;
215
358
  break;
216
359
  case 'keep-local':
217
- keptCount++;
360
+ results.kept++;
218
361
  break;
219
- case 'conflict':
220
- // Not a vendored file under TOOLKIT_DIR, so patchPath can't be
221
- // derived from relPath the way vendored-file conflicts below can
222
- // — it's set explicitly here instead.
223
- conflicts.push({
224
- relPath: `${targetFile} (managed block "${block.docId}")`,
225
- patchPath: `${targetFile}.managed-${block.docId}`,
226
- original: originalDocContent,
227
- local: block.content,
228
- updated: updatedDocContent,
362
+ case 'conflict': {
363
+ // Not a vendored file under TOOLKIT_DIR. The block isn't a whole
364
+ // file, so no line merge: a note with the upstream change.
365
+ const displayPath = `${targetFile} (managed block "${block.docId}")`;
366
+ recordConflict(ctx, {
367
+ relPath: displayPath,
368
+ noteName: `${targetFile}.managed-${block.docId}`,
369
+ displayPath,
370
+ kind: 'managed-block',
371
+ body:
372
+ `The managed block "${block.docId}" in ${targetFile} was edited locally AND changed upstream.\n` +
373
+ `It was left as-is. Reconcile it by hand or ask your AI assistant.\n\n` +
374
+ upstreamDiff(ctx, `${targetFile}.managed-${block.docId}`, originalDocContent, updatedDocContent),
229
375
  });
230
376
  break;
377
+ }
231
378
  }
232
379
  }
233
380
 
@@ -235,8 +382,6 @@ async function mergeManagedBlocks(projectRoot, oldRelease, newRelease, changes,
235
382
  changes.propose(targetFile, currentFileContent, proposedFileContent, targetFile);
236
383
  }
237
384
  }
238
-
239
- return { updatedCount, keptCount };
240
385
  }
241
386
 
242
387
  export async function mergeCommand(options) {
@@ -250,6 +395,12 @@ export async function mergeCommand(options) {
250
395
  return;
251
396
  }
252
397
 
398
+ if (hasStagedWork(projectRoot)) {
399
+ p.log.error(STAGED_WORK_MESSAGE);
400
+ process.exitCode = 1;
401
+ return;
402
+ }
403
+
253
404
  const spinner = p.spinner();
254
405
  spinner.start(`Fetching current (v${lock.version}) and target (${options.version}) releases`);
255
406
  // Resolved once, then reused as a concrete version for every fetch below
@@ -304,23 +455,25 @@ export async function mergeCommand(options) {
304
455
  }
305
456
 
306
457
  const changes = new PendingChanges();
307
- const conflicts = [];
308
-
309
- const coreDiff = diffReleaseFiles(projectRoot, oldRelease, newRelease, changes, conflicts);
310
- let updatedCount = coreDiff.updatedCount;
311
- let keptCount = coreDiff.keptCount;
312
- let deletedCount = coreDiff.deletedCount;
458
+ const results = newResults();
459
+ // `mergeEngine` is a test seam ('git' | 'js'), not a CLI flag.
460
+ const engine = options.mergeEngine ?? ((await isGitInstalled()) ? 'git' : 'js');
461
+ const ctx = { changes, results, engine, oldVersion: oldRelease.version, newVersion: newRelease.version };
313
462
 
463
+ await diffReleaseFiles(projectRoot, oldRelease, newRelease, ctx);
314
464
  if (oldTestsRelease && newTestsRelease) {
315
- const testsDiff = diffReleaseFiles(projectRoot, oldTestsRelease, newTestsRelease, changes, conflicts);
316
- updatedCount += testsDiff.updatedCount;
317
- keptCount += testsDiff.keptCount;
318
- deletedCount += testsDiff.deletedCount;
465
+ await diffReleaseFiles(projectRoot, oldTestsRelease, newTestsRelease, ctx);
319
466
  }
320
467
 
321
- const managedBlockCounts = await mergeManagedBlocks(projectRoot, oldRelease, newRelease, changes, conflicts);
322
- updatedCount += managedBlockCounts.updatedCount;
323
- keptCount += managedBlockCounts.keptCount;
468
+ await mergeManagedBlocks(projectRoot, oldRelease, newRelease, ctx);
469
+
470
+ const known = new Set([
471
+ ...oldRelease.allFiles(),
472
+ ...newRelease.allFiles(),
473
+ ...(oldTestsRelease?.allFiles() ?? []),
474
+ ...(newTestsRelease?.allFiles() ?? []),
475
+ ]);
476
+ results.projectAdded = findProjectAdded(projectRoot, known, Boolean(lock.testsVersion));
324
477
 
325
478
  await cleanupAll();
326
479
 
@@ -394,32 +547,37 @@ export async function mergeCommand(options) {
394
547
  );
395
548
  }
396
549
 
397
- // Conflicts get their own patch showing the *upstream* diff (local vs.
398
- // untouched), so the human/AI can see exactly what upstream changed
399
- // without it silently overwriting local customizations.
400
- for (const conflict of conflicts) {
401
- changes.propose(
402
- `${conflict.patchPath}.upstream-diff`,
403
- '',
404
- buildConflictNote(conflict),
405
- `${conflict.relPath} (conflict)`
406
- );
407
- }
408
-
409
550
  if (!changes.isEmpty()) {
410
551
  await changes.writeAll(projectRoot);
411
552
  }
412
553
 
554
+ const conflicts = results.conflicts.filter((c) => !c.collision);
555
+ const collisions = results.conflicts.filter((c) => c.collision);
556
+
413
557
  p.log.success(
414
- `${updatedCount} file(s) updated cleanly, ${keptCount} local edit(s) preserved untouched` +
415
- (deletedCount > 0 ? `, ${deletedCount} file(s) removed upstream and proposed for deletion` : '') +
416
- '.'
558
+ `${results.updated} updated, ${results.merged.length} merged, ${results.absorbed.length} absorbed upstream, ` +
559
+ `${results.kept} kept-local, ${results.projectAdded.length} project-added, ` +
560
+ `${conflicts.length} conflict(s), ${collisions.length} collision(s), ${results.deleted} removed.`
417
561
  );
562
+ const list = (title, items) => {
563
+ if (items.length > 0) p.log.info(`${title}:\n${items.map((x) => ` ${x}`).join('\n')}`);
564
+ };
565
+ list('Merged (both sides changed, no overlap)', results.merged);
566
+ list('Absorbed upstream (the new release already contains your change)', results.absorbed);
567
+ list('Project-added (kept, not part of toolcrib)', results.projectAdded);
568
+ const conflictLine = (c) => ` ${c.displayPath} [${c.kind}] note: ${c.notePath}`;
418
569
  if (conflicts.length > 0) {
419
570
  p.log.warn(
420
571
  `${conflicts.length} conflict(s) — both local and upstream changed:\n` +
421
- conflicts.map((c) => ` ${c.relPath}`).join('\n') +
422
- `\n\nSee the .upstream-diff patch for each — ask your AI assistant to reconcile them.`
572
+ conflicts.map(conflictLine).join('\n') +
573
+ `\n\nFiles marked [markers] are staged with conflict markers to resolve after apply; for the others your file is untouched. ` +
574
+ `Notes live in ./toolcrib-patches/${NOTES_DIR}/ and are never applied into ./toolcrib/.`
575
+ );
576
+ }
577
+ if (collisions.length > 0) {
578
+ p.log.warn(
579
+ `${collisions.length} collision(s) — you added a file at a path the new release now ships:\n` +
580
+ collisions.map(conflictLine).join('\n')
423
581
  );
424
582
  }
425
583
 
@@ -440,18 +598,3 @@ export async function mergeCommand(options) {
440
598
 
441
599
  p.outro(changes.isEmpty() ? 'No changes to apply.' : 'Review ./toolcrib-patches/, then run `toolcrib apply`.');
442
600
  }
443
-
444
- function buildConflictNote(conflict) {
445
- if (conflict.removedUpstream) {
446
- return (
447
- `This file was modified locally, but removed upstream in the new version.\n` +
448
- `Automatic deletion was skipped — review manually or ask your AI assistant:\n` +
449
- `"reconcile my local changes to ${conflict.relPath}, which was removed upstream"\n`
450
- );
451
- }
452
- return (
453
- `This file was modified locally AND changed upstream.\n` +
454
- `Automatic merge was skipped — review manually or ask your AI assistant:\n` +
455
- `"reconcile my local changes to ${conflict.relPath} with the upstream update"\n`
456
- );
457
- }
package/src/lib/git.js CHANGED
@@ -63,6 +63,53 @@ export async function gitInit(cwd) {
63
63
  return quietGit(['init'], cwd);
64
64
  }
65
65
 
66
+ /**
67
+ * Runs `git merge-file -p ours base theirs` inside `dir` (three files already
68
+ * written there under those exact names) and returns the merged text plus the
69
+ * conflict count. git's exit status IS the conflict count (capped at 127);
70
+ * anything else (255 = error, e.g. a binary file) throws. No shell, per the
71
+ * policy at the top of this file; `merge.conflictStyle=merge` is forced so a
72
+ * user's global diff3/zdiff3 setting can't change the marker layout.
73
+ */
74
+ export async function gitMergeFile(dir, labels) {
75
+ const args = [
76
+ '-c',
77
+ 'merge.conflictStyle=merge',
78
+ 'merge-file',
79
+ '-p',
80
+ '-L',
81
+ labels.ours,
82
+ '-L',
83
+ labels.base,
84
+ '-L',
85
+ labels.theirs,
86
+ 'ours',
87
+ 'base',
88
+ 'theirs',
89
+ ];
90
+ const run = async (a, shell) => {
91
+ try {
92
+ const { stdout } = await execFileAsync('git', a, {
93
+ ...baseOpts(dir, shell),
94
+ encoding: 'utf8',
95
+ maxBuffer: 256 * 1024 * 1024,
96
+ });
97
+ return { conflicts: 0, merged: stdout };
98
+ } catch (err) {
99
+ if (typeof err.code === 'number' && err.code >= 1 && err.code <= 127) {
100
+ return { conflicts: err.code, merged: err.stdout };
101
+ }
102
+ throw err;
103
+ }
104
+ };
105
+ try {
106
+ return await run(args, false);
107
+ } catch (err) {
108
+ if (shouldRetryWithShell(err)) return run(shellSafeArgs(args), true);
109
+ throw err;
110
+ }
111
+ }
112
+
66
113
  /**
67
114
  * Streaming apply — the user should see git's own output live, especially
68
115
  * on failure (git apply's "patch does not apply" messages point at the
@@ -0,0 +1,190 @@
1
+ import fs from 'node:fs';
2
+ import fsp from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { diffArrays } from 'diff';
6
+ import { gitMergeFile } from './git.js';
7
+
8
+ /**
9
+ * Line-level three-way merge for `toolcrib merge`.
10
+ *
11
+ * Two engines, same contract: `git merge-file -p` when git is available, and
12
+ * a pure-JS diff3 built on the `diff` package's Myers `diffArrays` otherwise.
13
+ * Both take LF-normalized text (callers normalize line endings first and
14
+ * restore the local file's EOL style afterwards) and return
15
+ * `{ merged, conflicts, engine }`, where `conflicts` is the number of
16
+ * conflict regions and `merged` carries standard markers
17
+ * (`<<<<<<< local` / `=======` / `>>>>>>> <newLabel>`) for each of them.
18
+ *
19
+ * The JS engine matches git on clean-vs-conflict outcome for ordinary edits:
20
+ * edits that touch or overlap conflict, identical edits on both sides
21
+ * resolve, and a conflicting region is refined down to the lines that
22
+ * actually differ (git's "zealous" behavior). It does not replicate git's
23
+ * extra heuristic of folding two conflicts separated by only a few
24
+ * non-alphanumeric lines into one, so marker granularity can differ from git
25
+ * in those rare layouts.
26
+ */
27
+
28
+ /** NUL byte, or bytes that are not valid UTF-8. Such content is never line-merged. */
29
+ export function isBinaryBuffer(buf) {
30
+ if (buf.includes(0)) return true;
31
+ try {
32
+ new TextDecoder('utf-8', { fatal: true }).decode(buf);
33
+ return false;
34
+ } catch {
35
+ return true;
36
+ }
37
+ }
38
+
39
+ /** 'crlf' when the text uses CRLF more than bare LF, else 'lf'. */
40
+ export function detectEol(text) {
41
+ const crlf = (text.match(/\r\n/g) || []).length;
42
+ const lf = (text.match(/\n/g) || []).length - crlf;
43
+ return crlf > lf ? 'crlf' : 'lf';
44
+ }
45
+
46
+ export function toEol(text, eol) {
47
+ return eol === 'crlf' ? text.replace(/\n/g, '\r\n') : text;
48
+ }
49
+
50
+ const splitLines = (text) => text.match(/[^\n]*\n|[^\n]+$/g) || [];
51
+ const ensureNl = (lines) =>
52
+ lines.length > 0 && !lines[lines.length - 1].endsWith('\n')
53
+ ? [...lines.slice(0, -1), lines[lines.length - 1] + '\n']
54
+ : lines;
55
+
56
+ /** Changed regions of `other` relative to `base`: [{ s, e, lines }] over base indexes [s, e). */
57
+ function hunks(base, other) {
58
+ const out = [];
59
+ let pos = 0;
60
+ let cur = null;
61
+ for (const part of diffArrays(base, other)) {
62
+ if (!part.added && !part.removed) {
63
+ if (cur) out.push(cur);
64
+ cur = null;
65
+ pos += part.value.length;
66
+ continue;
67
+ }
68
+ cur ??= { s: pos, e: pos, lines: [] };
69
+ if (part.removed) {
70
+ cur.e += part.value.length;
71
+ pos += part.value.length;
72
+ } else {
73
+ cur.lines.push(...part.value);
74
+ }
75
+ }
76
+ if (cur) out.push(cur);
77
+ return out;
78
+ }
79
+
80
+ function render(base, hs, start, end) {
81
+ const out = [];
82
+ let pos = start;
83
+ for (const h of hs) {
84
+ out.push(...base.slice(pos, h.s), ...h.lines);
85
+ pos = h.e;
86
+ }
87
+ out.push(...base.slice(pos, end));
88
+ return out;
89
+ }
90
+
91
+ const same = (a, b) => a.length === b.length && a.every((l, i) => l === b[i]);
92
+
93
+ export function mergeThreeWayJs(base, ours, theirs, labels) {
94
+ const b = splitLines(base);
95
+ const A = hunks(b, splitLines(ours));
96
+ const B = hunks(b, splitLines(theirs));
97
+ const out = [];
98
+ let conflicts = 0;
99
+ let pos = 0;
100
+ let i = 0;
101
+ let j = 0;
102
+
103
+ const conflictBlock = (o, t) => {
104
+ conflicts++;
105
+ out.push(`<<<<<<< ${labels.ours}\n`, ...ensureNl(o), '=======\n', ...ensureNl(t), `>>>>>>> ${labels.theirs}\n`);
106
+ };
107
+
108
+ while (i < A.length || j < B.length) {
109
+ const takeA = i < A.length && (j >= B.length || A[i].s <= B[j].s);
110
+ const first = takeA ? A[i++] : B[j++];
111
+ const gA = takeA ? [first] : [];
112
+ const gB = takeA ? [] : [first];
113
+ const start = first.s;
114
+ let end = first.e;
115
+ for (;;) {
116
+ if (i < A.length && A[i].s <= end) {
117
+ end = Math.max(end, A[i].e);
118
+ gA.push(A[i++]);
119
+ } else if (j < B.length && B[j].s <= end) {
120
+ end = Math.max(end, B[j].e);
121
+ gB.push(B[j++]);
122
+ } else break;
123
+ }
124
+
125
+ out.push(...b.slice(pos, start));
126
+ pos = end;
127
+
128
+ if (gB.length === 0) {
129
+ out.push(...render(b, gA, start, end));
130
+ } else if (gA.length === 0) {
131
+ out.push(...render(b, gB, start, end));
132
+ } else {
133
+ const o = render(b, gA, start, end);
134
+ const t = render(b, gB, start, end);
135
+ if (same(o, t)) {
136
+ out.push(...o);
137
+ } else {
138
+ // Refine: lines both sides agree on stay outside the markers.
139
+ let po = [];
140
+ let pt = [];
141
+ const flush = () => {
142
+ if (po.length || pt.length) conflictBlock(po, pt);
143
+ po = [];
144
+ pt = [];
145
+ };
146
+ for (const part of diffArrays(o, t)) {
147
+ if (part.removed) po.push(...part.value);
148
+ else if (part.added) pt.push(...part.value);
149
+ else {
150
+ flush();
151
+ out.push(...part.value);
152
+ }
153
+ }
154
+ flush();
155
+ }
156
+ }
157
+ }
158
+ out.push(...b.slice(pos));
159
+ return { merged: out.join(''), conflicts };
160
+ }
161
+
162
+ async function mergeWithGit(base, ours, theirs, labels) {
163
+ const dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'toolcrib-merge-'));
164
+ try {
165
+ fs.writeFileSync(path.join(dir, 'ours'), ours);
166
+ fs.writeFileSync(path.join(dir, 'base'), base);
167
+ fs.writeFileSync(path.join(dir, 'theirs'), theirs);
168
+ const { merged, conflicts } = await gitMergeFile(dir, { ours: labels.ours, base: 'base', theirs: labels.theirs });
169
+ return { merged, conflicts };
170
+ } finally {
171
+ await fsp.rm(dir, { recursive: true, force: true }).catch(() => {});
172
+ }
173
+ }
174
+
175
+ /**
176
+ * @param {{base:string, ours:string, theirs:string}} texts - LF-normalized, BOM-free
177
+ * @param {{engine?: 'git'|'js', newLabel: string}} opts - `engine` defaults to 'js';
178
+ * a git failure on one file falls back to the JS engine for that file.
179
+ */
180
+ export async function mergeThreeWay({ base, ours, theirs }, { engine = 'js', newLabel }) {
181
+ const labels = { ours: 'local', theirs: newLabel };
182
+ if (engine === 'git') {
183
+ try {
184
+ return { ...(await mergeWithGit(base, ours, theirs, labels)), engine: 'git' };
185
+ } catch {
186
+ // fall through to the pure-JS engine
187
+ }
188
+ }
189
+ return { ...mergeThreeWayJs(base, ours, theirs, labels), engine: 'js' };
190
+ }
@@ -2,6 +2,7 @@ import fs from 'node:fs';
2
2
  import fsp from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { createTwoFilesPatch } from 'diff';
5
+ import { listFilesRecursive } from './zip.js';
5
6
 
6
7
  export const PATCH_DIR = './toolcrib-patches';
7
8
 
@@ -92,6 +93,7 @@ export function buildPatch(relPath, currentContent, proposedContent, label) {
92
93
  export class PendingChanges {
93
94
  constructor() {
94
95
  this.entries = [];
96
+ this.files = [];
95
97
  }
96
98
 
97
99
  /**
@@ -113,8 +115,18 @@ export class PendingChanges {
113
115
  this.entries.push({ relPath, patch: built.patch, isNewFile: built.isNewFile, isDeletedFile: built.isDeletedFile });
114
116
  }
115
117
 
118
+ /**
119
+ * Stage a plain file (a conflict note, a binary upstream copy) next to the
120
+ * patches. It is never a `.patch`, so `apply` never writes it into the
121
+ * project. `relPath` is relative to the staging folder, forward-slash.
122
+ */
123
+ addStagedFile(relPath, content) {
124
+ relPath = relPath.replace(/\\/g, '/');
125
+ this.files.push({ relPath, content });
126
+ }
127
+
116
128
  isEmpty() {
117
- return this.entries.length === 0;
129
+ return this.entries.length === 0 && this.files.length === 0;
118
130
  }
119
131
 
120
132
  count() {
@@ -142,6 +154,31 @@ export class PendingChanges {
142
154
  written.push(filePath);
143
155
  });
144
156
 
157
+ const resolvedDir = path.resolve(dir);
158
+ for (const file of this.files) {
159
+ const target = path.resolve(dir, ...file.relPath.split('/'));
160
+ // Defense in depth, same spirit as patchFallback: a staged file never leaves the staging folder.
161
+ if (!target.startsWith(resolvedDir + path.sep)) continue;
162
+ fs.mkdirSync(path.dirname(target), { recursive: true });
163
+ fs.writeFileSync(target, file.content);
164
+ }
165
+
145
166
  return written;
146
167
  }
147
168
  }
169
+
170
+ /**
171
+ * True when ./toolcrib-patches/ exists and holds anything at all. `merge` and
172
+ * `init` refuse to start over it: they clear the folder when they write, which
173
+ * would silently destroy unapplied patches and conflict notes.
174
+ */
175
+ export function hasStagedWork(projectRoot) {
176
+ const dir = path.join(projectRoot, PATCH_DIR);
177
+ // Files, not directory entries: once every note is resolved and deleted,
178
+ // the empty `conflicts/` subfolders left behind are not staged work.
179
+ return fs.existsSync(dir) && listFilesRecursive(dir).length > 0;
180
+ }
181
+
182
+ export const STAGED_WORK_MESSAGE =
183
+ './toolcrib-patches/ already holds staged work (unapplied patches or conflict notes). ' +
184
+ 'Run `toolcrib apply` to apply the patches, or delete the folder if you are done with it, then run this command again.';
@@ -46,6 +46,8 @@ export async function fetchRelease(version) {
46
46
  config,
47
47
  tempDir,
48
48
  readFile: (relPath) => stripBOM(fs.readFileSync(path.join(tempDir, relPath), 'utf-8')),
49
+ // Exact bytes, for binary detection and whole-file staging (readFile is lossy for non-UTF-8).
50
+ readBuffer: (relPath) => fs.readFileSync(path.join(tempDir, relPath)),
49
51
  allFiles: () => listFilesRecursive(tempDir).filter((f) => f !== 'toolcrib.config.json'),
50
52
  cleanup: () => fsp.rm(tempDir, { recursive: true, force: true }),
51
53
  };
@@ -99,6 +101,7 @@ export async function fetchTestsRelease(version) {
99
101
  config,
100
102
  tempDir,
101
103
  readFile: (relPath) => stripBOM(fs.readFileSync(path.join(tempDir, relPath), 'utf-8')),
104
+ readBuffer: (relPath) => fs.readFileSync(path.join(tempDir, relPath)),
102
105
  allFiles: () => listFilesRecursive(tempDir).filter((f) => f !== 'toolcrib-tests.config.json'),
103
106
  cleanup: () => fsp.rm(tempDir, { recursive: true, force: true }),
104
107
  };