@foliox/transparent-compact-pi 0.10.0 → 0.11.1

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.
@@ -0,0 +1,251 @@
1
+ import path from 'node:path';
2
+ import { parseShell as parse } from './parse.mjs';
3
+
4
+ const PATH_COMMANDS = new Set(['cat', 'head', 'tail', 'wc', 'ls', 'tree', 'stat', 'file', 'du',
5
+ 'cp', 'mv', 'install', 'rm', 'mkdir', 'touch', 'tee', 'diff', 'cmp', 'readlink', 'realpath']);
6
+ const SUBCOMMANDS = new Set(['git', 'cargo', 'npm', 'pnpm', 'yarn', 'go', 'docker', 'tmux', 'uv']);
7
+ const VALUE_FLAGS = new Set(['-m', '-j', '--max-count', '--context',
8
+ '--glob', '-g', '--include', '--exclude', '--exclude-dir', '--color', '--max-time', '--connect-timeout',
9
+ '-H', '--header', '-w', '--write-out', '-X', '--request', '-u', '--user', '--features', '--bin',
10
+ '--dt', '--duration', '--record-every', '--target', '--model', '--provider']);
11
+ const PATH_FLAGS = new Set(['-o', '--output', '-T', '--upload-file', '-K', '--config',
12
+ '--cacert', '--cert', '--key', '--output-dir', '--directory', '--manifest-path']);
13
+ const SCRIPT_FLAGS = new Set(['-c', '-e', '--eval']);
14
+ const GIT_PATH_COMMANDS = new Set(['add', 'diff', 'status', 'restore', 'rm', 'mv', 'ls-files', 'checkout']);
15
+ const DATA_FLAGS = new Set(['-d', '--data', '--data-binary', '--data-raw', '--data-urlencode']);
16
+ const INTERPRETER = /^(?:python[\d.]*|node|ruby|perl|bash|sh)$/;
17
+ const MAX_AST_NODES = 2048;
18
+ const MAX_BODY_MENTIONS = 8;
19
+ const looksLikeLocation = value => !!value && !/[\n\r\x00]/.test(value) &&
20
+ (/^[a-z][a-z\d+.-]*:\/\//i.test(value) ||
21
+ (!/[;|<>()=:]/.test(value) && (/^(?:\.{1,2}(?:\/|$)|\/|~\/)/.test(value) ||
22
+ /\//.test(value) || /\.[a-z][a-z\d_-]{0,12}$/i.test(value))));
23
+
24
+ // AST positions are UTF-8 byte offsets, not JS string indices.
25
+ const sourceText = (source, node) => source.subarray(node.Pos.Offset, node.End.Offset).toString('utf8');
26
+ const expression = (source, node) => {
27
+ const raw = sourceText(source, node);
28
+ return /^(["']).*\1$/s.test(raw) ? raw.slice(1, -1) : raw;
29
+ };
30
+ function literal(word) {
31
+ if (!word?.Parts) return null;
32
+ let out = '';
33
+ for (const part of word.Parts) {
34
+ if (part.Type === 'Lit') out += (part.Value ?? '').replace(/\\([^\n])/g, '$1').replace(/\\\n/g, '');
35
+ else if (part.Type === 'SglQuoted' && !part.Dollar) out += part.Value ?? '';
36
+ else if (part.Type === 'DblQuoted' && !part.Dollar) {
37
+ let text = '';
38
+ for (const item of part.Parts ?? []) {
39
+ if (item.Type !== 'Lit') return null;
40
+ text += (item.Value ?? '').replace(/\\([$`"\\])/g, '$1').replace(/\\\n/g, '');
41
+ }
42
+ out += text;
43
+ } else return null;
44
+ }
45
+ return out;
46
+ }
47
+
48
+ /** Pure static description: never runs commands, opens paths, or expands globs. */
49
+ export async function shellSkeleton(command, locations) {
50
+ const ast = await parse(command);
51
+ const source = Buffer.from(command);
52
+ const refs = new Set();
53
+ let visited = 0;
54
+ const tick = () => { if (++visited > MAX_AST_NODES) throw new Error('AST node budget exceeded'); };
55
+ const location = (value, state, kind = 'path') => {
56
+ const entry = locations.ref(value, state.cwd, kind);
57
+ refs.add(entry.id);
58
+ return entry.id;
59
+ };
60
+ const join = statements => statements.filter(Boolean).join('; ');
61
+ const copy = state => ({ ...state });
62
+
63
+ function mentions(body, state) {
64
+ const found = new Set();
65
+ // Literal-looking quoted strings only; intentionally not a Python/JS parser.
66
+ for (const match of body.slice(0, 65536).matchAll(/(["'])([^"'\\\n]*(?:\\.[^"'\\\n]*)*)\1/g)) {
67
+ const value = match[2];
68
+ if (looksLikeLocation(value)) found.add(value);
69
+ if (found.size > MAX_BODY_MENTIONS) break;
70
+ }
71
+ const selected = [...found].slice(0, MAX_BODY_MENTIONS).map(value => location(value, state));
72
+ return selected.length ? ` mentions ${selected.join(',')}${found.size > MAX_BODY_MENTIONS ? ',…' : ''}` : '';
73
+ }
74
+
75
+ function nested(node, state) {
76
+ if (!node || typeof node !== 'object') return [];
77
+ // Upstream JSON includes several source-position fields per node. They are
78
+ // coordinates, not nested syntax, and must not consume the AST node budget.
79
+ if (typeof node.Offset === 'number' && typeof node.Line === 'number' && typeof node.Col === 'number') return [];
80
+ tick();
81
+ if (node.Type === 'CmdSubst' || node.Type === 'ProcSubst')
82
+ return [`${node.Type === 'CmdSubst' ? '$(' : node.Op}${list(node.Stmts, copy(state))})`];
83
+ return Object.values(node).flatMap(value => Array.isArray(value)
84
+ ? value.flatMap(item => nested(item, state)) : value && typeof value === 'object' ? nested(value, state) : []);
85
+ }
86
+
87
+ function call(node, state) {
88
+ const words = node.Args ?? [];
89
+ const values = words.map(literal);
90
+ const name = values[0] === null ? '[dynamic command]' : path.posix.basename(values[0] ?? '[assign]');
91
+ if (name.length > 160) throw new Error('command name exceeds display budget');
92
+ let text = name;
93
+ if (values[0]?.includes('/')) text += `[${location(values[0], state)}]`;
94
+ if (name === 'timeout' && /^\d+(?:\.\d+)?[smhd]?$/.test(values[1] ?? '') && words.length > 2)
95
+ return `${text} ${call({ ...node, Args: words.slice(2) }, state)}`;
96
+ if (name === 'uv' && values[1] === 'run' && values[2] && !values[2].startsWith('-'))
97
+ return `${text} run ${call({ ...node, Args: words.slice(2) }, state)}`;
98
+ if (name === 'env' && values[1] && !values[1].startsWith('-')) {
99
+ const start = values.findIndex((value, index) => index > 0 && value && !value.includes('='));
100
+ if (start > 0) return `${text} ${call({ ...node, Args: words.slice(start) }, state)}`;
101
+ }
102
+ let pattern = ['sed', 'awk', 'grep', 'rg'].includes(name);
103
+ let afterDash = false, needsSubcommand = SUBCOMMANDS.has(name), verb = null;
104
+ let cdTarget = null;
105
+ for (let i = 1; i < words.length; i++) {
106
+ const value = values[i], raw = expression(source, words[i]);
107
+ if (value === '--') { afterDash = true; continue; }
108
+ if (value?.startsWith('-') && !afterDash) {
109
+ if (name === 'find') break; // Roots precede the find expression.
110
+ const equal = value.indexOf('=');
111
+ const flag = equal < 0 ? value : value.slice(0, equal);
112
+ const argument = equal < 0 ? values[i + 1] : value.slice(equal + 1);
113
+ if (INTERPRETER.test(name) && (SCRIPT_FLAGS.has(flag) || (name === 'node' && flag === '-p'))) {
114
+ if (argument !== undefined) {
115
+ text += ` [inline${mentions(argument ?? sourceText(source, words[i + 1]), state)}]`;
116
+ if (equal < 0) i++;
117
+ }
118
+ } else if ((PATH_FLAGS.has(flag) && (!/^-[oTK]$/.test(flag) || name === 'curl')) ||
119
+ (flag === '-f' && ['sed', 'awk', 'grep', 'rg'].includes(name))) {
120
+ if (argument !== undefined) text += ` ${location(argument ?? expression(source, words[i + 1]), state)}`;
121
+ if (equal < 0) i++;
122
+ if (flag === '-f') pattern = false;
123
+ } else if (DATA_FLAGS.has(flag) && name === 'curl') {
124
+ if (argument?.startsWith('@')) text += ` ${location(argument.slice(1), state)}`;
125
+ if (equal < 0) i++;
126
+ } else if (flag === '-e' && pattern) {
127
+ pattern = false;
128
+ if (equal < 0) i++;
129
+ } else if (VALUE_FLAGS.has(flag) || (['-n', '-c'].includes(flag) && ['head', 'tail'].includes(name)) ||
130
+ (['-A', '-B', '-C'].includes(flag) && ['grep', 'rg'].includes(name)) ||
131
+ (flag === '-c' && name === 'git') || (flag === '-t' && name === 'tmux') || (flag === '-v' && name === 'awk')) {
132
+ if (equal < 0) i++;
133
+ }
134
+ continue;
135
+ }
136
+ if (needsSubcommand && value && /^[\w-]+$/.test(value)) {
137
+ text += ` ${value}`;
138
+ needsSubcommand = false;
139
+ verb = value;
140
+ } else if (pattern) pattern = false;
141
+ else if (name === 'curl' && value && /^(?:[a-z][a-z\d+.-]*:\/\/|(?:[\w-]+\.)+[a-z]{2,}(?:[:/]|$)|localhost(?=[:/]|$))/i.test(value))
142
+ text += ` ${location(value, state, 'url')}`;
143
+ else if (name === 'git' && value && /^[^:]+:.+/.test(value) && verb === 'show')
144
+ text += ` ${location(value, state, 'git')}`;
145
+ else if (value !== '-' && value !== null && (name === 'cd' || PATH_COMMANDS.has(name) ||
146
+ ['sed', 'awk', 'grep', 'rg', 'find'].includes(name) ||
147
+ (name === 'git' ? afterDash || (GIT_PATH_COMMANDS.has(verb) && (verb === 'add' || looksLikeLocation(value)))
148
+ : looksLikeLocation(value)))) {
149
+ text += ` ${location(value, state)}`;
150
+ if (name === 'cd') cdTarget = value;
151
+ } else if (value === null && looksLikeLocation(raw) && !raw.includes('$(') && !raw.includes('`')) {
152
+ text += ` ${location(raw, state)}`;
153
+ }
154
+ }
155
+ // Substitutions may be in arguments that were otherwise discarded as flags/patterns.
156
+ for (const word of words) for (const expansion of nested(word, state)) text += ` ${expansion}`;
157
+ for (const assignment of node.Assigns ?? []) {
158
+ for (const expansion of nested(assignment, state)) text += ` ${expansion}`;
159
+ }
160
+ if (name === 'cd') {
161
+ state.cwd = cdTarget && !/[$`*?{}\[\]~]/.test(cdTarget) && (state.cwd || cdTarget.startsWith('/'))
162
+ ? path.posix.resolve(state.cwd ?? '/', cdTarget) : null;
163
+ }
164
+ return text;
165
+ }
166
+
167
+ function stmt(node, state) {
168
+ tick();
169
+ if (!node) return '';
170
+ const initial = copy(state);
171
+ let text = render(node.Cmd, node.Background ? copy(state) : state);
172
+ if (node.Negated) text = `! ${text}`;
173
+ // Redirections resolve before a command changes cwd.
174
+ for (const redirect of node.Redirs ?? []) {
175
+ if (redirect.Hdoc) {
176
+ const body = literal(redirect.Hdoc) ?? sourceText(source, redirect.Hdoc);
177
+ text += ` [body${mentions(body, initial)}]`;
178
+ for (const expansion of nested(redirect.Hdoc, initial)) text += ` ${expansion}`;
179
+ } else {
180
+ const value = literal(redirect.Word), raw = expression(source, redirect.Word);
181
+ const expansions = nested(redirect.Word, initial);
182
+ const fd = redirect.N?.Value ?? '';
183
+ if (redirect.Op === '<<<') {
184
+ text += ` <<<[stdin${mentions(value ?? raw, initial)}]`;
185
+ } else {
186
+ const destination = /[<>]&/.test(redirect.Op) && /^\d+-?$|^-$/.test(value ?? '')
187
+ ? value : value === null && expansions.length ? '[dynamic]' : location(value ?? raw, initial);
188
+ text += ` ${fd}${redirect.Op}${destination}`;
189
+ }
190
+ for (const expansion of expansions) text += ` ${expansion}`;
191
+ }
192
+ }
193
+ if (node.Background) text += ' &';
194
+ return text;
195
+ }
196
+
197
+ function list(nodes = [], state) { return join(nodes.map(node => stmt(node, state))); }
198
+ function render(node, state, type = node?.Type) {
199
+ tick();
200
+ if (!node) return '[assignment]';
201
+ switch (type) {
202
+ case 'CallExpr': return call(node, state);
203
+ case 'BinaryCmd': {
204
+ const before = copy(state), leftState = copy(state);
205
+ const left = stmt(node.X, leftState);
206
+ const rightState = copy(node.Op === '&&' ? leftState : before);
207
+ const right = stmt(node.Y, rightState);
208
+ // An enclosing && RHS is reached only after the left chain succeeded.
209
+ // Track that lexical success-path cwd; no claim about observed execution.
210
+ state.cwd = node.Op === '&&' ? rightState.cwd : leftState.cwd === rightState.cwd ? leftState.cwd : null;
211
+ if (node.Op === '|' || node.Op === '|&') state.cwd = before.cwd;
212
+ return `${left} ${node.Op} ${right}`;
213
+ }
214
+ case 'Subshell': return `(${list(node.Stmts, copy(state))})`;
215
+ case 'Block': return `{${list(node.Stmts, state)}}`;
216
+ case 'IfClause': {
217
+ const yes = copy(state), no = copy(state);
218
+ const condition = list(node.Cond, yes);
219
+ const then = list(node.Then, yes);
220
+ // Else is a concrete *IfClause, so upstream JSON omits its Type.
221
+ const otherwise = node.Else ? render(node.Else, no, 'IfClause') : '';
222
+ state.cwd = yes.cwd === no.cwd ? yes.cwd : null;
223
+ return condition ? `if{${condition}} then{${then}}${otherwise ? ` else{${otherwise}}` : ''}` : then;
224
+ }
225
+ case 'ForClause': {
226
+ const loopState = copy(state);
227
+ const body = list(node.Do, loopState);
228
+ if (loopState.cwd !== state.cwd) state.cwd = null;
229
+ return `for{${body}}`;
230
+ }
231
+ case 'WhileClause': {
232
+ const local = copy(state), condition = list(node.Cond, local), body = list(node.Do, local);
233
+ if (local.cwd !== state.cwd) state.cwd = null;
234
+ return `${node.Until ? 'until' : 'while'}{${condition}} do{${body}}`;
235
+ }
236
+ case 'CaseClause': {
237
+ const body = (node.Items ?? []).map(item => `{${list(item.Stmts, copy(state))}}`).join('; ');
238
+ state.cwd = null;
239
+ return `case{${body}}`;
240
+ }
241
+ case 'FuncDecl': return `function ${node.Name.Value}{${stmt(node.Body, { cwd: null })}}`;
242
+ case 'TimeClause': return `time ${stmt(node.Stmt, state)}`;
243
+ case 'TestClause': return '[[test]]';
244
+ case 'ArithmCmd': return '((arithmetic))';
245
+ default: throw new Error(`unsupported AST node: ${type}`);
246
+ }
247
+ }
248
+
249
+ const text = list(ast.Stmts, { cwd: locations.cwd });
250
+ return { text, refs: [...refs] };
251
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foliox/transparent-compact-pi",
3
- "version": "0.10.0",
3
+ "version": "0.11.1",
4
4
  "description": "Deterministic, verbatim-preserving compaction for Pi, with session-backed subagent context recovery.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -31,12 +31,15 @@
31
31
  "docs/"
32
32
  ],
33
33
  "scripts": {
34
+ "build:shell-parser": "node scripts/build-shell-parser.cjs",
35
+ "test:shell-parser": "node --test scripts/shell-parser-tests.mjs",
34
36
  "test": "node scripts/test-all.cjs",
35
37
  "test:integration": "node test.cjs",
36
38
  "test:cap": "node test.cjs cap",
37
39
  "test:caphang": "node test.cjs caphang",
38
40
  "test:capspans": "node test.cjs capspans",
39
- "test:package": "node scripts/test-package.cjs"
41
+ "test:package": "node scripts/test-package.cjs",
42
+ "test:tool-stubs": "node --test scripts/tool-renderer-tests.mjs"
40
43
  },
41
44
  "devDependencies": {
42
45
  "@earendil-works/pi-coding-agent": "1.1.0"
@@ -52,6 +55,7 @@
52
55
  "node": ">=22.19.0"
53
56
  },
54
57
  "pi": {
58
+ "changelogPath": "",
55
59
  "extensions": [
56
60
  "./extensions/index.ts"
57
61
  ],