slicekit 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -2
- package/bin/slicekit.js +0 -0
- package/package.json +1 -1
- package/src/adapters/githost/fixture.js +106 -0
- package/src/adapters/githost/gh-json.js +201 -0
- package/src/adapters/githost/github.js +141 -0
- package/src/adapters/tracker/index.js +5 -1
- package/src/adapters/tracker/jira.js +133 -0
- package/src/build/commit.js +85 -7
- package/src/build/decline.js +17 -8
- package/src/build/record.js +11 -1
- package/src/check/ci-event.js +38 -6
- package/src/check/index.js +6 -1
- package/src/check/rules/ci-body.js +1 -1
- package/src/check/rules/ci-title.js +10 -4
- package/src/check/rules/frozen.js +127 -0
- package/src/check/rules/host-rules.js +149 -0
- package/src/check/rules/journal.js +130 -3
- package/src/check/rules/references.js +31 -0
- package/src/check/rules/sync-release.js +94 -0
- package/src/cli/build.js +8 -7
- package/src/cli/index.js +13 -0
- package/src/cli/init.js +29 -2
- package/src/cli/journal.js +44 -2
- package/src/cli/status.js +14 -2
- package/src/cli/sync.js +52 -0
- package/src/config.js +77 -3
- package/src/git.js +65 -1
- package/src/hooks/paths.js +103 -0
- package/src/hooks/pre-bash.js +642 -43
- package/src/hooks/pre-edit.js +23 -3
- package/src/init.js +136 -7
- package/src/journal.js +153 -12
- package/src/pr.js +1 -1
- package/src/prbody.js +1 -1
- package/src/release-version.js +196 -0
- package/src/render/settings.js +26 -2
- package/src/render/update.js +1 -1
- package/src/state/index.js +11 -0
- package/src/state/sync.js +182 -0
- package/src/workflow.js +141 -29
- package/templates/instructions/commands/build.md +12 -2
- package/templates/workflow/pins.json +2 -1
- package/templates/workflow/slicekit.yml +46 -11
package/src/hooks/pre-bash.js
CHANGED
|
@@ -1,4 +1,22 @@
|
|
|
1
|
-
// pre-bash (REQ-3.2, REQ-2.1, REQ-1.2): the PreToolUse guard on Bash. Fails closed through io.js.
|
|
1
|
+
// pre-bash (REQ-3.2, REQ-2.1, REQ-1.2, REQ-3.14): the PreToolUse guard on Bash. Fails closed through io.js.
|
|
2
|
+
//
|
|
3
|
+
// This guard is a check on the developer's machine, not a control: an agent with a shell can reach git
|
|
4
|
+
// by a route it does not parse, so it can be bypassed. The control is the git host's rules on the
|
|
5
|
+
// default branch (REQ-3.14), which `slicekit check` verifies, and the agent login's lack of admin
|
|
6
|
+
// rights on the repository (D-88).
|
|
7
|
+
//
|
|
8
|
+
// Before the rules below, in every session and on every branch (D-83): (0a) a command it cannot judge:
|
|
9
|
+
// a git or gh command whose arguments hold a variable or a command substitution; `eval`, a shell's
|
|
10
|
+
// `-c` (`sh`, `bash`, `zsh`, `pwsh`, `cmd /c`, ...) or an interpreter's inline code (`node -e`,
|
|
11
|
+
// `python -c`, `perl -e`, `ruby -e`) that names git or gh; (0b) a change to the host rules from the
|
|
12
|
+
// agent's shell: `slicekit init --protect`, or a `gh api` write (a method other than GET, or a field or
|
|
13
|
+
// input flag without `-X GET`) to rulesets, rules or branch protection; (0c) a write to a test frozen
|
|
14
|
+
// for the active slice (REQ-3.3) by redirection, `tee`, `sed -i`, `cp`, `mv`, `rm`, `unlink` or
|
|
15
|
+
// `truncate`; (0d) a command naming a path that matches a pattern of `agents.denyPaths` (REQ-3.13): any
|
|
16
|
+
// argument, redirection target, option value or `<rev>:<path>` path, resolved against the shell's
|
|
17
|
+
// directory, a glob or brace expression by what it expands to, and the directory a pattern starts with
|
|
18
|
+
// (`data` for `data/**`); the directory each command runs in and each `cd`/`pushd` target are judged
|
|
19
|
+
// too, and while the list is set a `cd` it cannot resolve from the text is refused.
|
|
2
20
|
//
|
|
3
21
|
// Rules in order, first deny wins: (1) commit on a protected branch; (2) push to a protected branch;
|
|
4
22
|
// (3) any force push; (4) a commit that changes a frozen intake snapshot; (5) from a subagent: commit,
|
|
@@ -14,15 +32,16 @@
|
|
|
14
32
|
// quotes, treats here-document bodies as data, strips shell keywords, env prefixes and wrappers
|
|
15
33
|
// (command/exec/sudo/env/timeout/nice/xargs/...), follows `cd`, `pushd`, `git -C`, `git checkout` and
|
|
16
34
|
// `bash -c "..."`. A directory it cannot resolve makes a commit or push refuse rather than pass.
|
|
17
|
-
// It does not expand variables, aliases,
|
|
18
|
-
//
|
|
35
|
+
// It does not expand variables, aliases, functions or encoded payloads; where git or gh is named in
|
|
36
|
+
// what it cannot expand, rule (0a) refuses the command. Deliberate obfuscation still gets through
|
|
37
|
+
// (`$G push`, a script file that runs git); the host rules are the control.
|
|
19
38
|
// Known gaps: `--git-dir` / `GIT_DIR` pointing at another repository are not followed (the branch is
|
|
20
39
|
// read from the shell's directory); a command substitution inside double quotes (`echo "$(git ...)"`)
|
|
21
40
|
// is not split out; `echo '...' | bash` (a piped string, not a here-document) and a shell function
|
|
22
41
|
// (`function f { ...; }; f`) are not followed; the default destructive list misses `rm -fr /`
|
|
23
|
-
// spellings and absolute paths inside the worktree;
|
|
24
|
-
//
|
|
25
|
-
//
|
|
42
|
+
// spellings and absolute paths inside the worktree; SQL read from a file (`psql -f f.sql`,
|
|
43
|
+
// `cat f.sql | psql`) is not matched against the destructive list; a frozen test written by a program
|
|
44
|
+
// that names it only inside its own code (`node -e "fs.writeFileSync(...)"`) is not seen.
|
|
26
45
|
import fs from 'node:fs';
|
|
27
46
|
import os from 'node:os';
|
|
28
47
|
import path from 'node:path';
|
|
@@ -30,7 +49,7 @@ import { compileDestructive } from '../config.js';
|
|
|
30
49
|
import { git, GitError, currentBranch } from '../git.js';
|
|
31
50
|
import { kitPaths } from '../paths.js';
|
|
32
51
|
import { allow, deny } from './io.js';
|
|
33
|
-
import { fromGitBash, real, toPosix } from './paths.js';
|
|
52
|
+
import { denyDir, denyPaths, frozenTests, fromGitBash, matchesDeny, real, toPosix } from './paths.js';
|
|
34
53
|
|
|
35
54
|
// ---- tokenising ----
|
|
36
55
|
|
|
@@ -38,30 +57,54 @@ import { fromGitBash, real, toPosix } from './paths.js';
|
|
|
38
57
|
const SEPARATORS = new Set([';', '\n', '|', '&', '(', ')', '`']);
|
|
39
58
|
const DELIM_END = /[\s;&|()<>`]/;
|
|
40
59
|
|
|
41
|
-
// -> [{toks: [{v, b}], heredocs: [string], stdin?}]: one entry per simple command. `v` is the
|
|
42
|
-
// quotes removed; `b` is only its unquoted characters
|
|
43
|
-
//
|
|
60
|
+
// -> [{toks: [{v, b, x}], heredocs: [string], stdin?, subst?}]: one entry per simple command. `v` is the
|
|
61
|
+
// word with quotes removed; `b` is only its unquoted characters; `x` is the characters the shell expands
|
|
62
|
+
// (`v` without single-quoted or backslash-escaped text). Here-document bodies are data, attached to the
|
|
63
|
+
// command that opened them; `stdin` is the command piped into this one; `subst` marks a command that
|
|
64
|
+
// an unquoted backtick substitution interrupts (its output becomes this command's next argument).
|
|
44
65
|
function lex(command) {
|
|
45
66
|
const s = String(command);
|
|
46
67
|
const out = [];
|
|
47
|
-
|
|
68
|
+
// `depth` counts the unquoted subshell parentheses a segment sits in.
|
|
69
|
+
let depth = 0;
|
|
70
|
+
let cur = { toks: [], heredocs: [], depth };
|
|
48
71
|
let word = null;
|
|
49
72
|
let bare = '';
|
|
73
|
+
let expand = '';
|
|
50
74
|
let pending = [];
|
|
51
|
-
|
|
75
|
+
let tickOpen = false;
|
|
76
|
+
// `m` is one character per character of the word: `1` where it was quoted or escaped, `0` where
|
|
77
|
+
// the shell reads it as syntax (a brace expression's braces and commas count only there).
|
|
78
|
+
let mask = '';
|
|
79
|
+
// Open `case` commands: in each, whether the next `)` ends a pattern rather than a subshell.
|
|
80
|
+
const cases = [];
|
|
81
|
+
const add = (text, quoted, expands = !quoted) => {
|
|
52
82
|
word = (word ?? '') + text;
|
|
53
83
|
if (!quoted) bare += text;
|
|
84
|
+
if (expands) expand += text;
|
|
85
|
+
mask += (quoted || !expands ? '1' : '0').repeat(text.length);
|
|
54
86
|
};
|
|
55
87
|
const endWord = () => {
|
|
56
|
-
if (word !== null)
|
|
88
|
+
if (word !== null) {
|
|
89
|
+
const plain = word === bare && !mask.includes('1');
|
|
90
|
+
// A command starts at a segment's first word or after the reserved words that open a
|
|
91
|
+
// construct: `then case ...`, `do case ...`, `{ case ...`, `! case ...`.
|
|
92
|
+
const atStart = cur.toks.every((t) => t.v === t.b && !t.m?.includes('1') && KEYWORDS.has(t.v));
|
|
93
|
+
if (plain && atStart && word === 'case') cases.push({ pattern: false, awaitIn: true });
|
|
94
|
+
else if (plain && atStart && word === 'esac' && cases.length) cases.pop();
|
|
95
|
+
else if (plain && word === 'in' && cases.at(-1)?.awaitIn) Object.assign(cases.at(-1), { awaitIn: false, pattern: true });
|
|
96
|
+
cur.toks.push({ v: word, b: bare, x: expand, m: mask });
|
|
97
|
+
}
|
|
57
98
|
word = null;
|
|
58
99
|
bare = '';
|
|
100
|
+
expand = '';
|
|
101
|
+
mask = '';
|
|
59
102
|
};
|
|
60
103
|
const endSegment = () => {
|
|
61
104
|
endWord();
|
|
62
105
|
const ended = cur;
|
|
63
106
|
if (cur.toks.length) out.push(cur);
|
|
64
|
-
cur = { toks: [], heredocs: [] };
|
|
107
|
+
cur = { toks: [], heredocs: [], depth };
|
|
65
108
|
return ended;
|
|
66
109
|
};
|
|
67
110
|
let i = 0;
|
|
@@ -70,7 +113,7 @@ function lex(command) {
|
|
|
70
113
|
if (c === "'") {
|
|
71
114
|
const j = s.indexOf("'", i + 1);
|
|
72
115
|
const end = j === -1 ? s.length : j;
|
|
73
|
-
add(s.slice(i + 1, end), true);
|
|
116
|
+
add(s.slice(i + 1, end), true, false);
|
|
74
117
|
i = end + 1;
|
|
75
118
|
} else if (c === '"') {
|
|
76
119
|
let j = i + 1;
|
|
@@ -84,10 +127,10 @@ function lex(command) {
|
|
|
84
127
|
j += 1;
|
|
85
128
|
}
|
|
86
129
|
}
|
|
87
|
-
add(buf, true);
|
|
130
|
+
add(buf, true, true);
|
|
88
131
|
i = j + 1;
|
|
89
132
|
} else if (c === '\\') {
|
|
90
|
-
if (i + 1 < s.length && s[i + 1] !== '\n') add(s[i + 1], false);
|
|
133
|
+
if (i + 1 < s.length && s[i + 1] !== '\n') add(s[i + 1], false, false);
|
|
91
134
|
i += 2;
|
|
92
135
|
} else if (c === '<' && s[i + 1] === '<' && s[i + 2] === '<') {
|
|
93
136
|
// A here-string: a redirect, its operand is the next word.
|
|
@@ -135,7 +178,24 @@ function lex(command) {
|
|
|
135
178
|
endWord();
|
|
136
179
|
i += 1;
|
|
137
180
|
} else if (SEPARATORS.has(c)) {
|
|
181
|
+
if (c === '`') {
|
|
182
|
+
if (!tickOpen) cur.subst = true;
|
|
183
|
+
tickOpen = !tickOpen;
|
|
184
|
+
}
|
|
138
185
|
const ended = endSegment();
|
|
186
|
+
const open = cases.at(-1);
|
|
187
|
+
if (open?.pattern && (c === '(' || c === ')')) {
|
|
188
|
+
// A case pattern's parentheses: `a)` and the optional `(a)`; no subshell starts or ends.
|
|
189
|
+
if (c === ')') open.pattern = false;
|
|
190
|
+
} else if (c === '(' || c === ')') {
|
|
191
|
+
depth = c === '(' ? depth + 1 : Math.max(0, depth - 1);
|
|
192
|
+
cur.depth = depth;
|
|
193
|
+
}
|
|
194
|
+
// `;;` (and `;&`, `;;&`) ends a case arm: the next `)` ends a pattern again.
|
|
195
|
+
if (c === ';' && open && (s[i + 1] === ';' || s[i + 1] === '&')) {
|
|
196
|
+
open.pattern = true;
|
|
197
|
+
i += s[i + 2] === '&' ? 2 : 1;
|
|
198
|
+
}
|
|
139
199
|
if (c === '|' && s[i + 1] === '|') i += 1;
|
|
140
200
|
else if (c === '|') cur.stdin = ended;
|
|
141
201
|
i += 1;
|
|
@@ -156,6 +216,11 @@ function lex(command) {
|
|
|
156
216
|
}
|
|
157
217
|
} else if (c === '#' && word === null) {
|
|
158
218
|
while (i < s.length && s[i] !== '\n') i += 1;
|
|
219
|
+
} else if (c === '>' && word !== null && !(word === bare && /^\d*>?$/.test(word))) {
|
|
220
|
+
// `x>f` is the word `x` and the redirect `>f`, as the shell reads it; `2>f` and `>>f` stay one word.
|
|
221
|
+
endWord();
|
|
222
|
+
add(c, false);
|
|
223
|
+
i += 1;
|
|
159
224
|
} else {
|
|
160
225
|
add(c, false);
|
|
161
226
|
i += 1;
|
|
@@ -398,29 +463,176 @@ function parseSwitch(sub, args) {
|
|
|
398
463
|
// From a subagent, every gh pr subcommand but these is a write.
|
|
399
464
|
const PR_READS = new Set(['view', 'list', 'status', 'checks', 'diff']);
|
|
400
465
|
|
|
466
|
+
// gh api flags that send a request body: without an explicit method they make the request a POST.
|
|
467
|
+
const GH_API_BODY = new Set(['-f', '-F', '--field', '--raw-field', '--input']);
|
|
468
|
+
// gh api flags that take a separate value.
|
|
469
|
+
const GH_API_VALUE = new Set(['-H', '--header', '-q', '--jq', '-t', '--template', '--hostname', '--cache', '-p', '--preview']);
|
|
470
|
+
|
|
471
|
+
// `gh api` from index k: {method, endpoint}. The method is the explicit one, else POST when a field or
|
|
472
|
+
// input flag is given, else GET.
|
|
473
|
+
function parseGhApi(w, k) {
|
|
474
|
+
let method = null;
|
|
475
|
+
let body = false;
|
|
476
|
+
let endpoint = null;
|
|
477
|
+
for (let j = k; j < w.length; j++) {
|
|
478
|
+
const a = w[j];
|
|
479
|
+
if (a === '-X' || a === '--method') {
|
|
480
|
+
if (w[j + 1] !== undefined) method = w[j + 1];
|
|
481
|
+
j += 1;
|
|
482
|
+
} else if (a.startsWith('--method=')) {
|
|
483
|
+
method = a.slice('--method='.length);
|
|
484
|
+
} else if (/^-X./.test(a)) {
|
|
485
|
+
method = a.slice(2);
|
|
486
|
+
} else if (GH_API_BODY.has(a)) {
|
|
487
|
+
body = true;
|
|
488
|
+
j += 1;
|
|
489
|
+
} else if (GH_API_BODY.has(a.startsWith('--') ? a.split('=')[0] : a.slice(0, 2))) {
|
|
490
|
+
body = true;
|
|
491
|
+
} else if (GH_API_VALUE.has(a)) {
|
|
492
|
+
j += 1;
|
|
493
|
+
} else if (!a.startsWith('-') && endpoint === null) {
|
|
494
|
+
endpoint = a;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
return { method: (method ?? (body ? 'POST' : 'GET')).toUpperCase(), endpoint };
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// A repository's (or organisation's) rulesets and rules, or a branch's protection.
|
|
501
|
+
const HOST_RULES_PATH = /^\/?(?:(?:repos\/[^/]+\/[^/]+|orgs\/[^/]+|enterprises\/[^/]+)\/(?:rulesets|rules)|repos\/[^/]+\/[^/]+\/branches\/.+\/protection)(?:[/?]|$)/;
|
|
502
|
+
|
|
503
|
+
// gh's command group and the index after it.
|
|
504
|
+
function ghGroup(w) {
|
|
505
|
+
let k = 1;
|
|
506
|
+
while (k < w.length && w[k].startsWith('-')) k += w[k] === '-R' || w[k] === '--repo' ? 2 : 1;
|
|
507
|
+
return { group: w[k], k: k + 1 };
|
|
508
|
+
}
|
|
509
|
+
|
|
401
510
|
// gh pr <sub> that writes -> 'pr'; gh api with a method other than GET -> 'api-write'; else null.
|
|
402
511
|
function classifyGh(w) {
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
while (k < w.length && w[k].startsWith('-')) k += w[k] === '-R' || w[k] === '--repo' ? 2 : 1;
|
|
406
|
-
};
|
|
407
|
-
skipFlags();
|
|
408
|
-
const group = w[k];
|
|
409
|
-
k += 1;
|
|
512
|
+
const { group, k: after } = ghGroup(w);
|
|
513
|
+
let k = after;
|
|
410
514
|
if (group === 'pr') {
|
|
411
|
-
|
|
515
|
+
while (k < w.length && w[k].startsWith('-')) k += w[k] === '-R' || w[k] === '--repo' ? 2 : 1;
|
|
412
516
|
return w[k] !== undefined && !PR_READS.has(w[k]) ? 'pr' : null;
|
|
413
517
|
}
|
|
414
|
-
if (group === 'api')
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
518
|
+
if (group === 'api') return parseGhApi(w, k).method === 'GET' ? null : 'api-write';
|
|
519
|
+
return null;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// -> a description of a write to the host's rules (REQ-3.14), or null.
|
|
523
|
+
function hostRulesChange(w) {
|
|
524
|
+
const head = base(w[0]);
|
|
525
|
+
if (head === 'gh') {
|
|
526
|
+
const { group, k } = ghGroup(w);
|
|
527
|
+
if (group !== 'api') return null;
|
|
528
|
+
const { method, endpoint } = parseGhApi(w, k);
|
|
529
|
+
return method !== 'GET' && endpoint !== null && HOST_RULES_PATH.test(endpoint) ? `gh api ${method} ${endpoint}` : null;
|
|
530
|
+
}
|
|
531
|
+
const i = w.findIndex((x, idx) => idx <= 3 && /^slicekit(\.[cm]?js)?$/.test(base(x)));
|
|
532
|
+
if (i === -1) return null;
|
|
533
|
+
const rest = w.slice(i + 1);
|
|
534
|
+
return rest.includes('init') && rest.some((a) => a === '--protect' || a.startsWith('--protect='))
|
|
535
|
+
? 'slicekit init --protect'
|
|
536
|
+
: null;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// ---- rule 0a: commands the guard cannot judge ----
|
|
540
|
+
|
|
541
|
+
// A git or gh word in code or a command string; `.git`, `github` and `git-lfs` are not.
|
|
542
|
+
const NAMES_GIT = /(?:^|[^A-Za-z0-9_.-])(?:git|gh)(?:[^A-Za-z0-9_-]|$)/;
|
|
543
|
+
const OTHER_SHELLS = new Set(['pwsh', 'powershell', 'cmd']);
|
|
544
|
+
|
|
545
|
+
// The inline code an interpreter runs, or undefined.
|
|
546
|
+
function inlineCode(head, w) {
|
|
547
|
+
let flag;
|
|
548
|
+
if (head === 'node' || head === 'nodejs' || head === 'bun') flag = (a) => /^-[ep]+$/.test(a) || a === '--eval' || a === '--print';
|
|
549
|
+
else if (/^python[0-9.]*$/.test(head) || head === 'py') flag = (a) => /^-[A-Za-z]*c$/.test(a);
|
|
550
|
+
else if (head === 'perl' || head === 'ruby') flag = (a) => /^-[A-Za-z]*[eE]$/.test(a);
|
|
551
|
+
else return undefined;
|
|
552
|
+
for (let k = 1; k < w.length; k++) {
|
|
553
|
+
if (/^--(eval|print)=/.test(w[k]) && (head === 'node' || head === 'nodejs' || head === 'bun')) return w[k].slice(w[k].indexOf('=') + 1);
|
|
554
|
+
if (flag(w[k])) return w[k + 1];
|
|
555
|
+
}
|
|
556
|
+
return undefined;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// -> why the command cannot be judged, or null. `toks` has prefixes stripped.
|
|
560
|
+
function unjudgeable(seg, toks, w, head) {
|
|
561
|
+
if (head === 'git' || head === 'gh') {
|
|
562
|
+
if (seg.subst || toks.slice(1).some((t) => /[$`]/.test(t.x ?? ''))) {
|
|
563
|
+
return `${head} takes an argument from a variable or a command substitution`;
|
|
420
564
|
}
|
|
421
|
-
return
|
|
565
|
+
return null;
|
|
422
566
|
}
|
|
423
|
-
return null;
|
|
567
|
+
if (head === 'eval') return NAMES_GIT.test(w.slice(1).join(' ')) ? 'eval runs a command that names git or gh' : null;
|
|
568
|
+
if (SHELLS.has(head)) {
|
|
569
|
+
const k = w.findIndex((x, idx) => idx > 0 && /^-[A-Za-z]*c[A-Za-z]*$/.test(x));
|
|
570
|
+
return k !== -1 && NAMES_GIT.test(w[k + 1] ?? '') ? `${head} -c runs a command string that names git or gh` : null;
|
|
571
|
+
}
|
|
572
|
+
if (OTHER_SHELLS.has(head)) {
|
|
573
|
+
const k = w.findIndex((x, idx) => idx > 0 && /^[-/](c|k|command|encodedcommand|ec)$/i.test(x));
|
|
574
|
+
if (k === -1) return null;
|
|
575
|
+
if (/^[-/](encodedcommand|ec)$/i.test(w[k])) return `${head} runs an encoded command`;
|
|
576
|
+
return NAMES_GIT.test(w.slice(k + 1).join(' ')) ? `${head} ${w[k]} runs a command string that names git or gh` : null;
|
|
577
|
+
}
|
|
578
|
+
const code = inlineCode(head, w);
|
|
579
|
+
return code !== undefined && NAMES_GIT.test(code) ? `${head}'s inline code names git or gh` : null;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// ---- rule 0c: what a command writes ----
|
|
583
|
+
|
|
584
|
+
// Redirection targets in the raw tokens: `> f`, `>>f`, `2> f`, `>| f`; not `>&2`.
|
|
585
|
+
function redirectTargets(toks) {
|
|
586
|
+
const out = [];
|
|
587
|
+
for (let k = 0; k < toks.length; k++) {
|
|
588
|
+
const m = /^\d*(>>|>\||>&|>)/.exec(toks[k].v);
|
|
589
|
+
if (!m || !toks[k].b.startsWith(m[0])) continue;
|
|
590
|
+
const target = toks[k].v === m[0] ? toks[k + 1]?.v : toks[k].v.slice(m[0].length);
|
|
591
|
+
if (toks[k].v === m[0]) k += 1;
|
|
592
|
+
if (target === undefined || (m[1] === '>&' && /^(\d+-?|-)$/.test(target))) continue;
|
|
593
|
+
out.push(target);
|
|
594
|
+
}
|
|
595
|
+
return out;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
// Non-option arguments, skipping the values of the options in `valued`.
|
|
599
|
+
function positionals(args, valued = new Set()) {
|
|
600
|
+
const out = [];
|
|
601
|
+
let endOpts = false;
|
|
602
|
+
for (let k = 0; k < args.length; k++) {
|
|
603
|
+
const a = args[k];
|
|
604
|
+
if (!endOpts && a === '--') endOpts = true;
|
|
605
|
+
else if (!endOpts && a.startsWith('-') && a !== '-') {
|
|
606
|
+
if (valued.has(a)) k += 1;
|
|
607
|
+
} else out.push(a);
|
|
608
|
+
}
|
|
609
|
+
return out;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
// -> [{word, removes?, into?}]: the paths a simple command writes. `removes` also covers a directory
|
|
613
|
+
// holding the file; `into` lists source names for a destination that may be a directory.
|
|
614
|
+
function writeTargets(seg, w, head) {
|
|
615
|
+
const out = redirectTargets(seg.toks).map((word) => ({ word }));
|
|
616
|
+
const args = w.slice(1);
|
|
617
|
+
if (head === 'tee') {
|
|
618
|
+
for (const word of positionals(args)) out.push({ word });
|
|
619
|
+
} else if (head === 'sed' && args.some((a) => /^-[A-Za-z]*i/.test(a) || a.startsWith('--in-place'))) {
|
|
620
|
+
for (const word of positionals(args, new Set(['-e', '-f', '--expression', '--file', '-l', '--line-length']))) out.push({ word });
|
|
621
|
+
} else if (head === 'cp' || head === 'mv') {
|
|
622
|
+
let target = args.find((a, k) => args[k - 1] === '-t' || args[k - 1] === '--target-directory');
|
|
623
|
+
const long = args.find((a) => a.startsWith('--target-directory='));
|
|
624
|
+
if (long) target = long.slice('--target-directory='.length);
|
|
625
|
+
const pos = positionals(args, new Set(['-t', '--target-directory', '-S', '--suffix']));
|
|
626
|
+
const sources = target === undefined ? pos.slice(0, -1) : pos;
|
|
627
|
+
const dest = target ?? pos.at(-1);
|
|
628
|
+
if (dest !== undefined) out.push({ word: dest, into: sources });
|
|
629
|
+
if (head === 'mv') for (const word of sources) out.push({ word, removes: true });
|
|
630
|
+
} else if (head === 'rm' || head === 'unlink') {
|
|
631
|
+
for (const word of positionals(args)) out.push({ word, removes: true });
|
|
632
|
+
} else if (head === 'truncate') {
|
|
633
|
+
for (const word of positionals(args, new Set(['-s', '--size', '-r', '--reference']))) out.push({ word });
|
|
634
|
+
}
|
|
635
|
+
return out;
|
|
424
636
|
}
|
|
425
637
|
|
|
426
638
|
// ---- rule 6: the text a destructive pattern is matched against ----
|
|
@@ -470,18 +682,56 @@ const tagLists = (args) => args.length === 0 || args.some((a) => a === '-l' || a
|
|
|
470
682
|
// One simple command -> invocations {kind, dir, label, ...}; `state` carries cd/pushd forward.
|
|
471
683
|
function walk(seg, state, acc) {
|
|
472
684
|
const toks = stripPrefixes(seg.toks);
|
|
473
|
-
|
|
685
|
+
// The directory a command runs in is judged too (rule 0d): `cd data && ls` reads data.
|
|
686
|
+
if (toks.length && state.cwd !== null) acc.named.push({ word: state.cwd, dir: null, isDir: true });
|
|
687
|
+
for (const n of namedWords(seg.toks, toks[0])) acc.named.push({ ...n, dir: state.cwd, globstar: !!state.globstar });
|
|
688
|
+
if (!toks.length) {
|
|
689
|
+
for (const word of redirectTargets(seg.toks)) acc.writes.push({ dir: state.cwd, word });
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
474
692
|
const w = toks.map((t) => t.v);
|
|
475
693
|
const text = destructiveText(toks, seg.heredocs);
|
|
476
694
|
if (text !== null) acc.texts.push(text);
|
|
477
695
|
const head = base(w[0]);
|
|
696
|
+
const why = unjudgeable(seg, toks, w, head);
|
|
697
|
+
if (why && acc.unjudgeable === null) acc.unjudgeable = why;
|
|
698
|
+
const host = hostRulesChange(w);
|
|
699
|
+
if (host && acc.hostRules === null) acc.hostRules = host;
|
|
700
|
+
for (const t of writeTargets(seg, w, head)) acc.writes.push({ ...t, dir: state.cwd });
|
|
478
701
|
const ownCommit = head === 'git' && w[gitSubIndex(w)] === 'commit';
|
|
479
702
|
if (state.cwd !== null && !MENTION_READERS.has(head) && !ownCommit) {
|
|
480
703
|
for (const x of w.slice(1)) if (!x.startsWith('-') && !/[$`]/.test(x)) acc.mentions.push({ dir: state.cwd, word: x });
|
|
481
704
|
}
|
|
482
705
|
const b = base(w[0]);
|
|
706
|
+
// `shopt -s globstar` makes a later `**` recursive, `shopt -u globstar` ends it; a subshell's
|
|
707
|
+
// setting ends with it.
|
|
708
|
+
if (b === 'shopt') {
|
|
709
|
+
const flags = w.slice(1).filter((x) => /^-[a-z]+$/.test(x)).join('');
|
|
710
|
+
const set = flags.includes('s') ? true : flags.includes('u') ? false : null;
|
|
711
|
+
if (set !== null && w.slice(1).includes('globstar')) state.globstar = set;
|
|
712
|
+
return;
|
|
713
|
+
}
|
|
483
714
|
if (b === 'cd' || b === 'pushd') {
|
|
484
|
-
const
|
|
715
|
+
const at = toks.findIndex((t, k) => k > 0 && (!t.v.startsWith('-') || t.v === '-'));
|
|
716
|
+
const target = at === -1 ? undefined : toks[at].v;
|
|
717
|
+
// Rule 0d judges where the cd goes, whether or not the directory exists yet; a target it
|
|
718
|
+
// cannot resolve from the text is recorded, and refused while agents.denyPaths is set.
|
|
719
|
+
const unknown = (label) => {
|
|
720
|
+
if (acc.cdUnknown === null) acc.cdUnknown = label;
|
|
721
|
+
};
|
|
722
|
+
// An unquoted backtick ends the segment in the lexer, so the real target, the substitution's
|
|
723
|
+
// output, is not among `toks`: `cd `echo data`` would otherwise read as a cd with no target.
|
|
724
|
+
if (seg.subst) unknown(`${b} \`...\``);
|
|
725
|
+
if (target === undefined) {
|
|
726
|
+
if (b === 'cd') acc.named.push({ word: os.homedir(), dir: null, isDir: true });
|
|
727
|
+
else unknown('pushd');
|
|
728
|
+
} else if (target === '-' || /[$`]/.test(toks[at].x ?? target) || (target.startsWith('~') && !/^~(\/|$)/.test(target))) {
|
|
729
|
+
unknown(`${b} ${target}`);
|
|
730
|
+
} else {
|
|
731
|
+
const t = fromGitBash((target === '~' || target.startsWith('~/') ? os.homedir() + target.slice(1) : target).replace(/\\/g, '/'));
|
|
732
|
+
if (state.cwd === null && !path.isAbsolute(t)) unknown(`${b} ${target}`);
|
|
733
|
+
else acc.named.push({ word: path.resolve(state.cwd ?? '', t), dir: null, isDir: true });
|
|
734
|
+
}
|
|
485
735
|
if (b === 'pushd') state.stack.push({ cwd: state.cwd, label: state.label });
|
|
486
736
|
if (target === undefined) {
|
|
487
737
|
state.cwd = b === 'cd' ? os.homedir() : null;
|
|
@@ -497,6 +747,7 @@ function walk(seg, state, acc) {
|
|
|
497
747
|
}
|
|
498
748
|
if (b === 'popd') {
|
|
499
749
|
const prev = state.stack.pop();
|
|
750
|
+
if (!prev && acc.cdUnknown === null) acc.cdUnknown = 'popd';
|
|
500
751
|
state.cwd = prev ? prev.cwd : null;
|
|
501
752
|
state.label = prev ? prev.label : 'popd';
|
|
502
753
|
return;
|
|
@@ -507,10 +758,16 @@ function walk(seg, state, acc) {
|
|
|
507
758
|
if (k !== -1 && w[k + 1] !== undefined) bodies = [w[k + 1]];
|
|
508
759
|
else if (seg.heredocs.length) bodies = seg.heredocs;
|
|
509
760
|
else bodies = seg.stdin ? seg.stdin.heredocs : [];
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
761
|
+
// A new shell starts with globstar off, unless its own options turn it on: `-O globstar`,
|
|
762
|
+
// `-Oglobstar`; `+O globstar` turns it off; the last one before the body wins.
|
|
763
|
+
let globstar = false;
|
|
764
|
+
for (let j = 1; j < (k === -1 ? w.length : k); j++) {
|
|
765
|
+
const opt = /^([-+])O(.*)$/.exec(w[j]);
|
|
766
|
+
if (!opt) continue;
|
|
767
|
+
const name = opt[2] === '' ? w[++j] : opt[2];
|
|
768
|
+
if (name === 'globstar') globstar = opt[1] === '-';
|
|
513
769
|
}
|
|
770
|
+
for (const body of bodies) walkAll(lex(body), { cwd: state.cwd, label: state.label, stack: [], globstar }, acc);
|
|
514
771
|
return;
|
|
515
772
|
}
|
|
516
773
|
if (b === 'gh') {
|
|
@@ -553,15 +810,27 @@ function walk(seg, state, acc) {
|
|
|
553
810
|
acc.invs.push({ ...inv, dir, label: dir === null ? label : (label ?? dir) });
|
|
554
811
|
}
|
|
555
812
|
|
|
556
|
-
// -> {invs, texts, mentions}: every git/gh invocation in order,
|
|
813
|
+
// -> {invs, texts, mentions, writes, unjudgeable, hostRules}: every git/gh invocation in order, each
|
|
814
|
+
// command's text for rule 6, the paths written (rule 0c), and the first reason for rules 0a and 0b.
|
|
557
815
|
// cwd null means unknown.
|
|
558
816
|
function parse(command, cwd) {
|
|
559
|
-
const acc = { invs: [], texts: [], mentions: [] };
|
|
560
|
-
|
|
561
|
-
for (const seg of lex(command)) walk(seg, state, acc);
|
|
817
|
+
const acc = { invs: [], texts: [], mentions: [], writes: [], named: [], unjudgeable: null, hostRules: null, cdUnknown: null };
|
|
818
|
+
walkAll(lex(command), { cwd, label: cwd, stack: [] }, acc);
|
|
562
819
|
return acc;
|
|
563
820
|
}
|
|
564
821
|
|
|
822
|
+
// Walks segments in order; a `cd` inside a subshell `( ... )` ends with it, so the directory is put
|
|
823
|
+
// back when the segments leave the parentheses.
|
|
824
|
+
function walkAll(segs, state, acc) {
|
|
825
|
+
const saved = [];
|
|
826
|
+
for (const seg of segs) {
|
|
827
|
+
const depth = seg.depth ?? 0;
|
|
828
|
+
while (saved.length < depth) saved.push({ cwd: state.cwd, label: state.label, stack: [...state.stack], globstar: state.globstar });
|
|
829
|
+
while (saved.length > depth) Object.assign(state, saved.pop());
|
|
830
|
+
walk(seg, state, acc);
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
|
|
565
834
|
export const invocations = (command, cwd = process.cwd()) => parse(command, cwd).invs;
|
|
566
835
|
|
|
567
836
|
// -> {kind: 'commit'|'push'|'force-push'|'pr'|'other', branchArg?} for the first such invocation.
|
|
@@ -654,6 +923,313 @@ function frozenIntake(root, cfg, invs, mentions) {
|
|
|
654
923
|
return null;
|
|
655
924
|
}
|
|
656
925
|
|
|
926
|
+
// ---- rule 0c: writes to frozen tests ----
|
|
927
|
+
|
|
928
|
+
const WIN = process.platform === 'win32';
|
|
929
|
+
const fkey = (p) => (WIN ? p.toLowerCase() : p);
|
|
930
|
+
const GLOB = /[*?[]/;
|
|
931
|
+
|
|
932
|
+
// A shell glob over POSIX paths as an anchored regular expression (`*` and `?` stay in one segment;
|
|
933
|
+
// `[!...]` and `[^...]` are both a negated class, as Bash reads them).
|
|
934
|
+
function globRe(pattern) {
|
|
935
|
+
const src = pattern.replace(/[.+^${}()|\\]/g, '\\$&').replace(/\[(?:!|\\\^)/g, '[^').replace(/\*/g, '[^/]*').replace(/\?/g, '[^/]');
|
|
936
|
+
return new RegExp(`^${src}$`, WIN ? 'i' : '');
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
// Whether a write {dir, word, removes?, into?} reaches the frozen file at absolute POSIX path `frozen`.
|
|
940
|
+
function reaches(wr, frozen) {
|
|
941
|
+
const word = fromGitBash(String(wr.word).replace(/\\/g, '/'));
|
|
942
|
+
if (word === '') return false;
|
|
943
|
+
if (/[$`]/.test(word) || (wr.dir === null && !path.isAbsolute(word))) {
|
|
944
|
+
// The directory or the name is unknown: judge by the last segment.
|
|
945
|
+
const last = word.split('/').pop();
|
|
946
|
+
return !/[$`]/.test(last) && (GLOB.test(last) ? globRe(last).test(path.posix.basename(frozen))
|
|
947
|
+
: fkey(last) === fkey(path.posix.basename(frozen)));
|
|
948
|
+
}
|
|
949
|
+
const target = toPosix(path.resolve(wr.dir === null ? '' : real(wr.dir), word));
|
|
950
|
+
if (GLOB.test(word)) {
|
|
951
|
+
const re = globRe(target);
|
|
952
|
+
return re.test(frozen) || (wr.removes === true && frozen.split('/').some((_, k, all) => re.test(all.slice(0, k).join('/'))));
|
|
953
|
+
}
|
|
954
|
+
const canon = toPosix(real(target));
|
|
955
|
+
if (fkey(canon) === fkey(frozen)) return true;
|
|
956
|
+
if (wr.removes && fkey(frozen).startsWith(`${fkey(canon)}/`)) return true;
|
|
957
|
+
if (wr.into?.length && fs.existsSync(canon) && fs.statSync(canon).isDirectory()) {
|
|
958
|
+
return wr.into.some((s) => fkey(`${canon}/${path.posix.basename(s.replace(/\\/g, '/'))}`) === fkey(frozen));
|
|
959
|
+
}
|
|
960
|
+
return false;
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
// -> {rel, id} for the first write that reaches a test frozen for the active slice of the hook's root
|
|
964
|
+
// or of the repository the write runs in; null for none.
|
|
965
|
+
function frozenWrite(root, cfg, writes) {
|
|
966
|
+
if (!writes.length) return null;
|
|
967
|
+
const hookTop = real(path.resolve(root));
|
|
968
|
+
const frozenAt = new Map();
|
|
969
|
+
const topAt = new Map();
|
|
970
|
+
for (const wr of writes) {
|
|
971
|
+
const tops = [hookTop];
|
|
972
|
+
if (wr.dir !== null) {
|
|
973
|
+
if (!topAt.has(wr.dir)) topAt.set(wr.dir, topOf(wr.dir));
|
|
974
|
+
const t = topAt.get(wr.dir);
|
|
975
|
+
if (t && !tops.some((x) => fkey(toPosix(x)) === fkey(toPosix(t)))) tops.push(t);
|
|
976
|
+
}
|
|
977
|
+
for (const top of tops) {
|
|
978
|
+
if (!frozenAt.has(top)) frozenAt.set(top, frozenTests(top, cfg));
|
|
979
|
+
const f = frozenAt.get(top);
|
|
980
|
+
if (!f) continue;
|
|
981
|
+
for (const rel of f.files) {
|
|
982
|
+
if (reaches(wr, toPosix(path.join(top, rel)))) return { rel, id: f.id };
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
return null;
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
// ---- rule 0d: paths agents may not touch (REQ-3.13) ----
|
|
990
|
+
|
|
991
|
+
// Every word of a simple command that may name a path, as {word, fromTop?}: the command and its
|
|
992
|
+
// arguments, a redirection's target with the operator cut off, the value of `--opt=value` or
|
|
993
|
+
// `NAME=value`, the value a short option carries attached (`-fFILE`), and the path of a
|
|
994
|
+
// `<rev>:<path>` word (`fromTop` when git reads it from the repository's top); `glob` marks a word
|
|
995
|
+
// the shell would expand. A word holding a
|
|
996
|
+
// variable or a command substitution is not judged, nor the command's name when it holds no `/` (the
|
|
997
|
+
// shell looks that up on PATH).
|
|
998
|
+
function namedWords(toks, head) {
|
|
999
|
+
const out = [];
|
|
1000
|
+
// `cd` and `pushd` read nothing; the commands after them are judged from the new directory.
|
|
1001
|
+
if (head && (base(head.v) === 'cd' || base(head.v) === 'pushd')) return out;
|
|
1002
|
+
for (const t of toks) {
|
|
1003
|
+
if (t === head && !/[/\\]/.test(t.v)) continue;
|
|
1004
|
+
if (/[$`]/.test(t.x ?? '')) continue;
|
|
1005
|
+
const cuts = [];
|
|
1006
|
+
const op = /^\d*(<<<|>>|>\||>&|<&|&>|>|<)/.exec(t.v);
|
|
1007
|
+
if (op && t.b.startsWith(op[0])) cuts.push(op[0].length);
|
|
1008
|
+
else if (/^(--[^=]+|[A-Za-z_][A-Za-z0-9_]*)=/.test(t.v)) cuts.push(t.v.indexOf('=') + 1);
|
|
1009
|
+
else if (/^-[^-]./.test(t.v)) {
|
|
1010
|
+
// Bundled short options (`tar -tfdata/x.tar`): the value may start after any option letter, so
|
|
1011
|
+
// the tail after each leading letter is judged.
|
|
1012
|
+
cuts.push(2);
|
|
1013
|
+
for (let k = 3; k < t.v.length && /[A-Za-z]/.test(t.v[k - 1]); k++) cuts.push(k);
|
|
1014
|
+
} else if (t.v.startsWith('-')) continue;
|
|
1015
|
+
else cuts.push(0);
|
|
1016
|
+
for (const cut of cuts) wordPaths(t, cut, out);
|
|
1017
|
+
}
|
|
1018
|
+
return out;
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
// Appends to `out` the paths word `t` names from character `cut` on: each word its braces expand to,
|
|
1022
|
+
// with `~` as the home directory, and the path of a `<rev>:<path>` word.
|
|
1023
|
+
function wordPaths(t, cut, out) {
|
|
1024
|
+
const v = t.v.slice(cut);
|
|
1025
|
+
if (v === '') return;
|
|
1026
|
+
const m = (t.m ?? '0'.repeat(t.v.length)).slice(cut);
|
|
1027
|
+
// An unquoted brace expression becomes each word it expands to; one too wide is refused.
|
|
1028
|
+
const variants = t.b.includes('{') && t.b.includes('}') ? expandBraces(v, m) : [v];
|
|
1029
|
+
if (variants === null) {
|
|
1030
|
+
out.push({ word: v, wide: true });
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
1033
|
+
const glob = GLOB.test(t.b);
|
|
1034
|
+
for (let w of variants) {
|
|
1035
|
+
// An unquoted `~` is the home directory; an unquoted glob character makes the word a glob.
|
|
1036
|
+
if ((w === '~' || w.startsWith('~/')) && t.b.includes('~')) w = os.homedir() + w.slice(1);
|
|
1037
|
+
out.push({ word: w, glob });
|
|
1038
|
+
// `<rev>:<path>`, `:<path>` and `:<stage>:<path>` (the index): git reads the path from the
|
|
1039
|
+
// repository's top, or from the shell's directory when it starts with `./` or `../`.
|
|
1040
|
+
const rev = /^[^:]*:(?:[0-3]:)?(.+)$/.exec(w);
|
|
1041
|
+
if (rev && !/^[A-Za-z]:[\\/]/.test(w)) {
|
|
1042
|
+
const p = rev[1];
|
|
1043
|
+
out.push({ word: p, glob, fromTop: !/^\.\.?\//.test(p) });
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
// The words a Bash brace expression expands to: `{a,b}` lists (nested too) and `{1..3}` or `{a..c}`
|
|
1049
|
+
// sequences, left to right; a `{` with no top-level `,` or `..` stays literal. `mask` marks each
|
|
1050
|
+
// character of `word` that was quoted or escaped (`1`): such a brace or comma is text, not syntax, as
|
|
1051
|
+
// Bash reads it (brace expansion runs before quotes are removed). Null when the expansion passes `cap`
|
|
1052
|
+
// words, so the caller refuses rather than judges a part.
|
|
1053
|
+
export function expandBraces(word, mask = '0'.repeat(word.length), cap = 1000) {
|
|
1054
|
+
const out = [];
|
|
1055
|
+
const stack = [[word, mask]];
|
|
1056
|
+
while (stack.length) {
|
|
1057
|
+
const [w, m] = stack.pop();
|
|
1058
|
+
const found = firstBrace(w, m);
|
|
1059
|
+
if (!found) {
|
|
1060
|
+
out.push(w);
|
|
1061
|
+
if (out.length > cap) return null;
|
|
1062
|
+
continue;
|
|
1063
|
+
}
|
|
1064
|
+
const { start, end, parts } = found;
|
|
1065
|
+
for (let k = parts.length - 1; k >= 0; k--) {
|
|
1066
|
+
stack.push([w.slice(0, start) + parts[k][0] + w.slice(end + 1), m.slice(0, start) + parts[k][1] + m.slice(end + 1)]);
|
|
1067
|
+
}
|
|
1068
|
+
if (stack.length + out.length > cap) return null;
|
|
1069
|
+
}
|
|
1070
|
+
return out;
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
// -> {start, end, parts: [[text, mask]]} for the first brace pair in w that expands, or null. Only
|
|
1074
|
+
// characters the mask leaves unquoted count as `{`, `,` and `}`; an unclosed `{` is skipped and a
|
|
1075
|
+
// later one tried.
|
|
1076
|
+
function firstBrace(w, m) {
|
|
1077
|
+
const syntax = (j, c) => w[j] === c && m[j] !== '1';
|
|
1078
|
+
for (let i = 0; i < w.length; i++) {
|
|
1079
|
+
if (!syntax(i, '{')) continue;
|
|
1080
|
+
let depth = 0;
|
|
1081
|
+
const commas = [];
|
|
1082
|
+
let end = -1;
|
|
1083
|
+
for (let j = i; j < w.length; j++) {
|
|
1084
|
+
if (syntax(j, '{')) depth += 1;
|
|
1085
|
+
else if (syntax(j, '}')) {
|
|
1086
|
+
depth -= 1;
|
|
1087
|
+
if (depth === 0) {
|
|
1088
|
+
end = j;
|
|
1089
|
+
break;
|
|
1090
|
+
}
|
|
1091
|
+
} else if (syntax(j, ',') && depth === 1) commas.push(j);
|
|
1092
|
+
}
|
|
1093
|
+
if (end === -1) continue;
|
|
1094
|
+
if (commas.length) {
|
|
1095
|
+
const parts = [];
|
|
1096
|
+
let from = i + 1;
|
|
1097
|
+
for (const c of [...commas, end]) {
|
|
1098
|
+
parts.push([w.slice(from, c), m.slice(from, c)]);
|
|
1099
|
+
from = c + 1;
|
|
1100
|
+
}
|
|
1101
|
+
return { start: i, end, parts };
|
|
1102
|
+
}
|
|
1103
|
+
const body = w.slice(i + 1, end);
|
|
1104
|
+
const seq = m.slice(i + 1, end).includes('1') ? null : /^(-?\d+|[A-Za-z])\.\.(-?\d+|[A-Za-z])$/.exec(body);
|
|
1105
|
+
if (seq) {
|
|
1106
|
+
const num = /^-?\d+$/.test(seq[1]) && /^-?\d+$/.test(seq[2]);
|
|
1107
|
+
if (num || (!/\d/.test(seq[1]) && !/\d/.test(seq[2]))) {
|
|
1108
|
+
const a = num ? Number(seq[1]) : seq[1].charCodeAt(0);
|
|
1109
|
+
const b = num ? Number(seq[2]) : seq[2].charCodeAt(0);
|
|
1110
|
+
if (Math.abs(b - a) > 100000) return { start: i, end, parts: new Array(100001).fill(['', '']) };
|
|
1111
|
+
const parts = [];
|
|
1112
|
+
for (let n = a; a <= b ? n <= b : n >= b; n += a <= b ? 1 : -1) {
|
|
1113
|
+
const text = num ? String(n) : String.fromCharCode(n);
|
|
1114
|
+
parts.push([text, '0'.repeat(text.length)]);
|
|
1115
|
+
}
|
|
1116
|
+
return { start: i, end, parts };
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
// Not an expansion: look for a later `{`, past this one.
|
|
1120
|
+
}
|
|
1121
|
+
return null;
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
// The existing paths a shell glob word expands to, segment by segment from `base` (`*`, `?` and `[...]`
|
|
1125
|
+
// in one segment; `**` as `*`, as Bash reads it by default); a segment starting with `.` alone matches
|
|
1126
|
+
// dot names. With `globstar` (the command ran `shopt -s globstar` first), a segment that is only `**`
|
|
1127
|
+
// is the directory itself and everything under it, at any depth (dot names and symlinked directories
|
|
1128
|
+
// aside). Null when a segment expands to more than `cap` entries, so the caller fails closed instead of
|
|
1129
|
+
// judging a part.
|
|
1130
|
+
function expandGlob(base, word, globstar = false, cap = 20000) {
|
|
1131
|
+
const target = toPosix(path.resolve(base, word));
|
|
1132
|
+
const segs = target.split('/');
|
|
1133
|
+
let found = [segs[0] === '' ? '/' : `${segs[0]}/`];
|
|
1134
|
+
for (const seg of segs.slice(1)) {
|
|
1135
|
+
if (seg === '') continue;
|
|
1136
|
+
const next = [];
|
|
1137
|
+
if (globstar && /^\*\*+$/.test(seg)) {
|
|
1138
|
+
const stack = [...found];
|
|
1139
|
+
while (stack.length) {
|
|
1140
|
+
const d = stack.pop();
|
|
1141
|
+
next.push(d);
|
|
1142
|
+
if (next.length > cap) return null;
|
|
1143
|
+
let entries = [];
|
|
1144
|
+
try {
|
|
1145
|
+
entries = fs.readdirSync(d, { withFileTypes: true });
|
|
1146
|
+
} catch {
|
|
1147
|
+
continue;
|
|
1148
|
+
}
|
|
1149
|
+
for (const e of entries) {
|
|
1150
|
+
if (e.name.startsWith('.')) continue;
|
|
1151
|
+
const p = path.posix.join(d, e.name);
|
|
1152
|
+
if (e.isDirectory()) stack.push(p);
|
|
1153
|
+
else next.push(p);
|
|
1154
|
+
if (next.length + stack.length > cap) return null;
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
} else if (!GLOB.test(seg)) {
|
|
1158
|
+
for (const d of found) next.push(path.posix.join(d, seg));
|
|
1159
|
+
} else {
|
|
1160
|
+
const re = globRe(seg.replace(/\*\*+/g, '*'));
|
|
1161
|
+
for (const d of found) {
|
|
1162
|
+
let names = [];
|
|
1163
|
+
try {
|
|
1164
|
+
names = fs.readdirSync(d);
|
|
1165
|
+
} catch {
|
|
1166
|
+
continue;
|
|
1167
|
+
}
|
|
1168
|
+
for (const n of names) {
|
|
1169
|
+
if (n.startsWith('.') && !seg.startsWith('.')) continue;
|
|
1170
|
+
if (re.test(n)) next.push(path.posix.join(d, n));
|
|
1171
|
+
if (next.length > cap) return null;
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
found = next;
|
|
1176
|
+
if (!found.length) return [];
|
|
1177
|
+
}
|
|
1178
|
+
return found.filter((p) => fs.existsSync(p));
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
// -> {rel, pattern} for the first named word that resolves, inside the hook's root or the repository
|
|
1182
|
+
// the word is named in, to a path matching agents.denyPaths, or to the directory a pattern names
|
|
1183
|
+
// (`data` for `data/**`); a glob word is judged by what it expands to. Null for none.
|
|
1184
|
+
function deniedPath(root, cfg, named) {
|
|
1185
|
+
const patterns = denyPaths(cfg);
|
|
1186
|
+
if (!patterns.length || !named.length) return null;
|
|
1187
|
+
const hookTop = real(path.resolve(root));
|
|
1188
|
+
const topAt = new Map();
|
|
1189
|
+
const seen = new Set();
|
|
1190
|
+
let dirHit = null;
|
|
1191
|
+
// The path is judged as written (`data/link`) and as resolved: a symlink under a listed directory
|
|
1192
|
+
// that points out of the repository resolves to a `..` path, and its listed name must still count.
|
|
1193
|
+
const judgeRel = (rel, abs, isDir) => {
|
|
1194
|
+
if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) return null;
|
|
1195
|
+
const r = toPosix(rel);
|
|
1196
|
+
let pattern = matchesDeny(r, patterns);
|
|
1197
|
+
if (pattern === null && (isDir || (fs.existsSync(abs) && fs.statSync(abs).isDirectory()))) pattern = denyDir(r, patterns);
|
|
1198
|
+
return pattern === null ? null : { rel: r, pattern };
|
|
1199
|
+
};
|
|
1200
|
+
const judge = (abs, top, isDir) => judgeRel(path.relative(top, abs), abs, isDir) ?? judgeRel(path.relative(top, real(abs)), abs, isDir);
|
|
1201
|
+
for (const { dir, word, fromTop, glob, wide, isDir, globstar } of named) {
|
|
1202
|
+
if (wide) return { wide: word };
|
|
1203
|
+
const once = JSON.stringify([dir, word, fromTop, glob, isDir, globstar]);
|
|
1204
|
+
if (seen.has(once)) continue;
|
|
1205
|
+
seen.add(once);
|
|
1206
|
+
const p = fromGitBash(word.replace(/\\/g, '/'));
|
|
1207
|
+
const tops = [hookTop];
|
|
1208
|
+
if (dir !== null) {
|
|
1209
|
+
if (!topAt.has(dir)) topAt.set(dir, topOf(dir));
|
|
1210
|
+
const t = topAt.get(dir);
|
|
1211
|
+
if (t && !tops.includes(t)) tops.push(t);
|
|
1212
|
+
}
|
|
1213
|
+
for (const top of tops) {
|
|
1214
|
+
const base = fromTop ? top : dir === null ? null : real(dir);
|
|
1215
|
+
if (base === null && !path.isAbsolute(p)) continue;
|
|
1216
|
+
const candidates = [path.resolve(base ?? top, p)];
|
|
1217
|
+
if (glob && GLOB.test(p)) {
|
|
1218
|
+
const expanded = expandGlob(base ?? top, p, globstar);
|
|
1219
|
+
if (expanded === null) return { wide: p };
|
|
1220
|
+
candidates.push(...expanded);
|
|
1221
|
+
}
|
|
1222
|
+
for (const abs of candidates) {
|
|
1223
|
+
const hit = judge(abs, top, isDir);
|
|
1224
|
+
// A path the command names is reported before the directory it runs in.
|
|
1225
|
+
if (hit && !isDir) return hit;
|
|
1226
|
+
if (hit && dirHit === null) dirHit = hit;
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
return dirHit;
|
|
1231
|
+
}
|
|
1232
|
+
|
|
657
1233
|
// ---- the hook ----
|
|
658
1234
|
|
|
659
1235
|
const unknownDir = (label) => deny(`cannot tell which branch ${label} is on; run the command from inside the repository`);
|
|
@@ -662,9 +1238,32 @@ export function handle(input, { root, cfg }) {
|
|
|
662
1238
|
const command = input?.tool_input?.command;
|
|
663
1239
|
if (typeof command !== 'string') throw new Error('tool_input.command is missing');
|
|
664
1240
|
const start = typeof input.cwd === 'string' && input.cwd !== '' ? resolveDir(null, input.cwd) : root;
|
|
665
|
-
const { invs, texts, mentions } = parse(command, start);
|
|
1241
|
+
const { invs, texts, mentions, writes, named, cdUnknown, unjudgeable: why, hostRules } = parse(command, start);
|
|
666
1242
|
const protectedSet = new Set(cfg.protectedBranches);
|
|
667
1243
|
|
|
1244
|
+
// (0a), in every session and on every branch (D-83)
|
|
1245
|
+
if (why) return deny(`cannot judge this command (REQ-3.2): ${why}; run git and gh with literal arguments`);
|
|
1246
|
+
// (0b)
|
|
1247
|
+
if (hostRules) {
|
|
1248
|
+
return deny(`${hostRules} changes the git host's rules (REQ-3.14); a human runs it from their own terminal`);
|
|
1249
|
+
}
|
|
1250
|
+
// (0c)
|
|
1251
|
+
const hit = frozenWrite(root, cfg, writes);
|
|
1252
|
+
if (hit) {
|
|
1253
|
+
return deny(`${hit.rel} is frozen for ${hit.id}; a Bash command may not write it (REQ-3.3); amend the slice file to change the evaluation set`);
|
|
1254
|
+
}
|
|
1255
|
+
// (0d)
|
|
1256
|
+
if (cdUnknown !== null && denyPaths(cfg).length) {
|
|
1257
|
+
return deny(`cannot tell where ${cdUnknown} goes, so its paths cannot be judged against agents.denyPaths (REQ-3.13); cd to a literal directory`);
|
|
1258
|
+
}
|
|
1259
|
+
const named0d = deniedPath(root, cfg, named);
|
|
1260
|
+
if (named0d?.wide) {
|
|
1261
|
+
return deny(`${named0d.wide} expands too wide to judge against agents.denyPaths (REQ-3.13); name the paths or narrow the expression`);
|
|
1262
|
+
}
|
|
1263
|
+
if (named0d) {
|
|
1264
|
+
return deny(`the command names ${named0d.rel}, which matches agents.denyPaths pattern ${named0d.pattern}; agents may not read or change it (REQ-3.13)`);
|
|
1265
|
+
}
|
|
1266
|
+
|
|
668
1267
|
// The branch each commit and push runs on, following checkouts earlier in the same command.
|
|
669
1268
|
const switched = new Map();
|
|
670
1269
|
for (const inv of invs) {
|