pi-odd-worktree 3.1.1 → 3.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 +2 -1
- package/extensions/odd-worktree-tools.ts +83 -3
- package/lib/bash-activity.js +405 -32
- package/lib/bash-inline-script.js +314 -0
- package/lib/codegraph-guard.js +36 -19
- package/lib/codegraph-prompt/generic.md +1 -1
- package/lib/codegraph-prompt/orchestrator.md +7 -7
- package/lib/codegraph-session.js +10 -2
- package/lib/odd-prompt/odd-worktrees-child.md +3 -0
- package/lib/odd-prompt/odd-worktrees.md +11 -7
- package/lib/odd-worktrees-prompt.js +68 -14
- package/lib/skill-read-guard.js +397 -0
- package/lib/worktree-guard.js +205 -5
- package/package.json +1 -1
- package/tools/bash-activity.test.js +400 -35
- package/tools/codegraph-guard.test.js +109 -11
- package/tools/codegraph-rules.test.js +8 -8
- package/tools/codegraph-session.test.js +45 -3
- package/tools/odd-worktrees-prompt.test.js +98 -11
- package/tools/package-surface.test.js +15 -1
- package/tools/skill-read-guard.test.js +316 -0
- package/tools/worktree-write-guard.test.js +516 -0
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// The activity an INLINE script names: the program an interpreter is handed on its command
|
|
3
|
+
// line (`python3 -c '…'`, `node -e '…'`, `python3 - <<'PY' … PY`), read from its own text.
|
|
4
|
+
//
|
|
5
|
+
// A script is code, and code can do anything, so this reader answers only what the text
|
|
6
|
+
// itself proves and refuses everything else:
|
|
7
|
+
// * `destructive` — the text calls a deleting function (`os.remove`, `shutil.rmtree`,
|
|
8
|
+
// `fs.rmSync`, `.unlink(`). The call provably deletes whatever else it does.
|
|
9
|
+
// * `preparing` — the text writes, creates, renames or copies a file; the same
|
|
10
|
+
// build-up a `cat > file` already names.
|
|
11
|
+
// * `exploring` — the text imports only modules from a short list of read-only
|
|
12
|
+
// standard libraries, writes nothing and runs nothing.
|
|
13
|
+
// * `undefined` — anything else: a module outside the list (it runs code of its own),
|
|
14
|
+
// a shell-out, a network call, `eval`, a dynamic import, a flag this reader does not
|
|
15
|
+
// know. The card stays generic, as it always did.
|
|
16
|
+
//
|
|
17
|
+
// Pure: no filesystem, no process, no Pi. It reads a list of words and a string.
|
|
18
|
+
|
|
19
|
+
const PYTHON_PROGRAM = /^python(3(\.\d+)?)?$/;
|
|
20
|
+
const NODE_PROGRAM = /^nodejs?$/;
|
|
21
|
+
|
|
22
|
+
// Interpreter flags that change nothing about which code runs. A flag outside these lists
|
|
23
|
+
// ends the reading: `-m` runs a module, `-r`/`--import` load code first.
|
|
24
|
+
const PYTHON_PLAIN_FLAGS = new Set(['-I', '-B', '-u', '-E', '-S', '-s', '-O', '-OO', '-q', '-b', '-bb', '-d', '-v']);
|
|
25
|
+
const NODE_PLAIN_FLAGS = new Set([
|
|
26
|
+
'--no-warnings', '--no-deprecation', '--experimental-strip-types', '--experimental-vm-modules',
|
|
27
|
+
'--experimental-default-type=module', '--input-type=module', '--input-type=commonjs', '--enable-source-maps',
|
|
28
|
+
]);
|
|
29
|
+
|
|
30
|
+
// Standard-library modules that only read: parsing, text, hashing, dates and path math. A
|
|
31
|
+
// module outside the list may run any code on import, so a script that needs one stays
|
|
32
|
+
// generic.
|
|
33
|
+
const PYTHON_MODULES = new Set([
|
|
34
|
+
'json', 'sys', 're', 'os', 'pathlib', 'tomllib', 'collections', 'itertools', 'functools', 'textwrap',
|
|
35
|
+
'datetime', 'time', 'math', 'hashlib', 'base64', 'csv', 'glob', 'fnmatch', 'io', 'string', 'typing',
|
|
36
|
+
'operator', 'statistics', 'difflib', 'unicodedata', 'copy', 'enum', 'dataclasses', 'argparse',
|
|
37
|
+
'configparser', 'plistlib', 'struct', 'binascii', 'html', 'shlex', 'pprint', 'posixpath', 'uuid', 'yaml', 'toml', 'PIL',
|
|
38
|
+
]);
|
|
39
|
+
const NODE_MODULES = new Set([
|
|
40
|
+
'fs', 'fs/promises', 'path', 'os', 'util', 'url', 'assert', 'assert/strict', 'crypto', 'readline',
|
|
41
|
+
'stream', 'zlib', 'events', 'buffer', 'string_decoder', 'querystring', 'perf_hooks', 'timers',
|
|
42
|
+
]);
|
|
43
|
+
|
|
44
|
+
// What a script may not contain whatever it imports: running another program, evaluating
|
|
45
|
+
// text as code, loading code by name, talking to the network or a process, or hiding a name
|
|
46
|
+
// behind an alias. Read on the whole text, strings included: a script that merely MENTIONS one
|
|
47
|
+
// of these stays generic, which is the safe side.
|
|
48
|
+
const PYTHON_UNREADABLE = /\b(os\.(system|popen|exec\w*|spawn\w*|fork|forkpty|kill|killpg|putenv|startfile)|eval|exec|compile|__import__|importlib|getattr|setattr|globals|locals|breakpoint|signal|webbrowser|pty)\b|\bsubprocess\b|\bsocket\b|\bimport\s+\*|\bimport\s+(os|shutil)\s+as\b|,\s*(os|shutil)\s+as\b/;
|
|
49
|
+
const NODE_UNREADABLE = /\b(eval|Function|fetch|XMLHttpRequest|WebSocket|process\.(kill|binding|dlopen|chdir))\b|\.constructor\s*\(/;
|
|
50
|
+
|
|
51
|
+
// What the CODE of a script calls, read with every string literal and comment emptied, so a
|
|
52
|
+
// script that only prints the word is not a script that does it.
|
|
53
|
+
// A bare name counts only when it is called; a property access (`os.remove`, `fs.rmSync`) counts
|
|
54
|
+
// as written, because it may be aliased and called later.
|
|
55
|
+
const PYTHON_DELETES = /\bos\.(remove|unlink|rmdir|removedirs)\b|\bshutil\.rmtree\b|\b(rmtree|unlink|removedirs)\s*\(|\.(unlink|rmdir)\s*\(/;
|
|
56
|
+
const NODE_DELETES = /\.(rmSync|rmdirSync|unlinkSync)\b|\b(rmSync|rmdirSync|unlinkSync|rimraf)\s*\(|\.(rm|rmdir|unlink)\s*\(/;
|
|
57
|
+
|
|
58
|
+
const PYTHON_WRITES = /\.(write|writelines|write_text|write_bytes|touch|mkdir|rename|chmod|chown|symlink_to|hardlink_to|save|to_csv|to_json)\s*\(|\b(makedirs|os\.(rename|replace|mkdir|chmod|chown|symlink|link|truncate|utime)|shutil\.\w+)\b|\b(json|pickle|yaml|toml|plistlib)\.dump\s*\(/;
|
|
59
|
+
const NODE_WRITES = /\b(writeFile\w*|appendFile\w*|createWriteStream|mkdir\w*|copyFile\w*|cp\w*|rename\w*|chmod\w*|chown\w*|symlink\w*|link\w*|truncate\w*|utimes\w*|writeSync|write\w*)\s*\(|\.write\s*\(|\bWriteStream\b/;
|
|
60
|
+
|
|
61
|
+
// Names a script may take out of the filesystem module by destructuring: reads only.
|
|
62
|
+
const NODE_FS_READ_NAMES = new Set([
|
|
63
|
+
'readFileSync', 'readFile', 'readdirSync', 'readdir', 'existsSync', 'statSync', 'stat', 'lstatSync', 'lstat',
|
|
64
|
+
'readlinkSync', 'realpathSync', 'access', 'accessSync', 'promises',
|
|
65
|
+
]);
|
|
66
|
+
const PYTHON_OS_READ_NAMES = new Set(['path', 'environ', 'getcwd', 'listdir', 'walk', 'scandir', 'stat', 'sep', 'linesep', 'name']);
|
|
67
|
+
|
|
68
|
+
// A print is not a write: the two standard streams are what a read-only script talks to.
|
|
69
|
+
const PRINTING = /\bsys\.(stdout|stderr)\.write\s*\(|\bprocess\.(stdout|stderr)\.write\s*\(/g;
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The text with the content of every string literal and comment emptied. An f-string and a
|
|
73
|
+
* template literal keep theirs: what sits inside their braces is code.
|
|
74
|
+
*/
|
|
75
|
+
function codeOf(language, text, keepModes = false) {
|
|
76
|
+
let out = '';
|
|
77
|
+
let index = 0;
|
|
78
|
+
while (index < text.length) {
|
|
79
|
+
const char = text[index];
|
|
80
|
+
if (language === 'python' && char === '#') {
|
|
81
|
+
while (index < text.length && text[index] !== '\n') index += 1;
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (language === 'node' && char === '/' && text[index + 1] === '/') {
|
|
85
|
+
while (index < text.length && text[index] !== '\n') index += 1;
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (language === 'node' && char === '/' && text[index + 1] === '*') {
|
|
89
|
+
const end = text.indexOf('*/', index + 2);
|
|
90
|
+
index = end < 0 ? text.length : end + 2;
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
if (char === '"' || char === "'" || char === '`') {
|
|
94
|
+
const triple = language === 'python' && text.startsWith(char.repeat(3), index);
|
|
95
|
+
const quote = triple ? char.repeat(3) : char;
|
|
96
|
+
let end = index + quote.length;
|
|
97
|
+
while (end < text.length && !text.startsWith(quote, end)) end += text[end] === '\\' ? 2 : 1;
|
|
98
|
+
const body = text.slice(index + quote.length, end);
|
|
99
|
+
// A short mode-shaped string (`'w'`, `'r+'`) is kept on request: it is what `open` reads.
|
|
100
|
+
const keep = char === '`' || (language === 'python' && /(^|[^a-z0-9_])(rf|fr|f)$/i.test(out.slice(-3))) || (keepModes && /^[rwxabt+U]{1,4}$/.test(body));
|
|
101
|
+
out += quote + (keep ? body : '') + quote;
|
|
102
|
+
index = end + quote.length;
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
out += char;
|
|
106
|
+
index += 1;
|
|
107
|
+
}
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The index of the parenthesis that closes the call whose opening one is at `open`. */
|
|
112
|
+
function callEnd(text, open) {
|
|
113
|
+
let depth = 0;
|
|
114
|
+
let quote;
|
|
115
|
+
for (let index = open; index < text.length; index += 1) {
|
|
116
|
+
const char = text[index];
|
|
117
|
+
if (quote !== undefined) {
|
|
118
|
+
if (char === '\\') index += 1;
|
|
119
|
+
else if (char === quote) quote = undefined;
|
|
120
|
+
} else if (char === '"' || char === "'") quote = char;
|
|
121
|
+
else if (char === '(') depth += 1;
|
|
122
|
+
else if (char === ')' && (depth -= 1) === 0) return index;
|
|
123
|
+
}
|
|
124
|
+
return text.length;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The top-level, comma-separated arguments of the call whose opening parenthesis is at `open`. */
|
|
128
|
+
function callArguments(text, open) {
|
|
129
|
+
const end = callEnd(text, open);
|
|
130
|
+
const args = [];
|
|
131
|
+
let depth = 0;
|
|
132
|
+
let quote;
|
|
133
|
+
let current = '';
|
|
134
|
+
for (let index = open + 1; index < end; index += 1) {
|
|
135
|
+
const char = text[index];
|
|
136
|
+
if (quote !== undefined) {
|
|
137
|
+
current += char;
|
|
138
|
+
if (char === '\\') {
|
|
139
|
+
current += text[index + 1] === undefined ? '' : text[index + 1];
|
|
140
|
+
index += 1;
|
|
141
|
+
} else if (char === quote) quote = undefined;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (char === '"' || char === "'") quote = char;
|
|
145
|
+
if (char === '(' || char === '[' || char === '{') depth += 1;
|
|
146
|
+
if (char === ')' || char === ']' || char === '}') depth -= 1;
|
|
147
|
+
if (char === ',' && depth === 0) {
|
|
148
|
+
args.push(current.trim());
|
|
149
|
+
current = '';
|
|
150
|
+
} else current += char;
|
|
151
|
+
}
|
|
152
|
+
if (current.trim() !== '') args.push(current.trim());
|
|
153
|
+
return args;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** A string literal's text, or undefined when the argument is anything else. */
|
|
157
|
+
function literal(arg) {
|
|
158
|
+
const found = /^[a-zA-Z]{0,2}(['"])([\s\S]*)\1$/.exec(arg === undefined ? '' : arg);
|
|
159
|
+
return found === null ? undefined : found[2];
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Whether the text opens a file for writing: a mode that creates, truncates, appends or
|
|
164
|
+
* updates, or a mode this reader cannot see. Nested calls in the path (`open(Path('a'), 'w')`)
|
|
165
|
+
* and `mode=` are read as arguments, not as a pattern.
|
|
166
|
+
*/
|
|
167
|
+
function pythonOpensForWrite(text) {
|
|
168
|
+
for (const found of text.matchAll(/(\.?)\bopen\s*\(/g)) {
|
|
169
|
+
const args = callArguments(text, found.index + found[0].length - 1);
|
|
170
|
+
if (found[1] === '.') {
|
|
171
|
+
// A method such as `Path.open('w')` or `Path.open(mode='w')`: a mode-shaped first
|
|
172
|
+
// argument, or `mode=`, is the mode.
|
|
173
|
+
const keyword = args.find((arg) => /^mode\s*=/.test(arg));
|
|
174
|
+
const mode = literal(keyword === undefined ? args[0] : keyword.replace(/^mode\s*=\s*/, ''));
|
|
175
|
+
if (mode !== undefined && /^[rwxabt+U]+$/.test(mode) && /[wax+]/.test(mode)) return true;
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
const keyword = args.find((arg) => /^mode\s*=/.test(arg));
|
|
179
|
+
const modeArg = keyword === undefined ? args[1] : keyword.replace(/^mode\s*=\s*/, '');
|
|
180
|
+
if (modeArg === undefined) continue;
|
|
181
|
+
const mode = literal(modeArg);
|
|
182
|
+
if (mode === undefined || /[wax+]/.test(mode)) return true;
|
|
183
|
+
}
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** The same for `fs.openSync(path, flags)`: a flag that writes, or one this reader cannot see. */
|
|
188
|
+
function nodeOpensForWrite(text) {
|
|
189
|
+
for (const found of text.matchAll(/\bopen(?:Sync)?\s*\(/g)) {
|
|
190
|
+
const flags = callArguments(text, found.index + found[0].length - 1)[1];
|
|
191
|
+
if (flags === undefined) continue;
|
|
192
|
+
const mode = literal(flags);
|
|
193
|
+
if (mode === undefined || /[wa+]/.test(mode)) return true;
|
|
194
|
+
}
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* The family the script text proves, or `undefined`.
|
|
200
|
+
* @param {'python'|'node'} language
|
|
201
|
+
* @param {string} source
|
|
202
|
+
*/
|
|
203
|
+
function readScript(language, source) {
|
|
204
|
+
if (typeof source !== 'string' || source.trim() === '') return undefined;
|
|
205
|
+
const text = source.replace(PRINTING, '');
|
|
206
|
+
if (language === 'python') return readPython(text);
|
|
207
|
+
if (language === 'node') return readNode(text);
|
|
208
|
+
return undefined;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function pythonImportsAreReadable(text) {
|
|
212
|
+
const pairs = [...text.matchAll(/(?:^|;)[ \t]*(?:import[ \t]+([^\n#;]+)|from[ \t]+(\S+)[ \t]+import[ \t]+([^\n#;]+))/gm)];
|
|
213
|
+
for (const found of pairs) {
|
|
214
|
+
const names = found[2] === undefined ? found[1].split(',').map((part) => part.trim().split(/\s+/)[0]) : [found[2]];
|
|
215
|
+
for (const name of names) {
|
|
216
|
+
const root = name === undefined ? '' : name.split('.')[0];
|
|
217
|
+
if (root === '' || !PYTHON_MODULES.has(root)) return false;
|
|
218
|
+
}
|
|
219
|
+
// Names pulled out of `os` may be the deleting ones, so only the reading ones pass.
|
|
220
|
+
if (found[2] === 'os') {
|
|
221
|
+
for (const name of found[3].split(',').map((part) => part.trim().split(/\s+/)[0])) {
|
|
222
|
+
if (!PYTHON_OS_READ_NAMES.has(name)) return false;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return true;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function readPython(text) {
|
|
230
|
+
const code = codeOf('python', text);
|
|
231
|
+
// A deletion the code calls is proven whatever else the script does or imports.
|
|
232
|
+
if (PYTHON_DELETES.test(code)) return 'destructive';
|
|
233
|
+
if (PYTHON_UNREADABLE.test(text)) return undefined;
|
|
234
|
+
if (!pythonImportsAreReadable(text)) return undefined;
|
|
235
|
+
if (PYTHON_WRITES.test(code) || pythonOpensForWrite(codeOf('python', text, true))) return 'preparing';
|
|
236
|
+
return 'exploring';
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function readNode(text) {
|
|
240
|
+
const code = codeOf('node', text);
|
|
241
|
+
if (NODE_DELETES.test(code)) return 'destructive';
|
|
242
|
+
if (NODE_UNREADABLE.test(text)) return undefined;
|
|
243
|
+
// Every module the script loads, by `require`, a static `import` or a dynamic one: a
|
|
244
|
+
// builtin from the list, or a JSON file. Anything else — a path, a package, an
|
|
245
|
+
// expression — is code this reader has not seen.
|
|
246
|
+
const specifiers = [];
|
|
247
|
+
for (const found of text.matchAll(/\b(?:require|import)\s*\(\s*(['"])([^'"]*)\1\s*\)/g)) specifiers.push(found[2]);
|
|
248
|
+
for (const found of text.matchAll(/\bimport\s+(?:[\w*${},\s]+\s+from\s+)?(['"])([^'"]+)\1/g)) specifiers.push(found[2]);
|
|
249
|
+
const calls = [...text.matchAll(/\b(?:require|import)\s*\(/g)].length;
|
|
250
|
+
const literals = [...text.matchAll(/\b(?:require|import)\s*\(\s*(['"])[^'"]*\1\s*\)/g)].length;
|
|
251
|
+
if (calls !== literals) return undefined;
|
|
252
|
+
for (const specifier of specifiers) {
|
|
253
|
+
const name = specifier.startsWith('node:') ? specifier.slice(5) : specifier;
|
|
254
|
+
if (/\.json$/.test(name) && !name.startsWith('http')) continue;
|
|
255
|
+
if (!NODE_MODULES.has(name)) return undefined;
|
|
256
|
+
}
|
|
257
|
+
// Names destructured out of the filesystem module may be the deleting or writing ones.
|
|
258
|
+
const destructured = /(?:\{([^}]*)\}\s*=\s*require\s*\(\s*['"](?:node:)?fs(?:\/promises)?['"]\s*\)|import\s*\{([^}]*)\}\s*from\s*['"](?:node:)?fs(?:\/promises)?['"])/g;
|
|
259
|
+
for (const found of text.matchAll(destructured)) {
|
|
260
|
+
for (const part of (found[1] === undefined ? found[2] : found[1]).split(',')) {
|
|
261
|
+
const name = part.trim().split(/\s*:\s*|\s+as\s+/)[0];
|
|
262
|
+
if (name !== '' && !NODE_FS_READ_NAMES.has(name)) return undefined;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
if (NODE_WRITES.test(code) || nodeOpensForWrite(codeOf('node', text, true))) return 'preparing';
|
|
266
|
+
return 'exploring';
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* The inline script a command's words hand an interpreter, or `undefined` when they hand it
|
|
271
|
+
* anything else (a file to run, a module, a flag this reader does not know).
|
|
272
|
+
* @param {string[]} words The words of ONE simple command, quotes folded.
|
|
273
|
+
* @param {string|undefined} body The text of the first heredoc the segment opens, if any.
|
|
274
|
+
*/
|
|
275
|
+
function inlineScript(words, body) {
|
|
276
|
+
// A node option that loads code before the script runs, wherever it stands.
|
|
277
|
+
if (words.some((word) => /^(-r|--require|--import|--loader|--experimental-loader|--env-file)(=|$)/.test(word))) return undefined;
|
|
278
|
+
const program = (words[0] === undefined ? '' : words[0]).split('/').pop();
|
|
279
|
+
const python = PYTHON_PROGRAM.test(program);
|
|
280
|
+
const node = NODE_PROGRAM.test(program) || program === 'node';
|
|
281
|
+
if (!python && !node) return undefined;
|
|
282
|
+
const plain = python ? PYTHON_PLAIN_FLAGS : NODE_PLAIN_FLAGS;
|
|
283
|
+
const payload = python ? new Set(['-c']) : new Set(['-e', '--eval', '-p', '--print']);
|
|
284
|
+
for (let index = 1; index < words.length; index += 1) {
|
|
285
|
+
const word = words[index] === undefined ? '' : words[index];
|
|
286
|
+
if (payload.has(word)) {
|
|
287
|
+
const script = words[index + 1];
|
|
288
|
+
return script === undefined ? undefined : { language: python ? 'python' : 'node', source: script };
|
|
289
|
+
}
|
|
290
|
+
if (word === '-') return body === undefined ? undefined : { language: python ? 'python' : 'node', source: body };
|
|
291
|
+
if (plain.has(word)) continue;
|
|
292
|
+
if (python && /^-[IBuESsOqbd]+$/.test(word)) continue;
|
|
293
|
+
// Anything else is a script path, a module, or a flag this reader cannot vouch for.
|
|
294
|
+
return undefined;
|
|
295
|
+
}
|
|
296
|
+
// No script argument: the interpreter reads its program from the heredoc on stdin.
|
|
297
|
+
return body === undefined ? undefined : { language: python ? 'python' : 'node', source: body };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* The family an inline script names, or `undefined`.
|
|
302
|
+
* @param {string[]} words
|
|
303
|
+
* @param {string|undefined} body
|
|
304
|
+
*/
|
|
305
|
+
function inlineScriptActivity(words, body) {
|
|
306
|
+
try {
|
|
307
|
+
const script = inlineScript(words, body);
|
|
308
|
+
return script === undefined ? undefined : readScript(script.language, script.source);
|
|
309
|
+
} catch {
|
|
310
|
+
return undefined;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
module.exports = { inlineScriptActivity, readScript };
|
package/lib/codegraph-guard.js
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
'use strict';
|
|
2
|
-
// T1 (S1, S2, S5, S6, S7): the two CodeGraph reminders, decided from a finished tool call.
|
|
2
|
+
// T1 (S1, S2, S5, S6, S7) and T6 (S3): the two CodeGraph reminders, decided from a finished tool call.
|
|
3
3
|
//
|
|
4
4
|
// Guard 1 says a call went to ANOTHER checkout and points the session at
|
|
5
5
|
// `mcp__codegraph__codegraph_explore` with that checkout as `projectPath`; it belongs to the primary
|
|
6
6
|
// session and fires once per checkout per session. Guard 2 says to reach CodeGraph first inside the
|
|
7
7
|
// session's OWN checkout; it belongs to the primary session and to every child except the `review-*`
|
|
8
|
-
// agents, and
|
|
8
|
+
// agents, and it reminds once on the first search of a checkout, while the graph is unused in that
|
|
9
|
+
// request, and then never again for that checkout in that request (S3, S7).
|
|
9
10
|
//
|
|
10
|
-
// Both are precise: a checkout the session already explored with the MCP tool silences guard 1, a
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
//
|
|
11
|
+
// Both are precise: a checkout the session already explored with the MCP tool silences guard 1, and a
|
|
12
|
+
// reminder that does not fire uses up no slot. A call that failed is no subject at all: the model got no
|
|
13
|
+
// result to read, so nothing is reminded, spent or recorded from it. A new request forgets guard 2's
|
|
14
|
+
// first-search slots and `used` flag; a compaction forgets everything, and so does a new session in the
|
|
15
|
+
// same process.
|
|
15
16
|
//
|
|
16
17
|
// The reminder is only a sentence. Appending it to the tool result is the wiring's job
|
|
17
18
|
// (`lib/codegraph-session.js`); nothing here blocks, notifies or writes. Git is reached through one
|
|
@@ -40,8 +41,8 @@ function sameCheckoutReminder(input = {}) {
|
|
|
40
41
|
const variant = input.variant;
|
|
41
42
|
const tools = Array.isArray(input.tools) ? input.tools : [];
|
|
42
43
|
return NATIVE_VARIANTS.includes(variant) && tools.includes(NATIVE_TOOL)
|
|
43
|
-
? 'Follow the CodeGraph rule: run `codegraph` `query` or `explore` first
|
|
44
|
-
: `Follow the CodeGraph rule: call \`${MCP_TOOL}\` first
|
|
44
|
+
? 'Follow the CodeGraph rule: run `codegraph` `query` or `explore` first.'
|
|
45
|
+
: `Follow the CodeGraph rule: call \`${MCP_TOOL}\` first.`;
|
|
45
46
|
}
|
|
46
47
|
|
|
47
48
|
function isExploreCall(event) {
|
|
@@ -52,13 +53,13 @@ function isCodegraphCall(event) {
|
|
|
52
53
|
return Boolean(event) && (event.toolName === NATIVE_TOOL || isExploreCall(event));
|
|
53
54
|
}
|
|
54
55
|
|
|
55
|
-
/** The once-per-key slots and what the
|
|
56
|
+
/** The once-per-key slots and what the request already used, forgotten together. */
|
|
56
57
|
function createGuardState() {
|
|
57
58
|
return {
|
|
58
|
-
checkouts: new Set(), // guard 1: the other checkouts already reminded
|
|
59
|
-
own: new Set(), // guard 2: the
|
|
59
|
+
checkouts: new Set(), // guard 1: the other checkouts already reminded, for the whole session
|
|
60
|
+
own: new Set(), // guard 2: the checkouts already reminded on their first search, for this request
|
|
60
61
|
explored: new Set(), // the absolute projectPath of every MCP explore call this session made
|
|
61
|
-
used: false, //
|
|
62
|
+
used: false, // this request already used CodeGraph
|
|
62
63
|
};
|
|
63
64
|
}
|
|
64
65
|
|
|
@@ -69,6 +70,15 @@ function resetGuardState(state) {
|
|
|
69
70
|
state.used = false;
|
|
70
71
|
}
|
|
71
72
|
|
|
73
|
+
/**
|
|
74
|
+
* S7: a new request forgets guard 2 alone — its first-search slots and `used`. Guard 1's slots and the
|
|
75
|
+
* explored checkouts are the session's, so they stay.
|
|
76
|
+
*/
|
|
77
|
+
function forgetRequestState(state) {
|
|
78
|
+
state.own.clear();
|
|
79
|
+
state.used = false;
|
|
80
|
+
}
|
|
81
|
+
|
|
72
82
|
/**
|
|
73
83
|
* What one finished call says about the session's use of CodeGraph: the native tool or the MCP tool is a
|
|
74
84
|
* use (S5), and an explore call aimed at a `projectPath` records that checkout. Returns whether this call
|
|
@@ -97,7 +107,8 @@ async function exploredCheckout(state, root, resolver) {
|
|
|
97
107
|
/**
|
|
98
108
|
* The reminder one call earns, or undefined. It marks the slot it used, so the same key is never
|
|
99
109
|
* reminded twice; a call whose reminder would duplicate one, or whose checkout the session already
|
|
100
|
-
* explored, marks nothing.
|
|
110
|
+
* explored, marks nothing. Guard 2 (S3, S7) reminds once on the first search of a checkout in a request
|
|
111
|
+
* while the graph is unused, and never again for that checkout in that request.
|
|
101
112
|
*/
|
|
102
113
|
async function decideGuard(input) {
|
|
103
114
|
const { state, call, ownRoot, tools, variant, resolver } = input;
|
|
@@ -112,7 +123,8 @@ async function decideGuard(input) {
|
|
|
112
123
|
state.checkouts.add(checkout.root);
|
|
113
124
|
return { kind: 'another-checkout', checkout: checkout.root, text: anotherCheckoutReminder(checkout.root) };
|
|
114
125
|
}
|
|
115
|
-
|
|
126
|
+
// The first search of a checkout is reminded at once, and only while the graph is still unused.
|
|
127
|
+
if (state.used !== false || state.own.has(checkout.root)) return undefined;
|
|
116
128
|
state.own.add(checkout.root);
|
|
117
129
|
return { kind: 'same-checkout', checkout: checkout.root, text: sameCheckoutReminder({ variant, tools }) };
|
|
118
130
|
}
|
|
@@ -125,10 +137,10 @@ function sessionCwd(event, ctx) {
|
|
|
125
137
|
|
|
126
138
|
/**
|
|
127
139
|
* The two guards of one session, with their own state. `observeTools` takes the session's tool list from
|
|
128
|
-
* the host's `before_agent_start` event (the only source of it); `
|
|
129
|
-
* one finished call; `onCompacted` and `onNewSession`
|
|
130
|
-
* `env`, `argv` (the child's agent name), `toplevel`
|
|
131
|
-
* is a directory, so a file costs one read).
|
|
140
|
+
* the host's `before_agent_start` event (the only source of it); `onNewRequest` re-arms guard 2 for a new
|
|
141
|
+
* request; `onToolResult` decides one reminder from one finished call; `onCompacted` and `onNewSession`
|
|
142
|
+
* forget everything. Every collaborator is injectable: `env`, `argv` (the child's agent name), `toplevel`
|
|
143
|
+
* (the cached git read) and `isDirectory` (whether a path is a directory, so a file costs one read).
|
|
132
144
|
*/
|
|
133
145
|
function createCodegraphGuard(deps = {}) {
|
|
134
146
|
const env = deps.env || process.env;
|
|
@@ -147,6 +159,11 @@ function createCodegraphGuard(deps = {}) {
|
|
|
147
159
|
selected = Array.isArray(selectedTools) ? selectedTools.filter((tool) => typeof tool === 'string') : [];
|
|
148
160
|
},
|
|
149
161
|
|
|
162
|
+
/** A new request re-arms guard 2: its first-search slots and what it used (S7). */
|
|
163
|
+
onNewRequest() {
|
|
164
|
+
forgetRequestState(state);
|
|
165
|
+
},
|
|
166
|
+
|
|
150
167
|
/** A compaction forgets what was reminded and what was used (S7). */
|
|
151
168
|
onCompacted() {
|
|
152
169
|
resetGuardState(state);
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Run one call to the CodeGraph tool you hold before you search or read code — `fd`, `find`, `rg`, `grep`,
|
|
4
4
|
`read` or `cat` — when the task needs structure rather than a lookup: where something lives, who calls it,
|
|
5
|
-
what a change reaches.
|
|
5
|
+
what a change reaches. Skip it only for an exact string or a file path you were given. The other tools stay
|
|
6
6
|
available after the first call.
|
|
7
7
|
|
|
8
8
|
The answer is a map, not proof: confirm it in the source, and read a file before editing it.
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
## CodeGraph
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
3
|
+
Before you `grep`, `rg`, `fd`, `find`, `read` or `cat` to answer where code lives, who calls it, how it
|
|
4
|
+
works, or what a change reaches, call CodeGraph first: `codegraph` with `operation: "explore"` and
|
|
5
|
+
`query: "<symbols or the question>"` returns the source and the call paths in one call, and it is
|
|
6
|
+
also what scope, size and any handoff depend on. Use `operation: "query"` only to find where one
|
|
7
|
+
symbol is defined. Skip it only for an exact string or a file path the user gave you. The other tools stay for
|
|
8
|
+
what the graph does not index. Its answer is a map: confirm it in the source, and a verdict comes
|
|
9
|
+
from the source and from tests.
|
|
10
10
|
|
|
11
11
|
`codegraph` answers only for the checkout the session runs in, and each worktree is its own workspace with
|
|
12
12
|
its own index. An ODD works in its own worktree: when the session runs elsewhere, look at that worktree, at
|
package/lib/codegraph-session.js
CHANGED
|
@@ -10,7 +10,8 @@
|
|
|
10
10
|
// - before a CodeGraph search: a bounded join of the index work this process already has in flight for that checkout
|
|
11
11
|
// (never a new one, and nothing at all when nothing is in flight);
|
|
12
12
|
// - a search or read call into another checkout, or into the session's own one: one reminder appended to
|
|
13
|
-
// that call's result (never a block, never a separate message),
|
|
13
|
+
// that call's result (never a block, never a separate message), re-armed at every new request and
|
|
14
|
+
// forgotten on a compaction and a new session;
|
|
14
15
|
// - the CodeGraph tool card, through the host's renderer hook;
|
|
15
16
|
// - shutdown: every pending window is cleared.
|
|
16
17
|
//
|
|
@@ -299,8 +300,15 @@ function registerCodegraph(pi, deps = {}) {
|
|
|
299
300
|
});
|
|
300
301
|
|
|
301
302
|
// The session's tools reach the guards from the ONE source that has them: the prompt options of
|
|
302
|
-
// `before_agent_start`.
|
|
303
|
+
// `before_agent_start`. S7: that same event is a new request, so guard 2 is re-armed there (its
|
|
304
|
+
// first-search slots and `used`), while guard 1's slots stay per session. Nothing here touches the
|
|
305
|
+
// prompt itself.
|
|
303
306
|
pi.on('before_agent_start', (event) => {
|
|
307
|
+
try {
|
|
308
|
+
guards.onNewRequest();
|
|
309
|
+
} catch {
|
|
310
|
+
// Re-arming a reminder never breaks a prompt.
|
|
311
|
+
}
|
|
304
312
|
try {
|
|
305
313
|
guards.observeTools(event && event.systemPromptOptions && event.systemPromptOptions.selectedTools);
|
|
306
314
|
} catch {
|
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
## ODD worktrees
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
read-only needs no worktree.
|
|
3
|
+
Every write goes in a worktree, whatever the size of the task, a one-line fix included. Never write
|
|
4
|
+
in the primary checkout or on the default branch.
|
|
6
5
|
|
|
7
|
-
A worktree lives at `<repo-parent>/<repo-name>-worktrees/<odd>`: the directory IS the ODD
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
6
|
+
A worktree lives at `<repo-parent>/<repo-name>-worktrees/<odd>`: the directory IS the ODD it serves, and
|
|
7
|
+
its feature branch lives there. Before your first `edit` or `write`:
|
|
8
|
+
|
|
9
|
+
1. Run `worktree_list`.
|
|
10
|
+
2. If the ODD has a worktree, work there.
|
|
11
|
+
3. If not, run `worktree_create` (`copy_changes: true` if the pending changes of the current checkout
|
|
12
|
+
belong to that work).
|
|
13
|
+
|
|
14
|
+
Reading anywhere is fine, and a request that stays read-only needs no worktree.
|
|
11
15
|
|
|
12
16
|
One ODD, one worktree. An ODD is one request and its follow-ups, big or small: everything
|
|
13
17
|
that belongs to it goes into the same ODD and worktree, and an unrelated request is another
|