@codeledger/cli 0.10.82 → 0.10.84

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
@@ -1,219 +1,22 @@
1
- # @codeledger/cli — ContextECF CodeLedger
1
+ # CodeLedger portable CLI
2
2
 
3
- **Deterministic, bounded context selection for AI coding agents.**
4
- Published by [Intelligent Context AI, Inc.](https://codeledger.dev).
3
+ Use Node.js 20 or newer and Git. The CLI returns literal matches from committed
4
+ source, tests and docs in the selected worktree. Each match includes the Git
5
+ revision, relative path, line number and matching text.
5
6
 
6
- - Website: https://codeledger.dev
7
- - Live demo: https://demo.codeledger.dev
8
- - Source: https://github.com/codeledgerECF/codeledger
9
- - npm: [`@codeledger/cli`](https://www.npmjs.com/package/@codeledger/cli)
7
+ For the ZIP, verify its SHA-256 against SHA256SUMS.txt before extracting it.
8
+ Run the following in a Git worktree with a committed HEAD.
10
9
 
11
- > **Installing ContextECF CodeLedger?** Make sure you use the scope: `npm install -g @codeledger/cli`.
12
- > There is an unrelated unscoped `codeledger` package on npm by a different
13
- > author. The real ContextECF CodeLedger package is published under the
14
- > `@codeledger` scope.
15
- >
16
- > Use the global `-g` form for normal CLI installs. `npm install @codeledger/cli`
17
- > inside an existing project modifies that project and `npm audit` reports the
18
- > whole project dependency tree, not just CodeLedger.
10
+ node /path/to/codeledger-open.cjs activate --task "Find the HTTP 429 fallback" --query "Retry-After"
19
11
 
20
- ## Install
12
+ For an npm installation, use the codeledger command in place of node and the CJS path.
13
+ Install one package. Both npm names provide the same commands.
21
14
 
22
- ```bash
23
- npm install -g @codeledger/cli@latest
24
- cd your-repo
25
- codeledger ready
26
- ```
15
+ For MCP, configure Claude Code or Codex to run codeledger with arguments
16
+ mcp start --repo /absolute/path/to/worktree. For a ZIP installation, configure
17
+ node as the command and put the absolute CJS path before those arguments.
18
+ The get_activation_payload tool takes task and query. Authorize the host to
19
+ receive excerpts from that worktree before configuring the server.
27
20
 
28
- The wrapper package declares no runtime npm dependencies. Release CI verifies
29
- that with a clean install audit fixture before `latest` is promoted.
30
-
31
- This package is a **thin npm wrapper**. When you install it, the
32
- `postinstall` step downloads the platform-specific hardened binary from
33
- the matching GitHub Release, verifies its SHA256 against
34
- `SHA256SUMS-v<version>.txt`, and caches it under
35
- `~/.cache/codeledger/bin/`.
36
-
37
- SHA256 verification confirms that the downloaded binary matches the bytes
38
- published by CodeLedger. It does not make the binary source-verifiable. If your
39
- organization requires source inspection for repo-reading tools, use the
40
- Enterprise Source-Build Profile in
41
- [`docs/security/ENTERPRISE_ASSURANCE.md`](../../docs/security/ENTERPRISE_ASSURANCE.md)
42
- instead of this npm wrapper path.
43
-
44
- Installation downloads and verifies the binary only. It does not rewrite repo
45
- hooks, vendored runtimes, or ambient setup by default. After install, run
46
- `cd your-repo && codeledger ready`. Existing repos can opt into the ambient
47
- refresh step with `codeledger upgrade`, or by setting `CODELEDGER_RUN_UPGRADE=1`
48
- during installation.
49
-
50
- No engine code, scoring logic, or formulas ship to npm. The wrapper is
51
- ~30 KB of plain JavaScript that fetches, verifies, and launches the
52
- real CodeLedger binary.
53
-
54
- For least-privilege enterprise review, build from source and run:
55
-
56
- ```bash
57
- pnpm install --frozen-lockfile
58
- pnpm build
59
- pnpm release:smoke:source
60
- node packages/cli/dist/index.js scan
61
- ```
62
-
63
- ## Supported platforms (tier 1)
64
-
65
- - `darwin-arm64` (Apple Silicon macOS)
66
- - `linux-x64`
67
-
68
- **Intel Mac (darwin-x64):** deferred in v0.10.6 — no working Intel
69
- Mac runner was available on the release CI plan at the time of the
70
- release. Intel Mac users can build from source or wait for the
71
- runner situation to stabilize in a later release.
72
-
73
- Other platforms fall through `postinstall` softly — `npm install`
74
- succeeds, but running `codeledger` will either use a repo-local vendored
75
- runtime if the selected repo has `.codeledger/bin/`, or report the unavailable
76
- native route. Skipping postinstall does not create a runtime for a fresh repo;
77
- `codeledger init` cannot bootstrap through that missing-runtime loop. Intel Macs
78
- cannot run Apple Silicon binaries through Rosetta. Use a supported host or
79
- review the source-build prerequisites, without assuming untested OS support.
80
-
81
- ## MCP First Use
82
-
83
- ```sh
84
- codeledger ready --cwd /absolute/path/to/repo --task "Inspect this repository"
85
- codeledger license status --cwd /absolute/path/to/repo
86
- codeledger mcp status --cwd /absolute/path/to/repo --json
87
- ```
88
-
89
- Use the printed repository-bound config, for example
90
- `npx -y @codeledger/cli@latest mcp start --cwd /absolute/path/to/repo`.
91
- Launch forms that all start the same stdio server:
92
-
93
- - `codeledger mcp start [--cwd <repo>] [--profile core|governance|panel|full]`
94
- - `codeledger-mcp [--cwd <repo>] ...` — bin alias that always runs `mcp start`
95
- with your arguments appended (for registries that cannot pass arguments;
96
- `npx -y -p @codeledger/cli codeledger-mcp`)
97
- - bare `codeledger` with stdin and stdout both piped (how MCP clients launch
98
- it). A terminal still gets help; `CODELEDGER_NO_MCP_AUTOSTART=1` forces help.
99
-
100
- Licensing is **free to list, licensed to call**: `initialize` and `tools/list`
101
- always work (even before `codeledger ready`), and tool calls need an active
102
- Team or Enterprise license. Without one, calls return a structured `locked`
103
- result (`codeledger/feature-lock/v1`) with the pricing link and activation
104
- steps; `get_activation_payload` stays free. In an uninitialized directory every
105
- call returns `not_evaluable` with the exact `codeledger ready --cwd <path>` fix.
106
- Install and configuration success do not establish a connection: reconnect, require
107
- initialize and tools/list, then call `get_active_context` with `{}` to read the
108
- prepared bundle. Missing activation is degraded context. Verify cold and warm
109
- cache behavior; diagnostics must stay on stderr. See
110
- [MCP First Use](https://github.com/codeledgerECF/codeledger/blob/main/docs/MCP.md).
111
-
112
- ## Usage
113
-
114
- After installing, start inside a repo with `codeledger ready`. It initializes
115
- CodeLedger if needed, scans the repo, vendors the browser/cloud runtime, and
116
- prints the ambient task-context status.
117
-
118
- ```bash
119
- codeledger ready
120
- codeledger ready --task "your task here"
121
- codeledger scan
122
- codeledger help
123
- ```
124
-
125
- If you installed an earlier CodeLedger version and `codeledger vendor`
126
- cannot find the standalone runtime, upgrade first and rerun the command:
127
-
128
- ```bash
129
- npm install -g @codeledger/cli@latest
130
- codeledger ready
131
- codeledger vendor
132
- ```
133
-
134
- All arguments, environment variables, stdin, and exit codes pass
135
- straight through to the hardened binary.
136
-
137
- If the global hardened binary is missing but the repo already has a
138
- vendored runtime, the npm shim automatically falls back to:
139
-
140
- ```bash
141
- ./.codeledger/bin/codeledger <command>
142
- ```
143
-
144
- This keeps existing repos usable after a skipped postinstall, air-gapped
145
- install, or unsupported global platform.
146
-
147
- ## Version parity
148
-
149
- When you run a globally installed `codeledger` inside a repo that has a
150
- repo-local CodeLedger (`.codeledger/bin/`), the CLI detects whether the
151
- running version differs from the repo-local version. If it does:
152
-
153
- 1. A warning is printed to stderr showing both versions.
154
- 2. The CLI automatically re-executes the command via the repo-local
155
- binary so that command behavior matches what the repo expects.
156
-
157
- This prevents a stale global install from silently producing different
158
- results than the repo-local CLI. To avoid the delegation overhead,
159
- invoke the repo-local wrapper directly:
160
-
161
- ```bash
162
- ./.codeledger/bin/codeledger <command>
163
- ```
164
-
165
- ## Environment variables
166
-
167
- | Variable | Purpose |
168
- |---|---|
169
- | `CODELEDGER_SKIP_POSTINSTALL=1` | Skip the binary download during `npm install`. Useful for air-gapped environments. You are responsible for placing the binary at the expected cache path afterwards. |
170
- | `CODELEDGER_RUN_UPGRADE=1` | After a successful binary download, also run `codeledger upgrade`. This is opt-in because upgrade may refresh repo-local wrappers, hooks, and ambient setup. |
171
- | `CODELEDGER_BINARY_URL=<url>` | Override the download base URL. Use this to fetch the binary from a corporate mirror or internal CDN. The URL must serve the same filenames as the GitHub Release, plus a `SHA256SUMS-v<version>.txt` sibling. |
172
- | `CODELEDGER_CACHE_DIR=<path>` | Override the cache directory (default `~/.cache/codeledger/bin`). |
173
-
174
- ## Air-gapped / offline install
175
-
176
- ```bash
177
- CODELEDGER_SKIP_POSTINSTALL=1 npm install -g @codeledger/cli@latest
178
-
179
- # then place the hardened binary at:
180
- # ~/.cache/codeledger/bin/codeledger-hardened-v<version>
181
- # and chmod +x it.
182
-
183
- # If this repo is already initialized, use the committed vendored runtime:
184
- ./.codeledger/bin/codeledger ready
185
- ```
186
-
187
- Download the binary + `SHA256SUMS` from the GitHub Release matching the
188
- installed version:
189
-
190
- ```
191
- https://github.com/codeledgerECF/codeledger/releases
192
- ```
193
-
194
- ## Recovery
195
-
196
- If `postinstall` was skipped (e.g. `npm install --ignore-scripts`),
197
- recover with any of:
198
-
199
- ```bash
200
- npm install -g @codeledger/cli@latest
201
- # or retry the current install
202
- npm rebuild @codeledger/cli
203
- # or
204
- node $(npm root -g)/@codeledger/cli/scripts/postinstall.js
205
- # or download the binary manually from the release page and chmod +x it
206
- ```
207
-
208
- ## License
209
-
210
- The npm wrapper is MIT licensed; see `LICENSE`.
211
-
212
- The downloaded CodeLedger hardened binary is governed by the CodeLedger Core
213
- Engine License; see `LICENSE-CORE`. `NOTICE` describes the wrapper/binary split.
214
-
215
- ## Source
216
-
217
- Source code lives at <https://github.com/codeledgerECF/codeledger>.
218
- The hardened binary shipped with this wrapper is published through the
219
- same public GitHub Releases channel used by the installer.
21
+ Use the host's regular discovery for uncommitted changes. The portable CLI's
22
+ scope is read-only committed context and local stdio MCP.
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ /* CodeLedger portable CLI */
3
+ "use strict";var x=require("node:util");var T=require("node:events");var L=require("node:child_process"),N=require("node:fs"),y=20,k=360,j=["ts","tsx","js","jsx","mjs","cjs","py","go","rs","java","kt","cs","cpp","c","h","rb","php","swift","md"],D=[".*","node_modules","vendor","dist","build","coverage"],P=[...j.map(e=>`:(glob)**/*.${e}`),...D.map(e=>`:(exclude,glob)**/${e}/**`),":(exclude,glob)**/.*"],G=Object.fromEntries(Object.entries(process.env).filter(([e])=>!/^git_/i.test(e)));function E(e,r){return(0,L.spawnSync)("git",["--no-replace-objects","-c","protocol.allow=never","-c","core.fsmonitor=false",...r],{cwd:e,encoding:"utf8",env:{...G,GIT_ALLOW_PROTOCOL:"",GIT_NO_LAZY_FETCH:"1",GIT_TERMINAL_PROMPT:"0"},maxBuffer:64*1024,timeout:5e3,windowsHide:!0})}function g(e,r=!1){let t=E(e,["rev-parse",r?"--show-prefix":"--show-toplevel"]);if(t.status!==0)throw new Error("Choose a local Git worktree with Git on PATH.");let n=t.stdout.replace(/\r?\n$/,"");if(r&&n!=="")throw new Error("--repo must point to the root of the intended Git worktree.");return N.realpathSync.native(r?e:n)}function I(e){let r=E(e,["rev-parse","--verify","HEAD^{commit}"]),t=r.stdout?.trim();if(r.status!==0||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(t))throw new Error("The selected worktree needs a committed HEAD.");return t}function V(e,r){let t=[],n=r+":",o=/([^\0]+)\0([1-9]\d*)\0([^\n]*)\n/gy;for(;o.lastIndex<e.length&&t.length<=y;){let s=o.exec(e);if(!s||!s[1].startsWith(n)||s[1].includes("\uFFFD"))throw new Error("Unsupported Git match format.");let u=s[3].replace(/\r$/,"");t.push({path:s[1].slice(n.length),line:Number(s[2]),excerpt:u.slice(0,k),excerpt_truncated:u.length>k})}return t}function v(e,r,t){if(typeof r!="string"||!r.trim()||r.length>1e3||typeof t!="string"||t.trim().length<3||t.length>100||/[\x00-\x1f\x7f]/.test(t))throw new Error("Provide a task of 1\u20131000 characters and a literal search term of 3\u2013100 characters.");if(g(e,!0)!==e)throw new Error("The selected worktree changed. Reconnect to it.");let n=I(e),o=E(e,["grep","--full-name","--no-recurse-submodules","--no-textconv","--no-color","--no-column","--threads=1","-IzFn","-m","21","-e",t.trim(),n,"--",...P]);if(o.error||o.status!==0&&o.status!==1)throw new Error("Git search failed or exceeded its limit. Try a more specific literal.");if(I(e)!==n)throw new Error("Git HEAD moved during lookup. Run activation again.");let s=V(o.stdout,n);return{source_revision:n,source_scope:"committed HEAD in the selected worktree",selection:"literal Git search",status:s.length>y?"truncated":s.length>0?"matched":"no_matches",query:t.trim(),matches:s.slice(0,y),transaction_id:null,session_id:null,context_status:"stateless open activation"}}var H=new Set(["bundle","ensure-session"]),$=new Set(["help","--help","-h","version","--version","-v","init","doctor","vendor","validate","features","upgrade","update","license","enable","about","stats","setup-github-action","commands","capabilities","activate","mcp",...H]),_="get_activation_payload";var R=require("node:module"),S=require("node:url"),F={};function q(){return"0.10.84"}var h=q();var C=["2025-11-25","2025-06-18","2025-03-26","2024-11-05"],A={name:_,description:"Find a literal symbol or phrase in committed source, tests and docs for this task. Returns Git revision, path, line and matching text. Search the working tree separately for uncommitted changes.",inputSchema:{type:"object",properties:{task:{type:"string",minLength:1,maxLength:1e3},query:{type:"string",minLength:3,maxLength:100}},required:["task","query"],additionalProperties:!1},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}};function O(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}async function M(e){let r=g(e,!0),t=!1,n=!1;async function o(d,i){process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:d,...i})+`
4
+ `)||await(0,T.once)(process.stdout,"drain")}async function s(d){let i;try{i=O(JSON.parse(d))}catch{await o(null,{error:{code:-32700,message:"Invalid JSON"}});return}let{id:f,method:p}=i;if(i.jsonrpc!=="2.0"||typeof p!="string"||f!==void 0&&typeof f!="string"&&!Number.isSafeInteger(f)){await o(null,{error:{code:-32600,message:"Invalid request"}});return}if(f===void 0){p==="notifications/initialized"&&t&&(n=!0);return}let a=f,m=O(i.params);if(p==="initialize"&&!t&&typeof m.protocolVersion=="string"){t=!0;let c=C.includes(m.protocolVersion)?m.protocolVersion:C[0];await o(a,{result:{protocolVersion:c,capabilities:{tools:{}},serverInfo:{name:"codeledger-open",version:h}}})}else if(p==="ping")await o(a,{result:{}});else if(!n)await o(a,{error:{code:-32600,message:"Initialize the CodeLedger MCP session first"}});else if(p==="tools/list")await o(a,{result:{tools:[A]}});else if(p==="tools/call"){if(m.name!==A.name){await o(a,{error:{code:-32602,message:"Unknown CodeLedger tool"}});return}try{let c=O(m.arguments);if(Object.keys(c).some(b=>b!=="task"&&b!=="query"))throw new Error("Only task and query are accepted.");let w=v(r,c.task,c.query);await o(a,{result:{content:[{type:"text",text:JSON.stringify(w)}],structuredContent:w}})}catch(c){let w=c instanceof Error?c.message:"CodeLedger lookup failed";await o(a,{result:{isError:!0,content:[{type:"text",text:w}]}})}}else await o(a,{error:{code:-32601,message:"Method not supported"}})}let u=16*1024,l=Buffer.alloc(0);for await(let d of process.stdin){l=Buffer.concat([l,d]);let i;for(;(i=l.indexOf(10))!==-1;){if(i>u)throw new Error("MCP message exceeded 16 KiB.");await s(l.subarray(0,i).toString("utf8")),l=l.subarray(i+1)}if(l.length>u)throw new Error("MCP message exceeded 16 KiB.")}}var U=["CodeLedger portable CLI",' codeledger activate --task "<question>" --query "<literal>" [--repo <worktree-root>]'," codeledger mcp start --repo <worktree-root> [--profile core]"," codeledger capabilities --json"," codeledger --version"].join(`
5
+ `);async function B([e,...r]){if(!e||["help","--help","-h"].includes(e)||r.includes("--help")){console.log(U);return}if(["version","--version","-v"].includes(e)&&r.length===0){console.log(`codeledger v${h}`);return}if(e==="capabilities"&&r.length===1&&r[0]==="--json"){console.log(JSON.stringify({schema:"codeledger/capabilities/v1",runtime_version:h,distribution:"open",commands:["activate","capabilities","help","mcp","version"],mcp:{transports:["stdio"],default_profile:"core",profiles:{core:[_]}}}));return}if(e==="activate"){let{values:t}=(0,x.parseArgs)({args:r,options:{repo:{type:"string"},task:{type:"string"},query:{type:"string"}}}),n=g(t.repo??process.cwd(),t.repo!==void 0);console.log(JSON.stringify(v(n,t.task,t.query),null,2));return}if(e==="mcp"&&r[0]==="start"){let{values:t}=(0,x.parseArgs)({args:r.slice(1),options:{repo:{type:"string"},profile:{type:"string",default:"core"}}});if(!t.repo||t.profile!=="core")throw new Error("Supply --repo <worktree-root> and the core profile.");await M(t.repo);return}throw new Error("Unsupported portable command. Run codeledger --help.")}B(process.argv.slice(2)).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});
package/package.json CHANGED
@@ -1,49 +1,17 @@
1
1
  {
2
2
  "name": "@codeledger/cli",
3
- "version": "0.10.82",
4
- "mcpName": "io.github.codeledgerECF/codeledger",
5
- "description": "Official ContextECF CodeLedger CLI wrapper. Installs the hardened binary from GitHub Releases; zero engine code ships in this package.",
6
- "type": "commonjs",
7
- "bin": {
8
- "codeledger": "./bin/codeledger.js",
9
- "codeledger-mcp": "./bin/codeledger.js"
10
- },
11
- "files": [
12
- "bin/",
13
- "scripts/",
14
- "README.md",
15
- "LICENSE",
16
- "LICENSE-CORE",
17
- "NOTICE"
18
- ],
19
- "dependencies": {},
20
- "devDependencies": {
21
- "vitest": "^4.1.12"
22
- },
3
+ "version": "0.10.84",
4
+ "description": "CodeLedger portable Git context and MCP CLI",
5
+ "license": "MIT",
23
6
  "engines": {
24
- "node": ">=18"
7
+ "node": ">=20"
8
+ },
9
+ "bin": {
10
+ "codeledger": "codeledger-open.cjs",
11
+ "codeledger-mcp": "codeledger-open.cjs"
25
12
  },
26
13
  "repository": {
27
14
  "type": "git",
28
- "url": "github:codeledgerECF/codeledger"
29
- },
30
- "license": "MIT",
31
- "keywords": [
32
- "codeledger",
33
- "contextecf",
34
- "context",
35
- "ai",
36
- "claude",
37
- "cursor",
38
- "copilot"
39
- ],
40
- "publishConfig": {
41
- "access": "public"
42
- },
43
- "scripts": {
44
- "postinstall": "node scripts/postinstall.js",
45
- "test": "vitest run",
46
- "build": "echo 'no build — ships as-is'",
47
- "typecheck": "echo 'no ts — ships as-is'"
15
+ "url": "git+https://github.com/codeledgerECF/codeledger.git"
48
16
  }
49
- }
17
+ }
package/LICENSE-CORE DELETED
@@ -1,61 +0,0 @@
1
- CodeLedger Core Engine License
2
- Version 1.0, 2025
3
-
4
- Copyright (c) 2025 Intelligent Context AI, Inc.
5
- All rights reserved.
6
-
7
- GRANT OF LICENSE
8
-
9
- Subject to the terms of this license, Intelligent Context AI, Inc. ("Licensor")
10
- grants you a non-exclusive, non-transferable, revocable license to use the
11
- CodeLedger Core Engine binary ("Software") under the following conditions:
12
-
13
- 1. INDIVIDUAL USE (FREE)
14
- You may use the Software for personal, non-commercial development work
15
- at no cost. This includes individual developers using the Software on
16
- their own projects or contributing to open-source projects.
17
-
18
- 2. OPEN-SOURCE PROJECTS (FREE)
19
- You may use the Software in open-source projects licensed under
20
- OSI-approved licenses at no cost.
21
-
22
- 3. COMMERCIAL USE (LICENSE REQUIRED)
23
- Use of the Software in commercial settings, including but not limited to:
24
- - CI/CD pipelines
25
- - Team development environments (>1 developer)
26
- - Enterprise deployments
27
- - Products or services that incorporate the Software
28
- requires a CodeLedger Pro license. Contact team@codeledger.dev for pricing.
29
-
30
- RESTRICTIONS
31
-
32
- You may NOT:
33
- - Reverse engineer, decompile, or disassemble the Software
34
- - Redistribute the Software as a standalone product
35
- - Remove or modify any license notices or proprietary markings
36
- - Use the Software to build a competing product or service
37
-
38
- PRIVACY GUARANTEE
39
-
40
- The Software:
41
- - Runs entirely on your local machine
42
- - Makes no network calls
43
- - Collects no telemetry, analytics, or usage data
44
- - Does not transmit your source code or any data to external services
45
-
46
- DISCLAIMER
47
-
48
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
49
- IMPLIED. IN NO EVENT SHALL THE LICENSOR BE LIABLE FOR ANY CLAIM, DAMAGES, OR
50
- OTHER LIABILITY ARISING FROM THE USE OF THE SOFTWARE.
51
-
52
- TERMINATION
53
-
54
- This license terminates automatically if you breach any of its terms.
55
- Upon termination, you must destroy all copies of the Software.
56
-
57
- CONTACT
58
-
59
- Intelligent Context AI, Inc.
60
- team@codeledger.dev
61
- https://codeledger.dev/license
package/NOTICE DELETED
@@ -1,11 +0,0 @@
1
- CodeLedger CLI Wrapper Notice
2
-
3
- The npm package @codeledger/cli is a thin JavaScript wrapper licensed under
4
- the MIT License in LICENSE.
5
-
6
- During installation, the wrapper may download a platform-specific CodeLedger
7
- hardened binary from the matching GitHub Release. That downloaded binary is
8
- not part of the npm wrapper source package and is governed by LICENSE-CORE.
9
-
10
- The wrapper contains no CodeLedger engine source, scoring formulas, or model
11
- weights. It fetches, verifies, caches, and launches the hardened binary.
package/bin/codeledger.js DELETED
@@ -1,230 +0,0 @@
1
- #!/usr/bin/env node
2
- /*
3
- * CodeLedger npm launcher — thin shim.
4
- *
5
- * This launcher and its installation helpers ship to npm under @codeledger/cli.
6
- * It contains no engine code, no scoring logic, no formulas. All CodeLedger
7
- * functionality lives inside the hardened binary that is downloaded during
8
- * `postinstall` from the GitHub Release for this exact version, verified
9
- * via SHA256, and cached under ~/.cache/codeledger/bin/.
10
- *
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.
16
- */
17
-
18
- 'use strict';
19
-
20
- const { spawnSync } = require('node:child_process');
21
- const fs = require('node:fs');
22
- const path = require('node:path');
23
- const crypto = require('node:crypto');
24
- const { resolveRuntimePin, compareRuntimeVersions, isRuntimePinTrusted } = require('../scripts/runtime-pin.js');
25
- const { existsSync, realpathSync, statSync } = require('node:fs');
26
- const { basename, dirname, join, resolve } = require('node:path');
27
- const { homedir, platform } = require('node:os');
28
-
29
- const { name: packageName, version } = require('../package.json');
30
-
31
- // `codeledger-mcp` bin alias (same file, no extra JS): for MCP registries
32
- // that cannot pass arguments, it always runs `mcp start` + the user's args.
33
- // Every other invocation forwards argv unchanged, including a bare launch,
34
- // so the CLI's own bare-launch MCP detection applies.
35
- const MCP_ALIAS = /^codeledger-mcp(\.c?js)?$/i.test(basename(process.argv[1] || ''));
36
- const ARGS = MCP_ALIAS ? ['mcp', 'start', ...process.argv.slice(2)] : process.argv.slice(2);
37
-
38
- const CACHE_DIR =
39
- process.env.CODELEDGER_CACHE_DIR ||
40
- join(homedir(), '.cache', 'codeledger', 'bin');
41
-
42
- const BINARY_NAME =
43
- platform() === 'win32'
44
- ? `codeledger-hardened-v${version}.exe`
45
- : `codeledger-hardened-v${version}`;
46
-
47
- const BINARY_PATH = join(CACHE_DIR, BINARY_NAME);
48
-
49
- function die(msg, code = 1) {
50
- process.stderr.write(`codeledger: ${msg}\n`);
51
- process.exit(code);
52
- }
53
-
54
- // Repair commands use the installed version, so an old pin cannot trap an upgrade.
55
- function repairing() {
56
- const commands = [];
57
- for (let i = 0; i < ARGS.length && ARGS[i] !== '--'; i++) {
58
- if (ARGS[i] === '--cwd') { i++; continue; }
59
- if (!ARGS[i].startsWith('-')) commands.push(ARGS[i]);
60
- }
61
- return ['vendor', 'upgrade', 'update', 'init'].includes(commands[0]);
62
- }
63
-
64
- function findPinnedRuntime(startDir) {
65
- if (process.env.CODELEDGER_GLOBAL_VERSION_PROBE === '1' || repairing()) return null;
66
- let root = resolve(startDir);
67
- while (true) {
68
- const pin = resolveRuntimePin(join(root, '.codeledger'), { fs, path, crypto }, compareRuntimeVersions);
69
- if (pin) {
70
- const trustDir = process.env.CODELEDGER_RUNTIME_TRUST_DIR || join(homedir(), '.cache', 'codeledger', 'runtime-trust');
71
- if (isRuntimePinTrusted(root, pin.manifest, { fs, path, crypto }, trustDir)) return { kind: 'standalone', path: pin.path, repoRoot: root };
72
- process.stderr.write('codeledger: repository runtime has no installed trust receipt; using the global installation. Run the installed codeledger vendor command to install and trust its verified runtime.\n');
73
- return null;
74
- }
75
- if (existsSync(join(root, '.git'))) return null;
76
- const parent = dirname(root);
77
- if (parent === root) return null;
78
- root = parent;
79
- }
80
- }
81
-
82
- // Repo-local fallback: an already-`codeledger init`'d repo vendors its own
83
- // runtime under .codeledger/bin/. Checked before attempting a network
84
- // download since it's instant and needs no connectivity — the global cache
85
- // miss just means this particular machine hasn't installed globally yet,
86
- // not that the user has no working CodeLedger available to them.
87
- function findRepoLocalRuntime(startDir) {
88
- if (process.env.CODELEDGER_GLOBAL_VERSION_PROBE === '1') return null;
89
- let current = resolve(startDir);
90
- while (true) {
91
- if (existsSync(join(current, '.codeledger', 'runtime.json'))) return null;
92
- // Legacy scripts require an explicit environment-level repository trust decision.
93
- if (process.env.CODELEDGER_TRUST_LEGACY_RUNTIME !== '1') return null;
94
- const wrapper = join(current, '.codeledger', 'bin', 'codeledger');
95
- const standalone = join(current, '.codeledger', 'bin', 'codeledger-standalone.cjs');
96
- if (existsSync(wrapper)) return { kind: 'wrapper', path: wrapper, repoRoot: current };
97
- if (existsSync(standalone)) return { kind: 'standalone', path: standalone, repoRoot: current };
98
- if (existsSync(join(current, '.git'))) return null;
99
- const parent = dirname(current);
100
- if (parent === current) return null;
101
- current = parent;
102
- }
103
- }
104
-
105
- function runRepoLocal(runtime) {
106
- process.stderr.write(
107
- [
108
- `codeledger: using the repository runtime instead of the global v${version} installation.`,
109
- `codeledger: using repo-local runtime at ${runtime.path}`,
110
- '',
111
- ].join('\n'),
112
- );
113
- const command = runtime.kind === 'standalone' ? process.execPath : runtime.path;
114
- const args = runtime.kind === 'standalone'
115
- ? [runtime.path, ...ARGS]
116
- : ARGS;
117
- const result = spawnSync(command, args, {
118
- stdio: 'inherit',
119
- cwd: process.cwd(),
120
- env: { ...process.env, CODELEDGER_DELEGATED: '1' },
121
- });
122
- if (result.error) {
123
- die(`failed to spawn repo-local runtime: ${result.error.message}`);
124
- }
125
- process.exit(result.status ?? 1);
126
- }
127
-
128
- // One-shot, on-demand fetch, used only when the binary isn't cached yet and
129
- // no repo-local runtime was found. Bounded well below postinstall's own
130
- // window since a live invocation is blocked on this, not a background
131
- // install step.
132
- const ON_DEMAND_DEADLINE_MS = 30_000;
133
-
134
- function launchDirectory() {
135
- const args = ARGS;
136
- let target;
137
- for (let i = 0; i < args.length && args[i] !== '--'; i++) {
138
- if (args[i].startsWith('--cwd=')) target = args[i].slice(6);
139
- else if (args[i] === '--cwd') {
140
- target = args[++i];
141
- if (!target || target.startsWith('--')) die('--cwd requires a repository directory.', 2);
142
- }
143
- }
144
- if (target === undefined && (args[0] === 'mcp' || (args.length === 0 && !process.stdin.isTTY))) target = process.env.CODELEDGER_REPO_ROOT;
145
- if (target !== undefined && !target.trim()) die('Repository target cannot be empty.', 2);
146
- try {
147
- const root = realpathSync(resolve(target ?? process.cwd()));
148
- if (!statSync(root).isDirectory()) throw new Error('Not a directory');
149
- return root;
150
- } catch { die('Repository target must be an existing directory. Check --cwd or CODELEDGER_REPO_ROOT.', 2); }
151
- }
152
-
153
- async function main() {
154
- const pinned = findPinnedRuntime(launchDirectory());
155
- if (pinned) runRepoLocal(pinned);
156
- if (existsSync(BINARY_PATH)) {
157
- const problem = require('../scripts/postinstall.js').verifyCachedBinary(BINARY_PATH);
158
- if (problem) {
159
- process.stderr.write(`codeledger: cached binary at ${BINARY_PATH} failed verification (${problem}); discarding it and downloading a verified copy.\n`);
160
- try { fs.unlinkSync(BINARY_PATH); } catch (error) { die(`could not remove the unverified cached binary: ${error.message}. Delete ${BINARY_PATH} and retry.`); }
161
- }
162
- }
163
- if (!existsSync(BINARY_PATH)) {
164
- const repoLocal = repairing() ? null : findRepoLocalRuntime(launchDirectory());
165
- if (repoLocal) {
166
- runRepoLocal(repoLocal);
167
- }
168
-
169
- const { arch } = require('node:os');
170
- const platformKey = `${platform()}-${arch()}`;
171
- const installerPath = join(__dirname, '..', 'scripts', 'postinstall.js');
172
-
173
- const { PLATFORM_MAP, downloadAndVerifyBinary, unsupportedPlatformMessage, readInstallFailure, unpublishedAssetsMessage } = require('../scripts/postinstall.js');
174
- if (!PLATFORM_MAP[platformKey]) {
175
- // Don't waste time on a download attempt that can only ever fail —
176
- // getBinaryPaths() would reject this platformKey immediately anyway.
177
- // See postinstall.js's matching message for why this is "no
178
- // committed timeline", not "try again later".
179
- die(unsupportedPlatformMessage(platformKey));
180
- }
181
-
182
- const priorFailure = readInstallFailure();
183
- if (priorFailure) {
184
- process.stderr.write(`codeledger: the install step could not fetch the hardened binary (${priorFailure.at}): ${priorFailure.message}\n`);
185
- }
186
- process.stderr.write(
187
- `codeledger: hardened binary for v${version} not cached locally — downloading now (one-time)...\n`,
188
- );
189
- try {
190
- await downloadAndVerifyBinary({ deadlineMs: ON_DEMAND_DEADLINE_MS });
191
- } catch (err) {
192
- const unpublished = unpublishedAssetsMessage(err);
193
- die(
194
- [
195
- `hardened binary for v${version} not found at ${BINARY_PATH}, and the on-demand download just failed: ${err.message}`,
196
- ...(unpublished ? ['', unpublished,
197
- 'Retrying or reinstalling this version will not help until they are published.',
198
- 'To use a published version instead, list them with: npm view @codeledger/cli versions'] : [
199
- '',
200
- 'The postinstall step may have been skipped (e.g. --ignore-scripts).']),
201
- 'Confirm the official scoped package is installed: @codeledger/cli.',
202
- 'Avoid the unrelated unscoped npm package: codeledger.',
203
- '',
204
- 'Recover with one of:',
205
- ' 1. Retry: codeledger --version',
206
- ` 2. Reinstall this version: npm install -g ${packageName}@${version}`,
207
- ` 3. node "${installerPath}"`,
208
- ' 4. Re-run the install without --ignore-scripts',
209
- ' 5. In an initialized repo, use: ./.codeledger/bin/codeledger ready',
210
- '',
211
- `Release page for v${version} (it exists only once that release is published):`,
212
- ` https://github.com/codeledgerECF/codeledger/releases/tag/v${version}`,
213
- ].join('\n'),
214
- );
215
- }
216
- }
217
-
218
- const result = spawnSync(BINARY_PATH, ARGS, {
219
- stdio: 'inherit',
220
- env: process.env,
221
- });
222
-
223
- if (result.error) {
224
- die(`failed to spawn binary: ${result.error.message}`);
225
- }
226
-
227
- process.exit(result.status ?? 1);
228
- }
229
-
230
- main().catch((error) => die(error.message));
@@ -1,463 +0,0 @@
1
- #!/usr/bin/env node
2
- /*
3
- * CodeLedger postinstall — download + verify the hardened binary.
4
- *
5
- * Runs automatically on `npm install -g @codeledger/cli`. Downloads the
6
- * platform-specific hardened binary from the GitHub Release for this
7
- * exact version, verifies its SHA256 against SHA256SUMS-v<version>.txt
8
- * (also downloaded from the release), and writes it to the cache dir.
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
- *
17
- * Environment variables (all optional):
18
- * CODELEDGER_SKIP_POSTINSTALL=1 — skip entirely (air-gapped installs)
19
- * CODELEDGER_RUN_UPGRADE=1 — after the binary download succeeds,
20
- * also run `codeledger upgrade`
21
- * CODELEDGER_BINARY_URL=<url> — override the release download base URL
22
- * (for corporate mirrors / internal CDNs).
23
- * Must serve the same filenames and a
24
- * SHA256SUMS-v<version>.txt sibling file.
25
- * CODELEDGER_CACHE_DIR=<path> — override the cache directory
26
- * (default: ~/.cache/codeledger/bin)
27
- * CODELEDGER_INSTALL_DEADLINE_MS=<ms> — override the download propagation
28
- * window (default: 150000 = 2.5 min)
29
- *
30
- * This file contains no engine logic. It only fetches, verifies, and writes
31
- * bytes. Safe to inspect, safe to mirror, safe to audit.
32
- */
33
-
34
- 'use strict';
35
-
36
- const https = require('node:https');
37
- const { URL } = require('node:url');
38
- const { createHash } = require('node:crypto');
39
- const {
40
- mkdirSync,
41
- writeFileSync,
42
- chmodSync,
43
- existsSync,
44
- unlinkSync,
45
- readFileSync,
46
- statSync,
47
- } = require('node:fs');
48
- const { join } = require('node:path');
49
- const { homedir, platform, arch } = require('node:os');
50
-
51
- const { version } = require('../package.json');
52
-
53
- // ─── platform / path resolution (pure — no I/O, no process.exit) ──────────
54
-
55
- // Only these native asset names are wired into this installer.
56
- const PLATFORM_MAP = {
57
- 'darwin-arm64': 'darwin-arm64',
58
- 'linux-x64': 'linux-x64',
59
- };
60
-
61
- function unsupportedPlatformMessage(platformKey) {
62
- return [
63
- `${platformKey} has no pre-built CodeLedger hardened binary.`,
64
- `Supported native routes: ${Object.keys(PLATFORM_MAP).join(', ')}.`,
65
- 'A successful npm install does not establish a working runtime or MCP connection.',
66
- 'For an already initialized repository with a trusted vendored runtime:',
67
- ' node .codeledger/bin/codeledger-standalone.cjs ready',
68
- 'For a fresh repository, use a supported host or a supported linux-x64 environment.',
69
- 'Skipping postinstall does not bootstrap a missing runtime; codeledger init cannot fix that loop.',
70
- 'Intel Macs cannot run an Apple Silicon binary through Rosetta.',
71
- 'Source-build prerequisites and limitations: https://github.com/codeledgerECF/codeledger/blob/main/docs/security/ENTERPRISE_ASSURANCE.md',
72
- ].join('\n');
73
- }
74
-
75
- function getPlatformKey() {
76
- return `${platform()}-${arch()}`;
77
- }
78
-
79
- function getCacheDir() {
80
- return (
81
- process.env.CODELEDGER_CACHE_DIR || join(homedir(), '.cache', 'codeledger', 'bin')
82
- );
83
- }
84
-
85
- // Binaries are hosted on the public CodeLedger GitHub Releases page so
86
- // `npm install -g @codeledger/cli` can fetch them without authentication.
87
- function getBinaryPaths(platformKey) {
88
- const platformSuffix = PLATFORM_MAP[platformKey];
89
- if (!platformSuffix) return null;
90
-
91
- const releaseBase =
92
- process.env.CODELEDGER_BINARY_URL ||
93
- `https://github.com/codeledgerECF/codeledger/releases/download/v${version}`;
94
- const binaryRemoteName = `codeledger-hardened-${platformSuffix}-v${version}`;
95
- const cacheDir = getCacheDir();
96
-
97
- return {
98
- binaryUrl: `${releaseBase}/${binaryRemoteName}`,
99
- checksumsUrl: `${releaseBase}/SHA256SUMS-v${version}.txt`,
100
- binaryRemoteName,
101
- cacheDir,
102
- binaryLocalPath: join(cacheDir, `codeledger-hardened-v${version}`),
103
- };
104
- }
105
-
106
- // The verified SHA-256 is recorded beside the cached binary so every launch can
107
- // reject a truncated, replaced, or tampered cache before executing it.
108
- function receiptPath(binaryPath) {
109
- return `${binaryPath}.sha256.json`;
110
- }
111
-
112
- function writeVerifiedReceipt(binaryPath, sha256) {
113
- const stat = statSync(binaryPath);
114
- writeFileSync(receiptPath(binaryPath), JSON.stringify({ schema: 1, version, sha256, size: stat.size }) + '\n');
115
- }
116
-
117
- /** Returns null when the cached binary matches its install receipt, else the reason it does not. */
118
- function verifyCachedBinary(binaryPath) {
119
- let receipt;
120
- try {
121
- receipt = JSON.parse(readFileSync(receiptPath(binaryPath), 'utf8'));
122
- } catch {
123
- return 'no install receipt';
124
- }
125
- if (!receipt || receipt.schema !== 1 || receipt.version !== version || !/^[a-f0-9]{64}$/.test(String(receipt.sha256))) return 'invalid install receipt';
126
- let stat;
127
- try {
128
- stat = statSync(binaryPath);
129
- } catch {
130
- return 'binary missing';
131
- }
132
- if (!stat.isFile() || stat.size === 0) return 'binary is empty or not a file';
133
- if (stat.size !== receipt.size) return 'binary size changed since install';
134
- // Hashed on every launch: size or timestamps can be preserved by a same-size replacement.
135
- const actual = createHash('sha256').update(readFileSync(binaryPath)).digest('hex');
136
- return actual === receipt.sha256 ? null : 'SHA256 mismatch with install receipt';
137
- }
138
-
139
- // npm hides postinstall output by default, so a soft failure is recorded where
140
- // the first `codeledger` run can report it.
141
- function installFailurePath() {
142
- return join(getCacheDir(), `install-failure-v${version}.json`);
143
- }
144
-
145
- function recordInstallFailure(err) {
146
- try {
147
- mkdirSync(getCacheDir(), { recursive: true });
148
- writeFileSync(installFailurePath(), JSON.stringify({
149
- schema: 1, version, at: new Date().toISOString(),
150
- status: typeof err.statusCode === 'number' ? err.statusCode : null,
151
- message: String(err.message).split('\n')[0].slice(0, 300),
152
- }) + '\n');
153
- } catch { /* Reporting is best effort; the install stays a soft failure. */ }
154
- }
155
-
156
- function readInstallFailure() {
157
- try {
158
- const record = JSON.parse(readFileSync(installFailurePath(), 'utf8'));
159
- return record && record.schema === 1 && record.version === version ? record : null;
160
- } catch {
161
- return null;
162
- }
163
- }
164
-
165
- function clearInstallFailure() {
166
- try { unlinkSync(installFailurePath()); } catch { /* Nothing recorded. */ }
167
- }
168
-
169
- /** A 404 after the propagation window means this version's release assets are not published. */
170
- function unpublishedAssetsMessage(err) {
171
- return err && err.statusCode === 404
172
- ? `The v${version} release assets were not found (HTTP 404): this version's hardened binaries are not published yet, or were withdrawn.`
173
- : null;
174
- }
175
-
176
- function isBinaryCached() {
177
- const paths = getBinaryPaths(getPlatformKey());
178
- return Boolean(paths && existsSync(paths.binaryLocalPath) && verifyCachedBinary(paths.binaryLocalPath) === null);
179
- }
180
-
181
- // ─── http ────────────────────────────────────────────────────────────────────
182
-
183
- const FETCH_TIMEOUT_MS = 60_000;
184
-
185
- function fetchBufferOnce(url, redirectDepth = 0, expiresAt = Date.now() + FETCH_TIMEOUT_MS) {
186
- if (redirectDepth > 5) {
187
- return Promise.reject(new Error(`too many redirects fetching ${url}`));
188
- }
189
- return new Promise((resolve, reject) => {
190
- const remaining = Math.min(FETCH_TIMEOUT_MS, expiresAt - Date.now());
191
- if (remaining <= 0) { reject(new Error('Binary download deadline exceeded.')); return; }
192
- const req = https.get(
193
- url,
194
- {
195
- timeout: FETCH_TIMEOUT_MS,
196
- headers: {
197
- 'User-Agent': `codeledger-installer/${version}`,
198
- Accept: 'application/octet-stream',
199
- },
200
- },
201
- (res) => {
202
- if (
203
- (res.statusCode === 301 ||
204
- res.statusCode === 302 ||
205
- res.statusCode === 307 ||
206
- res.statusCode === 308) &&
207
- res.headers.location
208
- ) {
209
- res.resume();
210
- const next = new URL(res.headers.location, url).toString();
211
- fetchBufferOnce(next, redirectDepth + 1, expiresAt).then(resolve, reject);
212
- return;
213
- }
214
- if (res.statusCode !== 200) {
215
- res.resume();
216
- const err = new Error(`HTTP ${res.statusCode} fetching ${url}`);
217
- err.statusCode = res.statusCode;
218
- reject(err);
219
- return;
220
- }
221
- const chunks = [];
222
- res.on('data', (c) => chunks.push(c));
223
- res.on('end', () => resolve(Buffer.concat(chunks)));
224
- res.on('error', reject);
225
- },
226
- );
227
- const timer = setTimeout(() => {
228
- const error = new Error('Binary download deadline exceeded.');
229
- req.destroy(error);
230
- reject(error);
231
- }, remaining);
232
- req.on('error', reject);
233
- req.once('close', () => clearTimeout(timer));
234
- });
235
- }
236
-
237
- // Default propagation window for the postinstall-time attempt. Deliberately
238
- // a wall-clock deadline, not a fixed attempt count: the question is "how
239
- // long is it plausible for a just-published release's assets to still be
240
- // propagating," not "how many times did we try." A version whose GitHub
241
- // Release will never exist (npm published ahead of a working release — the
242
- // actual incident this retry policy is designed around) now fails within
243
- // this window instead of retrying for ~8 minutes that were never going to
244
- // succeed.
245
- const DEFAULT_DEADLINE_MS = Number(process.env.CODELEDGER_INSTALL_DEADLINE_MS) || 150_000; // 2.5 minutes
246
-
247
- // Retry wrapper that tolerates the short propagation window where a freshly
248
- // published package may be visible before all release assets are available.
249
- // A 404 is retried with exponential backoff bounded by deadlineMs;
250
- // non-404 errors fail fast.
251
- async function fetchBuffer(url, deadlineMs = DEFAULT_DEADLINE_MS) {
252
- const start = Date.now();
253
- let attempt = 0;
254
- let lastErr;
255
- for (;;) {
256
- try {
257
- return await fetchBufferOnce(url, 0, start + deadlineMs);
258
- } catch (err) {
259
- lastErr = err;
260
- // Only retry on 404 — everything else is a hard failure.
261
- if (err.statusCode !== 404) throw err;
262
- const elapsed = Date.now() - start;
263
- const wait = Math.min(20_000, 5_000 * 2 ** attempt);
264
- if (elapsed + wait >= deadlineMs) break;
265
- attempt += 1;
266
- const remainingSec = Math.round((deadlineMs - elapsed) / 1000);
267
- console.error(
268
- `codeledger: Binary pending — retrying in ${Math.round(wait / 1000)}s ` +
269
- `(${remainingSec}s left in propagation window).`,
270
- );
271
- await new Promise((r) => setTimeout(r, wait));
272
- }
273
- }
274
- throw lastErr;
275
- }
276
-
277
- // ─── checksum parsing ───────────────────────────────────────────────────────
278
-
279
- function findExpectedSha(checksumsText, filename) {
280
- // SHA256SUMS format: "<hex> <filename>\n" per line (coreutils sha256sum)
281
- const lines = checksumsText.split('\n');
282
- for (const line of lines) {
283
- const trimmed = line.trim();
284
- if (!trimmed || trimmed.startsWith('#')) continue;
285
- const parts = trimmed.split(/\s+/);
286
- if (parts.length < 2) continue;
287
- const [hex, ...nameParts] = parts;
288
- const name = nameParts.join(' ').replace(/^\*/, ''); // strip binary-mode prefix
289
- if (name === filename) {
290
- return hex.toLowerCase();
291
- }
292
- }
293
- return null;
294
- }
295
-
296
- // ─── download + verify (the reusable, side-effect-scoped core) ────────────
297
-
298
- // Downloads, verifies, and caches the hardened binary for the current
299
- // platform + this package's version. Throws on failure — does not exit the
300
- // process. Callers decide what "failure" means for them: postinstall.js
301
- // soft-fails (exit 0, retry later); bin/codeledger.js's on-demand path
302
- // falls through to a hard failure message since the user is blocked right
303
- // now.
304
- async function downloadAndVerifyBinary({ deadlineMs = DEFAULT_DEADLINE_MS } = {}) {
305
- const platformKey = getPlatformKey();
306
- const paths = getBinaryPaths(platformKey);
307
- if (!paths) {
308
- throw new Error(`unsupported platform ${platformKey}`);
309
- }
310
-
311
- console.error(`codeledger: installing v${version} hardened binary for ${platformKey}`);
312
- console.error(` source: ${paths.binaryUrl}`);
313
-
314
- const [checksumsBuf, binary] = await Promise.all([
315
- fetchBuffer(paths.checksumsUrl, deadlineMs),
316
- fetchBuffer(paths.binaryUrl, deadlineMs),
317
- ]);
318
- const checksums = checksumsBuf.toString('utf8');
319
-
320
- const expectedSha = findExpectedSha(checksums, paths.binaryRemoteName);
321
- if (!expectedSha) {
322
- throw new Error(
323
- `${paths.binaryRemoteName} not listed in SHA256SUMS-v${version}.txt — cannot verify binary integrity`,
324
- );
325
- }
326
-
327
- const actualSha = createHash('sha256').update(binary).digest('hex');
328
- if (actualSha !== expectedSha) {
329
- throw new Error(
330
- `SHA256 mismatch for ${paths.binaryRemoteName}:\n expected ${expectedSha}\n got ${actualSha}`,
331
- );
332
- }
333
-
334
- mkdirSync(paths.cacheDir, { recursive: true });
335
-
336
- // Atomic-ish write: write to tmp, rename
337
- const tmpPath = `${paths.binaryLocalPath}.tmp`;
338
- if (existsSync(tmpPath)) unlinkSync(tmpPath);
339
- writeFileSync(tmpPath, binary);
340
- chmodSync(tmpPath, 0o755);
341
- if (existsSync(paths.binaryLocalPath)) unlinkSync(paths.binaryLocalPath);
342
- require('node:fs').renameSync(tmpPath, paths.binaryLocalPath);
343
- writeVerifiedReceipt(paths.binaryLocalPath, actualSha);
344
- clearInstallFailure();
345
-
346
- console.error(`codeledger: installed ${paths.binaryLocalPath}`);
347
- console.error(` sha256: ${actualSha}`);
348
-
349
- return paths.binaryLocalPath;
350
- }
351
-
352
- // Optional post-download step: run `codeledger upgrade` in the most likely
353
- // target repo so existing repos pick up refreshed ambient hooks/runtime
354
- // without a second manual command. Opt-in only — never runs by default.
355
- function maybeRunUpgrade() {
356
- if (process.env.CODELEDGER_RUN_UPGRADE === '1') {
357
- const { spawnSync } = require('node:child_process');
358
- const path = require('node:path');
359
- const fs = require('node:fs');
360
- const codeledgerBin = path.join(__dirname, '..', 'bin', 'codeledger.js');
361
- const initCwd = process.env['INIT_CWD'];
362
- const homeCwd = process.env['HOME'] ?? process.env['USERPROFILE'] ?? process.cwd();
363
- const upgradeCwd =
364
- initCwd && fs.existsSync(path.join(initCwd, '.codeledger')) ? initCwd : homeCwd;
365
- console.error('codeledger: CODELEDGER_RUN_UPGRADE=1 set, running upgrade...');
366
- const upgradeResult = spawnSync(process.execPath, [codeledgerBin, 'upgrade'], {
367
- stdio: 'inherit',
368
- cwd: upgradeCwd,
369
- env: { ...process.env, CODELEDGER_SKIP_AMBIENT_ACTIVATION: '1' },
370
- });
371
- if ((upgradeResult.status ?? 0) !== 0) {
372
- console.error('');
373
- console.error('codeledger: upgrade step encountered an issue. Run manually:');
374
- console.error(' codeledger upgrade');
375
- }
376
- }
377
- }
378
-
379
- // ─── postinstall entry point ───────────────────────────────────────────────
380
- // All side-effecting decisions (env skip, dev-workspace skip, platform
381
- // gating, process.exit) live here, gated behind `require.main === module`
382
- // below — so requiring this file as a library (from bin/codeledger.js, or
383
- // from tests) never has side effects.
384
-
385
- async function runPostinstall() {
386
- if (process.env.CODELEDGER_SKIP_POSTINSTALL === '1') {
387
- console.error(
388
- 'codeledger: CODELEDGER_SKIP_POSTINSTALL=1 set, skipping ContextECF CodeLedger hardened binary download.',
389
- );
390
- return;
391
- }
392
-
393
- // Skip when running inside this source workspace (dev mode). The presence
394
- // of pnpm-workspace.yaml two directories up is a reliable signal that
395
- // this is not a real end-user install, and the release binary for this
396
- // version may not exist yet.
397
- try {
398
- const path = require('node:path');
399
- const fs = require('node:fs');
400
- const workspaceRoot = path.resolve(__dirname, '..', '..', '..');
401
- if (fs.existsSync(path.join(workspaceRoot, 'pnpm-workspace.yaml'))) {
402
- console.error(
403
- 'codeledger: in-workspace dev install detected, skipping ContextECF CodeLedger hardened binary download.',
404
- );
405
- return;
406
- }
407
- } catch {
408
- // fall through to normal install
409
- }
410
-
411
- const platformKey = getPlatformKey();
412
-
413
- if (!PLATFORM_MAP[platformKey]) {
414
- // Soft install failure does not create a fresh runtime on this platform.
415
- console.error(`codeledger: ${unsupportedPlatformMessage(platformKey)}`);
416
- return;
417
- }
418
-
419
- try {
420
- await downloadAndVerifyBinary();
421
- console.error('');
422
- console.error('codeledger: install complete.');
423
- console.error(' Next: cd your-repo && codeledger ready');
424
- console.error(' Existing repos can refresh ambient hooks/runtime with: codeledger upgrade');
425
- console.error('codeledger: ready initializes, scans, and prepares ambient task context.');
426
- maybeRunUpgrade();
427
- } catch (err) {
428
- // Soft-fail, deliberately: exit 0 either way. A failed postinstall
429
- // makes npm treat the whole install as failed, which can roll back an
430
- // existing working install (the exact incident this is designed
431
- // around). bin/codeledger.js retries this same download on-demand,
432
- // synchronously, the first time it's actually needed.
433
- recordInstallFailure(err);
434
- console.error(`codeledger: could not pre-fetch the hardened binary — ${err.message}`);
435
- const unpublished = unpublishedAssetsMessage(err);
436
- if (unpublished) console.error(`codeledger: ${unpublished}`);
437
- console.error('codeledger: not fatal — it will download automatically on first "codeledger" invocation.');
438
- console.error('codeledger: or, in an initialized repo, use: ./.codeledger/bin/codeledger ready');
439
- }
440
- }
441
-
442
- // Only run the postinstall entry point when invoked directly (npm
443
- // postinstall, node scripts/postinstall.js). When required — from
444
- // bin/codeledger.js's on-demand download path, or from tests — this file
445
- // has no side effects; only the exported pure/reusable functions are used.
446
- if (require.main === module) {
447
- runPostinstall().then(() => process.exit(0));
448
- }
449
-
450
- module.exports = {
451
- findExpectedSha,
452
- PLATFORM_MAP,
453
- downloadAndVerifyBinary,
454
- getPlatformKey,
455
- getBinaryPaths,
456
- isBinaryCached,
457
- unsupportedPlatformMessage,
458
- verifyCachedBinary,
459
- writeVerifiedReceipt,
460
- readInstallFailure,
461
- recordInstallFailure,
462
- unpublishedAssetsMessage,
463
- };
@@ -1,125 +0,0 @@
1
- /* Generated by scripts/generate-runtime-resolver.mjs. Public installation contract only. */
2
- 'use strict';
3
- module.exports = (() => {
4
- /** Strict SemVer 2.0, shared by pin validation and explicit installation. */
5
- function parseRuntimeVersion(value) {
6
- const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/.exec(value);
7
- if (!match || match[0] !== value) throw new Error(`Invalid runtime version: ${value}. Use an exact semantic version.`);
8
- const core = match.slice(1, 4).map(Number);
9
- const prerelease = match[4]?.split('.') ?? [];
10
- if (core.some((n) => !Number.isSafeInteger(n)) || prerelease.some((p) => /^\d+$/.test(p) && (p.length > 1 && p.startsWith('0')))) {
11
- throw new Error(`Invalid runtime version: ${value}`);
12
- }
13
- return { core, prerelease };
14
- }
15
-
16
- function compareRuntimeVersions(left, right) {
17
- const a = parseRuntimeVersion(left);
18
- const b = parseRuntimeVersion(right);
19
- for (let i = 0; i < 3; i++) {
20
- if (a.core[i] !== b.core[i]) return a.core[i] < b.core[i] ? -1 : 1;
21
- }
22
- if (!a.prerelease.length || !b.prerelease.length) {
23
- return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length ? -1 : 1;
24
- }
25
- for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i++) {
26
- const x = a.prerelease[i];
27
- const y = b.prerelease[i];
28
- if (x === y) continue;
29
- if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
30
- const xn = /^\d+$/.test(x);
31
- const yn = /^\d+$/.test(y);
32
- if (xn && yn) return x.length !== y.length ? (x.length < y.length ? -1 : 1) : x < y ? -1 : 1;
33
- if (xn !== yn) return xn ? -1 : 1;
34
- return x < y ? -1 : 1;
35
- }
36
- return 0;
37
- }
38
-
39
- function runtimeGenerationSha256(bytes, notices, crypto) {
40
- return crypto.createHash('sha256').update(String(bytes.length) + ':').update(bytes).update(notices === null ? '-1:' : String(notices.length) + ':').update(notices || Buffer.alloc(0)).digest('hex');
41
- }
42
-
43
- function resolveRuntimePin(
44
- codeledgerDir,
45
- io,
46
- compare,
47
- ) {
48
- const manifestPath = io.path.join(codeledgerDir, 'runtime.json');
49
- if (!io.fs.existsSync(manifestPath)) return null;
50
- if (io.fs.lstatSync(codeledgerDir).isSymbolicLink() || io.fs.lstatSync(manifestPath).isSymbolicLink()) throw new Error('Runtime state must not be symlinked. Run codeledger vendor from the owning repository.');
51
- if (io.fs.statSync(manifestPath).size > 65536) throw new Error('runtime.json exceeds its 64 KiB contract bound. Repair with codeledger vendor.');
52
- let raw;
53
- try { raw = JSON.parse(io.fs.readFileSync(manifestPath, 'utf8')); } catch (error) { throw new Error('.codeledger/runtime.json is not valid JSON (' + error.message + '). Restore it from version control, or repair with codeledger vendor.'); }
54
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('Invalid runtime.json: expected an object. Repair with codeledger vendor.');
55
- const m = raw;
56
- if (m.schema_version !== 'codeledger/runtime/v1' || typeof m.installation_id !== 'string' || typeof m.version !== 'string' || typeof m.min_runtime !== 'string'
57
- || typeof m.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(m.sha256)
58
- || (m.distribution !== 'full' && m.distribution !== 'open') || !['fail-open-v1', 'legacy'].includes(m.hook_contract)
59
- || !m.source || typeof m.source.kind !== 'string' || typeof m.source.location !== 'string'
60
- || !m.build || m.build.content_sha256 !== m.sha256 || (m.build.revision !== null && typeof m.build.revision !== 'string')
61
- || (m.build.source_dirty !== undefined && m.build.source_dirty !== null && typeof m.build.source_dirty !== 'boolean')
62
- || (m.build.generation_sha256 === undefined && m.build.legal_sha256 !== undefined)
63
- || (m.build.generation_sha256 !== undefined && (typeof m.build.generation_sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(m.build.generation_sha256) || (m.build.legal_sha256 !== null && !/^[a-f0-9]{64}$/.test(m.build.legal_sha256))))
64
- || typeof m.entrypoint !== 'string' || m.entrypoint !== `bin/runtime/${m.version}-${m.build.generation_sha256 || m.sha256}/codeledger-standalone.cjs`) {
65
- throw new Error('Invalid runtime.json contract. Repair with codeledger vendor.');
66
- }
67
- for (const reference of [m.previous, m.migration_fallback]) {
68
- if (reference === undefined) continue;
69
- if (!reference || typeof reference !== 'object' || !/^[a-f0-9]{64}$/.test(reference.sha256) || typeof reference.entrypoint !== 'string') throw new Error('Invalid previous runtime reference. Repair with codeledger vendor.');
70
- if (reference.version !== null) compare(reference.version, reference.version);
71
- const generation = reference.generation_sha256 || reference.sha256;
72
- if (!/^[a-f0-9]{64}$/.test(generation) || (reference.entrypoint !== `bin/runtime/legacy-${reference.sha256}/codeledger-standalone.cjs` && (reference.version === null || reference.entrypoint !== `bin/runtime/${reference.version}-${generation}/codeledger-standalone.cjs`))) throw new Error('Invalid previous runtime path. Repair with codeledger vendor.');
73
- }
74
- if (compare(m.version, m.min_runtime) < 0) throw new Error('Pinned runtime is older than its configuration contract. Run codeledger upgrade.');
75
- if (compare(m.version, '0.10.82-0') >= 0 && m.build.generation_sha256 === undefined) throw new Error('Runtime generation identity is missing. Repair with codeledger vendor.');
76
- const root = io.fs.realpathSync(codeledgerDir);
77
- if (!io.fs.existsSync(io.path.resolve(root, m.entrypoint))) throw new Error('Pinned runtime is missing: .codeledger/' + m.entrypoint + '. Restore it from version control (git checkout -- .codeledger/bin), or repair with codeledger vendor.');
78
- const runtimePath = io.fs.realpathSync(io.path.resolve(root, m.entrypoint));
79
- const rel = io.path.relative(root, runtimePath);
80
- if (rel.startsWith('..') || io.path.isAbsolute(rel) || runtimePath !== io.path.resolve(root, m.entrypoint) || !io.fs.statSync(runtimePath).isFile()) {
81
- throw new Error('Pinned runtime escapes the repository. Repair with codeledger vendor.');
82
- }
83
- const bytes = io.fs.readFileSync(runtimePath);
84
- if (io.crypto.createHash('sha256').update(bytes).digest('hex') !== m.sha256) {
85
- throw new Error('Pinned runtime checksum mismatch. Repair with codeledger vendor; do not execute the modified artifact.');
86
- }
87
- if (m.build.generation_sha256 !== undefined) {
88
- let notices = null;
89
- if (m.build.legal_sha256 !== null) {
90
- const legal = runtimePath + '.LEGAL.txt';
91
- if (!io.fs.existsSync(legal)) throw new Error('Pinned notices are missing: ' + legal + '. Restore them from version control, or repair with codeledger vendor.');
92
- if (io.fs.lstatSync(legal).isSymbolicLink()) throw new Error('Pinned notices must not be symlinked. Repair with codeledger vendor.');
93
- notices = io.fs.readFileSync(legal);
94
- if (io.crypto.createHash('sha256').update(notices).digest('hex') !== m.build.legal_sha256) throw new Error('Pinned notices checksum mismatch. Repair with codeledger vendor.');
95
- }
96
- if (runtimeGenerationSha256(bytes, notices, io.crypto) !== m.build.generation_sha256) throw new Error('Pinned generation checksum mismatch. Repair with codeledger vendor.');
97
- }
98
- const header = bytes.subarray(0, 65536).toString('utf8');
99
- const version = /^\/\* CODELEDGER_STANDALONE_VERSION:([^\s*]+) \*\//m.exec(header)?.[1];
100
- const flavor = header.includes('/* CodeLedger Open CLI') ? 'open' : header.includes('/* CodeLedger Standalone CLI') ? 'full' : null;
101
- if (version !== m.version || flavor !== m.distribution) throw new Error('Pinned runtime version or distribution does not match runtime.json.');
102
- return { manifest: m, path: runtimePath };
103
- }
104
-
105
-
106
- function runtimeTrustKey(root, manifest, io) {
107
- return io.crypto.createHash('sha256').update(JSON.stringify([io.fs.realpathSync(root), manifest])).digest('hex');
108
- }
109
- function isRuntimePinTrusted(root, manifest, io, trustDir) {
110
- if (!trustDir || trustDir === 'disabled') return false;
111
- try {
112
- const directory = io.fs.realpathSync(trustDir);
113
- const repo = io.fs.realpathSync(root);
114
- const relative = io.path.relative(repo, directory);
115
- if (!relative || (!relative.startsWith('..' + io.path.sep) && relative !== '..' && !io.path.isAbsolute(relative))) return false;
116
- const key = runtimeTrustKey(root, manifest, io);
117
- const file = io.path.join(directory, key + '.json');
118
- const stat = io.fs.lstatSync(file);
119
- if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 4096) return false;
120
- const receipt = JSON.parse(io.fs.readFileSync(file, 'utf8'));
121
- return receipt.schema === 1 && receipt.key === key;
122
- } catch { return false; }
123
- }
124
- return {parseRuntimeVersion, compareRuntimeVersions, resolveRuntimePin, runtimeGenerationSha256, runtimeTrustKey, isRuntimePinTrusted};
125
- })();