@codeledger/cli 0.10.53 → 0.10.55

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/bin/codeledger.js CHANGED
@@ -8,7 +8,11 @@
8
8
  * `postinstall` from the GitHub Release for this exact version, verified
9
9
  * via SHA256, and cached under ~/.cache/codeledger/bin/.
10
10
  *
11
- * See scripts/postinstall.js for the download + verification logic.
11
+ * postinstall soft-fails (see scripts/postinstall.js) rather than blocking
12
+ * `npm install`, so the binary may not be cached yet the first time this
13
+ * shim runs. When that happens, this shim first looks for a repo-local
14
+ * runtime (an already-initialized repo's `.codeledger/bin/`) before making
15
+ * one synchronous, on-demand download attempt itself.
12
16
  */
13
17
 
14
18
  'use strict';
@@ -36,6 +40,11 @@ function die(msg, code = 1) {
36
40
  process.exit(code);
37
41
  }
38
42
 
43
+ // Repo-local fallback: an already-`codeledger init`'d repo vendors its own
44
+ // runtime under .codeledger/bin/. Checked before attempting a network
45
+ // download since it's instant and needs no connectivity — the global cache
46
+ // miss just means this particular machine hasn't installed globally yet,
47
+ // not that the user has no working CodeLedger available to them.
39
48
  function findRepoLocalRuntime(startDir) {
40
49
  if (process.env.CODELEDGER_GLOBAL_VERSION_PROBE === '1') return null;
41
50
  let current = resolve(startDir);
@@ -73,64 +82,106 @@ function runRepoLocal(runtime) {
73
82
  process.exit(result.status ?? 1);
74
83
  }
75
84
 
76
- if (!existsSync(BINARY_PATH)) {
77
- const repoLocal = findRepoLocalRuntime(process.cwd());
78
- if (repoLocal) {
79
- runRepoLocal(repoLocal);
80
- }
85
+ // One-shot, on-demand fetch, used only when the binary isn't cached yet and
86
+ // no repo-local runtime was found. Bounded well below postinstall's own
87
+ // window since a live invocation is blocked on this, not a background
88
+ // install step.
89
+ const ON_DEMAND_DEADLINE_MS = 30_000;
81
90
 
82
- const { arch } = require('node:os');
83
- const platformKey = `${platform()}-${arch()}`;
84
- const installerPath = join(__dirname, '..', 'scripts', 'postinstall.js');
85
-
86
- if (platformKey === 'darwin-x64') {
87
- die(
88
- [
89
- `ContextECF CodeLedger hardened binary for v${version} not found at ${BINARY_PATH}.`,
90
- '',
91
- 'You are on an Intel Mac (darwin-x64). Pre-built binaries are',
92
- 'available for Apple Silicon (darwin-arm64) only.',
93
- '',
94
- 'Options:',
95
- ' 1. Use Rosetta 2 (recommended):',
96
- ' arch -arm64 npm install -g @codeledger/cli@latest',
97
- ' 2. If this repo was already initialized, use the vendored CLI:',
98
- ' ./.codeledger/bin/codeledger ready',
99
- ' node .codeledger/bin/codeledger-standalone.cjs ready',
100
- ' 3. Download a binary manually from:',
101
- ` https://github.com/codeledgerECF/codeledger/releases/tag/v${version}`,
102
- ].join('\n'),
103
- );
104
- } else {
105
- die(
106
- [
107
- `ContextECF CodeLedger hardened binary for v${version} not found at ${BINARY_PATH}.`,
108
- '',
109
- 'The postinstall step may have been skipped (e.g. --ignore-scripts).',
110
- 'Confirm the official scoped package is installed: @codeledger/cli.',
111
- 'Avoid the unrelated unscoped npm package: codeledger.',
112
- '',
113
- 'Recover with one of:',
114
- ` 1. Upgrade: npm install -g @codeledger/cli@latest`,
115
- ` 2. Retry this install: npm rebuild @codeledger/cli`,
116
- ` 3. node "${installerPath}"`,
117
- ` 4. Re-run the install without --ignore-scripts`,
118
- ` 5. In an initialized repo, use: ./.codeledger/bin/codeledger ready`,
119
- '',
120
- 'Or download the binary manually from:',
121
- ` https://github.com/codeledgerECF/codeledger/releases/tag/v${version}`,
122
- ].join('\n'),
91
+ async function main() {
92
+ if (!existsSync(BINARY_PATH)) {
93
+ const repoLocal = findRepoLocalRuntime(process.cwd());
94
+ if (repoLocal) {
95
+ runRepoLocal(repoLocal);
96
+ }
97
+
98
+ const { arch } = require('node:os');
99
+ const platformKey = `${platform()}-${arch()}`;
100
+ const installerPath = join(__dirname, '..', 'scripts', 'postinstall.js');
101
+
102
+ if (platformKey === 'darwin-x64') {
103
+ die(
104
+ [
105
+ `ContextECF CodeLedger hardened binary for v${version} not found at ${BINARY_PATH}.`,
106
+ '',
107
+ 'You are on an Intel Mac (darwin-x64). Pre-built binaries are',
108
+ 'available for Apple Silicon (darwin-arm64) only.',
109
+ '',
110
+ 'Options:',
111
+ ' 1. Use Rosetta 2 (recommended):',
112
+ ' arch -arm64 npm install -g @codeledger/cli@latest',
113
+ ' 2. If this repo was already initialized, use the vendored CLI:',
114
+ ' ./.codeledger/bin/codeledger ready',
115
+ ' node .codeledger/bin/codeledger-standalone.cjs ready',
116
+ ' 3. Update CodeLedger, then use the vendored standalone CLI:',
117
+ ' npm install -g @codeledger/cli@latest',
118
+ ' codeledger init # in your repo, sets up vendored Node.js-based CLI',
119
+ ' ./.codeledger/bin/codeledger --version',
120
+ ' 4. Download a binary manually from:',
121
+ ` https://github.com/codeledgerECF/codeledger/releases/tag/v${version}`,
122
+ ].join('\n'),
123
+ );
124
+ }
125
+
126
+ const { PLATFORM_MAP, downloadAndVerifyBinary } = require('../scripts/postinstall.js');
127
+ if (!PLATFORM_MAP[platformKey]) {
128
+ // Don't waste time on a download attempt that can only ever fail —
129
+ // getBinaryPaths() would reject this platformKey immediately anyway.
130
+ // See postinstall.js's matching message for why this is "no
131
+ // committed timeline", not "try again later".
132
+ die(
133
+ [
134
+ `${platformKey} is not currently supported by the hardened binary.`,
135
+ `Supported: ${Object.keys(PLATFORM_MAP).join(', ')}. No committed timeline for ${platformKey} support.`,
136
+ '',
137
+ 'Use the vendored standalone CLI instead (pure Node.js, no native binary):',
138
+ ' CODELEDGER_SKIP_POSTINSTALL=1 npm install -g @codeledger/cli@latest',
139
+ ' codeledger init # sets up the vendored Node.js-based CLI',
140
+ ' ./.codeledger/bin/codeledger --version',
141
+ '',
142
+ `Track or request ${platformKey} support: https://github.com/codeledgerECF/codeledger/issues`,
143
+ ].join('\n'),
144
+ );
145
+ }
146
+
147
+ process.stderr.write(
148
+ `codeledger: hardened binary for v${version} not cached locally — downloading now (one-time)...\n`,
123
149
  );
150
+ try {
151
+ await downloadAndVerifyBinary({ deadlineMs: ON_DEMAND_DEADLINE_MS });
152
+ } catch (err) {
153
+ die(
154
+ [
155
+ `hardened binary for v${version} not found at ${BINARY_PATH}, and the on-demand download just failed: ${err.message}`,
156
+ '',
157
+ 'The postinstall step may have been skipped (e.g. --ignore-scripts).',
158
+ 'Confirm the official scoped package is installed: @codeledger/cli.',
159
+ 'Avoid the unrelated unscoped npm package: codeledger.',
160
+ '',
161
+ 'Recover with one of:',
162
+ ' 1. Retry: codeledger --version',
163
+ ' 2. Reinstall: npm install -g @codeledger/cli@latest',
164
+ ` 3. node "${installerPath}"`,
165
+ ' 4. Re-run the install without --ignore-scripts',
166
+ ' 5. In an initialized repo, use: ./.codeledger/bin/codeledger ready',
167
+ '',
168
+ 'Or download the binary manually from:',
169
+ ` https://github.com/codeledgerECF/codeledger/releases/tag/v${version}`,
170
+ ].join('\n'),
171
+ );
172
+ }
124
173
  }
125
- }
126
174
 
127
- const result = spawnSync(BINARY_PATH, process.argv.slice(2), {
128
- stdio: 'inherit',
129
- env: process.env,
130
- });
175
+ const result = spawnSync(BINARY_PATH, process.argv.slice(2), {
176
+ stdio: 'inherit',
177
+ env: process.env,
178
+ });
179
+
180
+ if (result.error) {
181
+ die(`failed to spawn binary: ${result.error.message}`);
182
+ }
131
183
 
132
- if (result.error) {
133
- die(`failed to spawn binary: ${result.error.message}`);
184
+ process.exit(result.status ?? 1);
134
185
  }
135
186
 
136
- process.exit(result.status ?? 1);
187
+ main();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codeledger/cli",
3
- "version": "0.10.53",
3
+ "version": "0.10.55",
4
4
  "mcpName": "io.github.codeledgerECF/codeledger",
5
5
  "description": "Official ContextECF CodeLedger CLI wrapper. Installs the hardened binary from GitHub Releases; zero engine code ships in this package.",
6
6
  "type": "commonjs",
@@ -7,6 +7,13 @@
7
7
  * exact version, verifies its SHA256 against SHA256SUMS-v<version>.txt
8
8
  * (also downloaded from the release), and writes it to the cache dir.
9
9
  *
10
+ * This is best-effort and always exits 0: if the download can't complete
11
+ * within the propagation window (e.g. installing a version whose release
12
+ * assets haven't landed yet, or aren't going to), npm must NOT treat the
13
+ * install as failed — a failed postinstall can roll back an existing
14
+ * working install. bin/codeledger.js retries the same download on-demand,
15
+ * synchronously, the first time the binary is actually needed.
16
+ *
10
17
  * Environment variables (all optional):
11
18
  * CODELEDGER_SKIP_POSTINSTALL=1 — skip entirely (air-gapped installs)
12
19
  * CODELEDGER_RUN_UPGRADE=1 — after the binary download succeeds,
@@ -17,6 +24,8 @@
17
24
  * SHA256SUMS-v<version>.txt sibling file.
18
25
  * CODELEDGER_CACHE_DIR=<path> — override the cache directory
19
26
  * (default: ~/.cache/codeledger/bin)
27
+ * CODELEDGER_INSTALL_DEADLINE_MS=<ms> — override the download propagation
28
+ * window (default: 150000 = 2.5 min)
20
29
  *
21
30
  * This file contains no engine logic. It only fetches, verifies, and writes
22
31
  * bytes. Safe to inspect, safe to mirror, safe to audit.
@@ -39,101 +48,56 @@ const { homedir, platform, arch } = require('node:os');
39
48
 
40
49
  const { version } = require('../package.json');
41
50
 
42
- // ─── config ──────────────────────────────────────────────────────────────────
43
-
44
- if (process.env.CODELEDGER_SKIP_POSTINSTALL === '1') {
45
- console.log(
46
- 'codeledger: CODELEDGER_SKIP_POSTINSTALL=1 set, skipping ContextECF CodeLedger hardened binary download.',
47
- );
48
- process.exit(0);
49
- }
51
+ // ─── platform / path resolution (pure — no I/O, no process.exit) ──────────
50
52
 
51
- // Skip when running inside this source workspace (dev mode). The presence of
52
- // pnpm-workspace.yaml two directories up is a reliable signal that this is not
53
- // a real end-user install, and the release binary for this version may not
54
- // exist yet.
55
- try {
56
- const path = require('node:path');
57
- const fs = require('node:fs');
58
- const workspaceRoot = path.resolve(__dirname, '..', '..', '..');
59
- if (fs.existsSync(path.join(workspaceRoot, 'pnpm-workspace.yaml'))) {
60
- console.log(
61
- 'codeledger: in-workspace dev install detected, skipping ContextECF CodeLedger hardened binary download.',
62
- );
63
- process.exit(0);
64
- }
65
- } catch {
66
- // fall through to normal install
67
- }
68
-
69
- // darwin-x64 is temporarily absent from v0.10.6 — no working Intel
70
- // Mac runner on the release CI plan as of 2026-04-09. Intel Mac
71
- // users hit the "unsupported platform" soft-fail below, which tells
72
- // them to download manually from the GitHub Release. Re-add when a
73
- // working Intel Mac binary is available.
53
+ // darwin-x64 is temporarily absent — no working Intel Mac runner on the
54
+ // release CI plan as of 2026-04-09. Re-add when a working Intel Mac binary
55
+ // is available.
74
56
  const PLATFORM_MAP = {
75
57
  'darwin-arm64': 'darwin-arm64',
76
58
  'linux-x64': 'linux-x64',
77
59
  };
78
60
 
79
- const platformKey = `${platform()}-${arch()}`;
80
- const platformSuffix = PLATFORM_MAP[platformKey];
61
+ function getPlatformKey() {
62
+ return `${platform()}-${arch()}`;
63
+ }
81
64
 
82
- if (!platformSuffix) {
83
- if (platformKey === 'darwin-x64') {
84
- console.log('');
85
- console.log('codeledger: ContextECF CodeLedger Intel Mac (darwin-x64) detected.');
86
- console.log('codeledger: Pre-built binaries are available for Apple Silicon (darwin-arm64) only.');
87
- console.log('');
88
- console.log('Options:');
89
- console.log(' Official package: @codeledger/cli. Avoid unrelated unscoped package: codeledger.');
90
- console.log(' 1. Use Rosetta 2 (recommended):');
91
- console.log(' arch -arm64 npm install -g @codeledger/cli@latest');
92
- console.log(' 2. If this repo was already initialized, use the vendored CLI:');
93
- console.log(' ./.codeledger/bin/codeledger ready');
94
- console.log(' node .codeledger/bin/codeledger-standalone.cjs ready');
95
- console.log(' 3. For a new repo without a vendored CLI, use a supported platform or Docker.');
96
- console.log(' 4. Download a binary manually from:');
97
- console.log(` https://github.com/codeledgerECF/codeledger/releases/tag/v${version}`);
98
- console.log('');
99
- } else {
100
- console.error(
101
- `codeledger: unsupported platform ${platformKey}. Supported: ${Object.keys(
102
- PLATFORM_MAP,
103
- ).join(', ')}`,
104
- );
105
- console.error('codeledger: this installer is for ContextECF CodeLedger (@codeledger/cli).');
106
- console.error(
107
- `codeledger: v${version} does not provide a hardened binary for ${platformKey}.`,
108
- );
109
- console.error(
110
- 'codeledger: you can still use the published source package or a supported release asset.',
111
- );
112
- }
113
- // Fail softly: don't block `npm install` for unsupported platforms. The
114
- // bin shim will tell the user what happened when they first run `codeledger`.
115
- process.exit(0);
65
+ function getCacheDir() {
66
+ return (
67
+ process.env.CODELEDGER_CACHE_DIR || join(homedir(), '.cache', 'codeledger', 'bin')
68
+ );
116
69
  }
117
70
 
118
71
  // Binaries are hosted on the public CodeLedger GitHub Releases page so
119
72
  // `npm install -g @codeledger/cli` can fetch them without authentication.
120
- const RELEASE_BASE =
121
- process.env.CODELEDGER_BINARY_URL ||
122
- `https://github.com/codeledgerECF/codeledger/releases/download/v${version}`;
123
-
124
- const BINARY_REMOTE_NAME = `codeledger-hardened-${platformSuffix}-v${version}`;
125
- const BINARY_URL = `${RELEASE_BASE}/${BINARY_REMOTE_NAME}`;
126
- const CHECKSUMS_URL = `${RELEASE_BASE}/SHA256SUMS-v${version}.txt`;
127
-
128
- const CACHE_DIR =
129
- process.env.CODELEDGER_CACHE_DIR ||
130
- join(homedir(), '.cache', 'codeledger', 'bin');
131
- const BINARY_LOCAL_NAME = `codeledger-hardened-v${version}`;
132
- const BINARY_LOCAL_PATH = join(CACHE_DIR, BINARY_LOCAL_NAME);
133
- const FETCH_TIMEOUT_MS = 60_000;
73
+ function getBinaryPaths(platformKey) {
74
+ const platformSuffix = PLATFORM_MAP[platformKey];
75
+ if (!platformSuffix) return null;
76
+
77
+ const releaseBase =
78
+ process.env.CODELEDGER_BINARY_URL ||
79
+ `https://github.com/codeledgerECF/codeledger/releases/download/v${version}`;
80
+ const binaryRemoteName = `codeledger-hardened-${platformSuffix}-v${version}`;
81
+ const cacheDir = getCacheDir();
82
+
83
+ return {
84
+ binaryUrl: `${releaseBase}/${binaryRemoteName}`,
85
+ checksumsUrl: `${releaseBase}/SHA256SUMS-v${version}.txt`,
86
+ binaryRemoteName,
87
+ cacheDir,
88
+ binaryLocalPath: join(cacheDir, `codeledger-hardened-v${version}`),
89
+ };
90
+ }
91
+
92
+ function isBinaryCached() {
93
+ const paths = getBinaryPaths(getPlatformKey());
94
+ return Boolean(paths && existsSync(paths.binaryLocalPath));
95
+ }
134
96
 
135
97
  // ─── http ────────────────────────────────────────────────────────────────────
136
98
 
99
+ const FETCH_TIMEOUT_MS = 60_000;
100
+
137
101
  function fetchBufferOnce(url, redirectDepth = 0) {
138
102
  if (redirectDepth > 5) {
139
103
  return Promise.reject(new Error(`too many redirects fetching ${url}`));
@@ -181,33 +145,43 @@ function fetchBufferOnce(url, redirectDepth = 0) {
181
145
  });
182
146
  }
183
147
 
148
+ // Default propagation window for the postinstall-time attempt. Deliberately
149
+ // a wall-clock deadline, not a fixed attempt count: the question is "how
150
+ // long is it plausible for a just-published release's assets to still be
151
+ // propagating," not "how many times did we try." A version whose GitHub
152
+ // Release will never exist (npm published ahead of a working release — the
153
+ // actual incident this retry policy is designed around) now fails within
154
+ // this window instead of retrying for ~8 minutes that were never going to
155
+ // succeed.
156
+ const DEFAULT_DEADLINE_MS = Number(process.env.CODELEDGER_INSTALL_DEADLINE_MS) || 150_000; // 2.5 minutes
157
+
184
158
  // Retry wrapper that tolerates the short propagation window where a freshly
185
159
  // published package may be visible before all release assets are available.
186
- // A 404 is retried with exponential backoff; non-404 errors fail fast.
187
- async function fetchBuffer(url) {
188
- const backoffs = [10, 20, 40, 60, 60, 60, 60, 60, 60, 60]; // seconds
160
+ // A 404 is retried with exponential backoff bounded by deadlineMs;
161
+ // non-404 errors fail fast.
162
+ async function fetchBuffer(url, deadlineMs = DEFAULT_DEADLINE_MS) {
163
+ const start = Date.now();
164
+ let attempt = 0;
189
165
  let lastErr;
190
- for (let i = 0; i <= backoffs.length; i++) {
166
+ for (;;) {
191
167
  try {
192
168
  return await fetchBufferOnce(url);
193
169
  } catch (err) {
194
170
  lastErr = err;
195
- // Only retry on 404 — everything else is a hard failure
171
+ // Only retry on 404 — everything else is a hard failure.
196
172
  if (err.statusCode !== 404) throw err;
197
- if (i === backoffs.length) break;
198
- const wait = backoffs[i];
173
+ const elapsed = Date.now() - start;
174
+ const wait = Math.min(20_000, 5_000 * 2 ** attempt);
175
+ if (elapsed + wait >= deadlineMs) break;
176
+ attempt += 1;
177
+ const remainingSec = Math.round((deadlineMs - elapsed) / 1000);
199
178
  console.log(
200
- `codeledger: Binary pending — new release detected, retrying in ${wait}s ` +
201
- `(attempt ${i + 1}/${backoffs.length + 1}). ` +
202
- `This is normal for the first ~10 minutes after a release.`,
179
+ `codeledger: Binary pending — retrying in ${Math.round(wait / 1000)}s ` +
180
+ `(${remainingSec}s left in propagation window).`,
203
181
  );
204
- await new Promise((r) => setTimeout(r, wait * 1000));
182
+ await new Promise((r) => setTimeout(r, wait));
205
183
  }
206
184
  }
207
- console.log(
208
- 'codeledger: Binary not yet available after all retries. ' +
209
- 'Upgrade or retry later with: npm install -g @codeledger/cli@latest',
210
- );
211
185
  throw lastErr;
212
186
  }
213
187
 
@@ -230,51 +204,64 @@ function findExpectedSha(checksumsText, filename) {
230
204
  return null;
231
205
  }
232
206
 
233
- // ─── main ────────────────────────────────────────────────────────────────────
207
+ // ─── download + verify (the reusable, side-effect-scoped core) ────────────
208
+
209
+ // Downloads, verifies, and caches the hardened binary for the current
210
+ // platform + this package's version. Throws on failure — does not exit the
211
+ // process. Callers decide what "failure" means for them: postinstall.js
212
+ // soft-fails (exit 0, retry later); bin/codeledger.js's on-demand path
213
+ // falls through to a hard failure message since the user is blocked right
214
+ // now.
215
+ async function downloadAndVerifyBinary({ deadlineMs = DEFAULT_DEADLINE_MS } = {}) {
216
+ const platformKey = getPlatformKey();
217
+ const paths = getBinaryPaths(platformKey);
218
+ if (!paths) {
219
+ throw new Error(`unsupported platform ${platformKey}`);
220
+ }
234
221
 
235
- async function main() {
236
222
  console.log(`codeledger: installing v${version} hardened binary for ${platformKey}`);
237
- console.log(` source: ${BINARY_URL}`);
223
+ console.log(` source: ${paths.binaryUrl}`);
238
224
 
239
225
  const [checksumsBuf, binary] = await Promise.all([
240
- fetchBuffer(CHECKSUMS_URL),
241
- fetchBuffer(BINARY_URL),
226
+ fetchBuffer(paths.checksumsUrl, deadlineMs),
227
+ fetchBuffer(paths.binaryUrl, deadlineMs),
242
228
  ]);
243
229
  const checksums = checksumsBuf.toString('utf8');
244
230
 
245
- const expectedSha = findExpectedSha(checksums, BINARY_REMOTE_NAME);
231
+ const expectedSha = findExpectedSha(checksums, paths.binaryRemoteName);
246
232
  if (!expectedSha) {
247
233
  throw new Error(
248
- `${BINARY_REMOTE_NAME} not listed in SHA256SUMS-v${version}.txt — cannot verify binary integrity`,
234
+ `${paths.binaryRemoteName} not listed in SHA256SUMS-v${version}.txt — cannot verify binary integrity`,
249
235
  );
250
236
  }
251
237
 
252
238
  const actualSha = createHash('sha256').update(binary).digest('hex');
253
239
  if (actualSha !== expectedSha) {
254
240
  throw new Error(
255
- `SHA256 mismatch for ${BINARY_REMOTE_NAME}:\n expected ${expectedSha}\n got ${actualSha}`,
241
+ `SHA256 mismatch for ${paths.binaryRemoteName}:\n expected ${expectedSha}\n got ${actualSha}`,
256
242
  );
257
243
  }
258
244
 
259
- mkdirSync(CACHE_DIR, { recursive: true });
245
+ mkdirSync(paths.cacheDir, { recursive: true });
260
246
 
261
247
  // Atomic-ish write: write to tmp, rename
262
- const tmpPath = `${BINARY_LOCAL_PATH}.tmp`;
248
+ const tmpPath = `${paths.binaryLocalPath}.tmp`;
263
249
  if (existsSync(tmpPath)) unlinkSync(tmpPath);
264
250
  writeFileSync(tmpPath, binary);
265
251
  chmodSync(tmpPath, 0o755);
266
- if (existsSync(BINARY_LOCAL_PATH)) unlinkSync(BINARY_LOCAL_PATH);
267
- // rename via fs for portability
268
- require('node:fs').renameSync(tmpPath, BINARY_LOCAL_PATH);
252
+ if (existsSync(paths.binaryLocalPath)) unlinkSync(paths.binaryLocalPath);
253
+ require('node:fs').renameSync(tmpPath, paths.binaryLocalPath);
269
254
 
270
- console.log(`codeledger: installed ${BINARY_LOCAL_PATH}`);
255
+ console.log(`codeledger: installed ${paths.binaryLocalPath}`);
271
256
  console.log(` sha256: ${actualSha}`);
272
- console.log('');
273
257
 
274
- console.log('codeledger: install complete.');
275
- console.log(' Next: cd your-repo && codeledger ready');
276
- console.log(' Existing repos can refresh ambient hooks/runtime with: codeledger upgrade');
258
+ return paths.binaryLocalPath;
259
+ }
277
260
 
261
+ // Optional post-download step: run `codeledger upgrade` in the most likely
262
+ // target repo so existing repos pick up refreshed ambient hooks/runtime
263
+ // without a second manual command. Opt-in only — never runs by default.
264
+ function maybeRunUpgrade() {
278
265
  if (process.env.CODELEDGER_RUN_UPGRADE === '1') {
279
266
  const { spawnSync } = require('node:child_process');
280
267
  const path = require('node:path');
@@ -298,28 +285,116 @@ async function main() {
298
285
  }
299
286
  }
300
287
 
301
- // Only run main() when invoked directly (npm postinstall, node scripts/postinstall.js).
302
- // When require()'d from tests, just export the helper functions.
303
- if (require.main === module) {
304
- main().catch((err) => {
305
- console.error(`codeledger: postinstall failed — ${err.message}`);
288
+ // ─── postinstall entry point ───────────────────────────────────────────────
289
+ // All side-effecting decisions (env skip, dev-workspace skip, platform
290
+ // gating, process.exit) live here, gated behind `require.main === module`
291
+ // below — so requiring this file as a library (from bin/codeledger.js, or
292
+ // from tests) never has side effects.
293
+
294
+ async function runPostinstall() {
295
+ if (process.env.CODELEDGER_SKIP_POSTINSTALL === '1') {
296
+ console.log(
297
+ 'codeledger: CODELEDGER_SKIP_POSTINSTALL=1 set, skipping ContextECF CodeLedger hardened binary download.',
298
+ );
299
+ return;
300
+ }
301
+
302
+ // Skip when running inside this source workspace (dev mode). The presence
303
+ // of pnpm-workspace.yaml two directories up is a reliable signal that
304
+ // this is not a real end-user install, and the release binary for this
305
+ // version may not exist yet.
306
+ try {
307
+ const path = require('node:path');
308
+ const fs = require('node:fs');
309
+ const workspaceRoot = path.resolve(__dirname, '..', '..', '..');
310
+ if (fs.existsSync(path.join(workspaceRoot, 'pnpm-workspace.yaml'))) {
311
+ console.log(
312
+ 'codeledger: in-workspace dev install detected, skipping ContextECF CodeLedger hardened binary download.',
313
+ );
314
+ return;
315
+ }
316
+ } catch {
317
+ // fall through to normal install
318
+ }
319
+
320
+ const platformKey = getPlatformKey();
321
+
322
+ if (platformKey === 'darwin-x64') {
323
+ console.log('');
324
+ console.log('codeledger: ContextECF CodeLedger Intel Mac (darwin-x64) detected.');
325
+ console.log('codeledger: Pre-built binaries are available for Apple Silicon (darwin-arm64) only.');
326
+ console.log('');
327
+ console.log('Options:');
328
+ console.log(' Official package: @codeledger/cli. Avoid unrelated unscoped package: codeledger.');
329
+ console.log(' 1. Use Rosetta 2 (recommended):');
330
+ console.log(' arch -arm64 npm install -g @codeledger/cli@latest');
331
+ console.log(' 2. If this repo was already initialized, use the vendored CLI:');
332
+ console.log(' ./.codeledger/bin/codeledger ready');
333
+ console.log(' node .codeledger/bin/codeledger-standalone.cjs ready');
334
+ console.log(' 3. Use the vendored standalone CLI after init:');
335
+ console.log(' CODELEDGER_SKIP_POSTINSTALL=1 npm install -g @codeledger/cli@latest');
336
+ console.log(' codeledger init # sets up vendored Node.js-based CLI');
337
+ console.log(' 4. Download a binary manually from:');
338
+ console.log(` https://github.com/codeledgerECF/codeledger/releases/tag/v${version}`);
339
+ console.log('');
340
+ return;
341
+ }
342
+
343
+ if (!PLATFORM_MAP[platformKey]) {
344
+ // Unlike darwin-x64 above (a documented, transient CI-runner gap with a
345
+ // committed path back), win32 and linux-arm64 have no hardened binary
346
+ // in the release pipeline at all and no committed timeline to add one.
347
+ // Say that plainly rather than implying support is imminent — the
348
+ // vendored standalone CLI (pure Node.js, no native binary) works on any
349
+ // platform Node itself runs on, so there IS a real path forward, just
350
+ // not the hardened-binary one.
306
351
  console.error('');
307
- console.error('Recovery options:');
308
- console.error(' 1. Upgrade: npm install -g @codeledger/cli@latest');
309
- console.error(' 2. Retry this install: npm rebuild @codeledger/cli');
310
- console.error(' 3. Air-gapped install:');
311
- console.error(' CODELEDGER_SKIP_POSTINSTALL=1 npm install -g @codeledger/cli@latest');
312
- console.error(' then manually place the binary at:');
313
- console.error(` ${BINARY_LOCAL_PATH}`);
314
- console.error(' or, in an initialized repo, use: ./.codeledger/bin/codeledger ready');
315
- console.error(' 4. Use a mirror:');
316
- console.error(' CODELEDGER_BINARY_URL=https://your-mirror/path npm install -g @codeledger/cli@latest');
352
+ console.error(`codeledger: ${platformKey} is not currently supported by the hardened binary.`);
353
+ console.error(`codeledger: Supported: ${Object.keys(PLATFORM_MAP).join(', ')}. No committed timeline for ${platformKey} support.`);
354
+ console.error('codeledger: this installer is for ContextECF CodeLedger (@codeledger/cli).');
317
355
  console.error('');
318
- console.error(
319
- `Manual download: https://github.com/codeledgerECF/codeledger/releases/tag/v${version}`,
320
- );
321
- process.exit(1);
322
- });
356
+ console.error('Use the vendored standalone CLI instead (pure Node.js, no native binary):');
357
+ console.error(' CODELEDGER_SKIP_POSTINSTALL=1 npm install -g @codeledger/cli@latest');
358
+ console.error(' codeledger init # sets up the vendored Node.js-based CLI');
359
+ console.error(' ./.codeledger/bin/codeledger --version');
360
+ console.error('');
361
+ console.error(`Track or request ${platformKey} support: https://github.com/codeledgerECF/codeledger/issues`);
362
+ return;
363
+ }
364
+
365
+ try {
366
+ await downloadAndVerifyBinary();
367
+ console.log('');
368
+ console.log('codeledger: install complete.');
369
+ console.log(' Next: cd your-repo && codeledger ready');
370
+ console.log(' Existing repos can refresh ambient hooks/runtime with: codeledger upgrade');
371
+ console.log('codeledger: ready initializes, scans, and prepares ambient task context.');
372
+ maybeRunUpgrade();
373
+ } catch (err) {
374
+ // Soft-fail, deliberately: exit 0 either way. A failed postinstall
375
+ // makes npm treat the whole install as failed, which can roll back an
376
+ // existing working install (the exact incident this is designed
377
+ // around). bin/codeledger.js retries this same download on-demand,
378
+ // synchronously, the first time it's actually needed.
379
+ console.log(`codeledger: could not pre-fetch the hardened binary — ${err.message}`);
380
+ console.log('codeledger: not fatal — it will download automatically on first "codeledger" invocation.');
381
+ console.log('codeledger: or, in an initialized repo, use: ./.codeledger/bin/codeledger ready');
382
+ }
323
383
  }
324
384
 
325
- module.exports = { findExpectedSha, PLATFORM_MAP };
385
+ // Only run the postinstall entry point when invoked directly (npm
386
+ // postinstall, node scripts/postinstall.js). When required — from
387
+ // bin/codeledger.js's on-demand download path, or from tests — this file
388
+ // has no side effects; only the exported pure/reusable functions are used.
389
+ if (require.main === module) {
390
+ runPostinstall().then(() => process.exit(0));
391
+ }
392
+
393
+ module.exports = {
394
+ findExpectedSha,
395
+ PLATFORM_MAP,
396
+ downloadAndVerifyBinary,
397
+ getPlatformKey,
398
+ getBinaryPaths,
399
+ isBinaryCached,
400
+ };