@redue/cli 0.1.0-alpha.25 → 0.1.0-alpha.27
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/CHANGELOG.md +84 -0
- package/README.md +27 -12
- package/bin/redue.mjs +77 -10
- package/docs/README.md +1 -0
- package/docs/user/node-script.md +10 -6
- package/docs/user/sandbox.md +221 -0
- package/docs/user/supported-projects.md +9 -5
- package/package.json +1 -1
- package/src/claude-hook.mjs +60 -14
- package/src/cli.mjs +136 -16
- package/src/daemon.mjs +51 -6
- package/src/decision-validation.mjs +2 -1
- package/src/declared-plan.mjs +10 -1
- package/src/index.mjs +37 -3
- package/src/landlock.py +228 -0
- package/src/node-onboarding.mjs +41 -20
- package/src/node-script.mjs +16 -1
- package/src/presentation.mjs +2 -1
- package/src/python-onboarding.mjs +87 -0
- package/src/sandbox.mjs +493 -0
- package/src/setup.mjs +7 -2
- package/src/stats.mjs +72 -0
package/src/sandbox.mjs
ADDED
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
// The sandboxed recipe: a typecheck or lint command run inside an OS sandbox
|
|
2
|
+
// that lets it read only the checkout, its installed packages, the toolchain,
|
|
3
|
+
// system directories and a private home and temporary directory, with no
|
|
4
|
+
// network: Seatbelt (sandbox-exec) on macOS, Landlock (landlock.py) on Linux.
|
|
5
|
+
// The sandbox holds for every process the run starts, so programs REDUE
|
|
6
|
+
// cannot record (native compilers and linters, Python tools) are covered.
|
|
7
|
+
// The claim: the result holds for a run that sees only the project, its
|
|
8
|
+
// installed packages and the toolchain, the way CI does.
|
|
9
|
+
//
|
|
10
|
+
// The run gets a controlled environment: the check's declared variables and
|
|
11
|
+
// prefixes, a normalized PATH, a private HOME kept between runs, and a fresh
|
|
12
|
+
// TMPDIR. All of it is fingerprinted (sandboxContext), with the identity of
|
|
13
|
+
// the toolchain's executables.
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import os from 'node:os';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import {createHash} from 'node:crypto';
|
|
18
|
+
import {spawn,spawnSync} from 'node:child_process';
|
|
19
|
+
import {fileURLToPath} from 'node:url';
|
|
20
|
+
import {lookup,scriptCaches,scriptCheckInputs,scriptProject,toolchainDirs} from './node-script.mjs';
|
|
21
|
+
import {displayVariables} from './test-direct.mjs';
|
|
22
|
+
import picomatch from 'picomatch';
|
|
23
|
+
|
|
24
|
+
export const sandboxQualification='sandbox-v1';
|
|
25
|
+
export const sandboxInterpretation='sandbox@1';
|
|
26
|
+
// The same recipe with the checkout's git-ignored files hidden from the run
|
|
27
|
+
// (hiddenEntries): they are not its inputs, so build and test outputs do not
|
|
28
|
+
// make it STALE. init gives it when the run gives the same result that way.
|
|
29
|
+
export const hiddenQualification='sandbox-v2';
|
|
30
|
+
export const hiddenInterpretation='sandbox@2';
|
|
31
|
+
export const hiddenListIssue='git cannot list the ignored files';
|
|
32
|
+
export const isSandboxed=qualification=>qualification===sandboxQualification||qualification===hiddenQualification;
|
|
33
|
+
export const sandboxInterpretationOf=qualification=>qualification===hiddenQualification?hiddenInterpretation:sandboxInterpretation;
|
|
34
|
+
export const sandboxKinds=['typecheck','lint'];
|
|
35
|
+
const fail=code=>{throw Object.assign(Error(code),{code});};
|
|
36
|
+
const digest=value=>createHash('sha256').update(value).digest('hex');
|
|
37
|
+
const real=file=>{try{return fs.realpathSync(file);}catch{return null;}};
|
|
38
|
+
const within=(file,dir)=>file===dir||file.startsWith(dir.endsWith('/')?dir:dir+'/');
|
|
39
|
+
const landlockScript=path.join(path.dirname(fileURLToPath(import.meta.url)),'landlock.py');
|
|
40
|
+
|
|
41
|
+
// Python's caches in the checkout, as runner caches: not inputs.
|
|
42
|
+
const pythonCaches=['**/__pycache__/**','**/.mypy_cache/**','**/.ruff_cache/**','**/.pytest_cache/**'];
|
|
43
|
+
export const sandboxCaches=[...scriptCaches,...pythonCaches];
|
|
44
|
+
// The project's virtual environment: installed files, observed by identity,
|
|
45
|
+
// without Python's bytecode caches. Its interpreter links lead out of the
|
|
46
|
+
// checkout to the interpreter it was made from, which sandboxContext
|
|
47
|
+
// identifies instead.
|
|
48
|
+
// Python 3.14 adds a `𝜋thon` link beside `python`.
|
|
49
|
+
const venvInstalled=['.venv/**','!.venv/**/__pycache__/**','!.venv/bin/python*','!.venv/bin/pypy*','!.venv/bin/𝜋thon*'];
|
|
50
|
+
// Inputs: the whole checkout, git-ignored files included, except .git, the
|
|
51
|
+
// installed trees (node_modules, .venv) and runner caches.
|
|
52
|
+
export function sandboxCheckInputs(dirs=[]){
|
|
53
|
+
const base=scriptCheckInputs(dirs);
|
|
54
|
+
return {inputs:[...base.inputs,'!.venv/**',...pythonCaches.map(pattern=>`!${pattern}`)],
|
|
55
|
+
installedInputs:[...base.installedInputs,...venvInstalled]};
|
|
56
|
+
}
|
|
57
|
+
// A Python check runs a tool from the project's .venv: `.venv/bin/TOOL ARGS`.
|
|
58
|
+
export const pythonTool=check=>Array.isArray(check?.command)&&/^\.venv\/bin\/[A-Za-z0-9_.-]+$/.test(check.command[0]||'')?
|
|
59
|
+
path.basename(check.command[0]):null;
|
|
60
|
+
// The variables a run gets from the caller, compared before reuse. HOME,
|
|
61
|
+
// TMPDIR, PATH and the XDG directories are set by REDUE (sandboxEnv). A
|
|
62
|
+
// script check names its package manager first among the executables, as the
|
|
63
|
+
// general recipe does.
|
|
64
|
+
const managers=['npm','pnpm','yarn','corepack'];
|
|
65
|
+
export function sandboxEnvironment(python=false,manager=null){
|
|
66
|
+
return {variables:['TZ','LANG','LANGUAGE','CI','USER','LOGNAME'],
|
|
67
|
+
prefixes:['LC_','DYLD_','LD_',...python?['PYTHON','MYPY','RUFF_','PYRIGHT','TY_']:
|
|
68
|
+
['NODE_','npm_config_','PNPM_','YARN_','COREPACK_','TSGO_']],
|
|
69
|
+
...manager?{pathExecutables:['node',manager,...managers.filter(name=>name!==manager)]}:{}};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Whether this machine can sandbox a run: {mode} or {issue}. Asked once per process.
|
|
73
|
+
let support=null;
|
|
74
|
+
export function sandboxSupport(){
|
|
75
|
+
if(support)return support;
|
|
76
|
+
if(process.env.VSTATE_TEST_FAULTS==='1'&&process.env.VSTATE_TEST_SANDBOX==='unavailable')
|
|
77
|
+
return support={mode:null,issue:'the sandbox is turned off for this test'};
|
|
78
|
+
if(process.platform==='darwin'){
|
|
79
|
+
const r=spawnSync('/usr/bin/sandbox-exec',['-p','(version 1)(allow default)','/usr/bin/true'],{encoding:'utf8',timeout:10000});
|
|
80
|
+
// Seatbelt cannot start inside another Seatbelt sandbox (Claude Code's, for one).
|
|
81
|
+
return support=r.status===0?{mode:'seatbelt'}:{mode:null,issue:/Operation not permitted/.test(r.stderr||'')?
|
|
82
|
+
'sandbox-exec cannot start inside another sandbox':`sandbox-exec cannot start (${(r.stderr||r.error?.code||r.status||'').toString().trim().slice(0,120)})`};
|
|
83
|
+
}
|
|
84
|
+
if(process.platform==='linux'){
|
|
85
|
+
const python=launcherPython();
|
|
86
|
+
if(!python)return support={mode:null,issue:'the Landlock launcher needs Python 3'};
|
|
87
|
+
let abi=null;
|
|
88
|
+
try{abi=JSON.parse(spawnSync(python,['-I','-W','ignore',landlockScript,'--probe'],{encoding:'utf8',timeout:10000}).stdout).abi;}catch{}
|
|
89
|
+
if(!Number.isInteger(abi))return support={mode:null,issue:'Landlock is unavailable in this kernel'};
|
|
90
|
+
// ABI 4 (Linux 6.7) is the first that can refuse TCP connections.
|
|
91
|
+
if(abi<4)return support={mode:null,issue:`Landlock ABI ${abi} cannot keep a run off the network; it needs ABI 4 (Linux 6.7)`};
|
|
92
|
+
return support={mode:'landlock',abi,python};
|
|
93
|
+
}
|
|
94
|
+
return support={mode:null,issue:'the sandboxed recipe runs on macOS and Linux only'};
|
|
95
|
+
}
|
|
96
|
+
const launcherPython=()=>['/usr/bin/python3','/bin/python3'].find(file=>{try{fs.accessSync(file,fs.constants.X_OK);return true;}catch{return false;}})||
|
|
97
|
+
lookup('python3',process.env.PATH,process.cwd());
|
|
98
|
+
|
|
99
|
+
export const systemPlaces=process.platform==='darwin'?
|
|
100
|
+
['/usr','/bin','/sbin','/System','/Library','/Applications','/opt/homebrew','/private/etc','/private/var/db','/private/var/select','/dev']:
|
|
101
|
+
['/usr','/bin','/sbin','/lib','/lib32','/lib64','/libx32','/etc','/proc','/sys','/dev','/run'];
|
|
102
|
+
// The PATH a run gets: the caller's, without the project's .venv/bin, which
|
|
103
|
+
// `uv run`, `poetry run` and an activated environment put first; a Python
|
|
104
|
+
// check gets it first again. So the forms of a command agree.
|
|
105
|
+
export function sandboxPath(check,env,root){
|
|
106
|
+
const venvBin=path.join(root,'.venv','bin');
|
|
107
|
+
const rest=String(env.PATH??'').split(path.delimiter).filter(dir=>dir&&path.resolve(root,dir)!==venvBin);
|
|
108
|
+
return [...pythonTool(check)?[venvBin]:[],...rest].join(path.delimiter);
|
|
109
|
+
}
|
|
110
|
+
// The interpreter a .venv was made from: its real executable and installation
|
|
111
|
+
// (pyvenv.cfg's `home` is the directory of the executable it was made with).
|
|
112
|
+
export function venvBase(root){
|
|
113
|
+
const venv=path.join(root,'.venv');
|
|
114
|
+
let home=null;
|
|
115
|
+
try{home=/^home\s*=\s*(.+)$/m.exec(fs.readFileSync(path.join(venv,'pyvenv.cfg'),'utf8'))?.[1].trim()??null;}catch{}
|
|
116
|
+
const executable=real(path.join(venv,'bin','python'));
|
|
117
|
+
return {home,executable,prefix:home&&path.isAbsolute(home)?path.dirname(home):null};
|
|
118
|
+
}
|
|
119
|
+
// Program files a run starts from outside the checkout: Node, the package
|
|
120
|
+
// managers, and a Python check's interpreter. Their identity is compared
|
|
121
|
+
// before reuse.
|
|
122
|
+
function toolchainExecutables(check,env,root){
|
|
123
|
+
if(pythonTool(check))return [venvBase(root).executable];
|
|
124
|
+
const searchPath=sandboxPath(check,env,root);
|
|
125
|
+
return ['node','npm','npx','pnpm','yarn','corepack'].map(name=>lookup(name,searchPath,root));
|
|
126
|
+
}
|
|
127
|
+
const sharedPrefixes=()=>{const home=os.homedir();return [home,path.join(home,'.local'),'/usr/local','/usr','/opt/homebrew','/'];};
|
|
128
|
+
// What a run may read and execute outside the checkout: the toolchain's
|
|
129
|
+
// installations and stores, and system directories.
|
|
130
|
+
export function sandboxPlaces(check,env,root){
|
|
131
|
+
const home=os.homedir(),places=new Set();
|
|
132
|
+
const add=dir=>{const resolved=dir&&path.isAbsolute(dir)?real(dir):null;
|
|
133
|
+
if(resolved&&resolved!=='/'&&resolved!==home&&!within(home,resolved))places.add(resolved);};
|
|
134
|
+
// An installation root (bin/..), or the program alone when bin/.. is shared (~/.local, /usr/local).
|
|
135
|
+
const addRoot=file=>{const dir=path.dirname(path.dirname(file));add(sharedPrefixes().includes(dir)?file:dir);};
|
|
136
|
+
for(const file of toolchainExecutables(check,env,root))if(file)addRoot(file);
|
|
137
|
+
if(pythonTool(check)){const base=venvBase(root);add(base.prefix);add(base.home);}
|
|
138
|
+
else{
|
|
139
|
+
for(const dir of toolchainDirs(env))add(dir);
|
|
140
|
+
const cache=path.isAbsolute(env.XDG_CACHE_HOME||'')?env.XDG_CACHE_HOME:path.join(home,'.cache');
|
|
141
|
+
add(path.isAbsolute(env.COREPACK_HOME||'')?env.COREPACK_HOME:path.join(cache,'node','corepack'));
|
|
142
|
+
add(path.join(home,'.yarn','berry'));
|
|
143
|
+
}
|
|
144
|
+
return [...places].sort();
|
|
145
|
+
}
|
|
146
|
+
// The environment a run gets.
|
|
147
|
+
export function sandboxEnv(check,env,{root,home,tmp}){
|
|
148
|
+
const variables=check.environment?.variables||[],prefixes=(check.environment?.prefixes||[]).map(prefix=>prefix.toLowerCase());
|
|
149
|
+
const out={};
|
|
150
|
+
for(const [key,value] of Object.entries(env))
|
|
151
|
+
if(variables.includes(key)||prefixes.some(prefix=>key.toLowerCase().startsWith(prefix))||displayVariables.includes(key))out[key]=value;
|
|
152
|
+
delete out._;delete out.REDUE_RUN_RECORD;
|
|
153
|
+
Object.assign(out,{PATH:sandboxPath(check,env,root),HOME:home,XDG_CONFIG_HOME:path.join(home,'.config'),
|
|
154
|
+
XDG_CACHE_HOME:path.join(home,'.cache'),XDG_DATA_HOME:path.join(home,'.local','share'),XDG_STATE_HOME:path.join(home,'.local','state'),
|
|
155
|
+
TMPDIR:tmp,TMP:tmp,TEMP:tmp,
|
|
156
|
+
// The checkout's .git is not an input. Tools may still see it, as in CI,
|
|
157
|
+
// but git commands find no repository.
|
|
158
|
+
GIT_DIR:path.join(home,'.no-repository'),GIT_CEILING_DIRECTORIES:path.dirname(root)});
|
|
159
|
+
if(pythonTool(check))out.VIRTUAL_ENV=path.join(root,'.venv');
|
|
160
|
+
else{
|
|
161
|
+
// Corepack's downloads stay where Corepack keeps them; npm's and pnpm's
|
|
162
|
+
// update checks read the network; Nx would hand work to its daemon.
|
|
163
|
+
const cache=path.isAbsolute(env.XDG_CACHE_HOME||'')?env.XDG_CACHE_HOME:path.join(os.homedir(),'.cache');
|
|
164
|
+
out.COREPACK_HOME=path.isAbsolute(env.COREPACK_HOME||'')?env.COREPACK_HOME:path.join(cache,'node','corepack');
|
|
165
|
+
Object.assign(out,{npm_config_update_notifier:'false',NX_DAEMON:'false'});
|
|
166
|
+
}
|
|
167
|
+
return out;
|
|
168
|
+
}
|
|
169
|
+
// The files in the repository's .git that tools read to choose files (ruff's
|
|
170
|
+
// and biome's ignore rules), and that decide what sandbox-v2 hides: its
|
|
171
|
+
// exclude file and config. For a project in a subdirectory of the
|
|
172
|
+
// repository, also the .gitignore files above it. The observer watches
|
|
173
|
+
// neither, so they are compared as context.
|
|
174
|
+
function gitIgnoreSources(root){
|
|
175
|
+
let top=root;
|
|
176
|
+
while(!fs.existsSync(path.join(top,'.git'))){const up=path.dirname(top);if(up===top)return [];top=up;}
|
|
177
|
+
let dir=path.join(top,'.git');
|
|
178
|
+
try{if(fs.statSync(dir).isFile()){
|
|
179
|
+
const gitdir=path.resolve(top,/^gitdir:\s*(.+)$/m.exec(fs.readFileSync(dir,'utf8'))?.[1].trim()??'');
|
|
180
|
+
let common=gitdir;try{common=path.resolve(gitdir,fs.readFileSync(path.join(gitdir,'commondir'),'utf8').trim());}catch{}
|
|
181
|
+
dir=common;}}catch{return [];}
|
|
182
|
+
const read=file=>{try{return digest(fs.readFileSync(file));}catch{return null;}};
|
|
183
|
+
const above=[];
|
|
184
|
+
for(let at=path.dirname(root);top!==root&&(at===top||at.startsWith(top+path.sep));at=path.dirname(at)){
|
|
185
|
+
above.push([path.relative(top,path.join(at,'.gitignore')),read(path.join(at,'.gitignore'))]);
|
|
186
|
+
if(at===top)break;
|
|
187
|
+
}
|
|
188
|
+
return [...['info/exclude','config'].map(rel=>[rel,read(path.join(dir,rel))]),...above];
|
|
189
|
+
}
|
|
190
|
+
// What a sandboxed result depends on outside the observed files, compared
|
|
191
|
+
// before reuse, one entry each so a change can be named (sandboxChange): every
|
|
192
|
+
// variable the run gets (but its private directories and display variables),
|
|
193
|
+
// the places it may read, the identity of the toolchain's executables and of
|
|
194
|
+
// every directory on PATH (an installed or upgraded program changes its
|
|
195
|
+
// directory), and the ignore rules in .git.
|
|
196
|
+
export const sandboxPrefix='__redue_sandbox_';
|
|
197
|
+
export function sandboxContext(check,env,root){
|
|
198
|
+
const identity=(file,keys=['dev','ino','mode','size','mtimeNs','ctimeNs'])=>{try{const st=fs.statSync(file,{bigint:true});
|
|
199
|
+
return [file,...keys.map(key=>String(st[key]))];}catch{return [file,'<unavailable>'];}};
|
|
200
|
+
const environment=sandboxEnv(check,env,{root,home:'<home>',tmp:'<tmp>'});
|
|
201
|
+
for(const key of displayVariables)delete environment[key];
|
|
202
|
+
const out={[`${sandboxPrefix}places__`]:digest(JSON.stringify(sandboxPlaces(check,env,root))),
|
|
203
|
+
[`${sandboxPrefix}executables__`]:digest(JSON.stringify(toolchainExecutables(check,env,root).map(file=>file?identity(file):null))),
|
|
204
|
+
[`${sandboxPrefix}git__`]:digest(JSON.stringify(gitIgnoreSources(root)))};
|
|
205
|
+
for(const [key,value] of Object.entries(environment))out[`${sandboxPrefix}variable:${key}__`]=digest(value);
|
|
206
|
+
for(const dir of environment.PATH.split(path.delimiter).filter(dir=>path.isAbsolute(dir)))
|
|
207
|
+
out[`${sandboxPrefix}directory:${dir}__`]=digest(JSON.stringify(identity(dir,['dev','ino','mtimeNs','ctimeNs'])));
|
|
208
|
+
return out;
|
|
209
|
+
}
|
|
210
|
+
// What changed between two sandboxed contexts, in words, or null.
|
|
211
|
+
export function sandboxChange(before={},now={}){
|
|
212
|
+
const keys=[...new Set([...Object.keys(before),...Object.keys(now)])].filter(key=>key.startsWith(sandboxPrefix)).sort();
|
|
213
|
+
const key=keys.find(key=>before[key]!==now[key]);
|
|
214
|
+
if(!key)return null;
|
|
215
|
+
const name=key.slice(sandboxPrefix.length,-2);
|
|
216
|
+
return name==='places'?'the places a sandboxed run may read changed':
|
|
217
|
+
name==='executables'?'Node, a package manager or the interpreter changed':
|
|
218
|
+
name==='git'?'.git/info/exclude or .git/config changed':
|
|
219
|
+
name.startsWith('variable:')?`environment variable ${name.slice(9)} differs from the last run`:
|
|
220
|
+
!(key in now)?`PATH no longer has directory ${name.slice(10)}`:!(key in before)?`PATH has a new directory ${name.slice(10)}`:
|
|
221
|
+
`PATH directory ${name.slice(10)} changed (a program in it was installed, removed or upgraded)`;
|
|
222
|
+
}
|
|
223
|
+
// A run's private directories, in REDUE's state: the home it keeps between
|
|
224
|
+
// runs, and a fresh temporary directory.
|
|
225
|
+
// The temporary directory is under the system's, so a Unix socket path in it
|
|
226
|
+
// stays short enough.
|
|
227
|
+
export function sandboxDirs(state,name){
|
|
228
|
+
const home=path.join(state,'sandbox',digest(name).slice(0,16),'home');
|
|
229
|
+
fs.mkdirSync(home,{recursive:true,mode:0o700});
|
|
230
|
+
return {home,tmp:fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'redue-run-')))};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// The checkout's git-ignored entries a run may be kept from reading: what
|
|
234
|
+
// `git ls-files --others --ignored --exclude-standard --directory` lists (a
|
|
235
|
+
// wholly ignored directory as one entry, ending in /), but the installed
|
|
236
|
+
// trees (node_modules, .venv) and runner caches. Relative to root. null when
|
|
237
|
+
// git cannot list them. Only the project's rules count (.gitignore files and
|
|
238
|
+
// .git/info/exclude), not a user's global excludes file, as on CI.
|
|
239
|
+
const installedTree=/(?:^|\/)(?:node_modules|\.venv)(?:\/|$)/;
|
|
240
|
+
const runnerCache=picomatch(sandboxCaches,{dot:true});
|
|
241
|
+
const projectGit=['-c','core.excludesFile=/dev/null'],gitEnv=()=>({...process.env,GIT_OPTIONAL_LOCKS:'0'});
|
|
242
|
+
export function hiddenEntries(root){
|
|
243
|
+
const r=spawnSync('git',[...projectGit,'ls-files','-z','--others','--ignored','--exclude-standard','--directory'],
|
|
244
|
+
{cwd:root,encoding:'utf8',maxBuffer:256*1024*1024,timeout:60000,stdio:['ignore','pipe','ignore'],env:gitEnv()});
|
|
245
|
+
if(r.status!==0)return null;
|
|
246
|
+
return r.stdout.split('\0').filter(Boolean).filter(rel=>!installedTree.test(rel)&&
|
|
247
|
+
!runnerCache(rel)&&!runnerCache(rel.replace(/\/$/,'')+'/x'));
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// What git lists now as ignored at or beneath `paths` (relative files, or
|
|
251
|
+
// directories ending in /), as hiddenEntries would: nested repositories are
|
|
252
|
+
// not entered, and an entry that is an installed tree is not ignored (one
|
|
253
|
+
// inside an ignored build directory is). {has(rel)} for a file, or null when
|
|
254
|
+
// git cannot tell. A directory git ignores holds no file it does not, so
|
|
255
|
+
// asking a new directory once covers its files.
|
|
256
|
+
export function ignoredNow(root,paths){
|
|
257
|
+
const asked=paths;
|
|
258
|
+
if(!asked.length)return {has:()=>false};
|
|
259
|
+
const listed=new Set();
|
|
260
|
+
for(let at=0;at<asked.length;at+=500){
|
|
261
|
+
const r=spawnSync('git',[...projectGit,'ls-files','-z','--others','--ignored','--exclude-standard','--directory','--',...asked.slice(at,at+500)],
|
|
262
|
+
{cwd:root,encoding:'utf8',maxBuffer:256*1024*1024,timeout:10000,stdio:['ignore','pipe','ignore'],env:gitEnv()});
|
|
263
|
+
if(r.status!==0)return null;
|
|
264
|
+
for(const entry of r.stdout.split('\0'))if(entry)listed.add(entry);
|
|
265
|
+
}
|
|
266
|
+
const entries=[...listed].filter(entry=>!installedTree.test(entry));
|
|
267
|
+
return {has:rel=>entries.some(entry=>rel===entry||entry.endsWith('/')&&rel.startsWith(entry))};
|
|
268
|
+
}
|
|
269
|
+
// The files git tracks now beneath `entries` (relative). null when git cannot tell.
|
|
270
|
+
export function trackedBeneath(root,entries){
|
|
271
|
+
if(!entries.length)return new Set();
|
|
272
|
+
const r=spawnSync('git',['ls-files','-z','--cached','--',...entries],
|
|
273
|
+
{cwd:root,encoding:'utf8',maxBuffer:256*1024*1024,timeout:10000,stdio:['ignore','pipe','ignore'],env:gitEnv()});
|
|
274
|
+
return r.status===0?new Set(r.stdout.split('\0').filter(Boolean)):null;
|
|
275
|
+
}
|
|
276
|
+
// A refusal line that names a hidden entry (relative): a refusal by the
|
|
277
|
+
// sandbox, or a missing file, which Linux tools report for an unreadable one.
|
|
278
|
+
export function hiddenRefusal(text,hidden){
|
|
279
|
+
const names=hidden.map(file=>file.replace(/\/$/,'')).filter(Boolean)
|
|
280
|
+
.map(name=>new RegExp(`(?:^|[\\s'"\`(=/])${escape(name)}(?:[/\\s'"\`):,]|$)`));
|
|
281
|
+
for(const line of String(text).split(/\r?\n/))
|
|
282
|
+
if((denial.test(line)||missing.test(line))&&names.some(name=>name.test(line)))return line.trim().slice(0,200);
|
|
283
|
+
return null;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const ancestors=list=>[...new Set(list.flatMap(dir=>{const out=[];for(let at=path.dirname(dir);at!=='/'&&at!=='.';at=path.dirname(at))out.push(at);return out;}))];
|
|
287
|
+
// The Seatbelt profile: reads and executes only beneath the places, the
|
|
288
|
+
// metadata of their parent directories, and no network but Unix sockets in
|
|
289
|
+
// the run's own temporary directory (`own`), which is new for each run: a
|
|
290
|
+
// daemon an earlier run left behind cannot answer a later one. `hidden`:
|
|
291
|
+
// absolute paths it may not read at all, not even their metadata.
|
|
292
|
+
export function seatbeltProfile(reads,own=null,hidden=[]){
|
|
293
|
+
const quote=value=>JSON.stringify(value);
|
|
294
|
+
const all=[...new Set(reads.flatMap(dir=>[dir,real(dir)]).filter(Boolean))];
|
|
295
|
+
return ['(version 1)','(allow default)','(deny file-read* process-exec*)',
|
|
296
|
+
`(allow file-read* process-exec* ${all.map(dir=>`(subpath ${quote(dir)})`).join(' ')} (literal "/") (literal "/etc") (literal "/var") (literal "/tmp"))`,
|
|
297
|
+
`(allow file-read-metadata ${ancestors(all).map(dir=>`(literal ${quote(dir)})`).join(' ')})`,
|
|
298
|
+
// The entry's own path, by its directory's real path: a hidden link's target is not hidden.
|
|
299
|
+
...hidden.length?[`(deny file-read* process-exec* ${[...new Set(hidden.flatMap(file=>[file,path.join(real(path.dirname(file))??path.dirname(file),path.basename(file))]))]
|
|
300
|
+
.map(file=>`(subpath ${quote(file)})`).join(' ')})`]:[],
|
|
301
|
+
'(deny network*)',...own?[`(allow network* ${[own,real(own)].filter(Boolean).map(dir=>`(subpath ${quote(dir)})`).join(' ')})`]:[]].join('\n');
|
|
302
|
+
}
|
|
303
|
+
// The argv that runs `argv` sandboxed: reads beneath `reads`, no network but
|
|
304
|
+
// Unix sockets beneath `tmp` on macOS, nothing beneath `hidden` (absolute).
|
|
305
|
+
// On Linux a hidden directory can still be listed and its entries stat'ed:
|
|
306
|
+
// Landlock restricts neither beneath a listable parent.
|
|
307
|
+
export function sandboxArgv(mode,argv,{reads,tmp=null,python,hidden=[],stats=null}){
|
|
308
|
+
if(mode==='seatbelt')return ['/usr/bin/sandbox-exec','-p',seatbeltProfile(reads,tmp,hidden),...argv];
|
|
309
|
+
// The launcher's own warnings would become the check's output.
|
|
310
|
+
if(mode==='landlock')return [python,'-I','-W','ignore',landlockScript,...reads.flatMap(dir=>['--read',dir]),
|
|
311
|
+
...hidden.flatMap(file=>['--hide',file]),...stats?['--stats',stats]:[],'--no-tcp','--',...argv];
|
|
312
|
+
throw Error(`unknown sandbox ${mode}`);
|
|
313
|
+
}
|
|
314
|
+
// A line of a failed run's output that looks like the sandbox refused
|
|
315
|
+
// something: a refused read or write, or the network unreachable. Such a
|
|
316
|
+
// failure is run again outside the sandbox to tell a denial from a real one.
|
|
317
|
+
const denial=/operation not permitted|permission denied|read-only file system|\bE(?:PERM|ACCES|ROFS|NOTFOUND|AI_AGAIN|CONNREFUSED|NETUNREACH|HOSTUNREACH)\b|sandbox-exec:|landlock\.py:|network is unreachable|could not resolve host|name or service not known|nodename nor servname|temporary failure in name resolution|getaddrinfo|connection refused/i;
|
|
318
|
+
// A missing file counts only when the line names a path the run was kept
|
|
319
|
+
// from (`hidden`, relative to the checkout or absolute): Linux tools report
|
|
320
|
+
// an unreadable file as not found.
|
|
321
|
+
const missing=/not found|no such file|cannot find|can't find|could not find|cannot read|\bENOENT\b/i;
|
|
322
|
+
const escape=text=>text.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');
|
|
323
|
+
export function denialLine(text,hidden=[]){
|
|
324
|
+
// A name as a whole path or path component, not inside a longer word.
|
|
325
|
+
const names=hidden.map(file=>file.replace(/\/$/,'')).filter(Boolean)
|
|
326
|
+
.map(name=>new RegExp(`(?:^|[\\s'"\`(=/])${escape(name)}(?:[/\\s'"\`):,]|$)`));
|
|
327
|
+
for(const line of String(text).split(/\r?\n/))
|
|
328
|
+
if(denial.test(line)||missing.test(line)&&names.some(name=>name.test(line)))return line.trim().slice(0,200);
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// Links in the .venv that lead out of the checkout, other than the
|
|
333
|
+
// interpreter's in bin/: REDUE cannot observe what they point to. Looks in
|
|
334
|
+
// the .venv itself, bin/, and the top of each site-packages.
|
|
335
|
+
export function venvOutsideLinks(root){
|
|
336
|
+
const venv=path.join(root,'.venv'),found=[],realRoot=real(root)||root;
|
|
337
|
+
const look=dir=>{let entries;try{entries=fs.readdirSync(dir,{withFileTypes:true});}catch{return;}
|
|
338
|
+
for(const entry of entries){
|
|
339
|
+
if(!entry.isSymbolicLink())continue;
|
|
340
|
+
const file=path.join(dir,entry.name),rel=path.relative(root,file).split(path.sep).join('/');
|
|
341
|
+
if(/^\.venv\/bin\/(?:python|pypy|𝜋thon)/.test(rel))continue;
|
|
342
|
+
const target=real(file);
|
|
343
|
+
if(!target||!within(target,realRoot))found.push(rel);
|
|
344
|
+
}};
|
|
345
|
+
look(venv);look(path.join(venv,'bin'));
|
|
346
|
+
// lib64 is often a link to lib: looked at once.
|
|
347
|
+
for(const lib of ['lib','lib64']){let versions=[];
|
|
348
|
+
try{if(lib==='lib64'&&fs.lstatSync(path.join(venv,lib)).isSymbolicLink())continue;versions=fs.readdirSync(path.join(venv,lib));}catch{}
|
|
349
|
+
for(const version of versions)look(path.join(venv,lib,version,'site-packages'));}
|
|
350
|
+
return [...new Set(found)].sort();
|
|
351
|
+
}
|
|
352
|
+
// Plan qualification: the check is what `init` writes for the project now.
|
|
353
|
+
export function qualifySandbox(root,selected){
|
|
354
|
+
const issues=[];
|
|
355
|
+
if(!['darwin','linux'].includes(process.platform))issues.push('the sandboxed recipe runs on macOS and Linux only');
|
|
356
|
+
if(!sandboxKinds.includes(selected.kind))issues.push(`the sandboxed recipe takes ${sandboxKinds.join(' and ')} checks`);
|
|
357
|
+
if(selected.cwd&&selected.cwd!=='.')issues.push('the sandboxed recipe runs checks at the project root');
|
|
358
|
+
const tool=pythonTool(selected);
|
|
359
|
+
try{
|
|
360
|
+
let dirs=[];
|
|
361
|
+
if(tool){
|
|
362
|
+
try{fs.accessSync(path.join(root,selected.command[0]),fs.constants.X_OK);}catch{fail(`${selected.command[0]} is not installed`);}
|
|
363
|
+
const base=venvBase(root);
|
|
364
|
+
if(!base.home||!base.executable)fail('.venv has no pyvenv.cfg home or bin/python');
|
|
365
|
+
// The interpreter's own site-packages are not observed.
|
|
366
|
+
if(/^include-system-site-packages\s*=\s*true\s*$/mi.test(fs.readFileSync(path.join(root,'.venv','pyvenv.cfg'),'utf8')))
|
|
367
|
+
issues.push('.venv uses the system site-packages, which REDUE does not observe');
|
|
368
|
+
for(const rel of venvOutsideLinks(root))issues.push(`${rel} links outside the checkout, where REDUE does not observe it`);
|
|
369
|
+
}else{
|
|
370
|
+
if(typeof selected.script!=='string')fail('script-missing');
|
|
371
|
+
const project=scriptProject(root,selected.script);
|
|
372
|
+
if(JSON.stringify(selected.command?.slice(1))!==JSON.stringify(['run',selected.script])||selected.environment?.pathExecutables?.[1]!==project.manager)
|
|
373
|
+
issues.push('the package manager or script changed; run redue init again');
|
|
374
|
+
dirs=project.dirs;
|
|
375
|
+
}
|
|
376
|
+
const expected=sandboxCheckInputs(dirs),sorted=list=>JSON.stringify([...(list||[])].sort());
|
|
377
|
+
if(sorted(selected.inputs)!==sorted(expected.inputs)||sorted(selected.installedInputs)!==sorted(expected.installedInputs))
|
|
378
|
+
issues.push('inputs must be the whole checkout, with node_modules and .venv observed as installed files; run redue init again');
|
|
379
|
+
const environment=sandboxEnvironment(Boolean(tool));
|
|
380
|
+
if(!environment.variables.every(key=>selected.environment?.variables?.includes(key))||
|
|
381
|
+
!environment.prefixes.every(key=>selected.environment?.prefixes?.includes(key)))
|
|
382
|
+
issues.push('execution context incomplete; run redue init again');
|
|
383
|
+
}catch(e){issues.push(e.code||'sandboxed check prerequisites unavailable');}
|
|
384
|
+
if(selected.probes?.length)issues.push('the sandboxed recipe takes no probes');
|
|
385
|
+
if(selected.generatedInputs?.length)issues.push('the sandboxed recipe takes no generated inputs');
|
|
386
|
+
return {qualified:issues.length===0,issues};
|
|
387
|
+
}
|
|
388
|
+
// Installed paths a sandboxed plan leaves out: the .venv's links that lead out
|
|
389
|
+
// of the checkout, which the index cannot observe. Qualification reports them.
|
|
390
|
+
export const sandboxInstalledExclusions=root=>venvOutsideLinks(root).map(rel=>`!${rel}`);
|
|
391
|
+
// A run's output for comparison: without colors, timings, the temporary and
|
|
392
|
+
// home directories each run had, and lines about caches, which differ
|
|
393
|
+
// between two runs of the same check (a task runner's cache hit).
|
|
394
|
+
const units='(?:ns|µs|us|ms|s|sec|secs|seconds?|m|min|mins|minutes?|h)';
|
|
395
|
+
export function comparableOutput(text,paths=[]){
|
|
396
|
+
let out=String(text).replace(/\x1b\[[0-9;?]*[A-Za-z]/g,'');
|
|
397
|
+
for(const [from,to] of paths.filter(([from])=>from).sort((a,b)=>b[0].length-a[0].length))out=out.split(from).join(to);
|
|
398
|
+
return out.split(/\r?\n/).filter(line=>!/\bcache[ds]?\b|\bcached\b/i.test(line))
|
|
399
|
+
.map(line=>line.replace(new RegExp(`\\d+(?:[.,]\\d+)?\\s?${units}\\b`,'g'),'<time>')
|
|
400
|
+
.replace(/\b\d{1,2}:\d{2}(?::\d{2}(?:\.\d+)?)?\b/g,'<clock>').replace(/\d{4}-\d{2}-\d{2}T[\d:.]+Z?/g,'<date>').trimEnd())
|
|
401
|
+
.filter(Boolean).join('\n');
|
|
402
|
+
}
|
|
403
|
+
// `init` runs a proposed check both ways before it writes it: plainly, as the
|
|
404
|
+
// project would, and sandboxed. The check is proposed only when both give
|
|
405
|
+
// the same exit status and the same output (comparableOutput), and a failure
|
|
406
|
+
// shows no sign of a refusal by the sandbox; else the reason names the
|
|
407
|
+
// difference.
|
|
408
|
+
// Stops what a run left running when it ends, as a CI job's end does: the
|
|
409
|
+
// run's process group gets SIGTERM, and SIGKILL a second later if it still
|
|
410
|
+
// has members. Its pid is not signalled again once the group is empty, so a
|
|
411
|
+
// reused number is never hit. The timer keeps REDUE alive until then, and
|
|
412
|
+
// the promise settles then. On Linux the Landlock launcher also stops
|
|
413
|
+
// processes that left the group (landlock.py).
|
|
414
|
+
export function stopGroup(pid){
|
|
415
|
+
const signal=name=>{try{process.kill(-pid,name);return true;}catch{return false;}};
|
|
416
|
+
if(!signal('SIGTERM'))return Promise.resolve();
|
|
417
|
+
const until=Date.now()+1000;
|
|
418
|
+
return new Promise(resolve=>{const check=setInterval(()=>{
|
|
419
|
+
if(!signal(0)){clearInterval(check);resolve();return;}
|
|
420
|
+
if(Date.now()>=until){signal('SIGKILL');clearInterval(check);resolve();}
|
|
421
|
+
},100);});
|
|
422
|
+
}
|
|
423
|
+
// A sandboxed run's end: when the command exits, what it left running is
|
|
424
|
+
// stopped, and its pipes are closed a second later, so a helper that holds
|
|
425
|
+
// them open does not hold the run.
|
|
426
|
+
export function endWithChild(child){
|
|
427
|
+
child.on('exit',()=>{stopGroup(child.pid);setTimeout(()=>{child.stdout?.destroy();child.stderr?.destroy();},1000).unref();});
|
|
428
|
+
}
|
|
429
|
+
// Runs argv in its own process group to the end, with no terminal input:
|
|
430
|
+
// {status, signal, error, timedOut, stdout, stderr}, each output kept up to
|
|
431
|
+
// 64 MB and decoded at the end. `echo` also passes the output through.
|
|
432
|
+
// `started` gets the child, so a caller can forward signals to its group;
|
|
433
|
+
// without one, an interrupt stops the group and then REDUE.
|
|
434
|
+
const outputCap=64*1024*1024;
|
|
435
|
+
export function runToEnd(argv,{cwd,env,timeout=0,echo=false,started=null}){
|
|
436
|
+
return new Promise(resolve=>{
|
|
437
|
+
const kept={stdout:[],stderr:[]},size={stdout:0,stderr:0};
|
|
438
|
+
let timer=null,timedOut=false;
|
|
439
|
+
const child=spawn(argv[0],argv.slice(1),{cwd,env,detached:true,stdio:['ignore','pipe','pipe']});
|
|
440
|
+
const stop=async name=>{process.off('SIGINT',interrupt);process.off('SIGTERM',terminate);
|
|
441
|
+
await stopGroup(child.pid);process.kill(process.pid,name);};
|
|
442
|
+
const interrupt=()=>stop('SIGINT'),terminate=()=>stop('SIGTERM');
|
|
443
|
+
if(started)started(child);else{process.once('SIGINT',interrupt);process.once('SIGTERM',terminate);}
|
|
444
|
+
for(const name of ['stdout','stderr'])child[name].on('data',chunk=>{
|
|
445
|
+
if(echo)process[name].write(chunk);
|
|
446
|
+
if(size[name]<outputCap){kept[name].push(chunk);size[name]+=chunk.length;}
|
|
447
|
+
});
|
|
448
|
+
if(timeout)timer=setTimeout(()=>{timedOut=true;stopGroup(child.pid);},timeout);
|
|
449
|
+
endWithChild(child);
|
|
450
|
+
const finish=value=>{clearTimeout(timer);process.off('SIGINT',interrupt);process.off('SIGTERM',terminate);
|
|
451
|
+
resolve({...value,timedOut,stdout:Buffer.concat(kept.stdout).toString('utf8'),stderr:Buffer.concat(kept.stderr).toString('utf8')});};
|
|
452
|
+
child.on('error',error=>finish({status:null,signal:null,error}));
|
|
453
|
+
child.on('close',(status,signal)=>finish({status,signal}));
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
// {same, plain, sandboxed, line} or {issue} when the sandbox cannot run here.
|
|
457
|
+
// With `hide`, the git-ignored entries hiddenEntries lists are kept from the
|
|
458
|
+
// sandboxed run, and it also returns them, their count, the run times and, on
|
|
459
|
+
// Linux, the launcher's rule count and setup time.
|
|
460
|
+
// `plain`: the plain run of an earlier trial of the same check, reused.
|
|
461
|
+
export async function sandboxTrial(root,check,{timeout=300000,hide=false,plain:earlier=null}={}){
|
|
462
|
+
const supported=sandboxSupport();
|
|
463
|
+
if(supported.issue)return {issue:supported.issue};
|
|
464
|
+
const python=Boolean(pythonTool(check));
|
|
465
|
+
const command=python?check.command:[lookup(scriptProject(root,check.script).manager,process.env.PATH,root)||'npm','run',check.script];
|
|
466
|
+
const selected={...check,command,environment:sandboxEnvironment(python,python?null:scriptProject(root,check.script).manager)};
|
|
467
|
+
const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'redue-trial-')),home=path.join(scratch,'home'),tmp=path.join(scratch,'tmp');
|
|
468
|
+
fs.mkdirSync(home);fs.mkdirSync(tmp);
|
|
469
|
+
try{
|
|
470
|
+
const entries=hide?hiddenEntries(root):[];
|
|
471
|
+
if(!entries)return {issue:hiddenListIssue};
|
|
472
|
+
const hidden=entries.map(rel=>path.join(root,rel.replace(/\/$/,""))),stats=hide&&supported.mode==='landlock'?path.join(scratch,'stats.json'):null;
|
|
473
|
+
const run=async(argv,env)=>{const started=Date.now(),r=await runToEnd(argv,{cwd:root,env,timeout});
|
|
474
|
+
return {status:r.timedOut?'timeout':r.status??r.signal??r.error?.code,output:`${r.stdout}\n${r.stderr}`,ms:Date.now()-started};};
|
|
475
|
+
const plain=earlier??await run(command,{...process.env,...python?{}:{npm_config_update_notifier:'false'}});
|
|
476
|
+
const reads=[root,home,tmp,...sandboxPlaces(selected,process.env,root),...systemPlaces];
|
|
477
|
+
const sandboxed=await run(sandboxArgv(supported.mode,command,{reads,tmp,python:supported.python,hidden,stats}),sandboxEnv(selected,process.env,{root,home,tmp}));
|
|
478
|
+
// A failure both ways counts as the same only without a sign of a refusal.
|
|
479
|
+
const denied=sandboxed.status===0?null:denialLine(sandboxed.output,entries);
|
|
480
|
+
const realOf=dir=>{try{return fs.realpathSync(dir);}catch{return null;}},plainTmp=process.env.TMPDIR||os.tmpdir();
|
|
481
|
+
const paths=[[home,'<home>'],[realOf(home),'<home>'],[tmp,'<tmp>'],[realOf(tmp),'<tmp>'],[plainTmp,'<tmp>'],[realOf(plainTmp),'<tmp>'],
|
|
482
|
+
[os.homedir(),'<home>'],[realOf(os.homedir()),'<home>']];
|
|
483
|
+
const [a,b]=[plain,sandboxed].map(r=>comparableOutput(r.output,paths).split('\n'));
|
|
484
|
+
// The first line that differs; past the end of the shorter output when one goes on.
|
|
485
|
+
let at=a.findIndex((line,i)=>line!==b[i]);
|
|
486
|
+
if(at<0&&b.length>a.length)at=a.length;
|
|
487
|
+
const output=at<0?null:{plain:(a[at]??'(no more output)').slice(0,160),sandboxed:(b[at]??'(no more output)').slice(0,160)};
|
|
488
|
+
let launcher=null;if(stats)try{launcher=JSON.parse(fs.readFileSync(stats,'utf8'));}catch{}
|
|
489
|
+
return {same:plain.status===sandboxed.status&&!denied&&!output,plain:plain.status,sandboxed:sandboxed.status,output,plainRun:plain,
|
|
490
|
+
line:denied||(plain.status===sandboxed.status?null:sandboxed.output.trim().split('\n').at(-1)?.slice(0,200)||null),
|
|
491
|
+
...hide?{hidden:entries.length,entries,plainMs:plain.ms,sandboxedMs:sandboxed.ms,...launcher?{rules:launcher.rules,setupMs:launcher.ms}:{}}:{}};
|
|
492
|
+
}finally{fs.rmSync(scratch,{recursive:true,force:true});}
|
|
493
|
+
}
|
package/src/setup.mjs
CHANGED
|
@@ -38,7 +38,8 @@ export async function setupCommand(args,{entry,cwd=process.cwd()}){
|
|
|
38
38
|
const top=git(cwd,'rev-parse','--show-toplevel');
|
|
39
39
|
if(top.status!==0)throw Error('run this inside a Git checkout');
|
|
40
40
|
const root=fs.realpathSync(top.stdout.trim());
|
|
41
|
-
if(!fs.existsSync(path.join(root,
|
|
41
|
+
if(!['package.json','pyproject.toml','setup.cfg','setup.py','requirements.txt'].some(file=>fs.existsSync(path.join(root,file))))
|
|
42
|
+
throw Error(`no package.json or Python project at the repository root (${root})`);
|
|
42
43
|
// The entry as invoked, so a hook written by a child names the install's
|
|
43
44
|
// stable bin link rather than the versioned file behind it.
|
|
44
45
|
const invoked=typeof process.argv[1]==='string'&&path.isAbsolute(process.argv[1])&&
|
|
@@ -59,8 +60,12 @@ export async function setupCommand(args,{entry,cwd=process.cwd()}){
|
|
|
59
60
|
}
|
|
60
61
|
|
|
61
62
|
async function setup({root,redue,yes,record:previous,recordFile,exclude,save}){
|
|
62
|
-
|
|
63
|
+
// A Node project needs node_modules; a Python one its .venv.
|
|
64
|
+
const node=fs.existsSync(path.join(root,'package.json'));
|
|
65
|
+
if(node&&!fs.existsSync(path.join(root,'node_modules')))
|
|
63
66
|
throw Error('dependencies are not installed: run your package manager\'s install (npm install, pnpm install, yarn) first');
|
|
67
|
+
if(!node&&!fs.existsSync(path.join(root,'.venv','pyvenv.cfg')))
|
|
68
|
+
throw Error('no .venv in the project root: create it first (uv sync, or Poetry with virtualenvs.in-project)');
|
|
64
69
|
if(fs.existsSync(path.join(root,'vstate.config.json'))&&!fs.existsSync(path.join(root,configName)))
|
|
65
70
|
throw Error('a legacy vstate.config.json exists; rename it to redue.config.json or remove it first');
|
|
66
71
|
if(git(root,'ls-files','--error-unmatch',localSettings).status===0)
|
package/src/stats.mjs
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// `redue stats`: what REDUE did for each check, from a local log. The hook,
|
|
2
|
+
// `run --if-due` and recorded runs append one line each to stats-v1.jsonl in
|
|
3
|
+
// the project's state: a skip (with the skipped run's duration), a recorded
|
|
4
|
+
// run, or a check that was due (STALE or UNVERIFIED, with the reason). The log
|
|
5
|
+
// stays on this machine and goes away with `redue remove-state`.
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
|
|
9
|
+
export const statsFile=state=>path.join(state,'stats-v1.jsonl');
|
|
10
|
+
|
|
11
|
+
// Never fails the command it is called from.
|
|
12
|
+
export function note(state,entry){
|
|
13
|
+
try{fs.appendFileSync(statsFile(state),JSON.stringify({at:Date.now(),...entry})+'\n',{mode:0o600});}catch{}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// A skip of `name`, from a status row that allowed it.
|
|
17
|
+
export const skipNote=(status,name,via)=>{
|
|
18
|
+
const ms=status?.checks?.find(row=>row?.name===name)?.invocation?.durationMs;
|
|
19
|
+
return {kind:'skip',check:name,via,savedMs:Number.isFinite(ms)&&ms>=0?ms:null};
|
|
20
|
+
};
|
|
21
|
+
// A check about to run because its last result does not apply, or null.
|
|
22
|
+
export const dueNote=(status,name)=>{
|
|
23
|
+
const row=status?.observation?.healthy===true?status.checks?.find(item=>item?.name===name):null;
|
|
24
|
+
return row&&row.freshness!=='CURRENT'?{kind:'due',check:name,freshness:row.freshness,reason:row.reason??null}:null;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
// Run ids, hashes and digits in a reason say nothing about its kind.
|
|
28
|
+
const reasonKind=reason=>String(reason??'no reason').replace(/[0-9a-f]{8}(?:-?[0-9a-f]{4,})+|[0-9a-f]{12,}/g,'…').slice(0,160);
|
|
29
|
+
|
|
30
|
+
export function readStats(state,names=[]){
|
|
31
|
+
let text='';try{text=fs.readFileSync(statsFile(state),'utf8');}catch{}
|
|
32
|
+
// Configured checks first, in config order, then any the log still names.
|
|
33
|
+
const checks=new Map();
|
|
34
|
+
const row=name=>{let value=checks.get(name);
|
|
35
|
+
if(!value)checks.set(name,value={name,skips:0,savedMs:0,runs:0,passed:0,failed:0,runMs:0,stale:0,unverified:0,reasons:{}});
|
|
36
|
+
return value;};
|
|
37
|
+
for(const name of names)row(name);
|
|
38
|
+
let since=null;
|
|
39
|
+
for(const line of text.split('\n')){
|
|
40
|
+
let entry;try{entry=JSON.parse(line);}catch{continue;}
|
|
41
|
+
if(typeof entry?.check!=='string')continue;
|
|
42
|
+
since??=entry.at;
|
|
43
|
+
const value=row(entry.check);
|
|
44
|
+
if(entry.kind==='skip'){value.skips++;value.savedMs+=entry.savedMs??0;}
|
|
45
|
+
else if(entry.kind==='run'){value.runs++;value.runMs+=entry.ms??0;
|
|
46
|
+
if(entry.result==='PASS')value.passed++;else if(entry.result==='FAIL')value.failed++;}
|
|
47
|
+
else if(entry.kind==='due'&&entry.freshness==='STALE')value.stale++;
|
|
48
|
+
else if(entry.kind==='due'&&entry.freshness==='UNVERIFIED'){value.unverified++;
|
|
49
|
+
const kind=reasonKind(entry.reason);value.reasons[kind]=(value.reasons[kind]??0)+1;}
|
|
50
|
+
}
|
|
51
|
+
const list=[...checks.values()].map(({reasons,...value})=>({...value,
|
|
52
|
+
topUnverified:Object.entries(reasons).sort((a,b)=>b[1]-a[1]).slice(0,3).map(([reason,count])=>({reason,count}))}));
|
|
53
|
+
return {schema:1,since:since===null?null:new Date(since).toISOString(),checks:list};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export const duration=ms=>!ms?'0s':ms<60_000?`${(ms/1000).toFixed(ms<10_000?1:0)}s`:
|
|
57
|
+
ms<3_600_000?`${Math.floor(ms/60_000)}m ${Math.round(ms%60_000/1000)}s`:`${Math.floor(ms/3_600_000)}h ${Math.round(ms%3_600_000/60_000)}m`;
|
|
58
|
+
|
|
59
|
+
export function renderStats(value){
|
|
60
|
+
if(!value.since)return 'No skips or recorded runs yet.';
|
|
61
|
+
const head=['check','skips','saved','runs','pass','fail','stale','unverified'];
|
|
62
|
+
const rows=value.checks.map(c=>[c.name,c.skips,duration(c.savedMs),c.runs,c.passed,c.failed,c.stale,c.unverified].map(String));
|
|
63
|
+
const total=value.checks.reduce((sum,c)=>({skips:sum.skips+c.skips,savedMs:sum.savedMs+c.savedMs}),{skips:0,savedMs:0});
|
|
64
|
+
const widths=head.map((h,i)=>Math.max(h.length,...rows.map(r=>r[i].length)));
|
|
65
|
+
const line=r=>r.map((cell,i)=>i?cell.padStart(widths[i]):cell.padEnd(widths[i])).join(' ');
|
|
66
|
+
const lines=[`Since ${value.since.slice(0,10)}: ${total.skips} skips saved ${duration(total.savedMs)}.`,'',line(head),...rows.map(line)];
|
|
67
|
+
const reasons=value.checks.filter(c=>c.topUnverified.length);
|
|
68
|
+
if(reasons.length){lines.push('','Why checks were UNVERIFIED when they were due:');
|
|
69
|
+
for(const c of reasons)for(const r of c.topUnverified)lines.push(` ${c.name} ${r.count}× ${r.reason}`);}
|
|
70
|
+
lines.push('','Saved is the duration of the run each skip reused.');
|
|
71
|
+
return lines.join('\n');
|
|
72
|
+
}
|