@primitive.ai/prim 0.1.0-alpha.12 → 0.1.0-alpha.121
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 +550 -38
- package/SKILL.md +320 -75
- package/assets/primitive-gameplan/SKILL.md +134 -0
- package/assets/primitive-gameplan/claude-hooks.json +28 -0
- package/assets/primitive-gameplan/scripts/activate.mjs +37 -0
- package/dist/chunk-2DNC2MUN.js +503 -0
- package/dist/chunk-2PFJJO2M.js +262 -0
- package/dist/chunk-4GLVJLEQ.js +55 -0
- package/dist/chunk-4GYJHN26.js +1440 -0
- package/dist/chunk-6DEROXLM.js +22695 -0
- package/dist/chunk-7LXRFXZG.js +1992 -0
- package/dist/chunk-AKGRY7OU.js +1572 -0
- package/dist/chunk-BHT6X3T5.js +1450 -0
- package/dist/chunk-DQ4I3FLF.js +164 -0
- package/dist/chunk-DVHD6LBQ.js +258 -0
- package/dist/chunk-EZXEWFDG.js +210 -0
- package/dist/chunk-HG7FJK7R.js +253 -0
- package/dist/chunk-JSBRDJBE.js +30 -0
- package/dist/chunk-JXRJLHE4.js +168 -0
- package/dist/chunk-JZC2LHS6.js +209 -0
- package/dist/chunk-KZB4ABIB.js +13 -0
- package/dist/chunk-LQLP26RL.js +459 -0
- package/dist/chunk-M4NZJCPQ.js +135 -0
- package/dist/chunk-MRDY7VQP.js +96 -0
- package/dist/chunk-NMZSCSMY.js +157 -0
- package/dist/chunk-NQZLXYTW.js +36 -0
- package/dist/chunk-OXW6PSPT.js +439 -0
- package/dist/chunk-OYHYCK4K.js +13 -0
- package/dist/chunk-S3ZIMGXV.js +844 -0
- package/dist/chunk-WN7OURQ3.js +175 -0
- package/dist/daemon/server.js +26506 -0
- package/dist/hook-runtime/daemon/server.js +26507 -0
- package/dist/hook-runtime/hooks/post-commit.js +23898 -0
- package/dist/hook-runtime/hooks/post-rewrite.js +23797 -0
- package/dist/hook-runtime/hooks/post-tool-use.js +36213 -0
- package/dist/hook-runtime/hooks/pre-commit.js +1741 -0
- package/dist/hook-runtime/hooks/pre-tool-use-worker.js +35071 -0
- package/dist/hook-runtime/hooks/pre-tool-use.js +96 -0
- package/dist/hook-runtime/hooks/prim-hook.js +36273 -0
- package/dist/hook-runtime/hooks/session-end.js +1250 -0
- package/dist/hook-runtime/hooks/session-start.js +34021 -0
- package/dist/hook-runtime/index.js +71700 -0
- package/dist/hook-runtime/statusline-main.js +954 -0
- package/dist/hooks/post-commit.js +197 -0
- package/dist/hooks/post-rewrite.js +206 -0
- package/dist/hooks/post-tool-use.js +295 -0
- package/dist/hooks/pre-commit.js +16 -108
- package/dist/hooks/pre-tool-use-worker.js +238 -0
- package/dist/hooks/pre-tool-use.js +87 -0
- package/dist/hooks/prim-hook.js +245 -0
- package/dist/hooks/session-end.js +67 -0
- package/dist/hooks/session-start.js +312 -0
- package/dist/index.js +11249 -572
- package/dist/statusline-main.js +953 -0
- package/package.json +51 -17
- package/skills/prim-welcome/SKILL.md +197 -0
- package/dist/chunk-3APLWTLB.js +0 -165
|
@@ -0,0 +1,1450 @@
|
|
|
1
|
+
import {
|
|
2
|
+
inspectHookRuntime
|
|
3
|
+
} from "./chunk-AKGRY7OU.js";
|
|
4
|
+
import {
|
|
5
|
+
isDemoStatusResponse
|
|
6
|
+
} from "./chunk-6DEROXLM.js";
|
|
7
|
+
import {
|
|
8
|
+
atomicWriteFile,
|
|
9
|
+
primConfigDirectory,
|
|
10
|
+
withFileLock,
|
|
11
|
+
withFileLockSync
|
|
12
|
+
} from "./chunk-4GYJHN26.js";
|
|
13
|
+
|
|
14
|
+
// src/hooks/pre-tool-use-scoring.ts
|
|
15
|
+
import { isAbsolute, relative, sep } from "path";
|
|
16
|
+
function anyUnverified(results) {
|
|
17
|
+
return results.some((r) => r.verdict === "unavailable" || r.truncated);
|
|
18
|
+
}
|
|
19
|
+
function unverifiedNote(results) {
|
|
20
|
+
const causes = [];
|
|
21
|
+
const unavailable = results.find((r) => r.verdict === "unavailable");
|
|
22
|
+
if (unavailable) {
|
|
23
|
+
causes.push(
|
|
24
|
+
unavailable.unavailable ? `decision check skipped \u2014 ${unavailable.unavailable}` : "decision check skipped \u2014 not verified"
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
if (results.some((r) => r.truncated)) {
|
|
28
|
+
causes.push("decision check partial \u2014 conflict set truncated (per-file cap hit)");
|
|
29
|
+
}
|
|
30
|
+
return causes.map((c) => `[primitive] ${c}`).join("\n");
|
|
31
|
+
}
|
|
32
|
+
function blockingReason(results) {
|
|
33
|
+
const parts = results.filter((result) => result.verdict === "ask" || result.verdict === "deny").flatMap((result) => [result.reason, result.additionalContext]).filter((value) => value.length > 0);
|
|
34
|
+
return [...new Set(parts)].join("\n\n") || "[primitive] conflict detected (no detail available)";
|
|
35
|
+
}
|
|
36
|
+
function approvalReason(results) {
|
|
37
|
+
const summaries = results.filter((result) => result.verdict === "ask" || result.verdict === "deny").map((result) => result.reason).filter(Boolean);
|
|
38
|
+
return [
|
|
39
|
+
...new Set(summaries),
|
|
40
|
+
"Approve runs this edit once; it does not change these decisions."
|
|
41
|
+
].join("\n");
|
|
42
|
+
}
|
|
43
|
+
function agentContext(results) {
|
|
44
|
+
return [...new Set(results.map((result) => result.additionalContext).filter(Boolean))].join(
|
|
45
|
+
"\n\n"
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
function advisoryNote(aggregate, results) {
|
|
49
|
+
const details = results.flatMap((result) => [
|
|
50
|
+
...aggregate === "warn" ? [result.reason] : [],
|
|
51
|
+
result.additionalContext
|
|
52
|
+
]);
|
|
53
|
+
if (anyUnverified(results)) details.push(unverifiedNote(results));
|
|
54
|
+
return [...new Set(details.filter((value) => value.length > 0))].join("\n\n");
|
|
55
|
+
}
|
|
56
|
+
function buildHookOutput(aggregate, results) {
|
|
57
|
+
if (aggregate === "ask") {
|
|
58
|
+
const context = agentContext(results);
|
|
59
|
+
return {
|
|
60
|
+
hookSpecificOutput: {
|
|
61
|
+
hookEventName: "PreToolUse",
|
|
62
|
+
permissionDecision: "ask",
|
|
63
|
+
permissionDecisionReason: approvalReason(results),
|
|
64
|
+
...context ? { additionalContext: context } : {}
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
if (aggregate === "deny") {
|
|
69
|
+
return {
|
|
70
|
+
hookSpecificOutput: {
|
|
71
|
+
hookEventName: "PreToolUse",
|
|
72
|
+
permissionDecision: aggregate,
|
|
73
|
+
permissionDecisionReason: blockingReason(results)
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
const notes = advisoryNote(aggregate, results);
|
|
78
|
+
if (notes.length > 0) {
|
|
79
|
+
return {
|
|
80
|
+
systemMessage: notes,
|
|
81
|
+
hookSpecificOutput: {
|
|
82
|
+
hookEventName: "PreToolUse",
|
|
83
|
+
permissionDecision: "allow",
|
|
84
|
+
additionalContext: notes
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
hookSpecificOutput: {
|
|
90
|
+
hookEventName: "PreToolUse",
|
|
91
|
+
permissionDecision: "allow"
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
function buildCodexOutput(aggregate, results) {
|
|
96
|
+
if (aggregate === "deny" || aggregate === "ask") {
|
|
97
|
+
return {
|
|
98
|
+
hookSpecificOutput: {
|
|
99
|
+
hookEventName: "PreToolUse",
|
|
100
|
+
permissionDecision: "deny",
|
|
101
|
+
permissionDecisionReason: blockingReason(results)
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
const notes = advisoryNote(aggregate, results);
|
|
106
|
+
return notes ? {
|
|
107
|
+
systemMessage: notes,
|
|
108
|
+
hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: notes }
|
|
109
|
+
} : {};
|
|
110
|
+
}
|
|
111
|
+
function buildCursorOutput(aggregate, results) {
|
|
112
|
+
if (aggregate === "deny" || aggregate === "ask") {
|
|
113
|
+
const reason = blockingReason(results);
|
|
114
|
+
return { permission: "deny", user_message: reason, agent_message: reason };
|
|
115
|
+
}
|
|
116
|
+
const notes = advisoryNote(aggregate, results);
|
|
117
|
+
return notes ? { permission: "allow", agent_message: notes } : { permission: "allow" };
|
|
118
|
+
}
|
|
119
|
+
function failOpenOutput() {
|
|
120
|
+
return {
|
|
121
|
+
hookSpecificOutput: {
|
|
122
|
+
hookEventName: "PreToolUse",
|
|
123
|
+
permissionDecision: "allow"
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
function failOpenCodex() {
|
|
128
|
+
return {};
|
|
129
|
+
}
|
|
130
|
+
function failOpenCursor() {
|
|
131
|
+
return { permission: "allow" };
|
|
132
|
+
}
|
|
133
|
+
function buildHermesOutput(aggregate, results) {
|
|
134
|
+
if (aggregate !== "deny" && aggregate !== "ask") {
|
|
135
|
+
return {};
|
|
136
|
+
}
|
|
137
|
+
const reason = results.filter((r) => r.verdict === "deny" || r.verdict === "ask").map((r) => r.reason).filter((s) => s.length > 0).join("\n\n");
|
|
138
|
+
const directive = results.map((r) => r.additionalContext).filter((s) => s.length > 0 && s !== reason).join("\n");
|
|
139
|
+
const message = [reason, directive].filter((s) => s.length > 0).join("\n\n") || "[primitive] conflict detected (no detail available)";
|
|
140
|
+
return { action: "block", message };
|
|
141
|
+
}
|
|
142
|
+
function failOpenHermes() {
|
|
143
|
+
return {};
|
|
144
|
+
}
|
|
145
|
+
var SUPPORTED_TOOLS = /* @__PURE__ */ new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
|
|
146
|
+
var APPLY_PATCH_FILE_RE = /^\*\*\* (?:Update|Add|Delete) File: (?<path>.+)$/;
|
|
147
|
+
var MOVE_FILE_RE = /^\*\*\* Move File:\s*(?<src>.+?)\s*->\s*(?<dst>.+?)\s*$/;
|
|
148
|
+
var MOVE_TO_RE = /^\*\*\* Move to: (?<dst>.+)$/;
|
|
149
|
+
var LINE_SPLIT_RE = /\r?\n/;
|
|
150
|
+
function parseApplyPatchTargets(command) {
|
|
151
|
+
const paths = /* @__PURE__ */ new Set();
|
|
152
|
+
let activeUpdate = false;
|
|
153
|
+
let complete = true;
|
|
154
|
+
for (const line of command.split(LINE_SPLIT_RE)) {
|
|
155
|
+
const path = APPLY_PATCH_FILE_RE.exec(line)?.groups?.path;
|
|
156
|
+
if (path) {
|
|
157
|
+
paths.add(path);
|
|
158
|
+
activeUpdate = line.startsWith("*** Update File:");
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
const moveTo = MOVE_TO_RE.exec(line)?.groups?.dst;
|
|
162
|
+
if (moveTo) {
|
|
163
|
+
if (activeUpdate) paths.add(moveTo);
|
|
164
|
+
else complete = false;
|
|
165
|
+
activeUpdate = false;
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
const move = MOVE_FILE_RE.exec(line)?.groups;
|
|
169
|
+
if (move?.src) {
|
|
170
|
+
paths.add(move.src);
|
|
171
|
+
if (move.dst) {
|
|
172
|
+
paths.add(move.dst);
|
|
173
|
+
}
|
|
174
|
+
activeUpdate = false;
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
if (line === "*** Begin Patch" || line === "*** End Patch") activeUpdate = false;
|
|
178
|
+
else if (line.startsWith("*** ")) complete = false;
|
|
179
|
+
}
|
|
180
|
+
return { paths: [...paths], complete: complete && paths.size > 0 };
|
|
181
|
+
}
|
|
182
|
+
function extractCodexFileTargets(toolName, toolInput) {
|
|
183
|
+
if (toolName !== "apply_patch") {
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
const text = codexPatchText(toolInput);
|
|
187
|
+
return text !== null ? parseApplyPatchTargets(text) : { paths: [], complete: false };
|
|
188
|
+
}
|
|
189
|
+
function codexPatchText(toolInput) {
|
|
190
|
+
if (typeof toolInput === "string") return toolInput;
|
|
191
|
+
if (!toolInput || typeof toolInput !== "object") return null;
|
|
192
|
+
const input = toolInput;
|
|
193
|
+
for (const key of ["command", "input", "patch"]) {
|
|
194
|
+
const value = input[key];
|
|
195
|
+
if (typeof value === "string") return value;
|
|
196
|
+
}
|
|
197
|
+
return null;
|
|
198
|
+
}
|
|
199
|
+
var HERMES_EDITING_TOOLS = /* @__PURE__ */ new Set(["write_file", "patch"]);
|
|
200
|
+
function extractHermesFileTargets(toolName, toolInput) {
|
|
201
|
+
if (!HERMES_EDITING_TOOLS.has(toolName)) {
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
if (!toolInput || typeof toolInput !== "object") {
|
|
205
|
+
return { paths: [], complete: false };
|
|
206
|
+
}
|
|
207
|
+
const input = toolInput;
|
|
208
|
+
if (toolName === "patch" && input.mode === "patch") {
|
|
209
|
+
return typeof input.patch === "string" ? parseApplyPatchTargets(input.patch) : { paths: [], complete: false };
|
|
210
|
+
}
|
|
211
|
+
const paths = typeof input.path === "string" && input.path.length > 0 ? [input.path] : [];
|
|
212
|
+
const mode = input.mode;
|
|
213
|
+
return { paths, complete: paths.length > 0 && (mode === void 0 || mode === "replace") };
|
|
214
|
+
}
|
|
215
|
+
function extractCursorFileTargets(toolName, toolInput) {
|
|
216
|
+
if (toolName !== "Write" && toolName !== "Delete") return null;
|
|
217
|
+
if (!toolInput || typeof toolInput !== "object" || Array.isArray(toolInput)) {
|
|
218
|
+
return { paths: [], complete: false };
|
|
219
|
+
}
|
|
220
|
+
const input = toolInput;
|
|
221
|
+
const candidates = [input.file_path, input.path].filter(
|
|
222
|
+
(value) => typeof value === "string" && value.length > 0
|
|
223
|
+
);
|
|
224
|
+
const paths = [...new Set(candidates)];
|
|
225
|
+
return { paths, complete: paths.length === 1 };
|
|
226
|
+
}
|
|
227
|
+
function extractFileTargets(toolName, toolInput, agent = "claude_code") {
|
|
228
|
+
if (agent === "codex") {
|
|
229
|
+
return extractCodexFileTargets(toolName, toolInput);
|
|
230
|
+
}
|
|
231
|
+
if (agent === "cursor") {
|
|
232
|
+
return extractCursorFileTargets(toolName, toolInput);
|
|
233
|
+
}
|
|
234
|
+
if (agent === "hermes") {
|
|
235
|
+
return extractHermesFileTargets(toolName, toolInput);
|
|
236
|
+
}
|
|
237
|
+
if (!SUPPORTED_TOOLS.has(toolName)) {
|
|
238
|
+
return null;
|
|
239
|
+
}
|
|
240
|
+
if (!toolInput || typeof toolInput !== "object") {
|
|
241
|
+
return { paths: [], complete: false };
|
|
242
|
+
}
|
|
243
|
+
const input = toolInput;
|
|
244
|
+
if (toolName === "NotebookEdit") {
|
|
245
|
+
const paths2 = typeof input.notebook_path === "string" && input.notebook_path.length > 0 ? [input.notebook_path] : [];
|
|
246
|
+
return { paths: paths2, complete: paths2.length > 0 };
|
|
247
|
+
}
|
|
248
|
+
const paths = typeof input.file_path === "string" && input.file_path.length > 0 ? [input.file_path] : [];
|
|
249
|
+
return { paths, complete: paths.length > 0 };
|
|
250
|
+
}
|
|
251
|
+
function readHookMode(env) {
|
|
252
|
+
if (env.PRIM_BYPASS === "1" || env.PRIM_BYPASS === "true") {
|
|
253
|
+
return "off";
|
|
254
|
+
}
|
|
255
|
+
const mode = env.PRIM_HOOK_MODE;
|
|
256
|
+
if (mode === "off" || mode === "warn") {
|
|
257
|
+
return mode;
|
|
258
|
+
}
|
|
259
|
+
return "block";
|
|
260
|
+
}
|
|
261
|
+
function demoteForMode(verdict, mode) {
|
|
262
|
+
if (mode === "off") {
|
|
263
|
+
return "allow";
|
|
264
|
+
}
|
|
265
|
+
if (mode === "warn" && (verdict === "ask" || verdict === "deny")) {
|
|
266
|
+
return "warn";
|
|
267
|
+
}
|
|
268
|
+
return verdict;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// src/hooks/shell-targets.ts
|
|
272
|
+
import { realpathSync } from "fs";
|
|
273
|
+
import { posix, resolve } from "path";
|
|
274
|
+
import { parse } from "unbash";
|
|
275
|
+
|
|
276
|
+
// src/hooks/script-targets.ts
|
|
277
|
+
import { parser as javascript } from "@lezer/javascript";
|
|
278
|
+
import { parser as python } from "@lezer/python";
|
|
279
|
+
var MAX_SCRIPT_BYTES = 65536;
|
|
280
|
+
var WRITERS = /* @__PURE__ */ new Set(["writeFile", "writeFileSync", "appendFile", "appendFileSync"]);
|
|
281
|
+
var FS_MODULES = /* @__PURE__ */ new Set(["fs", "node:fs", "fs/promises", "node:fs/promises"]);
|
|
282
|
+
var IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
|
|
283
|
+
function children(node) {
|
|
284
|
+
const nodes = [];
|
|
285
|
+
for (let child = node?.firstChild; child; child = child.nextSibling) nodes.push(child);
|
|
286
|
+
return nodes;
|
|
287
|
+
}
|
|
288
|
+
function literal(text) {
|
|
289
|
+
const quote2 = text[0];
|
|
290
|
+
if (quote2 !== '"' && quote2 !== "'" || text.at(-1) !== quote2) return;
|
|
291
|
+
let value = "";
|
|
292
|
+
for (let i = 1; i < text.length - 1; i++) {
|
|
293
|
+
const char = text[i];
|
|
294
|
+
if (char === quote2 || char === "\n" || char === "\r") return;
|
|
295
|
+
if (char !== "\\") {
|
|
296
|
+
value += char;
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
299
|
+
const escaped = text[++i];
|
|
300
|
+
const simple = {
|
|
301
|
+
"\\": "\\",
|
|
302
|
+
"'": "'",
|
|
303
|
+
'"': '"',
|
|
304
|
+
n: "\n",
|
|
305
|
+
r: "\r",
|
|
306
|
+
t: " "
|
|
307
|
+
};
|
|
308
|
+
if (Object.hasOwn(simple, escaped)) value += simple[escaped];
|
|
309
|
+
else if (escaped === "u" || escaped === "x") {
|
|
310
|
+
const length = escaped === "u" ? 4 : 2;
|
|
311
|
+
const digits = text.slice(i + 1, i + 1 + length);
|
|
312
|
+
if (digits.length !== length || !/^[\da-f]+$/i.test(digits)) return;
|
|
313
|
+
value += String.fromCharCode(Number.parseInt(digits, 16));
|
|
314
|
+
i += length;
|
|
315
|
+
} else return;
|
|
316
|
+
}
|
|
317
|
+
return value;
|
|
318
|
+
}
|
|
319
|
+
function scriptWriteTargets(source, language) {
|
|
320
|
+
if (Buffer.byteLength(source) > MAX_SCRIPT_BYTES) return [];
|
|
321
|
+
try {
|
|
322
|
+
const tree = (language === "python" ? python : javascript).parse(source);
|
|
323
|
+
const cursor = tree.cursor();
|
|
324
|
+
let nodes = 0;
|
|
325
|
+
do {
|
|
326
|
+
if (++nodes > 2e4 || cursor.type.isError) return [];
|
|
327
|
+
if (language === "javascript" && cursor.name === "VariableDefinition" && source.slice(cursor.from, cursor.to) === "require")
|
|
328
|
+
return [];
|
|
329
|
+
if (["PropertyName", "VariableName", "VariableDefinition"].includes(cursor.name) && ["chdir", "exec", "eval"].includes(source.slice(cursor.from, cursor.to)))
|
|
330
|
+
return [];
|
|
331
|
+
} while (cursor.next());
|
|
332
|
+
const bindings = /* @__PURE__ */ new Map();
|
|
333
|
+
if (language === "python") bindings.set("open", { kind: "symbol", value: "open" });
|
|
334
|
+
else bindings.set("require", { kind: "symbol", value: "require" });
|
|
335
|
+
if (language === "javascript") {
|
|
336
|
+
for (const statement of children(tree.topNode)) {
|
|
337
|
+
if (statement.name !== "FunctionDeclaration") continue;
|
|
338
|
+
const name = statement.getChild("VariableDefinition");
|
|
339
|
+
if (name) bindings.set(source.slice(name.from, name.to), void 0);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
const paths = /* @__PURE__ */ new Set();
|
|
343
|
+
const text = (node) => source.slice(node.from, node.to);
|
|
344
|
+
const symbol = (value) => ({ kind: "symbol", value });
|
|
345
|
+
const bind = (name, value) => {
|
|
346
|
+
bindings.set(name, bindings.has(name) ? void 0 : value);
|
|
347
|
+
};
|
|
348
|
+
const forget = () => {
|
|
349
|
+
for (const name of bindings.keys()) bindings.set(name, void 0);
|
|
350
|
+
};
|
|
351
|
+
const args = (node) => children(node.getChild("ArgList")).filter((child) => !["(", ")", ","].includes(child.name));
|
|
352
|
+
const resolveValue = (node) => {
|
|
353
|
+
if (!node) return;
|
|
354
|
+
if (node.name === "String") {
|
|
355
|
+
const value = literal(text(node));
|
|
356
|
+
return value === void 0 ? void 0 : { kind: "string", value };
|
|
357
|
+
}
|
|
358
|
+
if (node.name === "VariableName") return bindings.get(text(node));
|
|
359
|
+
if (node.name === "MemberExpression") {
|
|
360
|
+
const [base, dot, property] = children(node);
|
|
361
|
+
if (dot?.name !== "." || property?.name !== "PropertyName") return;
|
|
362
|
+
const owner = resolveValue(base);
|
|
363
|
+
const name = text(property);
|
|
364
|
+
if (owner?.kind === "symbol") {
|
|
365
|
+
if (owner.value === "pathlib" && name === "Path") return symbol("Path");
|
|
366
|
+
if (owner.value === "fs" && name === "promises") return symbol("fs");
|
|
367
|
+
if (owner.value === "fs" && WRITERS.has(name)) return symbol("write");
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
if (node.name === "CallExpression") {
|
|
371
|
+
const callee = resolveValue(node.firstChild ?? void 0);
|
|
372
|
+
const parameters = args(node);
|
|
373
|
+
const first = resolveValue(parameters[0]);
|
|
374
|
+
if (callee?.kind === "symbol" && first?.kind === "string" && parameters.length === 1) {
|
|
375
|
+
if (callee.value === "Path") return { kind: "path", value: first.value };
|
|
376
|
+
if (callee.value === "require" && FS_MODULES.has(first.value)) return symbol("fs");
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
const inspect = (node) => {
|
|
381
|
+
if (/Function|Class|Lambda|ArrowFunction/.test(node.name)) return;
|
|
382
|
+
if (["AssignmentExpression", "UpdateExpression", "NamedExpression"].includes(node.name) || node.name.includes("Comprehension")) {
|
|
383
|
+
forget();
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
if (node.name === "CallExpression") {
|
|
387
|
+
const calleeNode = node.firstChild;
|
|
388
|
+
if (!calleeNode) return;
|
|
389
|
+
const callee = resolveValue(calleeNode);
|
|
390
|
+
const parameters = args(node);
|
|
391
|
+
const first = resolveValue(parameters[0]);
|
|
392
|
+
if (callee?.kind === "symbol" && callee.value === "write" && first?.kind === "string")
|
|
393
|
+
paths.add(first.value);
|
|
394
|
+
if (callee?.kind === "symbol" && callee.value === "open") {
|
|
395
|
+
const modeAt = parameters.findIndex(
|
|
396
|
+
(p) => p.name === "VariableName" && text(p) === "mode"
|
|
397
|
+
);
|
|
398
|
+
const mode = resolveValue(modeAt < 0 ? parameters[1] : parameters[modeAt + 2]);
|
|
399
|
+
if (first && ["string", "path"].includes(first.kind) && mode?.kind === "string" && /^[rwax][bt+]*$/.test(mode.value) && /[wax+]/.test(mode.value))
|
|
400
|
+
paths.add(first.value);
|
|
401
|
+
}
|
|
402
|
+
if (calleeNode.name === "MemberExpression") {
|
|
403
|
+
const [base, dot, property] = children(calleeNode);
|
|
404
|
+
const owner = resolveValue(base);
|
|
405
|
+
if (dot?.name === "." && property && owner?.kind === "path" && ["write_text", "write_bytes"].includes(text(property)))
|
|
406
|
+
paths.add(owner.value);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
for (const child of children(node)) inspect(child);
|
|
410
|
+
};
|
|
411
|
+
const importStatement = (node) => {
|
|
412
|
+
const statement = text(node).trim().replace(/;$/, "");
|
|
413
|
+
if (language === "python") {
|
|
414
|
+
const module = /^import pathlib(?: as (\w+))?$/.exec(statement);
|
|
415
|
+
const path = /^from pathlib import Path(?: as (\w+))?$/.exec(statement);
|
|
416
|
+
if (module) bind(module[1] ?? "pathlib", symbol("pathlib"));
|
|
417
|
+
else if (path) bind(path[1] ?? "Path", symbol("Path"));
|
|
418
|
+
else forget();
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
const sourceNode = node.getChild("String");
|
|
422
|
+
if (!sourceNode || !FS_MODULES.has(literal(text(sourceNode)) ?? "")) {
|
|
423
|
+
forget();
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
const group = node.getChild("ImportGroup");
|
|
427
|
+
if (group) {
|
|
428
|
+
for (const entry of text(group).slice(1, -1).split(",")) {
|
|
429
|
+
const match = /^\s*(\w+)(?:\s+as\s+(\w+))?\s*$/.exec(entry);
|
|
430
|
+
if (match)
|
|
431
|
+
bind(match[2] ?? match[1], WRITERS.has(match[1]) ? symbol("write") : void 0);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
const name = node.getChild("VariableDefinition");
|
|
435
|
+
if (name) bind(text(name), symbol("fs"));
|
|
436
|
+
};
|
|
437
|
+
const statements = children(tree.topNode).flatMap(
|
|
438
|
+
(statement) => statement.name === "StatementGroup" ? children(statement) : [statement]
|
|
439
|
+
);
|
|
440
|
+
for (const statement of statements) {
|
|
441
|
+
if (["Comment", "LineComment", "BlockComment", ";"].includes(statement.name)) continue;
|
|
442
|
+
if (["ImportStatement", "ImportDeclaration"].includes(statement.name)) {
|
|
443
|
+
importStatement(statement);
|
|
444
|
+
continue;
|
|
445
|
+
}
|
|
446
|
+
if (statement.name === "AssignStatement" || statement.name === "VariableDeclaration") {
|
|
447
|
+
const parts = children(statement).filter(
|
|
448
|
+
(p) => !["const", "let", "var", ";"].includes(p.name)
|
|
449
|
+
);
|
|
450
|
+
const [target, operator, expression] = parts;
|
|
451
|
+
if (parts.length !== 3 || !target || !operator || text(operator) !== "=") {
|
|
452
|
+
forget();
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
inspect(expression);
|
|
456
|
+
if (["VariableName", "VariableDefinition"].includes(target.name) && IDENTIFIER.test(text(target)))
|
|
457
|
+
bind(text(target), resolveValue(expression));
|
|
458
|
+
else if (target.name === "ObjectPattern" && resolveValue(expression)?.kind === "symbol" && resolveValue(expression)?.value === "fs") {
|
|
459
|
+
for (const entry of text(target).slice(1, -1).split(",")) {
|
|
460
|
+
const match = /^\s*(\w+)(?:\s*:\s*(\w+))?\s*$/.exec(entry);
|
|
461
|
+
if (match)
|
|
462
|
+
bind(match[2] ?? match[1], WRITERS.has(match[1]) ? symbol("write") : void 0);
|
|
463
|
+
else forget();
|
|
464
|
+
}
|
|
465
|
+
} else forget();
|
|
466
|
+
} else if (statement.name === "ExpressionStatement") inspect(statement);
|
|
467
|
+
else if (statement.name === "WithStatement") {
|
|
468
|
+
for (const child of children(statement)) {
|
|
469
|
+
if (child.name === "as") forget();
|
|
470
|
+
if (child.name === "CallExpression") inspect(child);
|
|
471
|
+
}
|
|
472
|
+
forget();
|
|
473
|
+
} else forget();
|
|
474
|
+
}
|
|
475
|
+
return [...paths];
|
|
476
|
+
} catch {
|
|
477
|
+
return [];
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// src/hooks/shell-targets.ts
|
|
482
|
+
var OUTPUT_REDIRECTS = /* @__PURE__ */ new Set([">", ">>", ">|", "&>", "&>>"]);
|
|
483
|
+
var READ_ONLY_COMMANDS = new Set(": cat echo false printf pwd test true [".split(" "));
|
|
484
|
+
var SINKS = /* @__PURE__ */ new Set(["/dev/null", "/dev/stdout", "/dev/stderr"]);
|
|
485
|
+
var STATIC_PARTS = /* @__PURE__ */ new Set(["Literal", "SingleQuoted", "AnsiCQuoted"]);
|
|
486
|
+
var set = (values) => new Set(values.split(" ").filter(Boolean));
|
|
487
|
+
var INFO_OPTIONS = set("--help --version");
|
|
488
|
+
var COMMAND_OPTIONS = {
|
|
489
|
+
rg: {
|
|
490
|
+
shortFlags: "0FHILNPSUabchilnopqsvwx",
|
|
491
|
+
shortValues: "ABCEgjMmrtTef",
|
|
492
|
+
longFlags: set(
|
|
493
|
+
"--binary --case-sensitive --column --count --count-matches --crlf --debug --files --files-with-matches --files-without-match --fixed-strings --follow --heading --hidden --ignore-case --invert-match --json --line-number --line-regexp --multiline --multiline-dotall --no-filename --no-heading --no-hidden --no-ignore --no-ignore-parent --no-ignore-vcs --no-line-number --null --null-data --one-file-system --only-matching --passthru --pcre2 --pretty --quiet --smart-case --stats --text --trim --unrestricted --with-filename --word-regexp"
|
|
494
|
+
),
|
|
495
|
+
longValues: set(
|
|
496
|
+
"--after-context --before-context --context --dfa-size-limit --encoding --engine --file --glob --iglob --max-columns --max-count --max-depth --path-separator --regexp --regex-size-limit --replace --sort --sortr --threads --type --type-add --type-clear --type-not"
|
|
497
|
+
),
|
|
498
|
+
longOptionalValues: set("--color")
|
|
499
|
+
},
|
|
500
|
+
grep: {
|
|
501
|
+
shortFlags: "EFGHIPRTUVabcdhiLlnoqrsuvwxyZz",
|
|
502
|
+
shortValues: "ABCDefm",
|
|
503
|
+
longFlags: set(
|
|
504
|
+
"--basic-regexp --binary-files-without-match --byte-offset --count --extended-regexp --files-with-matches --files-without-match --fixed-regexp --fixed-strings --help --ignore-case --initial-tab --invert-match --line-buffered --line-number --line-regexp --null --null-data --only-matching --perl-regexp --quiet --recursive --silent --unix-byte-offsets --version --with-filename --word-regexp"
|
|
505
|
+
),
|
|
506
|
+
longValues: set(
|
|
507
|
+
"--after-context --before-context --binary-files --context --devices --directories --exclude --exclude-dir --exclude-from --file --include --label --max-count --regexp"
|
|
508
|
+
),
|
|
509
|
+
longOptionalValues: set("--color")
|
|
510
|
+
},
|
|
511
|
+
head: {
|
|
512
|
+
numericCount: true,
|
|
513
|
+
shortFlags: "qvz",
|
|
514
|
+
shortValues: "cn",
|
|
515
|
+
longFlags: set("--help --quiet --verbose --version --zero-terminated"),
|
|
516
|
+
longValues: set("--bytes --lines")
|
|
517
|
+
},
|
|
518
|
+
tail: {
|
|
519
|
+
numericCount: true,
|
|
520
|
+
shortFlags: "Fqsvz",
|
|
521
|
+
shortValues: "cn",
|
|
522
|
+
longFlags: set("--help --quiet --retry --silent --verbose --version --zero-terminated"),
|
|
523
|
+
longValues: set("--bytes --lines --max-unchanged-stats --pid --sleep-interval"),
|
|
524
|
+
longOptionalValues: set("--follow")
|
|
525
|
+
},
|
|
526
|
+
wc: {
|
|
527
|
+
shortFlags: "cLlmw",
|
|
528
|
+
longFlags: set("--bytes --chars --help --lines --max-line-length --version --words"),
|
|
529
|
+
longValues: set("--files0-from")
|
|
530
|
+
},
|
|
531
|
+
ls: {
|
|
532
|
+
shortFlags: "ABCDFGHILNQRSTUXZabcdfghiklmnopqrstuvwxy",
|
|
533
|
+
shortValues: "ITw",
|
|
534
|
+
longFlags: set(
|
|
535
|
+
"--all --almost-all --author --classify --dereference --directory --dired --file-type --group-directories-first --help --hide-control-chars --human-readable --ignore-backups --inode --kibibytes --literal --no-group --numeric-uid-gid --quote-name --recursive --reverse --show-control-chars --size --version"
|
|
536
|
+
),
|
|
537
|
+
longValues: set(
|
|
538
|
+
"--block-size --format --hide --ignore --indicator-style --quoting-style --sort --tabsize --time --time-style --width"
|
|
539
|
+
),
|
|
540
|
+
longOptionalValues: set("--color --hyperlink")
|
|
541
|
+
}
|
|
542
|
+
};
|
|
543
|
+
var GIT_INSPECTION_OPTIONS = {
|
|
544
|
+
numericCount: true,
|
|
545
|
+
shortFlags: "abcdfhiklmnprstuvwz",
|
|
546
|
+
shortValues: "ABCGLMSU",
|
|
547
|
+
longFlags: set(
|
|
548
|
+
"--abbrev-commit --all --binary --branches --cached --check --children --date-order --deduplicate --deleted --error-unmatch --exclude-standard --exit-code --files-with-matches --full-history --full-index --full-name --graph --heading --ignore-all-space --ignore-blank-lines --ignore-space-at-eol --ignore-space-change --ignored --is-bare-repository --is-inside-git-dir --is-inside-work-tree --killed --left-only --line-number --merge-base --merges --modified --name-only --name-status --no-abbrev-commit --no-color --no-decorate --no-ext-diff --no-renames --no-textconv --numstat --objects --oneline --others --patch --quiet --remotes --right-only --root --short --shortstat --show-current --show-toplevel --stage --staged --stat --summary --symbolic-full-name --tags --topo-order --unmerged --verify --zero-commit"
|
|
549
|
+
),
|
|
550
|
+
longValues: set(
|
|
551
|
+
"--after --author --before --committer --date --decorate-refs-exclude --diff-filter --exclude --format --git-path --grep --max-count --max-depth --max-parents --min-parents --object-format --path-format --pretty --since --skip --sort --until"
|
|
552
|
+
),
|
|
553
|
+
longOptionalValues: set(
|
|
554
|
+
"--abbrev --batch --batch-check --color --decorate --relative --word-diff"
|
|
555
|
+
)
|
|
556
|
+
};
|
|
557
|
+
var GIT_METADATA_OPTIONS = {
|
|
558
|
+
add: {
|
|
559
|
+
shortFlags: "Afnpuv",
|
|
560
|
+
longFlags: set(
|
|
561
|
+
"--all --dry-run --force --ignore-errors --ignore-missing --intent-to-add --no-all --no-ignore-removal --pathspec-file-nul --refresh --renormalize --sparse --update --verbose"
|
|
562
|
+
),
|
|
563
|
+
longValues: set("--chmod --pathspec-from-file")
|
|
564
|
+
},
|
|
565
|
+
commit: {
|
|
566
|
+
shortFlags: "anqsu",
|
|
567
|
+
shortValues: "CFm",
|
|
568
|
+
longFlags: set(
|
|
569
|
+
"--all --allow-empty --allow-empty-message --amend --branch --dry-run --include --long --no-edit --no-post-rewrite --no-status --no-verify --null --only --pathspec-file-nul --porcelain --reset-author --short --signoff --status"
|
|
570
|
+
),
|
|
571
|
+
longValues: set(
|
|
572
|
+
"--author --cleanup --date --file --fixup --message --pathspec-from-file --reuse-message --squash --trailer --untracked-files"
|
|
573
|
+
)
|
|
574
|
+
},
|
|
575
|
+
push: {
|
|
576
|
+
shortFlags: "fquv",
|
|
577
|
+
longFlags: set(
|
|
578
|
+
"--all --atomic --delete --dry-run --follow-tags --force --force-if-includes --mirror --no-verify --porcelain --prune --quiet --set-upstream --tags --verbose"
|
|
579
|
+
),
|
|
580
|
+
longValues: set("--push-option --recurse-submodules"),
|
|
581
|
+
longOptionalValues: set("--force-with-lease")
|
|
582
|
+
},
|
|
583
|
+
branch: {
|
|
584
|
+
shortFlags: "adfMmrqv",
|
|
585
|
+
longFlags: set(
|
|
586
|
+
"--all --copy --delete --force --ignore-case --list --merged --move --no-color --no-contains --no-merged --remotes --show-current --verbose"
|
|
587
|
+
),
|
|
588
|
+
longValues: set("--contains --format --points-at --sort"),
|
|
589
|
+
longOptionalValues: set("--color --column --track")
|
|
590
|
+
},
|
|
591
|
+
"update-index": {
|
|
592
|
+
shortFlags: "q",
|
|
593
|
+
longFlags: set(
|
|
594
|
+
"--add --again --assume-unchanged --force-remove --fsmonitor-valid --ignore-missing --index-info --info-only --no-assume-unchanged --no-fsmonitor-valid --refresh --remove --replace --skip-worktree --unresolve"
|
|
595
|
+
),
|
|
596
|
+
longValues: set("--cacheinfo --chmod --index-version")
|
|
597
|
+
}
|
|
598
|
+
};
|
|
599
|
+
var GH_PR_OPTIONS = {
|
|
600
|
+
view: {
|
|
601
|
+
longFlags: set("--comments"),
|
|
602
|
+
longValues: set("--jq --json --template")
|
|
603
|
+
},
|
|
604
|
+
list: {
|
|
605
|
+
longFlags: set("--draft"),
|
|
606
|
+
longValues: set(
|
|
607
|
+
"--app --assignee --author --base --head --jq --json --label --limit --search --state --template"
|
|
608
|
+
)
|
|
609
|
+
},
|
|
610
|
+
status: {},
|
|
611
|
+
checks: {
|
|
612
|
+
longFlags: set("--fail-fast --required --watch"),
|
|
613
|
+
longValues: set("--interval --jq --json --template")
|
|
614
|
+
},
|
|
615
|
+
diff: {
|
|
616
|
+
longFlags: set("--name-only --patch"),
|
|
617
|
+
longValues: set("--color")
|
|
618
|
+
},
|
|
619
|
+
create: {
|
|
620
|
+
longFlags: set("--draft --fill --fill-first --fill-verbose --no-maintainer-edit"),
|
|
621
|
+
longValues: set(
|
|
622
|
+
"--assignee --base --body --body-file --head --label --milestone --project --recover --reviewer --template --title"
|
|
623
|
+
)
|
|
624
|
+
},
|
|
625
|
+
edit: {
|
|
626
|
+
longValues: set(
|
|
627
|
+
"--add-assignee --add-label --add-project --add-reviewer --base --body --body-file --milestone --remove-assignee --remove-label --remove-milestone --remove-project --remove-reviewer --title"
|
|
628
|
+
)
|
|
629
|
+
},
|
|
630
|
+
close: {
|
|
631
|
+
longValues: set("--comment")
|
|
632
|
+
},
|
|
633
|
+
reopen: {
|
|
634
|
+
longValues: set("--comment")
|
|
635
|
+
},
|
|
636
|
+
ready: {
|
|
637
|
+
longFlags: set("--undo")
|
|
638
|
+
},
|
|
639
|
+
review: {
|
|
640
|
+
longFlags: set("--approve --comment --request-changes"),
|
|
641
|
+
longValues: set("--body --body-file")
|
|
642
|
+
},
|
|
643
|
+
merge: {
|
|
644
|
+
shortFlags: "mdrs",
|
|
645
|
+
longFlags: set("--admin --auto --disable-auto --merge --rebase --squash"),
|
|
646
|
+
longValues: set("--author-email --body --body-file --match-head-commit --subject")
|
|
647
|
+
},
|
|
648
|
+
comment: {
|
|
649
|
+
longFlags: set("--delete-last --edit-last"),
|
|
650
|
+
longValues: set("--body --body-file")
|
|
651
|
+
},
|
|
652
|
+
lock: {
|
|
653
|
+
longValues: set("--reason")
|
|
654
|
+
},
|
|
655
|
+
unlock: {}
|
|
656
|
+
};
|
|
657
|
+
function staticPart(part) {
|
|
658
|
+
return STATIC_PARTS.has(part.type) || part.type === "DoubleQuoted" && part.parts.every(staticPart);
|
|
659
|
+
}
|
|
660
|
+
function staticWord(word) {
|
|
661
|
+
if (!word || word.value.includes("\0") || word.value.includes("\n")) return;
|
|
662
|
+
if (word.parts ? !word.parts.every(staticPart) : word.value.startsWith("~") || /[*?\[$`]/.test(word.text))
|
|
663
|
+
return;
|
|
664
|
+
return word.value;
|
|
665
|
+
}
|
|
666
|
+
function parseOptions(args, spec) {
|
|
667
|
+
const result = {
|
|
668
|
+
operands: [],
|
|
669
|
+
seen: /* @__PURE__ */ new Set(),
|
|
670
|
+
values: /* @__PURE__ */ new Map()
|
|
671
|
+
};
|
|
672
|
+
let optionsEnded = false;
|
|
673
|
+
const recordValue = (option, value) => {
|
|
674
|
+
result.seen.add(option);
|
|
675
|
+
result.values.set(option, [...result.values.get(option) ?? [], value]);
|
|
676
|
+
};
|
|
677
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
678
|
+
const arg = args[index];
|
|
679
|
+
if (optionsEnded || arg === "-" || !arg.startsWith("-")) {
|
|
680
|
+
result.operands.push(arg);
|
|
681
|
+
continue;
|
|
682
|
+
}
|
|
683
|
+
if (arg === "--") {
|
|
684
|
+
optionsEnded = true;
|
|
685
|
+
continue;
|
|
686
|
+
}
|
|
687
|
+
if (spec.numericCount && /^-\d+$/.test(arg)) continue;
|
|
688
|
+
if (arg.startsWith("--")) {
|
|
689
|
+
const separator = arg.indexOf("=");
|
|
690
|
+
const option = separator === -1 ? arg : arg.slice(0, separator);
|
|
691
|
+
const attached = separator === -1 ? void 0 : arg.slice(separator + 1);
|
|
692
|
+
if (spec.longValues?.has(option)) {
|
|
693
|
+
const value = attached ?? args[++index];
|
|
694
|
+
if (!value) return;
|
|
695
|
+
recordValue(option, value);
|
|
696
|
+
} else if (spec.longOptionalValues?.has(option)) {
|
|
697
|
+
result.seen.add(option);
|
|
698
|
+
if (attached !== void 0) recordValue(option, attached);
|
|
699
|
+
} else if (spec.longFlags?.has(option) && attached === void 0) {
|
|
700
|
+
result.seen.add(option);
|
|
701
|
+
} else {
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
continue;
|
|
705
|
+
}
|
|
706
|
+
for (let offset = 1; offset < arg.length; offset += 1) {
|
|
707
|
+
const option = `-${arg[offset]}`;
|
|
708
|
+
if (spec.shortValues?.includes(arg[offset])) {
|
|
709
|
+
const attached = arg.slice(offset + 1);
|
|
710
|
+
const value = attached || args[++index];
|
|
711
|
+
if (!value) return;
|
|
712
|
+
recordValue(option, value);
|
|
713
|
+
break;
|
|
714
|
+
}
|
|
715
|
+
if (!spec.shortFlags?.includes(arg[offset])) return;
|
|
716
|
+
result.seen.add(option);
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
return result;
|
|
720
|
+
}
|
|
721
|
+
function staticArgs(words) {
|
|
722
|
+
const args = [];
|
|
723
|
+
for (const word of words) {
|
|
724
|
+
const value = staticWord(word);
|
|
725
|
+
if (value === void 0) return;
|
|
726
|
+
args.push(value);
|
|
727
|
+
}
|
|
728
|
+
return args;
|
|
729
|
+
}
|
|
730
|
+
function safeSedProgram(program) {
|
|
731
|
+
if (/^(?:(?:\d+|\$)(?:,(?:\d+|\$))?)?[dDpPqQnN=]$/.test(program) || /^\/(?:\\.|[^/])*\/[dDpPqQnN=]$/.test(program))
|
|
732
|
+
return true;
|
|
733
|
+
const match = /^(?:(?:\d+|\$)(?:,(?:\d+|\$))?)?s(.)(.*)$/s.exec(program);
|
|
734
|
+
if (!match || /[\\\nA-Za-z0-9]/.test(match[1])) return false;
|
|
735
|
+
const delimiter = match[1];
|
|
736
|
+
const tail = match[2];
|
|
737
|
+
let offset = 0;
|
|
738
|
+
for (let section = 0; section < 2; section += 1) {
|
|
739
|
+
let closed = false;
|
|
740
|
+
while (offset < tail.length) {
|
|
741
|
+
if (tail[offset] === "\\") {
|
|
742
|
+
offset += 2;
|
|
743
|
+
} else if (tail[offset] === delimiter) {
|
|
744
|
+
offset += 1;
|
|
745
|
+
closed = true;
|
|
746
|
+
break;
|
|
747
|
+
} else {
|
|
748
|
+
offset += 1;
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
if (!closed) return false;
|
|
752
|
+
}
|
|
753
|
+
return /^[0-9gIpMm]*$/.test(tail.slice(offset));
|
|
754
|
+
}
|
|
755
|
+
function safeSed(args) {
|
|
756
|
+
if (args.length === 1 && INFO_OPTIONS.has(args[0])) return true;
|
|
757
|
+
const parsed = parseOptions(args, {
|
|
758
|
+
shortFlags: "Enrsu",
|
|
759
|
+
shortValues: "e",
|
|
760
|
+
longFlags: set("--quiet --regexp-extended --separate --silent --unbuffered"),
|
|
761
|
+
longValues: set("--expression")
|
|
762
|
+
});
|
|
763
|
+
if (!parsed) return false;
|
|
764
|
+
const optionPrograms = [
|
|
765
|
+
...parsed.values.get("-e") ?? [],
|
|
766
|
+
...parsed.values.get("--expression") ?? []
|
|
767
|
+
];
|
|
768
|
+
const programs = optionPrograms.length > 0 ? optionPrograms : parsed.operands.length > 0 ? [parsed.operands.shift()] : [];
|
|
769
|
+
return programs.length > 0 && programs.every(safeSedProgram);
|
|
770
|
+
}
|
|
771
|
+
function safeFind(args) {
|
|
772
|
+
if (args.length === 1 && INFO_OPTIONS.has(args[0])) return true;
|
|
773
|
+
const noValue = set(
|
|
774
|
+
"! ( ) -a -and -daystart -empty -executable -false -follow -ignore_readdir_race -ls -mount -noignore_readdir_race -not -o -or -print -print0 -prune -readable -true -writable -xdev"
|
|
775
|
+
);
|
|
776
|
+
const oneValue = set(
|
|
777
|
+
"-amin -anewer -atime -cmin -cnewer -ctime -fstype -gid -group -ilname -iname -inum -ipath -iregex -iwholename -links -lname -maxdepth -mindepth -mmin -mtime -name -newer -path -perm -printf -regex -regextype -samefile -size -type -uid -used -user -wholename -xtype"
|
|
778
|
+
);
|
|
779
|
+
let expressionStarted = false;
|
|
780
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
781
|
+
const arg = args[index];
|
|
782
|
+
if (!expressionStarted && (arg === "-H" || arg === "-L" || arg === "-P" || /^-O\d+$/.test(arg)))
|
|
783
|
+
continue;
|
|
784
|
+
if (!expressionStarted && !arg.startsWith("-") && arg !== "!" && arg !== "(") continue;
|
|
785
|
+
expressionStarted = true;
|
|
786
|
+
if (noValue.has(arg)) continue;
|
|
787
|
+
if (/^-newer(?:a|B|c|m)t$/.test(arg) || /^-newer[acm][acm]$/.test(arg) || oneValue.has(arg)) {
|
|
788
|
+
if (!args[++index]) return false;
|
|
789
|
+
continue;
|
|
790
|
+
}
|
|
791
|
+
return false;
|
|
792
|
+
}
|
|
793
|
+
return true;
|
|
794
|
+
}
|
|
795
|
+
function withLongOptions(spec, flags, values) {
|
|
796
|
+
return {
|
|
797
|
+
...spec,
|
|
798
|
+
longFlags: /* @__PURE__ */ new Set([...spec.longFlags ?? [], ...flags.split(" ").filter(Boolean)]),
|
|
799
|
+
longValues: /* @__PURE__ */ new Set([...spec.longValues ?? [], ...values.split(" ").filter(Boolean)])
|
|
800
|
+
};
|
|
801
|
+
}
|
|
802
|
+
function safeGit(args) {
|
|
803
|
+
let index = 0;
|
|
804
|
+
while (index < args.length) {
|
|
805
|
+
const arg = args[index];
|
|
806
|
+
if (arg === "--no-pager" || arg === "--paginate") {
|
|
807
|
+
index += 1;
|
|
808
|
+
} else if (arg === "-C" || arg === "--git-dir" || arg === "--work-tree") {
|
|
809
|
+
if (!args[index + 1]) return false;
|
|
810
|
+
index += 2;
|
|
811
|
+
} else if (arg.startsWith("--git-dir=") || arg.startsWith("--work-tree=")) {
|
|
812
|
+
if (!arg.slice(arg.indexOf("=") + 1)) return false;
|
|
813
|
+
index += 1;
|
|
814
|
+
} else {
|
|
815
|
+
break;
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
const subcommand = args[index++];
|
|
819
|
+
if (!subcommand) return args.length === 1 && INFO_OPTIONS.has(args[0]);
|
|
820
|
+
const rest = args.slice(index);
|
|
821
|
+
if ((/* @__PURE__ */ new Set([
|
|
822
|
+
"blame",
|
|
823
|
+
"cat-file",
|
|
824
|
+
"describe",
|
|
825
|
+
"diff",
|
|
826
|
+
"for-each-ref",
|
|
827
|
+
"grep",
|
|
828
|
+
"log",
|
|
829
|
+
"ls-files",
|
|
830
|
+
"ls-tree",
|
|
831
|
+
"merge-base",
|
|
832
|
+
"name-rev",
|
|
833
|
+
"rev-list",
|
|
834
|
+
"rev-parse",
|
|
835
|
+
"shortlog",
|
|
836
|
+
"show",
|
|
837
|
+
"status"
|
|
838
|
+
])).has(subcommand))
|
|
839
|
+
return parseOptions(rest, GIT_INSPECTION_OPTIONS) !== void 0;
|
|
840
|
+
const metadata = GIT_METADATA_OPTIONS[subcommand];
|
|
841
|
+
if (metadata) {
|
|
842
|
+
const parsed = parseOptions(rest, metadata);
|
|
843
|
+
if (!parsed) return false;
|
|
844
|
+
if (subcommand !== "commit") return true;
|
|
845
|
+
return [
|
|
846
|
+
"-C",
|
|
847
|
+
"-F",
|
|
848
|
+
"-m",
|
|
849
|
+
"--dry-run",
|
|
850
|
+
"--file",
|
|
851
|
+
"--message",
|
|
852
|
+
"--no-edit",
|
|
853
|
+
"--reuse-message"
|
|
854
|
+
].some((option) => parsed.seen.has(option));
|
|
855
|
+
}
|
|
856
|
+
if (subcommand === "reset") {
|
|
857
|
+
const parsed = parseOptions(rest, {
|
|
858
|
+
shortFlags: "Npq",
|
|
859
|
+
longFlags: set("--intent-to-add --mixed --no-refresh --pathspec-file-nul --quiet --soft"),
|
|
860
|
+
longValues: set("--pathspec-from-file")
|
|
861
|
+
});
|
|
862
|
+
return parsed !== void 0;
|
|
863
|
+
}
|
|
864
|
+
if (subcommand === "restore") {
|
|
865
|
+
const parsed = parseOptions(rest, {
|
|
866
|
+
shortFlags: "pq",
|
|
867
|
+
longFlags: set(
|
|
868
|
+
"--ignore-skip-worktree-bits --no-overlay --overlay --pathspec-file-nul --staged"
|
|
869
|
+
),
|
|
870
|
+
longValues: set("--pathspec-from-file --source")
|
|
871
|
+
});
|
|
872
|
+
return parsed?.seen.has("--staged") === true;
|
|
873
|
+
}
|
|
874
|
+
if (subcommand === "rm") {
|
|
875
|
+
const parsed = parseOptions(rest, {
|
|
876
|
+
shortFlags: "fnqr",
|
|
877
|
+
longFlags: set(
|
|
878
|
+
"--cached --dry-run --force --ignore-unmatch --pathspec-file-nul --quiet --recursive"
|
|
879
|
+
),
|
|
880
|
+
longValues: set("--pathspec-from-file")
|
|
881
|
+
});
|
|
882
|
+
return parsed?.seen.has("--cached") === true;
|
|
883
|
+
}
|
|
884
|
+
if (subcommand === "update-ref")
|
|
885
|
+
return parseOptions(rest, {
|
|
886
|
+
shortFlags: "d",
|
|
887
|
+
longFlags: set("--create-reflog --delete --no-deref --stdin"),
|
|
888
|
+
longValues: set("--reason")
|
|
889
|
+
}) !== void 0;
|
|
890
|
+
return false;
|
|
891
|
+
}
|
|
892
|
+
function safeGh(args) {
|
|
893
|
+
let index = 0;
|
|
894
|
+
while (index < args.length) {
|
|
895
|
+
const arg = args[index];
|
|
896
|
+
if (arg === "-R" || arg === "--repo" || arg === "--hostname") {
|
|
897
|
+
if (!args[index + 1]) return false;
|
|
898
|
+
index += 2;
|
|
899
|
+
} else if (arg.startsWith("--repo=") || arg.startsWith("--hostname=")) {
|
|
900
|
+
if (!arg.slice(arg.indexOf("=") + 1)) return false;
|
|
901
|
+
index += 1;
|
|
902
|
+
} else {
|
|
903
|
+
break;
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
if (args[index++] !== "pr") return false;
|
|
907
|
+
const subcommand = args[index++];
|
|
908
|
+
if (!subcommand) return args.length === index && args.at(-1) === "--help";
|
|
909
|
+
const spec = GH_PR_OPTIONS[subcommand];
|
|
910
|
+
if (!spec) return false;
|
|
911
|
+
const common = withLongOptions(spec, "--help", "--hostname --repo");
|
|
912
|
+
const parsed = parseOptions(args.slice(index), {
|
|
913
|
+
...common,
|
|
914
|
+
shortValues: `${common.shortValues ?? ""}R`
|
|
915
|
+
});
|
|
916
|
+
if (!parsed) return false;
|
|
917
|
+
if (subcommand === "create") {
|
|
918
|
+
const filled = ["--fill", "--fill-first", "--fill-verbose", "--recover"].some(
|
|
919
|
+
(option) => parsed.seen.has(option)
|
|
920
|
+
);
|
|
921
|
+
return filled || parsed.seen.has("--title") && (parsed.seen.has("--body") || parsed.seen.has("--body-file"));
|
|
922
|
+
}
|
|
923
|
+
if (subcommand === "comment" && parsed.seen.has("--edit-last"))
|
|
924
|
+
return parsed.seen.has("--body") || parsed.seen.has("--body-file");
|
|
925
|
+
if (subcommand === "merge")
|
|
926
|
+
return ["--disable-auto", "--merge", "--rebase", "--squash", "-m", "-r", "-s"].some(
|
|
927
|
+
(option) => parsed.seen.has(option)
|
|
928
|
+
);
|
|
929
|
+
return true;
|
|
930
|
+
}
|
|
931
|
+
function knownNoWorktreeMutation(name, args) {
|
|
932
|
+
const options = COMMAND_OPTIONS[name];
|
|
933
|
+
if (options)
|
|
934
|
+
return args.length === 1 && INFO_OPTIONS.has(args[0]) || parseOptions(args, options) !== void 0;
|
|
935
|
+
if (name === "sed") return safeSed(args);
|
|
936
|
+
if (name === "find") return safeFind(args);
|
|
937
|
+
if (name === "git") return safeGit(args);
|
|
938
|
+
if (name === "gh") return safeGh(args);
|
|
939
|
+
return false;
|
|
940
|
+
}
|
|
941
|
+
function unknown(state) {
|
|
942
|
+
state.complete = false;
|
|
943
|
+
state.mutation = true;
|
|
944
|
+
}
|
|
945
|
+
function addTarget(path, state) {
|
|
946
|
+
if (state.cwdUncertain) {
|
|
947
|
+
state.complete = false;
|
|
948
|
+
return;
|
|
949
|
+
}
|
|
950
|
+
state.paths.add(
|
|
951
|
+
state.cwdPrefix && !posix.isAbsolute(path) ? posix.join(state.cwdPrefix, path) : path
|
|
952
|
+
);
|
|
953
|
+
}
|
|
954
|
+
function sedWriteTargets(words) {
|
|
955
|
+
const args = staticArgs(words);
|
|
956
|
+
if (!args) return;
|
|
957
|
+
let suffix;
|
|
958
|
+
let gnuInPlace = false;
|
|
959
|
+
const programs = [];
|
|
960
|
+
const files = [];
|
|
961
|
+
let positionalProgram = true;
|
|
962
|
+
let options = true;
|
|
963
|
+
for (let i = 0; i < args.length; i++) {
|
|
964
|
+
const arg = args[i];
|
|
965
|
+
if (options && arg === "--") {
|
|
966
|
+
options = false;
|
|
967
|
+
continue;
|
|
968
|
+
}
|
|
969
|
+
if (options && (arg === "-i" || arg === "--in-place")) {
|
|
970
|
+
if (suffix !== void 0) return;
|
|
971
|
+
suffix = "";
|
|
972
|
+
gnuInPlace = arg === "--in-place";
|
|
973
|
+
if (arg === "-i" && (args[i + 1] === "" || args[i + 1]?.startsWith("."))) suffix = args[++i];
|
|
974
|
+
} else if (options && (arg.startsWith("-i") || arg.startsWith("--in-place="))) {
|
|
975
|
+
if (suffix !== void 0) return;
|
|
976
|
+
gnuInPlace = arg.startsWith("--in-place=");
|
|
977
|
+
suffix = arg.startsWith("-i") ? arg.slice(2) : arg.slice("--in-place=".length);
|
|
978
|
+
} else if (options && (arg === "-e" || arg === "--expression")) {
|
|
979
|
+
const program = args[++i];
|
|
980
|
+
if (!program) return;
|
|
981
|
+
programs.push(program);
|
|
982
|
+
positionalProgram = false;
|
|
983
|
+
} else if (options && (arg.startsWith("-e") || arg.startsWith("--expression="))) {
|
|
984
|
+
programs.push(arg.startsWith("-e") ? arg.slice(2) : arg.slice("--expression=".length));
|
|
985
|
+
positionalProgram = false;
|
|
986
|
+
} else if (options && ["-E", "-r", "-n", "--regexp-extended", "--quiet", "--silent"].includes(arg)) {
|
|
987
|
+
} else if (options && arg.startsWith("-")) return;
|
|
988
|
+
else if (positionalProgram) {
|
|
989
|
+
programs.push(arg);
|
|
990
|
+
positionalProgram = false;
|
|
991
|
+
} else files.push(arg);
|
|
992
|
+
}
|
|
993
|
+
if (suffix === void 0 || !programs.length || !programs.every(safeSedProgram) || !files.length || files.some((file) => !file || file === "-"))
|
|
994
|
+
return;
|
|
995
|
+
if (suffix.includes("*") && !gnuInPlace) return;
|
|
996
|
+
return files.flatMap(
|
|
997
|
+
(file) => suffix ? [file, suffix.includes("*") ? suffix.replaceAll("*", file) : file + suffix] : [file]
|
|
998
|
+
);
|
|
999
|
+
}
|
|
1000
|
+
function recordTarget(word, state) {
|
|
1001
|
+
const path = staticWord(word);
|
|
1002
|
+
if (path === "-" || path && (SINKS.has(path) || path.startsWith("/dev/fd/"))) return;
|
|
1003
|
+
state.mutation = true;
|
|
1004
|
+
if (path) addTarget(path, state);
|
|
1005
|
+
else state.complete = false;
|
|
1006
|
+
}
|
|
1007
|
+
function visitRedirect(redirect, state) {
|
|
1008
|
+
const target = staticWord(redirect.target);
|
|
1009
|
+
if (redirect.operator === ">&" && (target === "-" || /^\d+$/.test(target ?? ""))) return;
|
|
1010
|
+
if (OUTPUT_REDIRECTS.has(redirect.operator) || redirect.operator === ">&")
|
|
1011
|
+
recordTarget(redirect.target, state);
|
|
1012
|
+
else unknown(state);
|
|
1013
|
+
}
|
|
1014
|
+
function visitApplyPatch(command, state) {
|
|
1015
|
+
state.mutation = true;
|
|
1016
|
+
state.definiteEdit = true;
|
|
1017
|
+
let hasBody = false;
|
|
1018
|
+
if (command.suffix.length > 0) state.complete = false;
|
|
1019
|
+
for (const redirect of command.redirects) {
|
|
1020
|
+
if (redirect.operator !== "<<") {
|
|
1021
|
+
visitRedirect(redirect, state);
|
|
1022
|
+
continue;
|
|
1023
|
+
}
|
|
1024
|
+
if (typeof redirect.content !== "string") {
|
|
1025
|
+
state.complete = false;
|
|
1026
|
+
continue;
|
|
1027
|
+
}
|
|
1028
|
+
hasBody = true;
|
|
1029
|
+
if (redirect.heredocQuoted !== true && redirect.body !== void 0) {
|
|
1030
|
+
state.complete = false;
|
|
1031
|
+
continue;
|
|
1032
|
+
}
|
|
1033
|
+
const targets = parseApplyPatchTargets(redirect.content);
|
|
1034
|
+
for (const path of targets.paths) addTarget(path, state);
|
|
1035
|
+
if (!targets.complete) state.complete = false;
|
|
1036
|
+
}
|
|
1037
|
+
if (!hasBody) state.complete = false;
|
|
1038
|
+
}
|
|
1039
|
+
function operands(words, short = "", long = /* @__PURE__ */ new Set()) {
|
|
1040
|
+
const result = [];
|
|
1041
|
+
let optionsEnded = false;
|
|
1042
|
+
for (const word of words) {
|
|
1043
|
+
const value = staticWord(word);
|
|
1044
|
+
if (value === void 0) return;
|
|
1045
|
+
if (optionsEnded || value === "-" || !value.startsWith("-")) result.push(value);
|
|
1046
|
+
else if (value === "--") optionsEnded = true;
|
|
1047
|
+
else if (value.startsWith("--") ? !long.has(value) : [...value.slice(1)].some((c) => !short.includes(c)))
|
|
1048
|
+
return;
|
|
1049
|
+
}
|
|
1050
|
+
return result;
|
|
1051
|
+
}
|
|
1052
|
+
function embeddedScript(command, name, state) {
|
|
1053
|
+
unknown(state);
|
|
1054
|
+
if (state.cwdUncertain || command.prefix.length) return;
|
|
1055
|
+
const words = command.suffix.map(
|
|
1056
|
+
(word) => (word.parts ? word.parts.every(staticPart) : staticWord(word) !== void 0) && !word.value.includes("\0") ? word.value : void 0
|
|
1057
|
+
);
|
|
1058
|
+
if (words.some((word) => word === void 0)) return;
|
|
1059
|
+
const args = words;
|
|
1060
|
+
const language = name === "node" ? "javascript" : "python";
|
|
1061
|
+
if (language === "javascript" && /^--input-type=(module|commonjs)$/.test(args[0] ?? ""))
|
|
1062
|
+
args.shift();
|
|
1063
|
+
const inlineFlag = language === "python" ? ["-c"] : ["-e", "--eval"];
|
|
1064
|
+
let source;
|
|
1065
|
+
if (args.length === 2 && inlineFlag.includes(args[0])) source = args[1];
|
|
1066
|
+
else if (args.length === 0 || args.length === 1 && args[0] === "-") {
|
|
1067
|
+
const input = command.redirects.filter((redirect) => redirect.operator.startsWith("<"));
|
|
1068
|
+
const heredoc = input[0];
|
|
1069
|
+
if (input.length === 1 && heredoc.operator === "<<" && heredoc.heredocQuoted === true)
|
|
1070
|
+
source = heredoc.content;
|
|
1071
|
+
}
|
|
1072
|
+
if (source !== void 0)
|
|
1073
|
+
for (const path of scriptWriteTargets(source, language)) addTarget(path, state);
|
|
1074
|
+
}
|
|
1075
|
+
function changesDirectory(value) {
|
|
1076
|
+
if (Array.isArray(value)) return value.some(changesDirectory);
|
|
1077
|
+
if (!value || typeof value !== "object") return false;
|
|
1078
|
+
const node = value;
|
|
1079
|
+
if (node.type === "Command" && ["cd", "pushd", "popd", "eval", "source", "."].includes(
|
|
1080
|
+
staticWord(value.name) ?? ""
|
|
1081
|
+
))
|
|
1082
|
+
return true;
|
|
1083
|
+
return Object.values(node).some(changesDirectory);
|
|
1084
|
+
}
|
|
1085
|
+
function visitCommand(command, state) {
|
|
1086
|
+
const name = staticWord(command.name);
|
|
1087
|
+
if (command.prefix.length) unknown(state);
|
|
1088
|
+
const literalApplyPatch = name === "apply_patch" && !command.redirects.some((redirect) => redirect.operator === "<<-");
|
|
1089
|
+
if (literalApplyPatch) {
|
|
1090
|
+
visitApplyPatch(command, state);
|
|
1091
|
+
} else {
|
|
1092
|
+
for (const redirect of command.redirects) visitRedirect(redirect, state);
|
|
1093
|
+
}
|
|
1094
|
+
if (name && (name === "node" || /^python(?:3(?:\.\d+)?)?$/.test(name))) {
|
|
1095
|
+
embeddedScript(command, name, state);
|
|
1096
|
+
} else if (!name || name.includes("/") || !literalApplyPatch && command.suffix.some((word) => staticWord(word) === void 0)) {
|
|
1097
|
+
unknown(state);
|
|
1098
|
+
} else if (literalApplyPatch) {
|
|
1099
|
+
} else if (!READ_ONLY_COMMANDS.has(name) && !knownNoWorktreeMutation(name, staticArgs(command.suffix))) {
|
|
1100
|
+
state.mutation = true;
|
|
1101
|
+
let targets;
|
|
1102
|
+
if (name === "sed") {
|
|
1103
|
+
targets = sedWriteTargets(command.suffix);
|
|
1104
|
+
} else if (name === "tee") {
|
|
1105
|
+
targets = operands(command.suffix, "ai", /* @__PURE__ */ new Set(["--append", "--ignore-interrupts"]));
|
|
1106
|
+
} else if (name === "touch") {
|
|
1107
|
+
targets = operands(command.suffix);
|
|
1108
|
+
} else if (name === "rm") {
|
|
1109
|
+
targets = operands(
|
|
1110
|
+
command.suffix,
|
|
1111
|
+
"fivI",
|
|
1112
|
+
/* @__PURE__ */ new Set(["--force", "--interactive", "--interactive=once", "--verbose"])
|
|
1113
|
+
);
|
|
1114
|
+
} else if (name === "cp" || name === "mv") {
|
|
1115
|
+
const pair = operands(command.suffix);
|
|
1116
|
+
if (pair?.length === 2) targets = name === "cp" ? [pair[1]] : pair;
|
|
1117
|
+
}
|
|
1118
|
+
if (!targets?.length) state.complete = false;
|
|
1119
|
+
else for (const target of targets) addTarget(target, state);
|
|
1120
|
+
}
|
|
1121
|
+
visitNested([command.name, command.prefix, command.suffix, command.redirects], state);
|
|
1122
|
+
}
|
|
1123
|
+
var CONTAINERS = /* @__PURE__ */ new Set(["Script", "Pipeline", "AndOr", "CompoundList"]);
|
|
1124
|
+
function visitNested(value, state) {
|
|
1125
|
+
if (Array.isArray(value)) {
|
|
1126
|
+
for (const child of value) visitNested(child, state);
|
|
1127
|
+
} else if (value && typeof value === "object") {
|
|
1128
|
+
const child = value;
|
|
1129
|
+
if (child.type === "Command") {
|
|
1130
|
+
visitCommand(child, state);
|
|
1131
|
+
} else if (child.type === "Statement") {
|
|
1132
|
+
visitStatement(child, state);
|
|
1133
|
+
} else if ("parts" in child) {
|
|
1134
|
+
for (const part of value.parts ?? []) visitNested(part, state);
|
|
1135
|
+
} else {
|
|
1136
|
+
const node = typeof child.type === "string" && "pos" in child && "end" in child;
|
|
1137
|
+
if (node && !CONTAINERS.has(child.type)) unknown(state);
|
|
1138
|
+
if (child.type === "Function") return;
|
|
1139
|
+
for (const nested of Object.values(child)) visitNested(nested, state);
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
function visitStatement(statement, state) {
|
|
1144
|
+
if (statement.background) unknown(state);
|
|
1145
|
+
for (const redirect of statement.redirects) visitRedirect(redirect, state);
|
|
1146
|
+
visitNested([statement.redirects, statement.command], state);
|
|
1147
|
+
}
|
|
1148
|
+
function visitStaticDirectoryChain(script, state, cwd) {
|
|
1149
|
+
if (script.errors?.length || script.commands.length !== 1) return false;
|
|
1150
|
+
const statement = script.commands[0];
|
|
1151
|
+
const chain = statement.command;
|
|
1152
|
+
if (statement.background || statement.redirects.length || chain.type !== "AndOr" || chain.operators.some((operator) => operator !== "&&") || chain.commands.some((command) => command.type !== "Command"))
|
|
1153
|
+
return false;
|
|
1154
|
+
const commands = chain.commands;
|
|
1155
|
+
if (!commands.some((command) => staticWord(command.name) === "cd")) return false;
|
|
1156
|
+
let prefix = "";
|
|
1157
|
+
const visits = [];
|
|
1158
|
+
for (const command of commands) {
|
|
1159
|
+
if (staticWord(command.name) !== "cd") {
|
|
1160
|
+
if (changesDirectory(command)) return false;
|
|
1161
|
+
visits.push({ command, prefix });
|
|
1162
|
+
continue;
|
|
1163
|
+
}
|
|
1164
|
+
const args = staticArgs(command.suffix);
|
|
1165
|
+
if (!args || command.prefix.length || command.redirects.length) return false;
|
|
1166
|
+
if (args[0] === "--") args.shift();
|
|
1167
|
+
if (args.length !== 1 || !args[0] || args[0].startsWith("-")) return false;
|
|
1168
|
+
if (process.env.CDPATH && !args[0].startsWith(".") && !posix.isAbsolute(args[0])) return false;
|
|
1169
|
+
prefix = posix.isAbsolute(args[0]) ? args[0] : posix.join(prefix, args[0]);
|
|
1170
|
+
if (cwd) {
|
|
1171
|
+
try {
|
|
1172
|
+
const absolute = resolve(realpathSync(cwd), prefix);
|
|
1173
|
+
if (realpathSync(absolute) !== absolute) return false;
|
|
1174
|
+
} catch {
|
|
1175
|
+
return false;
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
state.cwdUncertain = false;
|
|
1180
|
+
for (const visit of visits) {
|
|
1181
|
+
state.cwdPrefix = visit.prefix;
|
|
1182
|
+
visitCommand(visit.command, state);
|
|
1183
|
+
}
|
|
1184
|
+
return true;
|
|
1185
|
+
}
|
|
1186
|
+
function analyzeShellTargets(source, cwd) {
|
|
1187
|
+
if (!source.trim())
|
|
1188
|
+
return { paths: [], coverage: "complete", mutation: "none" };
|
|
1189
|
+
try {
|
|
1190
|
+
const script = parse(source);
|
|
1191
|
+
const state = {
|
|
1192
|
+
paths: /* @__PURE__ */ new Set(),
|
|
1193
|
+
complete: !script.errors?.length,
|
|
1194
|
+
mutation: false,
|
|
1195
|
+
definiteEdit: false,
|
|
1196
|
+
cwdUncertain: changesDirectory(script)
|
|
1197
|
+
};
|
|
1198
|
+
if (!visitStaticDirectoryChain(script, state, cwd)) {
|
|
1199
|
+
for (const statement of script.commands) visitStatement(statement, state);
|
|
1200
|
+
}
|
|
1201
|
+
if (script.errors?.length) state.mutation = true;
|
|
1202
|
+
return {
|
|
1203
|
+
paths: [...state.paths],
|
|
1204
|
+
coverage: state.complete ? "complete" : "unverified",
|
|
1205
|
+
mutation: state.mutation ? "present" : "none",
|
|
1206
|
+
...state.definiteEdit ? { definiteEdit: true } : {}
|
|
1207
|
+
};
|
|
1208
|
+
} catch {
|
|
1209
|
+
return { paths: [], coverage: "unverified", mutation: "present" };
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
// src/demo/state.ts
|
|
1214
|
+
import { createHash, randomUUID } from "crypto";
|
|
1215
|
+
import { existsSync, lstatSync, readFileSync, readdirSync } from "fs";
|
|
1216
|
+
import { join, resolve as resolve2 } from "path";
|
|
1217
|
+
var RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
|
|
1218
|
+
var demoDirectory = () => join(primConfigDirectory(), "demo");
|
|
1219
|
+
var runPath = (id) => {
|
|
1220
|
+
if (!RUN_ID.test(id)) throw new Error("invalid demo run ID");
|
|
1221
|
+
return join(demoDirectory(), "runs", `${id}.json`);
|
|
1222
|
+
};
|
|
1223
|
+
function readDemoJson(path) {
|
|
1224
|
+
const stat = lstatSync(path);
|
|
1225
|
+
if (!stat.isFile() || stat.size > 16384) throw new Error(`invalid demo state: ${path}`);
|
|
1226
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
1227
|
+
}
|
|
1228
|
+
function saveDemoJson(path, value) {
|
|
1229
|
+
atomicWriteFile(path, `${JSON.stringify(value)}
|
|
1230
|
+
`, { mode: 384, ensureParent: true });
|
|
1231
|
+
}
|
|
1232
|
+
function readRun(id) {
|
|
1233
|
+
const run = readDemoJson(runPath(id));
|
|
1234
|
+
if (![1, 2].includes(run.version) || run.id !== id || ![
|
|
1235
|
+
"prepared",
|
|
1236
|
+
"proposal",
|
|
1237
|
+
"conflict",
|
|
1238
|
+
"prompt",
|
|
1239
|
+
"approved",
|
|
1240
|
+
"applied",
|
|
1241
|
+
"cleanup",
|
|
1242
|
+
"completed",
|
|
1243
|
+
"skipped"
|
|
1244
|
+
].includes(run.stage) || run.needsStatus !== void 0 && typeof run.needsStatus !== "boolean" || run.server !== void 0 && !isDemoStatusResponse(run.server) || run.receipt !== void 0 && (!Number.isSafeInteger(run.receipt.revision) || run.receipt.revision < 0 || !/^[a-f0-9]{64}$/u.test(run.receipt.appliedDigest)) || typeof run.terminal !== "boolean" || !Array.isArray(run.launcher) || run.launcher.length !== 2 || run.launcher.some((value) => typeof value !== "string" || !value.startsWith("/")) || run.agent !== void 0 && !["claude_code", "codex", "cursor", "hermes"].includes(run.agent) || run.welcomeRepo !== void 0 && (typeof run.welcomeRepo !== "string" || !run.welcomeRepo.startsWith("/"))) {
|
|
1245
|
+
throw new Error("invalid demo run state");
|
|
1246
|
+
}
|
|
1247
|
+
return run;
|
|
1248
|
+
}
|
|
1249
|
+
var saveRun = (run) => saveDemoJson(runPath(run.id), run);
|
|
1250
|
+
var lockRun = (id, action) => withFileLockSync(`${runPath(id)}.lock`, () => action(readRun(id)), { timeoutMs: 500 });
|
|
1251
|
+
function prepareRun(agent, terminal = false, welcomeRepo) {
|
|
1252
|
+
const run = {
|
|
1253
|
+
version: 2,
|
|
1254
|
+
id: randomUUID(),
|
|
1255
|
+
stage: "prepared",
|
|
1256
|
+
terminal,
|
|
1257
|
+
agent,
|
|
1258
|
+
preparationKey: preparationKey(agent),
|
|
1259
|
+
launcher: [process.execPath, resolve2(process.argv[1])],
|
|
1260
|
+
...welcomeRepo ? { welcomeRepo } : {}
|
|
1261
|
+
};
|
|
1262
|
+
saveRun(run);
|
|
1263
|
+
return run;
|
|
1264
|
+
}
|
|
1265
|
+
function preparationKey(agent) {
|
|
1266
|
+
return agent === "codex" && process.env.CODEX_THREAD_ID ? sessionKey(agent, `${process.env.CODEX_THREAD_ID}\0${process.cwd()}`) : void 0;
|
|
1267
|
+
}
|
|
1268
|
+
var quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
|
|
1269
|
+
function demoCommand(run, action, choice, reason) {
|
|
1270
|
+
return [
|
|
1271
|
+
...run.launcher,
|
|
1272
|
+
"demo",
|
|
1273
|
+
action,
|
|
1274
|
+
run.id,
|
|
1275
|
+
...choice === void 0 ? [] : ["--choice", choice],
|
|
1276
|
+
...reason === void 0 ? [] : ["--reason", reason]
|
|
1277
|
+
].map(quote).join(" ");
|
|
1278
|
+
}
|
|
1279
|
+
function demoWelcomeCommand(run) {
|
|
1280
|
+
return [
|
|
1281
|
+
process.execPath,
|
|
1282
|
+
resolve2(process.argv[1]),
|
|
1283
|
+
"welcome",
|
|
1284
|
+
"--after-demo",
|
|
1285
|
+
...run.agent ? ["--agent", run.agent === "claude_code" ? "claude" : run.agent] : [],
|
|
1286
|
+
...run.binding ? ["--capture-excluded"] : []
|
|
1287
|
+
].map(quote).join(" ");
|
|
1288
|
+
}
|
|
1289
|
+
function demoDiagnosticCommand(run) {
|
|
1290
|
+
return [process.execPath, resolve2(process.argv[1]), "demo", "status", run.id].map(quote).join(" ");
|
|
1291
|
+
}
|
|
1292
|
+
function demoResumeCommand(run) {
|
|
1293
|
+
return [process.execPath, resolve2(process.argv[1]), "demo", "resume", run.id].map(quote).join(" ");
|
|
1294
|
+
}
|
|
1295
|
+
function onboardingFinished() {
|
|
1296
|
+
const path = join(demoDirectory(), "onboarding.json");
|
|
1297
|
+
if (!existsSync(path)) return false;
|
|
1298
|
+
const value = readDemoJson(path);
|
|
1299
|
+
if (value.outcome !== "completed" && value.outcome !== "skipped") {
|
|
1300
|
+
throw new Error("invalid local onboarding outcome");
|
|
1301
|
+
}
|
|
1302
|
+
return true;
|
|
1303
|
+
}
|
|
1304
|
+
function finishOnboarding(outcome) {
|
|
1305
|
+
saveDemoJson(join(demoDirectory(), "onboarding.json"), { outcome });
|
|
1306
|
+
}
|
|
1307
|
+
function runIds() {
|
|
1308
|
+
const path = join(demoDirectory(), "runs");
|
|
1309
|
+
if (!existsSync(path)) return [];
|
|
1310
|
+
return readdirSync(path).filter((name) => name.endsWith(".json") && RUN_ID.test(name.slice(0, -5))).map((name) => name.slice(0, -5));
|
|
1311
|
+
}
|
|
1312
|
+
function pendingRuns() {
|
|
1313
|
+
return runIds().filter((id) => !["completed", "skipped"].includes(readRun(id).stage));
|
|
1314
|
+
}
|
|
1315
|
+
function sessionKey(agent, session) {
|
|
1316
|
+
return createHash("sha256").update(`${agent}\0${session}`).digest("hex");
|
|
1317
|
+
}
|
|
1318
|
+
function exclusionPath(key) {
|
|
1319
|
+
if (!/^[0-9a-f]{64}$/u.test(key)) throw new Error("invalid demo session identity");
|
|
1320
|
+
return join(demoDirectory(), "excluded-sessions", `${key}.json`);
|
|
1321
|
+
}
|
|
1322
|
+
function sessionExcluded(agent, session) {
|
|
1323
|
+
if (typeof session !== "string" || !session) return false;
|
|
1324
|
+
const path = exclusionPath(sessionKey(agent, session));
|
|
1325
|
+
if (!existsSync(path)) return false;
|
|
1326
|
+
const record = readDemoJson(path);
|
|
1327
|
+
if (typeof record.runId !== "string" || !RUN_ID.test(record.runId)) {
|
|
1328
|
+
throw new Error("invalid demo capture exclusion");
|
|
1329
|
+
}
|
|
1330
|
+
return true;
|
|
1331
|
+
}
|
|
1332
|
+
var lockRunAsync = (id, action) => withFileLock(`${runPath(id)}.lock`, () => action(readRun(id)), { timeoutMs: 500 });
|
|
1333
|
+
function demoArgv(command) {
|
|
1334
|
+
const result = [];
|
|
1335
|
+
let i = 0;
|
|
1336
|
+
while (i < command.length) {
|
|
1337
|
+
if (command[i++] !== "'") return;
|
|
1338
|
+
let value = "";
|
|
1339
|
+
let closed = false;
|
|
1340
|
+
while (i < command.length) {
|
|
1341
|
+
if (command.slice(i, i + 4) === "'\\''") {
|
|
1342
|
+
value += "'";
|
|
1343
|
+
i += 4;
|
|
1344
|
+
} else if (command[i] === "'") {
|
|
1345
|
+
i++;
|
|
1346
|
+
closed = true;
|
|
1347
|
+
break;
|
|
1348
|
+
} else {
|
|
1349
|
+
value += command[i++];
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
if (!closed) return;
|
|
1353
|
+
result.push(value);
|
|
1354
|
+
if (i === command.length) return result;
|
|
1355
|
+
if (command[i++] !== " " || i === command.length) return;
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
// src/demo/diagnostics.ts
|
|
1360
|
+
import { existsSync as existsSync2 } from "fs";
|
|
1361
|
+
import { join as join2 } from "path";
|
|
1362
|
+
var observationPath = (id) => join2(demoDirectory(), "observations", `${id}.json`);
|
|
1363
|
+
function observeRun(id, observation) {
|
|
1364
|
+
try {
|
|
1365
|
+
saveDemoJson(observationPath(id), observation);
|
|
1366
|
+
} catch {
|
|
1367
|
+
process.stderr.write(
|
|
1368
|
+
"[prim] demo isolation diagnostic could not be saved; check access to Primitive's configuration directory.\n"
|
|
1369
|
+
);
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
function isolationDiagnostics(run) {
|
|
1373
|
+
let observation;
|
|
1374
|
+
let observationError;
|
|
1375
|
+
try {
|
|
1376
|
+
if (existsSync2(observationPath(run.id))) {
|
|
1377
|
+
const value = readDemoJson(observationPath(run.id));
|
|
1378
|
+
if (!value || !Number.isFinite(value.at) || !["claude_code", "codex", "cursor", "hermes"].includes(value.agent ?? "") || ![
|
|
1379
|
+
"acknowledged",
|
|
1380
|
+
"tool-mismatch",
|
|
1381
|
+
"command-mismatch",
|
|
1382
|
+
"session-mismatch",
|
|
1383
|
+
"session-missing",
|
|
1384
|
+
"write-failed"
|
|
1385
|
+
].includes(value.result ?? "") || value.runtimeVersion !== void 0 && !/^[a-zA-Z0-9.+-]{1,80}$/u.test(value.runtimeVersion) || value.session !== void 0 && !/^[a-f0-9]{64}$/u.test(value.session) || value.errorCode !== void 0 && !/^[A-Z0-9_]{1,32}$/u.test(value.errorCode))
|
|
1386
|
+
throw new Error("invalid demo observation");
|
|
1387
|
+
observation = value;
|
|
1388
|
+
}
|
|
1389
|
+
} catch {
|
|
1390
|
+
observationError = "unreadable";
|
|
1391
|
+
}
|
|
1392
|
+
const expected = run.agent === "codex" && process.env.CODEX_THREAD_ID ? sessionKey(run.agent, process.env.CODEX_THREAD_ID) : void 0;
|
|
1393
|
+
return {
|
|
1394
|
+
runtime: inspectHookRuntime(),
|
|
1395
|
+
expectedEvent: "PreToolUse",
|
|
1396
|
+
expectedTool: run.agent === "cursor" ? "Shell" : run.agent === "hermes" ? "terminal" : "Bash",
|
|
1397
|
+
hookObservation: observation ? {
|
|
1398
|
+
at: observation.at,
|
|
1399
|
+
agent: observation.agent,
|
|
1400
|
+
runtimeVersion: observation.runtimeVersion ?? "unknown",
|
|
1401
|
+
result: observation.result,
|
|
1402
|
+
ageMs: Math.max(0, Date.now() - observation.at),
|
|
1403
|
+
sessionMatches: expected ? observation.session === expected : "unknown",
|
|
1404
|
+
...observation.errorCode ? { errorCode: observation.errorCode } : {}
|
|
1405
|
+
} : null,
|
|
1406
|
+
...observationError ? { observationError } : {},
|
|
1407
|
+
trust: "unknown",
|
|
1408
|
+
capture: run.binding ? "excluded-for-bound-session" : "not-verified"
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
export {
|
|
1413
|
+
buildHookOutput,
|
|
1414
|
+
buildCodexOutput,
|
|
1415
|
+
buildCursorOutput,
|
|
1416
|
+
failOpenOutput,
|
|
1417
|
+
failOpenCodex,
|
|
1418
|
+
failOpenCursor,
|
|
1419
|
+
buildHermesOutput,
|
|
1420
|
+
failOpenHermes,
|
|
1421
|
+
extractFileTargets,
|
|
1422
|
+
readHookMode,
|
|
1423
|
+
demoteForMode,
|
|
1424
|
+
analyzeShellTargets,
|
|
1425
|
+
RUN_ID,
|
|
1426
|
+
demoDirectory,
|
|
1427
|
+
runPath,
|
|
1428
|
+
readDemoJson,
|
|
1429
|
+
saveDemoJson,
|
|
1430
|
+
readRun,
|
|
1431
|
+
saveRun,
|
|
1432
|
+
lockRun,
|
|
1433
|
+
prepareRun,
|
|
1434
|
+
preparationKey,
|
|
1435
|
+
demoCommand,
|
|
1436
|
+
demoWelcomeCommand,
|
|
1437
|
+
demoDiagnosticCommand,
|
|
1438
|
+
demoResumeCommand,
|
|
1439
|
+
onboardingFinished,
|
|
1440
|
+
finishOnboarding,
|
|
1441
|
+
runIds,
|
|
1442
|
+
pendingRuns,
|
|
1443
|
+
sessionKey,
|
|
1444
|
+
exclusionPath,
|
|
1445
|
+
sessionExcluded,
|
|
1446
|
+
lockRunAsync,
|
|
1447
|
+
demoArgv,
|
|
1448
|
+
observeRun,
|
|
1449
|
+
isolationDiagnostics
|
|
1450
|
+
};
|