@sentropic/h2a 0.98.7-rc.2 → 0.98.7-rc.3
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/.codex-plugin/plugin.json +1 -0
- package/dist/bin.js +3 -0
- package/dist/bin.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +38 -38
- package/dist/cli.js.map +1 -1
- package/dist/focus-build.d.ts +10 -0
- package/dist/focus-build.d.ts.map +1 -0
- package/dist/focus-build.js +175 -0
- package/dist/focus-build.js.map +1 -0
- package/dist/hosts/native-convergence.d.ts +36 -0
- package/dist/hosts/native-convergence.d.ts.map +1 -1
- package/dist/hosts/native-convergence.js +60 -4
- package/dist/hosts/native-convergence.js.map +1 -1
- package/dist/hosts/native-files.d.ts +5 -0
- package/dist/hosts/native-files.d.ts.map +1 -1
- package/dist/hosts/native-files.js +4 -0
- package/dist/hosts/native-files.js.map +1 -1
- package/dist/hosts/native-inspection.js +1 -1
- package/dist/hosts/native-inspection.js.map +1 -1
- package/dist/hosts/native-questions.d.ts +2 -0
- package/dist/hosts/native-questions.d.ts.map +1 -0
- package/dist/hosts/native-questions.js +22 -0
- package/dist/hosts/native-questions.js.map +1 -0
- package/dist/hosts/native-toml.d.ts.map +1 -1
- package/dist/hosts/native-toml.js +2 -0
- package/dist/hosts/native-toml.js.map +1 -1
- package/dist/hosts/plugin.d.ts +27 -0
- package/dist/hosts/plugin.d.ts.map +1 -1
- package/dist/hosts/plugin.js +28 -2
- package/dist/hosts/plugin.js.map +1 -1
- package/dist/hosts/vibe-discovery.js +1 -1
- package/dist/hosts/vibe-discovery.js.map +1 -1
- package/dist/hosts/vibe-equipment.d.ts +1 -0
- package/dist/hosts/vibe-equipment.d.ts.map +1 -1
- package/dist/hosts/vibe-equipment.js +14 -1
- package/dist/hosts/vibe-equipment.js.map +1 -1
- package/dist/runtime/mcp/tools.d.ts.map +1 -1
- package/dist/runtime/mcp/tools.js +5 -4
- package/dist/runtime/mcp/tools.js.map +1 -1
- package/focus-kit/dossier.schema.json +193 -0
- package/focus-kit/dossier.template.json +39 -0
- package/focus-kit/ecosystem.json +853 -0
- package/focus-kit/renderer-manifest.json +24 -0
- package/focus-kit/renderer.html +278 -0
- package/focus-kit/validator.mjs +789 -0
- package/hooks/hooks.json +11 -1
- package/hooks/workspace-scope-grant.mjs +22 -0
- package/hooks/workspace-scope-guard.mjs +277 -0
- package/hooks/workspace-scope-shell.mjs +558 -0
- package/hooks/workspace-scope-state.mjs +71 -0
- package/package.json +11 -5
- package/skills/h2a/SKILL.md +19 -0
- package/skills/h2a-run/SKILL.md +19 -0
- package/skills/harness/SKILL.md +19 -0
- package/skills/harness/track-report/SKILL.md +14 -0
- package/skills/harness/using-harness/SKILL.md +19 -0
|
@@ -0,0 +1,558 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import { basename, dirname, join, relative, resolve } from 'node:path';
|
|
4
|
+
import { canonical, inside } from './workspace-scope-state.mjs';
|
|
5
|
+
|
|
6
|
+
// Keep the uncertainty signal even for dangling links and before canonicalizing
|
|
7
|
+
// an option's path. Resolving a link is not authority to write through it.
|
|
8
|
+
export function uncertainPath(path) {
|
|
9
|
+
for (let current=resolve(path);;) {
|
|
10
|
+
try { if (fs.lstatSync(current).isSymbolicLink()) return true; }
|
|
11
|
+
catch (error) { if (!['ENOENT','ENOTDIR'].includes(error.code)) throw error; }
|
|
12
|
+
const parent=dirname(current);
|
|
13
|
+
if (parent===current) return false;
|
|
14
|
+
current=parent;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Resolve only the explicit shell subset. Never erase heredoc bodies or execute
|
|
19
|
+
// substitutions to guess at a protected operation. Uncertainty is a refusal.
|
|
20
|
+
export function shellWords(command) {
|
|
21
|
+
const groups = []; let words = [], word = '', started = false, quote = '', escape = false, uncertain = false;
|
|
22
|
+
const flush = () => { if (started) words.push(word); word = ''; started = false; };
|
|
23
|
+
const group = separator => { flush(); groups.push({ words, separator }); words = []; };
|
|
24
|
+
for (let i = 0; i < command.length; i++) {
|
|
25
|
+
const ch = command[i];
|
|
26
|
+
if (escape) { word += ch; started = true; escape = false; continue; }
|
|
27
|
+
if (ch === '\\' && command[i + 1] === '\n' && quote !== "'") { i++; continue; }
|
|
28
|
+
if (ch === '\\' && quote !== "'") { escape = true; started = true; continue; }
|
|
29
|
+
if (quote !== "'" && (command.startsWith('$(', i) || ch === '`')) {
|
|
30
|
+
return { groups: [], uncertain: true };
|
|
31
|
+
}
|
|
32
|
+
if (quote) {
|
|
33
|
+
if (ch === quote) quote = '';
|
|
34
|
+
else word += ch === '$' && quote === '"' ? '__H2A_DYNAMIC__' : ch;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (ch === '"' || ch === "'") { quote = ch; started = true; continue; }
|
|
38
|
+
if (ch === '#' && !started) { while (i < command.length && command[i] !== '\n') i++; group('\n'); continue; }
|
|
39
|
+
if (ch === '$') { word += '__H2A_DYNAMIC__'; started = true; continue; }
|
|
40
|
+
if (ch === '>' || ch === '&' && command[i + 1] === '>') {
|
|
41
|
+
const fd = /^\d+$/.test(word) ? word : ''; if (fd) { word = ''; started = false; }
|
|
42
|
+
flush(); let op = fd + ch;
|
|
43
|
+
if (ch === '&') { op += '>'; i++; }
|
|
44
|
+
if (command[i + 1] === '>' || command[i + 1] === '|') op += command[++i];
|
|
45
|
+
if (command[i + 1] === '&') {
|
|
46
|
+
op += command[++i];
|
|
47
|
+
while (/[\d-]/.test(command[i + 1] ?? 'x')) op += command[++i];
|
|
48
|
+
}
|
|
49
|
+
words.push(op); continue;
|
|
50
|
+
}
|
|
51
|
+
const brace = '{}'.includes(ch) && !started && /^(?:\s|;|$)/.test(command[i + 1] ?? '');
|
|
52
|
+
if ('{}'.includes(ch) && !brace) uncertain = true; // unquoted expansion is not a command boundary
|
|
53
|
+
if (';|&\n()'.includes(ch) || brace) {
|
|
54
|
+
let op = ch; if ('|&'.includes(ch) && command[i + 1] === ch) op += command[++i];
|
|
55
|
+
group(op);
|
|
56
|
+
} else if (/\s/.test(ch)) flush(); else { word += ch; started = true; }
|
|
57
|
+
}
|
|
58
|
+
group('');
|
|
59
|
+
return { groups, uncertain: uncertain || !!quote || escape || /<<|[<>]\(/.test(command) };
|
|
60
|
+
}
|
|
61
|
+
export function git(cwd, args) {
|
|
62
|
+
// Read-only plumbing, bounded and isolated from per-command environment.
|
|
63
|
+
const env = { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0' };
|
|
64
|
+
for (const key of Object.keys(env)) if (/^GIT_(DIR|WORK_TREE|COMMON_DIR|CONFIG|INDEX|OBJECT|ALTERNATE)/.test(key)) delete env[key];
|
|
65
|
+
const r = spawnSync('git', ['-C', cwd, ...args], { encoding: 'utf8', env, timeout: 2000, maxBuffer: 2_000_000 });
|
|
66
|
+
return r.status === 0 ? r.stdout.trim() : undefined;
|
|
67
|
+
}
|
|
68
|
+
export function repoIdentity(locator, cwd) {
|
|
69
|
+
if (!locator) return canonical(cwd);
|
|
70
|
+
const value = locator.replace(/^git\+/, '').replace(/\.git\/?$/, '').replace(/\/$/, '');
|
|
71
|
+
if (/^[\w.-]+\.[\w.-]+\/[^/]+\/[^/]+$/.test(value)) return value.toLowerCase();
|
|
72
|
+
const scp = value.match(/^(?:[^/@]+@)?([^/:]+):([^/].*)$/);
|
|
73
|
+
if (scp && !/^[A-Za-z]:/.test(value) && !value.includes('://')) return `${scp[1]}/${scp[2]}`.toLowerCase();
|
|
74
|
+
try { const url = new URL(value); if (url.protocol !== 'file:') return `${url.host}${url.pathname}`.toLowerCase(); return canonical(url.pathname); } catch { /* local path */ }
|
|
75
|
+
if (/^[\w.-]+\/[\w.-]+$/.test(value) && !value.startsWith('.')) return `github.com/${value}`.toLowerCase();
|
|
76
|
+
return canonical(resolve(cwd, value));
|
|
77
|
+
}
|
|
78
|
+
export function repository(cwd) {
|
|
79
|
+
let existing = cwd;
|
|
80
|
+
while (!fs.existsSync(existing) && dirname(existing) !== existing) existing = dirname(existing);
|
|
81
|
+
const root = git(existing, ['rev-parse', '--show-toplevel']);
|
|
82
|
+
const path = root ? canonical(root) : canonical(cwd);
|
|
83
|
+
return { path, repo: repoIdentity(git(existing, ['remote', 'get-url', 'origin']), path) };
|
|
84
|
+
}
|
|
85
|
+
function pushUrls(cwd, destination) {
|
|
86
|
+
const named = git(cwd, ['remote', 'get-url', '--push', '--all', destination]);
|
|
87
|
+
if (named !== undefined) return named.split('\n');
|
|
88
|
+
const rules = git(cwd, ['config', '--get-regexp', '^url\\..*\\.(pushinsteadof|insteadof)$']) ?? '';
|
|
89
|
+
for (const kind of ['pushinsteadof', 'insteadof']) {
|
|
90
|
+
const matches = rules.split('\n').map(line => line.match(/^url\.(.*)\.(pushinsteadof|insteadof) (.*)$/))
|
|
91
|
+
.filter(m => m && m[2] === kind && destination.startsWith(m[3])).sort((a, b) => b[3].length - a[3].length);
|
|
92
|
+
if (matches.length) return [matches[0][1] + destination.slice(matches[0][3].length)];
|
|
93
|
+
}
|
|
94
|
+
return [destination];
|
|
95
|
+
}
|
|
96
|
+
const valueAfter = (words, long, short) => {
|
|
97
|
+
for (let i = 0; i < words.length; i++) {
|
|
98
|
+
if (words[i] === long || words[i] === short) return words[i + 1];
|
|
99
|
+
if (words[i].startsWith(long + '=')) return words[i].slice(long.length + 1);
|
|
100
|
+
if (short && words[i].startsWith(short) && words[i].length > short.length) return words[i].slice(short.length);
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
function positional(words, valueOptions = []) {
|
|
104
|
+
const result = [];
|
|
105
|
+
for (let i = 0; i < words.length; i++) {
|
|
106
|
+
if (/^(?:\d*)>>?/.test(words[i])) { if (/^(?:\d*)>>?$/.test(words[i])) i++; continue; }
|
|
107
|
+
if (valueOptions.includes(words[i])) { i++; continue; }
|
|
108
|
+
if (!words[i].startsWith('-')) result.push(words[i]);
|
|
109
|
+
}
|
|
110
|
+
return result;
|
|
111
|
+
}
|
|
112
|
+
function npmWorkspaces(root, words) {
|
|
113
|
+
const selectors = [];
|
|
114
|
+
const all = words.includes('--workspaces') || words.includes('-ws');
|
|
115
|
+
for (let i = 0; i < words.length; i++) {
|
|
116
|
+
if (words[i] === '--workspace' || words[i] === '-w') selectors.push(words[++i]);
|
|
117
|
+
else if (words[i].startsWith('--workspace=')) selectors.push(words[i].slice(12));
|
|
118
|
+
else if (words[i].startsWith('-w') && words[i] !== '-ws') selectors.push(words[i].slice(2));
|
|
119
|
+
}
|
|
120
|
+
if (!selectors.length && !all) return [root];
|
|
121
|
+
const candidates = [];
|
|
122
|
+
try {
|
|
123
|
+
const config = JSON.parse(fs.readFileSync(join(root, 'package.json'), 'utf8')).workspaces;
|
|
124
|
+
for (const pattern of Array.isArray(config) ? config : config?.packages ?? []) {
|
|
125
|
+
let paths = [root];
|
|
126
|
+
for (const segment of pattern.split('/')) paths = paths.flatMap(path => {
|
|
127
|
+
if (segment === '*') {
|
|
128
|
+
try { return fs.readdirSync(path, { withFileTypes: true }).filter(e => e.isDirectory()).map(e => join(path, e.name)); }
|
|
129
|
+
catch { return []; }
|
|
130
|
+
}
|
|
131
|
+
return [join(path, segment)];
|
|
132
|
+
});
|
|
133
|
+
for (const path of paths) {
|
|
134
|
+
try { candidates.push({ path: canonical(path), name: JSON.parse(fs.readFileSync(join(path, 'package.json'), 'utf8')).name }); }
|
|
135
|
+
catch { /* Not a declared package directory. */ }
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
} catch { /* npm itself rejects invalid workspace configuration. */ }
|
|
139
|
+
return [...new Set(all ? candidates.map(c => c.path) : selectors.flatMap(selector => {
|
|
140
|
+
const direct = resolve(root, selector);
|
|
141
|
+
if (fs.existsSync(join(direct, 'package.json'))) return [canonical(direct)];
|
|
142
|
+
return candidates.filter(c => c.name === selector).map(c => c.path);
|
|
143
|
+
}))];
|
|
144
|
+
}
|
|
145
|
+
export function classify(command, initialCwd, context, depth = 0) {
|
|
146
|
+
if (depth > 5) return [{ action: 'shell.opaque', ref: '', repo: '', foreign: true, uncertain: true }];
|
|
147
|
+
const requests = [], parsed = shellWords(command); let cwd = initialCwd, pipeline, groupIndex = -1, conditionalState = false;
|
|
148
|
+
let candidateCwds = new Set([initialCwd]);
|
|
149
|
+
const conditional = parsed.groups.some(g=>['&&','||'].includes(g.separator));
|
|
150
|
+
const stack = [], directories = []; let variables = { ...context.toolEnv }, oldpwd;
|
|
151
|
+
const opaque = (action = 'shell.syntax') => requests.push({ action, ref: '', repo: context.repo, code: 'UNVERIFIABLE' });
|
|
152
|
+
if (parsed.uncertain) { opaque(); return requests; }
|
|
153
|
+
// Compound pipeline stages require a full shell AST. Never guess at their
|
|
154
|
+
// shared cwd/stack; simple pipeline stages are isolated below.
|
|
155
|
+
if (parsed.groups.some(g=>'{}()'.includes(g.separator) && g.separator) && parsed.groups.some(g=>g.separator==='|')) opaque();
|
|
156
|
+
for (const group of parsed.groups) {
|
|
157
|
+
groupIndex++;
|
|
158
|
+
if (pipeline) { cwd=pipeline.cwd; candidateCwds=new Set(pipeline.candidateCwds); variables={...pipeline.variables}; oldpwd=pipeline.oldpwd; directories.splice(0,directories.length,...pipeline.directories); }
|
|
159
|
+
if (group.separator === '(') {
|
|
160
|
+
if (group.words.some(w => !['!', 'time'].includes(w))) { opaque(); continue; }
|
|
161
|
+
stack.push({ cwd, candidateCwds:[...candidateCwds], variables: { ...variables }, oldpwd, directories: [...directories] }); continue;
|
|
162
|
+
}
|
|
163
|
+
if (group.separator === '|' && pipeline === undefined) pipeline = { cwd, candidateCwds:[...candidateCwds], variables: { ...variables }, oldpwd, directories: [...directories] };
|
|
164
|
+
let words = [...group.words]; const env = { ...variables }, groupCwd = cwd;
|
|
165
|
+
let envChdir = false;
|
|
166
|
+
try {
|
|
167
|
+
// Redirections belong to the outer shell, before any builtin, wrapper or
|
|
168
|
+
// early return. Remove them from argv so they cannot become git refspecs.
|
|
169
|
+
const argv = [];
|
|
170
|
+
for (let i = 0; i < words.length; i++) {
|
|
171
|
+
if (/^\d*>&[\d-]+$/.test(words[i])) continue;
|
|
172
|
+
if (!/^(?:\d*|&)>(?:>|\|)?$/.test(words[i])) { argv.push(words[i]); continue; }
|
|
173
|
+
const destination = words[++i];
|
|
174
|
+
if (['/dev/null', '/dev/stdout', '/dev/stderr'].includes(destination)) continue;
|
|
175
|
+
const selected = resolve(groupCwd,destination ?? '.');
|
|
176
|
+
const path = canonical(selected);
|
|
177
|
+
requests.push({ action: 'file.write', repo: repository(dirname(path)).repo, ref: path, foreign: !inside(context.workspace, path),
|
|
178
|
+
uncertain: !destination || uncertainPath(selected) || /__H2A_(DYNAMIC|SUB)/.test(path) });
|
|
179
|
+
}
|
|
180
|
+
words = argv;
|
|
181
|
+
while (words.length) {
|
|
182
|
+
const assignment = words[0].match(/^([A-Za-z_]\w*)=(.*)$/s);
|
|
183
|
+
if (assignment) { env[assignment[1]] = assignment[2]; words.shift(); continue; }
|
|
184
|
+
if (words[0] === 'env') {
|
|
185
|
+
words.shift();
|
|
186
|
+
while (words[0]?.startsWith('-')) {
|
|
187
|
+
const option = words.shift();
|
|
188
|
+
if (option === '-C' || option === '--chdir') { const selected=resolve(cwd,words.shift()); if(uncertainPath(selected)) opaque('shell.cwd-symlink'); cwd = canonical(selected); envChdir = true; }
|
|
189
|
+
else if (option.startsWith('--chdir=')) { const selected=resolve(cwd,option.slice(8)); if(uncertainPath(selected)) opaque('shell.cwd-symlink'); cwd = canonical(selected); envChdir = true; }
|
|
190
|
+
else if (option === '-u' || option === '--unset') delete env[words.shift()];
|
|
191
|
+
else if (option === '--') break;
|
|
192
|
+
}
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
if (['command', 'builtin', 'sudo', 'rtk', 'proxy', 'nohup', 'exec', '!', 'time', 'nice', 'timeout', 'stdbuf', 'setsid'].includes(basename(words[0]))) {
|
|
196
|
+
const wrapper = basename(words.shift());
|
|
197
|
+
while (words[0]?.startsWith('-')) {
|
|
198
|
+
const flag = words.shift();
|
|
199
|
+
if (flag === '--') break;
|
|
200
|
+
const valueFlags = {nice:['-n','--adjustment'],timeout:['-s','--signal','-k','--kill-after'],stdbuf:['-i','-o','-e'],sudo:['-u','-g','-h','-p','-C','-T']};
|
|
201
|
+
const plainFlags = {command:['-p','-v','-V'],time:['-p'],nice:[],timeout:['--foreground','--preserve-status','-v','--verbose'],setsid:['-f','-w','--fork','--wait','-c','--ctty'],sudo:['-n','-E','-H']};
|
|
202
|
+
if ((valueFlags[wrapper] ?? []).includes(flag)) words.shift();
|
|
203
|
+
else if (!(plainFlags[wrapper] ?? []).includes(flag) && !(valueFlags[wrapper] ?? []).some(name=>flag.startsWith(name+(name.startsWith('--')?'=':'')) && flag!==name) &&
|
|
204
|
+
!(wrapper==='nice' && /^-\d+$/.test(flag))) opaque('shell.wrapper');
|
|
205
|
+
}
|
|
206
|
+
if (wrapper === 'timeout') words.shift();
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
break;
|
|
210
|
+
}
|
|
211
|
+
if (!words.length) {
|
|
212
|
+
if (conditional && groupIndex>0 && JSON.stringify(variables)!==JSON.stringify(env)) conditionalState=true;
|
|
213
|
+
Object.assign(variables, env); continue;
|
|
214
|
+
}
|
|
215
|
+
const executable = words.shift() ?? '';
|
|
216
|
+
const exe = basename(executable);
|
|
217
|
+
if (/__H2A_(DYNAMIC|SUB)/.test(executable) || words.some(w => /__H2A_(DYNAMIC|SUB)/.test(w)) &&
|
|
218
|
+
['git','gh','npm','pnpm','yarn','bun','node','tsx','ts-node','deno','npx','bash','sh','zsh',
|
|
219
|
+
'rm','mv','cp','touch','mkdir','tee','chmod','chown','truncate','install','dd','ln'].includes(exe)) { opaque(); continue; }
|
|
220
|
+
if (['if','then','elif','else','fi','for','select','while','until','do','done','case','esac','function',
|
|
221
|
+
'source','.','eval','export','readonly','declare','typeset','local','set','unset','shopt','alias','unalias','hash','enable'].includes(exe)) {
|
|
222
|
+
opaque(); continue;
|
|
223
|
+
}
|
|
224
|
+
if (['cd', 'pushd', 'popd'].includes(exe)) {
|
|
225
|
+
const path = words.find(w => w === '-' || !w.startsWith('-'));
|
|
226
|
+
const previous = cwd;
|
|
227
|
+
if (exe === 'popd' || exe === 'pushd' && path === undefined) {
|
|
228
|
+
const next = directories.pop();
|
|
229
|
+
if (!next) { opaque('shell.cwd'); continue; }
|
|
230
|
+
if (exe === 'pushd') directories.push(cwd);
|
|
231
|
+
cwd = next;
|
|
232
|
+
} else {
|
|
233
|
+
if (exe === 'pushd') directories.push(cwd);
|
|
234
|
+
const next = path === '-' ? oldpwd ?? env.OLDPWD : path ?? env.HOME ?? process.env.HOME;
|
|
235
|
+
if (!next || words.some(w => /^[-+]\d+$/.test(w)) || env.CDPATH) { opaque('shell.cwd'); continue; }
|
|
236
|
+
const selected=resolve(cwd,next);
|
|
237
|
+
if (uncertainPath(selected)) { opaque('shell.cwd-symlink'); continue; }
|
|
238
|
+
cwd = canonical(selected);
|
|
239
|
+
}
|
|
240
|
+
const nextCandidates = [...candidateCwds].map(base => {
|
|
241
|
+
if (exe !== 'cd' || path === '-' || !path) return cwd;
|
|
242
|
+
return canonical(resolve(base, path));
|
|
243
|
+
});
|
|
244
|
+
candidateCwds = new Set(conditional && groupIndex>0 ? [...candidateCwds, ...nextCandidates] : nextCandidates);
|
|
245
|
+
if ([...candidateCwds].some(path => !inside(context.workspace, path) || repository(path).path !== context.path)) {
|
|
246
|
+
if (conditional && groupIndex > 0) conditionalState = true;
|
|
247
|
+
}
|
|
248
|
+
oldpwd = previous;
|
|
249
|
+
if (/__H2A_(DYNAMIC|SUB)/.test(cwd)) requests.push({ action: 'shell.cwd', code: 'UNVERIFIABLE', repo: context.repo, ref: cwd });
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
// Shell scripts/options/stdin are opaque. Ask for the direct command.
|
|
253
|
+
if (['bash','sh','zsh'].includes(exe) && words.some(w => /^-[a-z]*[cs]/.test(w) || ['/dev/stdin','/proc/self/fd/0'].includes(w))) {
|
|
254
|
+
opaque('shell.script'); continue;
|
|
255
|
+
}
|
|
256
|
+
const interpreter = ['node', 'tsx', 'ts-node', 'bash', 'sh', 'zsh', 'bun', 'deno', 'npx'].includes(exe);
|
|
257
|
+
if (interpreter && (words.length === 0 || words.includes('/dev/stdin') || words.includes('/proc/self/fd/0') || exe === 'deno' && words[0] === 'eval')) {
|
|
258
|
+
opaque('runtime.script'); continue;
|
|
259
|
+
}
|
|
260
|
+
if (candidateCwds.size > 1) {
|
|
261
|
+
const explicit = [executable,...words].map(w => "'" + w.replace(/'/g, "'\\''") + "'").join(' ');
|
|
262
|
+
for (const alternative of candidateCwds) if (alternative !== cwd)
|
|
263
|
+
requests.push(...classify(explicit, alternative, {...context,toolEnv:env}, depth+1).map(request=>({...request,uncertain:request.uncertain || request.foreign})));
|
|
264
|
+
}
|
|
265
|
+
const launches = name => exe === name || interpreter && words.some(w => basename(w) === name);
|
|
266
|
+
if (launches('workspace-scope-grant.mjs') || launches('workspace-scope-guard.mjs') && words.some(w => w.startsWith('--initialize-session'))) {
|
|
267
|
+
requests.push({ action: 'owner.grant', code: 'OWNER_ONLY', ref: '', repo: '' }); continue;
|
|
268
|
+
}
|
|
269
|
+
if (interpreter && words.some(w => /^(?:--(?:eval|print)(?:=|$)|-[ep])/.test(w))) {
|
|
270
|
+
requests.push({ action: 'runtime.inline', repo: context.repo, ref: '',
|
|
271
|
+
code: words.some(w => w.includes('workspace-scope') || context.ownerKey && w.includes(context.ownerKey)) ? 'OWNER_ONLY' : 'UNVERIFIABLE' });
|
|
272
|
+
}
|
|
273
|
+
let target = cwd, additionalTargets = [], action, ref = '', remote, extraRemotes = [], checkVersions = false, privateVersion = false, revision, versionRefs, ownerOnly = false, gitOptionsUncertain = false;
|
|
274
|
+
if (exe === 'git') {
|
|
275
|
+
let gitDir = env.GIT_DIR, workTree = env.GIT_WORK_TREE;
|
|
276
|
+
let i = 0;
|
|
277
|
+
for (; i < words.length; i++) {
|
|
278
|
+
const word = words[i];
|
|
279
|
+
if (word === '-C') { const selected = resolve(target, words[++i]); gitOptionsUncertain ||= uncertainPath(selected); target = selected; continue; }
|
|
280
|
+
if (word.startsWith('-C') && word.length > 2) { const selected = resolve(target, word.slice(2)); gitOptionsUncertain ||= uncertainPath(selected); target = selected; continue; }
|
|
281
|
+
if (word === '--work-tree') { workTree = words[++i]; continue; }
|
|
282
|
+
if (word.startsWith('--work-tree=')) { workTree = word.slice(12); continue; }
|
|
283
|
+
if (word === '--git-dir') { gitDir = words[++i]; continue; }
|
|
284
|
+
if (word.startsWith('--git-dir=')) { gitDir = word.slice(10); continue; }
|
|
285
|
+
if (word === '-c' || word.startsWith('--config-env')) gitOptionsUncertain = true;
|
|
286
|
+
if (['-c', '--namespace', '--config-env', '--exec-path', '--super-prefix', '--attr-source'].includes(word)) { i++; continue; }
|
|
287
|
+
if (!word.startsWith('-')) break;
|
|
288
|
+
if (!/^(?:--(?:namespace|config-env|exec-path|super-prefix|attr-source)=|--(?:no-pager|paginate|bare|no-optional-locks)$)/.test(word)) opaque('git.options');
|
|
289
|
+
}
|
|
290
|
+
if (workTree) {
|
|
291
|
+
const selected=resolve(target,workTree);
|
|
292
|
+
gitOptionsUncertain ||= uncertainPath(selected);
|
|
293
|
+
additionalTargets.push(canonical(selected));
|
|
294
|
+
}
|
|
295
|
+
if (gitDir) { additionalTargets.push(canonical(target)); target = dirname(resolve(target, gitDir)); gitOptionsUncertain = true; }
|
|
296
|
+
else if (workTree) target = resolve(target, workTree);
|
|
297
|
+
const sub = words[i], args = words.slice(i + 1), pos = positional(args, ['--repo', '--receive-pack', '--exec', '-m', '--message',
|
|
298
|
+
'--author', '--date', '-F', '--file', '-C', '-c', '--cleanup', '--trailer', '--fixup', '--squash', '--pathspec-from-file']);
|
|
299
|
+
if (['push', 'merge', 'tag', 'rebase', 'commit', 'reset', 'checkout', 'switch', 'cherry-pick', 'revert', 'clean', 'stash', 'add', 'rm', 'mv', 'config', 'update-ref', 'pull', 'apply', 'am', 'restore', 'worktree', 'send-pack'].includes(sub) ||
|
|
300
|
+
(sub === 'branch' && args.some(w => /^-[^-]*[DdMmCcf]/.test(w) || ['--delete', '--move', '--copy', '--force'].includes(w)))) action = `git.${sub}`;
|
|
301
|
+
ref = pos.at(-1) ?? git(target, ['symbolic-ref', '--short', 'HEAD']) ?? '';
|
|
302
|
+
if (sub === 'tag' && (!args.length || args.some(w => ['-l', '--list', '-v', '--verify'].includes(w)))) action = undefined;
|
|
303
|
+
if (sub === 'config' && (args.some(w => /^(--get|--list|-l)$/.test(w)) || pos.length < 2 && !args.some(w => /^--(?:unset|remove|rename)/.test(w)))) action = undefined;
|
|
304
|
+
if (sub === 'send-pack') opaque('git.send-pack');
|
|
305
|
+
checkVersions = ['push', 'commit', 'merge'].includes(sub);
|
|
306
|
+
if (sub === 'merge') revision = pos.find(w => !/^(?:--|FETCH_HEAD$)/.test(w));
|
|
307
|
+
// Every commit contains the index; path/--all commits additionally select
|
|
308
|
+
// worktree content. Option operands must never select the wrong tree.
|
|
309
|
+
if (sub === 'commit') { revision = ':INDEX'; versionRefs = [':INDEX', ...(args.includes('--all') || args.some(w => /^-[a-z]*a/.test(w)) || pos.length ? [undefined] : [])]; }
|
|
310
|
+
if (sub === 'update-ref') requests.push({ action, code: 'OWNER_ONLY', repo: context.repo, ref });
|
|
311
|
+
if (sub === 'remote' && !['', 'show', 'get-url'].includes(args.find(w => !w.startsWith('-')) ?? '') || sub === 'config' && action) opaque('git.config-mutation');
|
|
312
|
+
ownerOnly = sub === 'am' || sub === 'apply' && (args.includes('--apply') || !args.some(w=>['--check','--stat','--numstat','--summary'].includes(w)));
|
|
313
|
+
if (sub === 'clean' && !args.slice(0,args.includes('--') ? args.indexOf('--') : args.length).some(w => w === '--dry-run' || /^-[^-]*n/.test(w))) {
|
|
314
|
+
for (const path of pos.length ? pos : ['.']) requests.push({action:'file.rm',repo:context.repo,ref:canonical(resolve(target,path))});
|
|
315
|
+
}
|
|
316
|
+
if (sub === 'push') {
|
|
317
|
+
const branch = git(target, ['symbolic-ref', '--short', 'HEAD']);
|
|
318
|
+
const destination = valueAfter(args, '--repo') ?? pos[0] ??
|
|
319
|
+
git(target, ['config', `branch.${branch}.pushRemote`]) ?? git(target, ['config', 'remote.pushDefault']) ??
|
|
320
|
+
git(target, ['config', `branch.${branch}.remote`]) ?? 'origin';
|
|
321
|
+
const destinations = pushUrls(target, destination);
|
|
322
|
+
[remote, ...extraRemotes] = destinations;
|
|
323
|
+
// get-url expands pushInsteadOf/insteadOf and pushurl before comparison.
|
|
324
|
+
ref = pos.length <= 1 ? git(target, ['symbolic-ref', '--short', 'HEAD']) ?? '' : pos.slice(1).join(' ');
|
|
325
|
+
versionRefs = pos.length <= 1 ? ['HEAD'] : pos.slice(1).flatMap(p => p.replace(/^\+/, '') === ':' ?
|
|
326
|
+
(git(target, ['for-each-ref', '--format=%(refname)', 'refs/heads/']) ?? '').split('\n').filter(Boolean) :
|
|
327
|
+
[p.replace(/^\+/, '').split(':')[0]]).filter(Boolean);
|
|
328
|
+
if (args.some(w => ['--all','--branches','--tags','--mirror'].includes(w))) {
|
|
329
|
+
const namespaces = args.includes('--mirror') ? ['refs/'] : [
|
|
330
|
+
...(args.some(w => ['--all','--branches'].includes(w)) ? ['refs/heads/'] : []), ...(args.includes('--tags') ? ['refs/tags/'] : [])];
|
|
331
|
+
versionRefs.push(...(git(target, ['for-each-ref', '--format=%(refname)', ...namespaces]) ?? '').split('\n').filter(Boolean));
|
|
332
|
+
}
|
|
333
|
+
if (args.includes('--follow-tags')) versionRefs.push(...(git(target,['for-each-ref','--format=%(refname)','refs/tags/']) ?? '').split('\n').filter(Boolean));
|
|
334
|
+
revision = 'HEAD';
|
|
335
|
+
}
|
|
336
|
+
} else if (exe === 'gh') {
|
|
337
|
+
const selected = valueAfter(words, '--repo', '-R') ?? env.GH_REPO;
|
|
338
|
+
const pos = positional(words, ['--repo', '-R', '--body', '-b', '--title', '-t', '--subject', '--comment', '-c', '--body-file', '-F', '--target', '--notes-file']);
|
|
339
|
+
const [noun, verb, argument] = pos;
|
|
340
|
+
if (noun === 'api') {
|
|
341
|
+
const method = valueAfter(words, '--method', '-X') ?? (words.some(w => ['-f', '-F', '--field', '--raw-field', '--input'].includes(w)) ? 'POST' : 'GET');
|
|
342
|
+
const endpoint = positional(words.slice(words.indexOf('api') + 1), ['--method', '-X', '-f', '-F', '--field', '--raw-field', '--input'])[0];
|
|
343
|
+
if (!['GET', 'HEAD', 'OPTIONS'].includes(method.toUpperCase())) {
|
|
344
|
+
const match = endpoint?.match(/^\/?repos\/([^/]+\/[^/]+)\/(.*)$/);
|
|
345
|
+
const merge = match?.[2].match(/^pulls\/(\d+)\/merge$/);
|
|
346
|
+
action = merge ? 'gh.pr.merge' : `gh.api.${method.toUpperCase()}`;
|
|
347
|
+
remote = match ? `${env.GH_HOST ?? 'github.com'}/${match[1]}` : 'unresolved';
|
|
348
|
+
ref = merge ? merge[1] : endpoint ?? '';
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
if (noun === 'pr' && (['merge', 'ready', 'close'].includes(verb) || verb === 'review' && (words.includes('--approve') || words.includes('-a'))) || noun === 'release') {
|
|
352
|
+
if (noun === 'release' && (!verb || ['view', 'list', 'download'].includes(verb))) continue;
|
|
353
|
+
action = `gh.${noun}.${verb}`; ref = argument ?? '';
|
|
354
|
+
const url = argument?.match(/^https?:\/\/([^/]+)\/([^/]+\/[^/]+)\/pull\/(\d+)/);
|
|
355
|
+
remote = url ? `${url[1]}/${url[2]}` : selected;
|
|
356
|
+
if (url) ref = url[3];
|
|
357
|
+
}
|
|
358
|
+
} else if (['npm', 'pnpm', 'yarn', 'bun'].includes(exe)) {
|
|
359
|
+
target = resolve(cwd, valueAfter(words, '--prefix') ?? valueAfter(words, '--cwd', '-C') ?? cwd);
|
|
360
|
+
const scriptTargets = npmWorkspaces(target, words);
|
|
361
|
+
if (scriptTargets.length) [target, ...additionalTargets] = scriptTargets;
|
|
362
|
+
const pos = positional(words, ['--prefix', '--cwd', '-C', '--workspace', '-w']);
|
|
363
|
+
let [sub, script] = pos;
|
|
364
|
+
if (sub === 'run-script') sub = 'run';
|
|
365
|
+
else if (exe !== 'npm' && sub && !['run','publish','version','pkg','install','ci','add','remove','exec','test','list','info','help'].includes(sub)) {
|
|
366
|
+
script = sub; sub = 'run';
|
|
367
|
+
}
|
|
368
|
+
if (sub === 'version' && !script) continue; // npm version without an argument only prints versions.
|
|
369
|
+
if (sub === 'pkg' && script === 'set' && pos.slice(2).some(w => /^version=/.test(w))) {
|
|
370
|
+
action = `${exe}.version`; ref = pos.slice(2).join(' '); checkVersions = true;
|
|
371
|
+
} else if (['publish', 'version'].includes(sub) || sub === 'run' && /(?:^|[:/-])(release|publish|version|bump)(?:$|[:/-])/.test(script ?? '')) {
|
|
372
|
+
action = `${exe}.${sub}`; ref = script ?? sub; checkVersions = true;
|
|
373
|
+
} else if (['run', 'install', 'ci', 'add', 'remove'].includes(sub)) { action = `${exe}.${sub}`; ref = script ?? sub; }
|
|
374
|
+
if (action === `${exe}.version`) {
|
|
375
|
+
try { privateVersion = isPrivatePackage(target, context); }
|
|
376
|
+
catch { /* Unknown publication status keeps the release gate. */ }
|
|
377
|
+
if (privateVersion) checkVersions = false;
|
|
378
|
+
}
|
|
379
|
+
if (sub === 'run' && script) {
|
|
380
|
+
for (const directory of scriptTargets) {
|
|
381
|
+
try {
|
|
382
|
+
const body = JSON.parse(fs.readFileSync(join(directory, 'package.json'), 'utf8')).scripts?.[script];
|
|
383
|
+
if (typeof body === 'string') requests.push(...classify(body, directory, context, depth + 1));
|
|
384
|
+
} catch { /* Unknown aliases still retain the outer workspace check. */ }
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
} else if (/(?:^|[-_.])(release|publish|bump)(?:[-_.]|$)/i.test(exe) ||
|
|
388
|
+
['node', 'tsx', 'ts-node', 'deno', 'bash', 'sh', 'zsh', 'bun', 'npx'].includes(exe) &&
|
|
389
|
+
!(exe === 'node' && words.includes('--test') && words.indexOf('--test') < words.findIndex(w => !w.startsWith('-'))) &&
|
|
390
|
+
words.some(w => /(?:^|[/])(?:release|publish|bump)(?:[-_.]|$)/i.test(w))) {
|
|
391
|
+
action = 'script.release'; ref = words[0] ?? exe;
|
|
392
|
+
if (words[0] && /[\/]/.test(words[0])) target = dirname(resolve(cwd, words[0]));
|
|
393
|
+
} else if (['rm', 'mv', 'cp', 'touch', 'mkdir', 'tee', 'chmod', 'chown', 'truncate', 'install', 'dd', 'ln'].includes(exe)) {
|
|
394
|
+
const paths = positional(words, ['--target-directory','-t','--suffix','-S','--mode','-m','--owner','-o','--group','-g']);
|
|
395
|
+
const destination = valueAfter(words,'--target-directory','-t');
|
|
396
|
+
const targets = exe === 'dd' ? words.filter(w => w.startsWith('of=')).map(w => w.slice(3)) :
|
|
397
|
+
['cp','install','ln','mv'].includes(exe) ? [destination ?? paths.at(-1)].filter(Boolean) : paths;
|
|
398
|
+
// Copy/move into an existing directory writes the source basename, not
|
|
399
|
+
// the directory's protected descendants. Sources of mv are removed.
|
|
400
|
+
if (exe === 'mv') for (const source of paths.slice(0,destination ? undefined : -1))
|
|
401
|
+
requests.push({action:'file.rm',repo:context.repo,ref:canonical(resolve(cwd,source)),foreign:!inside(context.workspace,canonical(resolve(cwd,source)))});
|
|
402
|
+
for (const path of targets) {
|
|
403
|
+
const absolute = resolve(cwd,path), resolved = canonical(absolute);
|
|
404
|
+
let directory = false; try { directory=fs.statSync(resolved).isDirectory(); } catch {}
|
|
405
|
+
const written = directory && ['cp','install','ln','mv'].includes(exe) ?
|
|
406
|
+
paths.slice(0,destination ? undefined : -1).map(source=>join(resolved,basename(source))) : [resolved];
|
|
407
|
+
for (const path of written) {
|
|
408
|
+
const ref=canonical(path);
|
|
409
|
+
requests.push({ action: `file.${exe}`, repo: repository(dirname(ref)).repo, ref,
|
|
410
|
+
foreign: !inside(context.workspace, ref), uncertain: uncertainPath(absolute) || uncertainPath(path) });
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
if (!action) continue;
|
|
415
|
+
const repo = repository(canonical(target));
|
|
416
|
+
const destination = remote ? repoIdentity(remote, target) : repo.repo;
|
|
417
|
+
const request = { action, ref, repo: destination, cwd: canonical(target), checkVersions, revision, versionRefs,
|
|
418
|
+
foreign: repo.path !== context.path || !inside(context.workspace, canonical(target)) || destination !== context.repo,
|
|
419
|
+
release: /^(?:npm|pnpm|yarn|bun)\.publish$/.test(action) ||
|
|
420
|
+
/^(?:npm|pnpm|yarn|bun)\.version$/.test(action) && !privateVersion || action === 'script.release' ||
|
|
421
|
+
action.endsWith('.run') && /release|publish|version|bump/.test(ref) || action.startsWith('gh.release.'),
|
|
422
|
+
uncertain: uncertainPath(target) || [target, remote, ...words.filter((w, i) => i === 0 || words[i - 1] !== '-m' && words[i - 1] !== '--message')].some(w => /__H2A_(DYNAMIC|SUB)/.test(w ?? '')) || Object.keys(env).some(k => /^(?:GIT_CONFIG|GIT_COMMON_DIR)/.test(k)) ||
|
|
423
|
+
gitOptionsUncertain || exe === 'git' && words.includes('--mirror') };
|
|
424
|
+
requests.push(request);
|
|
425
|
+
if (ownerOnly) requests.push({...request,code:'OWNER_ONLY'});
|
|
426
|
+
for (const path of additionalTargets) {
|
|
427
|
+
const repo = repository(path);
|
|
428
|
+
let release = request.release, checkVersions = request.checkVersions;
|
|
429
|
+
if (/^(?:npm|pnpm|yarn|bun)\.version$/.test(action)) {
|
|
430
|
+
let privatePackage = false;
|
|
431
|
+
try { privatePackage = isPrivatePackage(path, context); } catch { /* Keep release gate. */ }
|
|
432
|
+
release = checkVersions = !privatePackage;
|
|
433
|
+
}
|
|
434
|
+
requests.push({ ...request, cwd: path, repo: repo.repo, release, checkVersions,
|
|
435
|
+
foreign: repo.path !== context.path || !inside(context.workspace, path) || repo.repo !== context.repo });
|
|
436
|
+
}
|
|
437
|
+
for (const locator of extraRemotes) {
|
|
438
|
+
const repo = repoIdentity(locator, target);
|
|
439
|
+
requests.push({ ...request, repo, foreign: request.foreign || repo !== context.repo });
|
|
440
|
+
}
|
|
441
|
+
} finally {
|
|
442
|
+
if (envChdir) cwd = groupCwd;
|
|
443
|
+
if (group.separator === ')') {
|
|
444
|
+
const previous = stack.pop();
|
|
445
|
+
if (!previous) opaque();
|
|
446
|
+
else { cwd = previous.cwd; candidateCwds=new Set(previous.candidateCwds); variables = previous.variables; oldpwd = previous.oldpwd; directories.splice(0,directories.length,...previous.directories); }
|
|
447
|
+
}
|
|
448
|
+
if (pipeline !== undefined && group.separator !== '|') {
|
|
449
|
+
cwd = pipeline.cwd; candidateCwds=new Set(pipeline.candidateCwds); variables = pipeline.variables; oldpwd=pipeline.oldpwd; directories.splice(0,directories.length,...pipeline.directories); pipeline = undefined;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
// A short-circuit can skip a later cwd/environment reset. The linear subset
|
|
454
|
+
// must never erase the prior foreign context by assuming that reset ran.
|
|
455
|
+
if (conditionalState) opaque('shell.conditional-state');
|
|
456
|
+
return requests;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
export function manifestAtBaseline(path, baseline) {
|
|
460
|
+
const root=repository(dirname(path)).path;
|
|
461
|
+
const base=baseline ?? git(root,['merge-base','origin/main','HEAD']) ?? git(root,['merge-base','main','HEAD']);
|
|
462
|
+
return base ? git(root,['show',`${base}:${relative(root,path)}`]) : undefined;
|
|
463
|
+
}
|
|
464
|
+
function isPrivatePackage(directory, context) {
|
|
465
|
+
const path=join(directory,'package.json');
|
|
466
|
+
const current=JSON.parse(fs.readFileSync(path,'utf8'));
|
|
467
|
+
const base=manifestAtBaseline(path,repository(directory).path===context.path?context.baseline:undefined);
|
|
468
|
+
return current.private === true && (!base || JSON.parse(base).private === true);
|
|
469
|
+
}
|
|
470
|
+
// Reconstruct proposed JSON before comparing top-level fields. No regex over
|
|
471
|
+
// added version lines: formatting and repeated sections must have no effect.
|
|
472
|
+
export function patchContent(path, patch, cwd) {
|
|
473
|
+
let content=fs.existsSync(path) ? fs.readFileSync(path,'utf8') : '';
|
|
474
|
+
const sections=patch.split(/^\*\*\* (Update File|Add File|Delete File): (.+)\n/m);
|
|
475
|
+
for (let i=1;i<sections.length;i+=3) {
|
|
476
|
+
if (canonical(resolve(cwd,sections[i+1])) !== path) continue;
|
|
477
|
+
const kind=sections[i], lines=sections[i+2].split('\n');
|
|
478
|
+
if (kind==='Delete File') return '{}';
|
|
479
|
+
if (kind==='Add File') { content=lines.filter(line=>line.startsWith('+')).map(line=>line.slice(1)).join('\n')+'\n'; continue; }
|
|
480
|
+
let before=[], after=[], cursor=0;
|
|
481
|
+
const flush=()=>{
|
|
482
|
+
if (!before.length && !after.length) return;
|
|
483
|
+
const old=before.join('\n'), next=after.join('\n');
|
|
484
|
+
const index=old ? content.indexOf(old,cursor) : cursor;
|
|
485
|
+
if(index<0) throw new Error('Unresolved manifest patch');
|
|
486
|
+
content=content.slice(0,index)+next+content.slice(index+old.length);
|
|
487
|
+
cursor=index+next.length; before=[];after=[];
|
|
488
|
+
};
|
|
489
|
+
for (const line of lines) {
|
|
490
|
+
if (line.startsWith('@@')) { flush();continue; }
|
|
491
|
+
if (line.startsWith('***') || line==='') { flush();continue; }
|
|
492
|
+
if (line[0]===' ' || line[0]==='-') before.push(line.slice(1));
|
|
493
|
+
if (line[0]===' ' || line[0]==='+') after.push(line.slice(1));
|
|
494
|
+
}
|
|
495
|
+
flush();
|
|
496
|
+
}
|
|
497
|
+
JSON.parse(content); // Unresolvable/invalid proposed JSON fails closed.
|
|
498
|
+
return content;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
export function prBump(request) {
|
|
502
|
+
if (!/^[\w.-]+\/[^/]+\/[^/]+$/.test(request.repo)) return undefined;
|
|
503
|
+
if (!request.ref) {
|
|
504
|
+
const result = spawnSync('gh', ['pr', 'view', '--repo', request.repo, '--json', 'number'],
|
|
505
|
+
{ cwd: request.cwd, encoding: 'utf8', timeout: 4000, maxBuffer: 100_000 });
|
|
506
|
+
try { request.ref = String(JSON.parse(result.stdout).number); } catch { return undefined; }
|
|
507
|
+
}
|
|
508
|
+
if (!/^\d+$/.test(request.ref)) return undefined;
|
|
509
|
+
const deadline = Date.now() + 10_000;
|
|
510
|
+
const read = args => {
|
|
511
|
+
if (Date.now() >= deadline) return;
|
|
512
|
+
const r = spawnSync('gh', args, { encoding: 'utf8', timeout: Math.min(4000, deadline - Date.now()), maxBuffer: 2_000_000 });
|
|
513
|
+
return r.status === 0 ? r.stdout : undefined;
|
|
514
|
+
};
|
|
515
|
+
const diff = read(['pr', 'diff', request.ref, '--repo', request.repo, '--color', 'never']);
|
|
516
|
+
if (diff === undefined) return;
|
|
517
|
+
let metadata;
|
|
518
|
+
for (const section of diff.split(/^diff --git /m)) {
|
|
519
|
+
const path = section.split('\n')[0].match(/ b\/(.*package\.json)$/)?.[1];
|
|
520
|
+
if (!path || basename(path) !== 'package.json') continue;
|
|
521
|
+
// Full before/after manifests distinguish private fixtures and nested
|
|
522
|
+
// metadata fields from the published package's top-level version.
|
|
523
|
+
try {
|
|
524
|
+
metadata ??= JSON.parse(read(['pr', 'view', request.ref, '--repo', request.repo, '--json', 'baseRefOid,headRefOid']));
|
|
525
|
+
if (![metadata.baseRefOid, metadata.headRefOid].every(s => /^[a-f0-9]{40,64}$/.test(s))) return;
|
|
526
|
+
const [hostname, owner, repo] = request.repo.split('/');
|
|
527
|
+
const endpoint = `repos/${owner}/${repo}/contents/${path.split('/').map(encodeURIComponent).join('/')}`;
|
|
528
|
+
const content = ref => read(['api', '--hostname', hostname, `${endpoint}?ref=${ref}`, '-H', 'Accept: application/vnd.github.raw+json']);
|
|
529
|
+
const before = content(metadata.baseRefOid), after = content(metadata.headRefOid);
|
|
530
|
+
if (before === undefined || after === undefined) return;
|
|
531
|
+
JSON.parse(before); JSON.parse(after);
|
|
532
|
+
if (publishedBump(before, after)) return true;
|
|
533
|
+
} catch { return; }
|
|
534
|
+
}
|
|
535
|
+
return false;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
export function publishedBump(before, after) {
|
|
539
|
+
try {
|
|
540
|
+
const old = JSON.parse(before), next = JSON.parse(after);
|
|
541
|
+
return old.name && old.version && old.private !== true && next.version !== old.version;
|
|
542
|
+
} catch { return false; }
|
|
543
|
+
}
|
|
544
|
+
export function branchBump(cwd, revision, baseline) {
|
|
545
|
+
const base = baseline ?? git(cwd, ['merge-base', 'origin/main', 'HEAD']) ?? git(cwd, ['merge-base', 'main', 'HEAD']);
|
|
546
|
+
if (!base) return undefined;
|
|
547
|
+
const root = git(cwd, ['rev-parse', '--show-toplevel']);
|
|
548
|
+
if (!root) return undefined;
|
|
549
|
+
const files = git(root, ['diff', '--name-only', ...(revision === ':INDEX' ? ['--cached'] : []), base,
|
|
550
|
+
...(revision && revision !== ':INDEX' ? [revision] : []), '--', '*package.json', 'package.json']);
|
|
551
|
+
if (files === undefined) return undefined;
|
|
552
|
+
return files.split('\n').filter(p => basename(p) === 'package.json').some(path => {
|
|
553
|
+
const before = git(root, ['show', `${base}:${path}`]);
|
|
554
|
+
let after;
|
|
555
|
+
try { after = revision ? git(root, ['show', `${revision === ':INDEX' ? '' : revision}:${path}`]) : fs.readFileSync(join(root, path), 'utf8'); } catch { return false; }
|
|
556
|
+
return before && publishedBump(before, after);
|
|
557
|
+
});
|
|
558
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { dirname, join, resolve, sep } from 'node:path';
|
|
3
|
+
import { createPublicKey, verify } from 'node:crypto';
|
|
4
|
+
|
|
5
|
+
export const stateDir = workspace => join(workspace, '.h2a', 'workspace-scope');
|
|
6
|
+
export function canonical(path) {
|
|
7
|
+
const absolute = resolve(path);
|
|
8
|
+
try { return fs.realpathSync(absolute); }
|
|
9
|
+
catch (error) {
|
|
10
|
+
if (error.code !== 'ENOENT') throw error;
|
|
11
|
+
const parent = dirname(absolute);
|
|
12
|
+
if (parent === absolute) throw error;
|
|
13
|
+
return join(canonical(parent), absolute.slice(parent.length));
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export const inside = (root, path) => path === root || path.startsWith(root + sep);
|
|
17
|
+
export function readRecords(workspace, file) {
|
|
18
|
+
const path = join(stateDir(workspace), file);
|
|
19
|
+
if (canonical(path) !== path) throw new Error('scope state is a symlink');
|
|
20
|
+
try { return fs.readFileSync(path, 'utf8').split('\n').filter(Boolean).map(JSON.parse); }
|
|
21
|
+
catch (error) { if (error.code === 'ENOENT') return []; throw error; }
|
|
22
|
+
}
|
|
23
|
+
export function appendRecord(workspace, file, record) {
|
|
24
|
+
const directory = stateDir(workspace);
|
|
25
|
+
// Never follow a workspace-state symlink, including one in .h2a.
|
|
26
|
+
for (const path of [join(workspace, '.h2a'), directory]) {
|
|
27
|
+
try { if (fs.lstatSync(path).isSymbolicLink()) throw new Error('scope state is a symlink'); }
|
|
28
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
29
|
+
fs.mkdirSync(path, { recursive: true, mode: 0o700 });
|
|
30
|
+
}
|
|
31
|
+
const fd = fs.openSync(join(directory, file), fs.constants.O_WRONLY | fs.constants.O_APPEND |
|
|
32
|
+
fs.constants.O_CREAT | (fs.constants.O_NOFOLLOW ?? 0), 0o600);
|
|
33
|
+
try { fs.writeSync(fd, JSON.stringify(record) + '\n'); fs.fsyncSync(fd); }
|
|
34
|
+
finally { fs.closeSync(fd); }
|
|
35
|
+
}
|
|
36
|
+
export function validGrant(grant, context, request) {
|
|
37
|
+
return grant?.schema === 1 && typeof grant.owner === 'string' && grant.owner.trim().length > 0 &&
|
|
38
|
+
grant.workspace === context.workspace && grant.session === context.session &&
|
|
39
|
+
grant.repo === request.repo && grant.action === request.action && grant.ref === request.ref &&
|
|
40
|
+
Number.isFinite(Date.parse(grant.expires)) && Date.parse(grant.expires) > Date.now() &&
|
|
41
|
+
[grant.repo, grant.action, grant.ref, grant.session].every(x => typeof x === 'string' && x.length > 0 && !x.includes('*'));
|
|
42
|
+
}
|
|
43
|
+
export function findGrant(context, request) {
|
|
44
|
+
if (!context.ownerKey || !context.session || !request.ref) return;
|
|
45
|
+
try {
|
|
46
|
+
const key = createPublicKey(fs.readFileSync(context.ownerKey));
|
|
47
|
+
if (key.asymmetricKeyType !== 'ed25519') return;
|
|
48
|
+
const path = join(stateDir(context.workspace), 'grants.jsonl');
|
|
49
|
+
if (canonical(path) !== path) return;
|
|
50
|
+
const lines = fs.readFileSync(path, 'utf8').split('\n');
|
|
51
|
+
for (const line of lines) {
|
|
52
|
+
if (!line.trim()) continue;
|
|
53
|
+
let row;
|
|
54
|
+
try { row = JSON.parse(line); } catch { continue; }
|
|
55
|
+
if (validGrant(row.grant, context, request) && typeof row.signature === 'string' &&
|
|
56
|
+
verify(null, Buffer.from(JSON.stringify(row.grant)), key, Buffer.from(row.signature, 'base64'))) return row;
|
|
57
|
+
}
|
|
58
|
+
} catch { /* Missing/untrusted state never authorizes an exception. */ }
|
|
59
|
+
}
|
|
60
|
+
export function options(argv) {
|
|
61
|
+
const result = {};
|
|
62
|
+
for (let i = 0; i < argv.length; i++) {
|
|
63
|
+
if (!argv[i].startsWith('--')) throw new Error('Expected --name value pairs');
|
|
64
|
+
const equal = argv[i].indexOf('=');
|
|
65
|
+
const name = argv[i].slice(2, equal < 0 ? undefined : equal);
|
|
66
|
+
const value = equal < 0 ? argv[++i] : argv[i].slice(equal + 1);
|
|
67
|
+
if (!name || !value) throw new Error('Expected --name value pairs');
|
|
68
|
+
result[name] = value;
|
|
69
|
+
}
|
|
70
|
+
return result;
|
|
71
|
+
}
|