@picassohq/cli 0.0.0-stage → 1.0.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.
Files changed (230) hide show
  1. package/agents/browser_agent.yaml +53 -0
  2. package/agents/code_reviewer.yaml +49 -0
  3. package/agents/codebase_investigator.yaml +70 -0
  4. package/agents/design_auditor.yaml +50 -0
  5. package/agents/devex_auditor.yaml +50 -0
  6. package/agents/doc_writer.yaml +54 -0
  7. package/agents/engineering_architect.yaml +51 -0
  8. package/agents/generalist.yaml +55 -0
  9. package/agents/migration_planner.yaml +51 -0
  10. package/agents/product_reviewer.yaml +48 -0
  11. package/agents/qa_operator.yaml +52 -0
  12. package/agents/release_engineer.yaml +50 -0
  13. package/agents/security_auditor.yaml +62 -0
  14. package/agents/test_writer.yaml +52 -0
  15. package/assets/first-light-lockup.png +0 -0
  16. package/assets/first-light-tagline.png +0 -0
  17. package/assets/house/README.md +26 -0
  18. package/assets/house/auraone-banner.png +0 -0
  19. package/assets/house/auraone-logo.png +0 -0
  20. package/assets/house/kiro-prism-banner.png +0 -0
  21. package/assets/house/kiro-prism-logo.png +0 -0
  22. package/assets/house/picasso-banner.png +0 -0
  23. package/assets/house/picasso-logo.png +0 -0
  24. package/assets/wordmark-app.png +0 -0
  25. package/assets/wordmark-tight.png +0 -0
  26. package/assets/wordmark.png +0 -0
  27. package/design/styles.css +1042 -0
  28. package/dist/build-info.json +37 -0
  29. package/dist/index.js +3028 -0
  30. package/goals/cli-hardening.yaml +40 -0
  31. package/goals/repo-maintenance.yaml +40 -0
  32. package/package.json +49 -4
  33. package/runtime/dsh/picasso-ecosystem.community.amendments.yml +24 -0
  34. package/runtime/dsh/picasso-ecosystem.community.json +185 -0
  35. package/runtime/dsh/picasso-ecosystem.community.patch.yml +40 -0
  36. package/runtime/dsh/picasso-ecosystem.cordis.patch.yml +143 -0
  37. package/runtime/dsh/picasso-isolation.patch.yml +25 -0
  38. package/runtime/dsh/picasso-providers.patch.yml +373 -0
  39. package/runtime/dsh/picasso-runtime.cordis.yml +738 -0
  40. package/runtime/dsh/picasso-sdk.patch.yml +204 -0
  41. package/runtime/engine-manifest.json +214 -0
  42. package/runtime/package.json +6 -0
  43. package/runtime/packages/picasso-cache-probe/cordis.patch.yml +5 -0
  44. package/runtime/packages/picasso-cache-probe/index.js +477 -0
  45. package/runtime/packages/picasso-cache-probe/package.json +38 -0
  46. package/runtime/packages/picasso-commands/cordis.patch.yml +4 -0
  47. package/runtime/packages/picasso-commands/fresh-review.js +573 -0
  48. package/runtime/packages/picasso-commands/index.js +497 -0
  49. package/runtime/packages/picasso-commands/package.json +28 -0
  50. package/runtime/packages/picasso-instructions/conflicts.js +115 -0
  51. package/runtime/packages/picasso-instructions/formats.js +145 -0
  52. package/runtime/packages/picasso-instructions/frontmatter.js +175 -0
  53. package/runtime/packages/picasso-instructions/glob.js +114 -0
  54. package/runtime/packages/picasso-instructions/globals.js +90 -0
  55. package/runtime/packages/picasso-instructions/imports.js +123 -0
  56. package/runtime/packages/picasso-instructions/index.js +326 -0
  57. package/runtime/packages/picasso-instructions/modes.js +64 -0
  58. package/runtime/packages/picasso-instructions/package.json +30 -0
  59. package/runtime/packages/picasso-instructions/parse.js +134 -0
  60. package/runtime/packages/picasso-instructions/report.js +161 -0
  61. package/runtime/packages/picasso-instructions/resolve.js +939 -0
  62. package/runtime/packages/picasso-instructions/scan.js +181 -0
  63. package/runtime/packages/picasso-instructions/settings.js +150 -0
  64. package/runtime/packages/picasso-instructions/skills.js +345 -0
  65. package/runtime/packages/picasso-lean-context/cordis.patch.yml +13 -0
  66. package/runtime/packages/picasso-lean-context/index.js +6049 -0
  67. package/runtime/packages/picasso-lean-context/package.json +26 -0
  68. package/runtime/packages/picasso-lean-context/timeline.js +417 -0
  69. package/runtime/packages/picasso-librarian/classify.js +146 -0
  70. package/runtime/packages/picasso-librarian/cordis.patch.yml +10 -0
  71. package/runtime/packages/picasso-librarian/index.js +878 -0
  72. package/runtime/packages/picasso-librarian/notes.js +159 -0
  73. package/runtime/packages/picasso-librarian/package.json +34 -0
  74. package/runtime/packages/picasso-librarian/state.js +478 -0
  75. package/runtime/packages/picasso-memory/index.js +1184 -0
  76. package/runtime/packages/picasso-memory/package.json +21 -0
  77. package/runtime/packages/picasso-model-router/connections.js +895 -0
  78. package/runtime/packages/picasso-model-router/cordis.patch.yml +17 -0
  79. package/runtime/packages/picasso-model-router/index.js +1081 -0
  80. package/runtime/packages/picasso-model-router/package.json +30 -0
  81. package/runtime/packages/picasso-options/cordis.patch.yml +4 -0
  82. package/runtime/packages/picasso-options/index.js +263 -0
  83. package/runtime/packages/picasso-options/package.json +28 -0
  84. package/runtime/packages/picasso-progress-reports/cordis.patch.yml +10 -0
  85. package/runtime/packages/picasso-progress-reports/index.js +267 -0
  86. package/runtime/packages/picasso-progress-reports/package.json +30 -0
  87. package/runtime/packages/picasso-progress-reports/report.js +235 -0
  88. package/runtime/packages/picasso-sdk-server/aside.js +128 -0
  89. package/runtime/packages/picasso-sdk-server/connections.js +38 -0
  90. package/runtime/packages/picasso-sdk-server/context-timeline.js +27 -0
  91. package/runtime/packages/picasso-sdk-server/egress-gate.js +520 -0
  92. package/runtime/packages/picasso-sdk-server/failure-policy.js +246 -0
  93. package/runtime/packages/picasso-sdk-server/file-input.js +169 -0
  94. package/runtime/packages/picasso-sdk-server/goal.js +131 -0
  95. package/runtime/packages/picasso-sdk-server/ignore-file.js +458 -0
  96. package/runtime/packages/picasso-sdk-server/ignore-plugin.js +12 -0
  97. package/runtime/packages/picasso-sdk-server/ignore-sandbox.js +122 -0
  98. package/runtime/packages/picasso-sdk-server/ignore-snapshot.js +131 -0
  99. package/runtime/packages/picasso-sdk-server/image-input.js +44 -0
  100. package/runtime/packages/picasso-sdk-server/index.js +886 -0
  101. package/runtime/packages/picasso-sdk-server/instructions.js +34 -0
  102. package/runtime/packages/picasso-sdk-server/jobs.js +113 -0
  103. package/runtime/packages/picasso-sdk-server/mcp-gate.js +51 -0
  104. package/runtime/packages/picasso-sdk-server/model-selection.js +162 -0
  105. package/runtime/packages/picasso-sdk-server/package.json +50 -0
  106. package/runtime/packages/picasso-sdk-server/picasso-records.js +50 -0
  107. package/runtime/packages/picasso-sdk-server/provider-reload.js +84 -0
  108. package/runtime/packages/picasso-sdk-server/queue.js +322 -0
  109. package/runtime/packages/picasso-sdk-server/requester.js +43 -0
  110. package/runtime/packages/picasso-sdk-server/rewind.js +108 -0
  111. package/runtime/packages/picasso-sdk-server/schedule.js +187 -0
  112. package/runtime/packages/picasso-sdk-server/session-grants.js +35 -0
  113. package/runtime/packages/picasso-sdk-server/session-state.js +118 -0
  114. package/runtime/packages/picasso-sdk-server/shell-paths.js +869 -0
  115. package/runtime/packages/picasso-sdk-server/stream-deltas.js +211 -0
  116. package/runtime/packages/picasso-sdk-server/team-tasks.js +451 -0
  117. package/runtime/packages/picasso-sdk-server/tool-output.js +128 -0
  118. package/runtime/packages/picasso-sdk-server/tools-list.js +51 -0
  119. package/runtime/packages/picasso-sdk-server/wave2-hooks.js +612 -0
  120. package/runtime/packages/picasso-sdk-server/workspace-archive.js +170 -0
  121. package/runtime/packages/picasso-sdk-server/workspace-restore.js +180 -0
  122. package/runtime/packages/picasso-web-search/backends.js +350 -0
  123. package/runtime/packages/picasso-web-search/config.js +121 -0
  124. package/runtime/packages/picasso-web-search/cordis.patch.yml +7 -0
  125. package/runtime/packages/picasso-web-search/failure.js +111 -0
  126. package/runtime/packages/picasso-web-search/format.js +35 -0
  127. package/runtime/packages/picasso-web-search/index.js +66 -0
  128. package/runtime/packages/picasso-web-search/package.json +38 -0
  129. package/runtime/packages/picasso-web-search/router.js +155 -0
  130. package/runtime/packages/picasso-x-reader/circle.js +324 -0
  131. package/runtime/packages/picasso-x-reader/command.js +169 -0
  132. package/runtime/packages/picasso-x-reader/cordis.patch.yml +8 -0
  133. package/runtime/packages/picasso-x-reader/index.js +170 -0
  134. package/runtime/packages/picasso-x-reader/package.json +39 -0
  135. package/runtime/packages/picasso-x-reader/read.js +370 -0
  136. package/runtime/packages/picasso-x-reader/rewrite.js +38 -0
  137. package/runtime/packages/picasso-x-reader/settings.js +131 -0
  138. package/runtime/packages/picasso-x-reader/urls.js +154 -0
  139. package/runtime/packages/picasso-x-reader/xmd.js +512 -0
  140. package/runtime/plugins/picasso-auth-bridge/index.js +380 -0
  141. package/runtime/plugins/picasso-auth-bridge/package.json +28 -0
  142. package/runtime/plugins/picasso-auto-approve/index.js +1003 -0
  143. package/runtime/plugins/picasso-auto-approve/package.json +28 -0
  144. package/runtime/plugins/picasso-browser/index.js +424 -0
  145. package/runtime/plugins/picasso-browser/package.json +28 -0
  146. package/runtime/plugins/picasso-checkpoints/evidence.js +210 -0
  147. package/runtime/plugins/picasso-checkpoints/index.js +885 -0
  148. package/runtime/plugins/picasso-checkpoints/package.json +29 -0
  149. package/runtime/plugins/picasso-commands/fresh-review.js +573 -0
  150. package/runtime/plugins/picasso-commands/index.js +497 -0
  151. package/runtime/plugins/picasso-commands/package.json +28 -0
  152. package/runtime/plugins/picasso-instructions/conflicts.js +115 -0
  153. package/runtime/plugins/picasso-instructions/formats.js +145 -0
  154. package/runtime/plugins/picasso-instructions/frontmatter.js +175 -0
  155. package/runtime/plugins/picasso-instructions/glob.js +114 -0
  156. package/runtime/plugins/picasso-instructions/globals.js +90 -0
  157. package/runtime/plugins/picasso-instructions/imports.js +123 -0
  158. package/runtime/plugins/picasso-instructions/index.js +326 -0
  159. package/runtime/plugins/picasso-instructions/modes.js +64 -0
  160. package/runtime/plugins/picasso-instructions/package.json +30 -0
  161. package/runtime/plugins/picasso-instructions/parse.js +134 -0
  162. package/runtime/plugins/picasso-instructions/report.js +161 -0
  163. package/runtime/plugins/picasso-instructions/resolve.js +939 -0
  164. package/runtime/plugins/picasso-instructions/scan.js +181 -0
  165. package/runtime/plugins/picasso-instructions/settings.js +150 -0
  166. package/runtime/plugins/picasso-instructions/skills.js +345 -0
  167. package/runtime/plugins/picasso-lean-context/index.js +6049 -0
  168. package/runtime/plugins/picasso-lean-context/package.json +26 -0
  169. package/runtime/plugins/picasso-lean-context/timeline.js +417 -0
  170. package/runtime/plugins/picasso-librarian/classify.js +146 -0
  171. package/runtime/plugins/picasso-librarian/index.js +878 -0
  172. package/runtime/plugins/picasso-librarian/notes.js +159 -0
  173. package/runtime/plugins/picasso-librarian/package.json +34 -0
  174. package/runtime/plugins/picasso-librarian/state.js +478 -0
  175. package/runtime/plugins/picasso-lifecycle-hooks/index.js +186 -0
  176. package/runtime/plugins/picasso-lifecycle-hooks/package.json +25 -0
  177. package/runtime/plugins/picasso-mail/inbox.js +207 -0
  178. package/runtime/plugins/picasso-mail/index.js +293 -0
  179. package/runtime/plugins/picasso-mail/package.json +22 -0
  180. package/runtime/plugins/picasso-memory/index.js +1184 -0
  181. package/runtime/plugins/picasso-memory/package.json +21 -0
  182. package/runtime/plugins/picasso-model-router/connections.js +895 -0
  183. package/runtime/plugins/picasso-model-router/index.js +1081 -0
  184. package/runtime/plugins/picasso-model-router/package.json +30 -0
  185. package/runtime/plugins/picasso-options/index.js +263 -0
  186. package/runtime/plugins/picasso-options/package.json +28 -0
  187. package/runtime/plugins/picasso-progress-reports/index.js +267 -0
  188. package/runtime/plugins/picasso-progress-reports/package.json +30 -0
  189. package/runtime/plugins/picasso-progress-reports/report.js +235 -0
  190. package/runtime/plugins/picasso-provider-models/index.js +436 -0
  191. package/runtime/plugins/picasso-provider-models/package.json +28 -0
  192. package/runtime/plugins/picasso-repo-index/index.js +1850 -0
  193. package/runtime/plugins/picasso-repo-index/package.json +28 -0
  194. package/runtime/plugins/picasso-schedule-pause/index.js +344 -0
  195. package/runtime/plugins/picasso-schedule-pause/package.json +28 -0
  196. package/runtime/plugins/picasso-session-lifecycle/index.js +796 -0
  197. package/runtime/plugins/picasso-session-lifecycle/package.json +28 -0
  198. package/runtime/plugins/picasso-trackers/index.js +895 -0
  199. package/runtime/plugins/picasso-trackers/package.json +28 -0
  200. package/runtime/plugins/picasso-web-search/backends.js +350 -0
  201. package/runtime/plugins/picasso-web-search/config.js +121 -0
  202. package/runtime/plugins/picasso-web-search/failure.js +111 -0
  203. package/runtime/plugins/picasso-web-search/format.js +35 -0
  204. package/runtime/plugins/picasso-web-search/index.js +66 -0
  205. package/runtime/plugins/picasso-web-search/package.json +38 -0
  206. package/runtime/plugins/picasso-web-search/router.js +155 -0
  207. package/runtime/plugins/picasso-x-reader/circle.js +324 -0
  208. package/runtime/plugins/picasso-x-reader/command.js +169 -0
  209. package/runtime/plugins/picasso-x-reader/index.js +170 -0
  210. package/runtime/plugins/picasso-x-reader/package.json +39 -0
  211. package/runtime/plugins/picasso-x-reader/read.js +370 -0
  212. package/runtime/plugins/picasso-x-reader/rewrite.js +38 -0
  213. package/runtime/plugins/picasso-x-reader/settings.js +131 -0
  214. package/runtime/plugins/picasso-x-reader/urls.js +154 -0
  215. package/runtime/plugins/picasso-x-reader/xmd.js +512 -0
  216. package/runtime/relay/attachment-text.mjs +737 -0
  217. package/runtime/relay/companion/companion.css +126 -0
  218. package/runtime/relay/companion/companion.js +648 -0
  219. package/runtime/relay/companion/icon.svg +5 -0
  220. package/runtime/relay/companion/index.html +25 -0
  221. package/runtime/relay/companion/manifest.json +13 -0
  222. package/runtime/relay/companion/sw.js +41 -0
  223. package/runtime/relay/main.mjs +37252 -0
  224. package/runtime/relay/model-listing.mjs +614 -0
  225. package/runtime/relay/versions-routes.mjs +1198 -0
  226. package/runtime/verify-plugins.mjs +205 -0
  227. package/runtime-lock/package-lock.json +10779 -0
  228. package/runtime-lock/package.json +7 -0
  229. package/scripts/install-runtime.mjs +400 -0
  230. package/README.md +0 -3
@@ -0,0 +1,869 @@
1
+ // Shell-command path references for the `.picassoignore` guard.
2
+ //
3
+ // A shell is open-ended, so this is a conservative static reading of a
4
+ // command line, not an interpreter. It tokenizes POSIX shell words (quotes,
5
+ // `$'…'`, backslashes, `$VAR`/`${VAR}`, `$(…)`, backticks, `<(…)`, `~`,
6
+ // brace expansion and globs), splits commands on `;`, `&&`, `||`, `|`, `&`,
7
+ // newlines and subshell parentheses, follows `cd`/`pushd` and variable
8
+ // assignments in order (subshells and command substitutions get their own
9
+ // scope), reads redirection targets (heredoc bodies and here-strings are data)
10
+ // and unwraps `sudo`, `env`, `xargs`, `timeout`, `bash -c`, `eval`, `find
11
+ // -exec`, `git -C` and friends. Every word that could name a file becomes a
12
+ // reference resolved against the command's working directory; commands that
13
+ // read directory trees (`grep -r`, `rg`, `find`, `tar`, `zip -r`, `cp -r`,
14
+ // `rsync -a`, `git show/diff/grep`, …) mark their directory operands (or the
15
+ // working directory when they name none) as recursive.
16
+ //
17
+ // Words whose value depends on something unknowable here (an unset variable,
18
+ // command output) are skipped: the dsh sandbox read-deny (ignore-sandbox.js)
19
+ // is the backstop for what a static reading cannot see.
20
+ import { readdirSync } from 'node:fs';
21
+ import { homedir } from 'node:os';
22
+ import { basename, dirname, isAbsolute, join, resolve, sep } from 'node:path';
23
+ import { fileURLToPath } from 'node:url';
24
+
25
+ const MAX_DEPTH = 8;
26
+ const MAX_GLOB_MATCHES = 2000;
27
+ const MAX_BRACE_EXPANSIONS = 256;
28
+
29
+ const OPERATOR_CHARS = new Set([';', '&', '|', '(', ')', '\n']);
30
+ const WORD_END = new Set([' ', '\t', '\n', ';', '&', '|', '(', ')', '<', '>']);
31
+
32
+ /** Index just past the `)` closing a `(` whose content starts at `start` (quotes, nesting and escapes respected). */
33
+ function matchParen(text, start) {
34
+ let depth = 1;
35
+ for (let index = start; index < text.length; index += 1) {
36
+ const char = text[index];
37
+ if (char === '\\') {
38
+ index += 1;
39
+ } else if (char === "'") {
40
+ const close = text.indexOf("'", index + 1);
41
+ if (close < 0) return text.length;
42
+ index = close;
43
+ } else if (char === '"') {
44
+ index = skipDoubleQuoted(text, index + 1) - 1;
45
+ } else if (char === '`') {
46
+ index = skipBacktick(text, index + 1) - 1;
47
+ } else if (char === '(') {
48
+ depth += 1;
49
+ } else if (char === ')') {
50
+ depth -= 1;
51
+ if (depth === 0) return index + 1;
52
+ }
53
+ }
54
+ return text.length;
55
+ }
56
+
57
+ function skipDoubleQuoted(text, start) {
58
+ for (let index = start; index < text.length; index += 1) {
59
+ const char = text[index];
60
+ if (char === '\\') index += 1;
61
+ else if (char === '"') return index + 1;
62
+ else if (char === '$' && text[index + 1] === '(') index = matchParen(text, index + 2) - 1;
63
+ else if (char === '`') index = skipBacktick(text, index + 1) - 1;
64
+ }
65
+ return text.length;
66
+ }
67
+
68
+ function skipBacktick(text, start) {
69
+ for (let index = start; index < text.length; index += 1) {
70
+ if (text[index] === '\\') index += 1;
71
+ else if (text[index] === '`') return index + 1;
72
+ }
73
+ return text.length;
74
+ }
75
+
76
+ function matchBrace(text, start) {
77
+ let depth = 1;
78
+ for (let index = start; index < text.length; index += 1) {
79
+ if (text[index] === '\\') index += 1;
80
+ else if (text[index] === '{') depth += 1;
81
+ else if (text[index] === '}' && --depth === 0) return index + 1;
82
+ }
83
+ return text.length;
84
+ }
85
+
86
+ const ANSI_ESCAPES = { n: '\n', t: '\t', r: '\r', a: '\x07', b: '\b', e: '\x1b', E: '\x1b', f: '\f', v: '\v', '\\': '\\', "'": "'", '"': '"', '?': '?' };
87
+
88
+ function ansiC(body) {
89
+ return body.replace(/\\(x[0-9a-fA-F]{1,2}|[0-7]{1,3}|.)/gu, (_match, code) => {
90
+ if (code.startsWith('x')) return String.fromCharCode(Number.parseInt(code.slice(1), 16));
91
+ if (/^[0-7]+$/u.test(code)) return String.fromCharCode(Number.parseInt(code, 8));
92
+ return ANSI_ESCAPES[code] ?? code;
93
+ });
94
+ }
95
+
96
+ /** Read one `$…` expansion at `index` (pointing at `$`); returns the part and the index after it. */
97
+ function readDollar(text, index, quoted) {
98
+ const next = text[index + 1];
99
+ if (next === '(') {
100
+ if (text[index + 2] === '(') {
101
+ const end = matchParen(text, index + 3);
102
+ return { part: { type: 'unknown' }, end: text[end] === ')' ? end + 1 : end };
103
+ }
104
+ const end = matchParen(text, index + 2);
105
+ return { part: { type: 'sub', script: text.slice(index + 2, end - 1) }, end };
106
+ }
107
+ if (next === '{') {
108
+ const end = matchBrace(text, index + 2);
109
+ const inner = text.slice(index + 2, end - 1);
110
+ const name = /^[A-Za-z_][A-Za-z0-9_]*$/u.test(inner) ? inner : undefined;
111
+ return { part: name === undefined ? { type: 'unknown' } : { type: 'var', name }, end };
112
+ }
113
+ if (next === "'" && !quoted) {
114
+ let close = index + 2;
115
+ while (close < text.length && text[close] !== "'") close += text[close] === '\\' ? 2 : 1;
116
+ return { part: { type: 'lit', value: ansiC(text.slice(index + 2, close)), quoted: true }, end: close + 1 };
117
+ }
118
+ const name = /^[A-Za-z_][A-Za-z0-9_]*/u.exec(text.slice(index + 1))?.[0];
119
+ if (name !== undefined) return { part: { type: 'var', name }, end: index + 1 + name.length };
120
+ if (next !== undefined && /[0-9@*#?$!-]/u.test(next)) return { part: { type: 'unknown' }, end: index + 2 };
121
+ return { part: { type: 'lit', value: '$', quoted }, end: index + 1 };
122
+ }
123
+
124
+ function readWord(text, start) {
125
+ const parts = [];
126
+ const lit = (value, quoted) => {
127
+ const last = parts.at(-1);
128
+ if (last?.type === 'lit' && last.quoted === quoted) last.value += value;
129
+ else parts.push({ type: 'lit', value, quoted });
130
+ };
131
+ let index = start;
132
+ while (index < text.length && !WORD_END.has(text[index])) {
133
+ const char = text[index];
134
+ if (char === '\\') {
135
+ if (text[index + 1] === '\n') {
136
+ index += 2;
137
+ continue;
138
+ }
139
+ if (index + 1 < text.length) lit(text[index + 1], true);
140
+ index += 2;
141
+ } else if (char === "'") {
142
+ const close = text.indexOf("'", index + 1);
143
+ const end = close < 0 ? text.length : close;
144
+ lit(text.slice(index + 1, end), true);
145
+ index = end + 1;
146
+ } else if (char === '"') {
147
+ index += 1;
148
+ while (index < text.length && text[index] !== '"') {
149
+ const inner = text[index];
150
+ if (inner === '\\' && '$`"\\\n'.includes(text[index + 1] ?? '')) {
151
+ if (text[index + 1] !== '\n') lit(text[index + 1], true);
152
+ index += 2;
153
+ } else if (inner === '$') {
154
+ const { part, end } = readDollar(text, index, true);
155
+ if (part.type === 'lit') lit(part.value, true);
156
+ else parts.push(part);
157
+ index = end;
158
+ } else if (inner === '`') {
159
+ const end = skipBacktick(text, index + 1);
160
+ parts.push({ type: 'sub', script: text.slice(index + 1, end - 1).replace(/\\([`\\$])/gu, '$1') });
161
+ index = end;
162
+ } else {
163
+ lit(inner, true);
164
+ index += 1;
165
+ }
166
+ }
167
+ index += 1;
168
+ } else if (char === '$') {
169
+ const { part, end } = readDollar(text, index, false);
170
+ if (part.type === 'lit') lit(part.value, part.quoted);
171
+ else parts.push(part);
172
+ index = end;
173
+ } else if (char === '`') {
174
+ const end = skipBacktick(text, index + 1);
175
+ parts.push({ type: 'sub', script: text.slice(index + 1, end - 1).replace(/\\([`\\$])/gu, '$1') });
176
+ index = end;
177
+ } else {
178
+ lit(char, false);
179
+ index += 1;
180
+ }
181
+ }
182
+ return { word: { type: 'word', parts }, end: index };
183
+ }
184
+
185
+ /**
186
+ * Tokenize a shell command line into words, operators and redirections.
187
+ * Heredoc bodies are consumed as data. Exported for tests.
188
+ */
189
+ export function tokenizeShell(text) {
190
+ const tokens = [];
191
+ const heredocs = [];
192
+ let index = 0;
193
+ while (index < text.length) {
194
+ const char = text[index];
195
+ if (char === ' ' || char === '\t' || char === '\r') {
196
+ index += 1;
197
+ continue;
198
+ }
199
+ if (char === '\\' && text[index + 1] === '\n') {
200
+ index += 2;
201
+ continue;
202
+ }
203
+ if (char === '#') {
204
+ while (index < text.length && text[index] !== '\n') index += 1;
205
+ continue;
206
+ }
207
+ if (char === '\n') {
208
+ tokens.push({ type: 'op', op: '\n' });
209
+ index += 1;
210
+ for (const { delimiter, strip } of heredocs.splice(0)) {
211
+ for (;;) {
212
+ if (index >= text.length) break;
213
+ const lineEnd = text.indexOf('\n', index);
214
+ const line = text.slice(index, lineEnd < 0 ? text.length : lineEnd);
215
+ index = lineEnd < 0 ? text.length : lineEnd + 1;
216
+ if ((strip ? line.replace(/^\t+/u, '') : line) === delimiter) break;
217
+ }
218
+ }
219
+ continue;
220
+ }
221
+ if ((char === '<' || char === '>') && text[index + 1] === '(') {
222
+ const end = matchParen(text, index + 2);
223
+ tokens.push({ type: 'word', parts: [{ type: 'sub', script: text.slice(index + 2, end - 1) }] });
224
+ index = end;
225
+ continue;
226
+ }
227
+ const redirect = /^(?:&>>|&>|<<<|<<-|<<|<>|<&|>>|>\||>&|<|>)/u.exec(text.slice(index))?.[0];
228
+ if (redirect !== undefined) {
229
+ index += redirect.length;
230
+ while (text[index] === ' ' || text[index] === '\t') index += 1;
231
+ const { word, end } = readWord(text, index);
232
+ index = end;
233
+ if (redirect === '<<' || redirect === '<<-') {
234
+ heredocs.push({ delimiter: word.parts.map((part) => (part.type === 'lit' ? part.value : '')).join(''), strip: redirect === '<<-' });
235
+ tokens.push({ type: 'redirect', op: redirect, target: undefined });
236
+ } else {
237
+ tokens.push({ type: 'redirect', op: redirect, target: word });
238
+ }
239
+ continue;
240
+ }
241
+ if (OPERATOR_CHARS.has(char)) {
242
+ const op = /^(?:&&|\|\||\|&|;;|;&|[;&|()])/u.exec(text.slice(index))[0];
243
+ tokens.push({ type: 'op', op });
244
+ index += op.length;
245
+ continue;
246
+ }
247
+ const { word, end } = readWord(text, index);
248
+ index = end;
249
+ // `2>file`, `10<file`: a digits-only word directly followed by a redirection is its fd.
250
+ if ((text[index] === '<' || text[index] === '>') && word.parts.length === 1 && word.parts[0].type === 'lit' && !word.parts[0].quoted && /^\d+$/u.test(word.parts[0].value)) continue;
251
+ tokens.push(word);
252
+ }
253
+ return tokens;
254
+ }
255
+
256
+ function braceExpand(text, budget = { left: MAX_BRACE_EXPANSIONS }) {
257
+ let depth = 0;
258
+ let open = -1;
259
+ for (let index = 0; index < text.length; index += 1) {
260
+ const char = text[index];
261
+ if (char === '\\') {
262
+ index += 1;
263
+ } else if (char === '{') {
264
+ if (depth === 0) open = index;
265
+ depth += 1;
266
+ } else if (char === '}' && depth > 0) {
267
+ depth -= 1;
268
+ if (depth !== 0) continue;
269
+ const body = text.slice(open + 1, index);
270
+ const prefix = text.slice(0, open);
271
+ const suffix = text.slice(index + 1);
272
+ const alternatives = [];
273
+ let level = 0;
274
+ let from = 0;
275
+ for (let cursor = 0; cursor < body.length; cursor += 1) {
276
+ if (body[cursor] === '\\') cursor += 1;
277
+ else if (body[cursor] === '{') level += 1;
278
+ else if (body[cursor] === '}') level -= 1;
279
+ else if (body[cursor] === ',' && level === 0) {
280
+ alternatives.push(body.slice(from, cursor));
281
+ from = cursor + 1;
282
+ }
283
+ }
284
+ if (alternatives.length > 0) alternatives.push(body.slice(from));
285
+ else {
286
+ const range = /^(-?\d+)\.\.(-?\d+)$/u.exec(body) ?? /^([a-zA-Z])\.\.([a-zA-Z])$/u.exec(body);
287
+ if (range === null) continue;
288
+ const numeric = /\d/u.test(range[1]);
289
+ const a = numeric ? Number(range[1]) : range[1].charCodeAt(0);
290
+ const b = numeric ? Number(range[2]) : range[2].charCodeAt(0);
291
+ const step = a <= b ? 1 : -1;
292
+ for (let value = a; step > 0 ? value <= b : value >= b; value += step) {
293
+ if (alternatives.length >= MAX_BRACE_EXPANSIONS) break;
294
+ alternatives.push(numeric ? String(value) : String.fromCharCode(value));
295
+ }
296
+ }
297
+ const results = [];
298
+ for (const alternative of alternatives) {
299
+ for (const expanded of braceExpand(`${prefix}${alternative}${suffix}`, budget)) {
300
+ if (budget.left <= 0) return results;
301
+ budget.left -= 1;
302
+ results.push(expanded);
303
+ }
304
+ }
305
+ return results;
306
+ }
307
+ }
308
+ return [text];
309
+ }
310
+
311
+ const GLOB_CHARS = /[*?[]/u;
312
+
313
+ function globSegmentRegex(segment) {
314
+ let source = '';
315
+ for (let index = 0; index < segment.length; index += 1) {
316
+ const char = segment[index];
317
+ if (char === '\\' && index + 1 < segment.length) {
318
+ index += 1;
319
+ source += segment[index].replace(/[.*+?^${}()|[\]\\/]/gu, '\\$&');
320
+ } else if (char === '*') source += '[^/]*';
321
+ else if (char === '?') source += '[^/]';
322
+ else if (char === '[') {
323
+ const close = segment.indexOf(']', index + 2);
324
+ if (close < 0) source += '\\[';
325
+ else {
326
+ let body = segment.slice(index + 1, close).replace(/\\/gu, '\\\\');
327
+ if (body.startsWith('!') || body.startsWith('^')) body = `^${body.slice(1)}`;
328
+ source += `[${body}]`;
329
+ index = close;
330
+ }
331
+ } else source += char.replace(/[.*+?^${}()|[\]\\/]/gu, '\\$&');
332
+ }
333
+ return new RegExp(`^${source}$`, 'u');
334
+ }
335
+
336
+ function unescapeGlob(segment) {
337
+ return segment.replace(/\\(.)/gu, '$1');
338
+ }
339
+
340
+ /** Expand a glob pattern (quoted characters backslash-escaped) against the filesystem. */
341
+ export function expandGlob(pattern, cwd) {
342
+ const absolute = isAbsolute(pattern);
343
+ const segments = pattern.split('/');
344
+ let bases = [absolute ? sep : cwd];
345
+ let prefixes = [absolute ? '/' : ''];
346
+ if (absolute) segments.shift();
347
+ for (const [position, segment] of segments.entries()) {
348
+ if (segment === '') continue;
349
+ const last = position === segments.length - 1;
350
+ const nextBases = [];
351
+ const nextPrefixes = [];
352
+ for (const [slot, base] of bases.entries()) {
353
+ if (!GLOB_CHARS.test(segment.replace(/\\./gu, ''))) {
354
+ nextBases.push(join(base, unescapeGlob(segment)));
355
+ nextPrefixes.push(`${prefixes[slot]}${unescapeGlob(segment)}${last ? '' : '/'}`);
356
+ continue;
357
+ }
358
+ let entries = [];
359
+ try {
360
+ entries = readdirSync(base, { withFileTypes: true });
361
+ } catch {
362
+ continue;
363
+ }
364
+ const regex = globSegmentRegex(segment);
365
+ for (const entry of entries) {
366
+ if (entry.name.startsWith('.') && !segment.startsWith('.')) continue;
367
+ if (!regex.test(entry.name)) continue;
368
+ if (!last && !entry.isDirectory() && !entry.isSymbolicLink()) continue;
369
+ nextBases.push(join(base, entry.name));
370
+ nextPrefixes.push(`${prefixes[slot]}${entry.name}${last ? '' : '/'}`);
371
+ if (nextBases.length >= MAX_GLOB_MATCHES) break;
372
+ }
373
+ }
374
+ bases = nextBases;
375
+ prefixes = nextPrefixes;
376
+ }
377
+ return bases;
378
+ }
379
+
380
+ /** One expanded word: its possible values, whether it is unresolvable, and whether it globbed. */
381
+ function expandWord(word, scope, onSub) {
382
+ let text = '';
383
+ let pattern = '';
384
+ let dynamic = false;
385
+ let globbing = false;
386
+ let braces = false;
387
+ for (const [position, part] of word.parts.entries()) {
388
+ if (part.type === 'lit') {
389
+ let value = part.value;
390
+ if (!part.quoted && position === 0 && (value === '~' || value.startsWith('~/'))) value = `${scope.home}${value.slice(1)}`;
391
+ text += value;
392
+ if (part.quoted) pattern += value.replace(/[*?[\]\\{}]/gu, '\\$&');
393
+ else {
394
+ pattern += value;
395
+ if (GLOB_CHARS.test(value)) globbing = true;
396
+ if (value.includes('{')) braces = true;
397
+ }
398
+ } else if (part.type === 'var') {
399
+ const value = scope.vars.get(part.name);
400
+ if (value === undefined) dynamic = true;
401
+ else {
402
+ text += value;
403
+ pattern += value.replace(/[*?[\]\\{}]/gu, '\\$&');
404
+ }
405
+ } else if (part.type === 'sub') {
406
+ onSub(part.script);
407
+ dynamic = true;
408
+ } else {
409
+ dynamic = true;
410
+ }
411
+ }
412
+ if (dynamic) return { values: [], dynamic: true, text };
413
+ const patterns = braces ? braceExpand(pattern) : [pattern];
414
+ const values = [];
415
+ for (const candidate of patterns) {
416
+ if (globbing && GLOB_CHARS.test(candidate.replace(/\\./gu, ''))) {
417
+ const matches = expandGlob(candidate, scope.cwd);
418
+ if (matches.length > 0) values.push(...matches.map((match) => ({ value: match, glob: true })));
419
+ else values.push({ value: unescapeGlob(candidate), glob: false });
420
+ } else values.push({ value: unescapeGlob(candidate), glob: false });
421
+ }
422
+ return { values, dynamic: false, text };
423
+ }
424
+
425
+ // Options whose next argument is a value, not a path operand (per command).
426
+ const VALUE_OPTIONS = {
427
+ grep: new Set(['-e', '-f', '-m', '-A', '-B', '-C', '-d', '-D', '--regexp', '--file', '--max-count', '--context', '--after-context', '--before-context', '--include', '--exclude', '--exclude-dir', '--label', '--color', '--colour', '--binary-files', '--devices', '--directories']),
428
+ rg: new Set(['-e', '-f', '-g', '-t', '-T', '-m', '-A', '-B', '-C', '-j', '-M', '-E', '-d', '-r', '--regexp', '--file', '--glob', '--iglob', '--type', '--type-not', '--type-add', '--max-count', '--context', '--after-context', '--before-context', '--threads', '--max-columns', '--encoding', '--max-depth', '--pre', '--pre-glob', '--sort', '--sortr', '--replace', '--max-filesize', '--path-separator', '--colors', '--color', '--context-separator', '--field-match-separator', '--field-context-separator', '--engine', '--dfa-size-limit', '--regex-size-limit', '--ignore-file', '--hostname-bin', '--hyperlink-format', '--generate', '--type-clear']),
429
+ tar: new Set(['-f', '-C', '-T', '-X', '-b', '-H', '-I', '--file', '--directory', '--files-from', '--exclude-from', '--exclude', '--format', '--use-compress-program', '--transform', '--owner', '--group', '--mode', '--mtime']),
430
+ zip: new Set(['-b', '-n', '-t', '-tt', '-x', '-i', '-P', '-Z', '-O', '--out']),
431
+ cp: new Set(['-t', '--target-directory', '-S', '--suffix']),
432
+ rsync: new Set(['-e', '--rsh', '--exclude', '--include', '--exclude-from', '--include-from', '--files-from', '--filter', '-f', '--rsync-path', '--log-file', '--partial-dir', '--temp-dir', '-T', '--compare-dest', '--copy-dest', '--link-dest', '--chmod', '--bwlimit', '--timeout', '--port', '--password-file']),
433
+ find: new Set([]),
434
+ git: new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path', '--super-prefix', '--config-env']),
435
+ sudo: new Set(['-u', '-g', '-h', '-p', '-C', '-D', '-R', '-T', '-r', '-t', '-U', '--user', '--group', '--host', '--prompt', '--close-from', '--chdir', '--chroot', '--command-timeout', '--role', '--type', '--other-user']),
436
+ env: new Set(['-u', '-C', '-S', '--unset', '--chdir', '--split-string']),
437
+ xargs: new Set(['-I', '-i', '-L', '-l', '-n', '-P', '-s', '-E', '-e', '-d', '-a', '--arg-file', '--delimiter', '--max-args', '--max-procs', '--max-chars', '--replace', '--eof', '--max-lines', '--process-slot-var']),
438
+ timeout: new Set(['-k', '-s', '--kill-after', '--signal']),
439
+ nice: new Set(['-n', '--adjustment']),
440
+ diff: new Set(['-x', '-X', '-I', '-F', '-L', '-C', '-U', '-W', '--exclude', '--exclude-from', '--ignore-matching-lines', '--label', '--horizon-lines', '--to-file', '--from-file', '--width', '--tabsize', '--line-format', '--old-line-format', '--new-line-format', '--unchanged-line-format', '--old-group-format', '--new-group-format', '--changed-group-format', '--unchanged-group-format', '--palette', '--color']),
441
+ fd: new Set(['-e', '-E', '-t', '-d', '-x', '-X', '-j', '-S', '-o', '-c', '--extension', '--exclude', '--type', '--max-depth', '--min-depth', '--exact-depth', '--exec', '--exec-batch', '--threads', '--size', '--owner', '--changed-within', '--changed-before', '--color', '--max-results', '--base-directory', '--path-separator', '--search-path', '--ignore-file', '--format']),
442
+ };
443
+
444
+ const GREP_LIKE = new Set(['grep', 'egrep', 'fgrep', 'zgrep', 'zegrep', 'zfgrep', 'ggrep', 'bzgrep', 'xzgrep', 'ugrep']);
445
+ const RG_LIKE = new Set(['rg', 'ag', 'ack', 'ack-grep', 'pt', 'sift', 'ripgrep']);
446
+ const FIND_LIKE = new Set(['find', 'gfind', 'bfs']);
447
+ const FD_LIKE = new Set(['fd', 'fdfind']);
448
+ const ARCHIVERS = new Set(['tar', 'gtar', 'bsdtar', 'pax', 'cpio', '7z', '7za', 'jar', 'rar']);
449
+ const ZIP_LIKE = new Set(['zip']);
450
+ const COPIERS = new Set(['cp', 'gcp', 'scp', 'rcp']);
451
+ const SYNCERS = new Set(['rsync']);
452
+ const ALWAYS_RECURSIVE = new Set(['ditto', 'du', 'tree', 'chezmoi', 'rclone', 'restic', 'borg', 'duplicity', 'shasum-r', 'hashdeep', 'md5deep', 'sha256deep', 'gsutil']);
453
+ const SHELLS = new Set(['bash', 'sh', 'zsh', 'dash', 'ksh', 'mksh', 'ash', 'fish', 'busybox']);
454
+ const INTERPRETERS = new Set(['python', 'python2', 'python3', 'node', 'nodejs', 'deno', 'bun', 'ruby', 'perl', 'php', 'lua', 'Rscript', 'osascript', 'pwsh', 'powershell', 'awk', 'gawk', 'mawk', 'jq']);
455
+ const WRITERS = new Set(['cp', 'mv', 'tee', 'touch', 'rm', 'ln', 'install', 'mkdir', 'truncate', 'chmod', 'chown', 'shred', 'unlink', 'rmdir', 'sed', 'perl', 'dd', 'patch']);
456
+ const GIT_RECURSIVE = new Set(['show', 'diff', 'log', 'grep', 'archive', 'whatchanged', 'format-patch', 'stash', 'bundle', 'difftool', 'range-diff', 'diff-tree', 'diff-index', 'diff-files', 'ls-files', 'ls-tree', 'cat-file', 'blame', 'annotate']);
457
+ const WRAPPERS = new Set(['sudo', 'doas', 'command', 'builtin', 'exec', 'nohup', 'nice', 'time', 'timeout', 'gtimeout', 'stdbuf', 'ionice', 'chrt', 'caffeinate', 'unbuffer', 'setsid', 'taskset', 'watch', 'strace', 'ltrace', 'dtruss', 'catchsegv', 'chronic', 'flock', 'script', 'arch', 'noglob', 'rlwrap']);
458
+
459
+ const isOption = (value) => value.length > 1 && value.startsWith('-');
460
+
461
+ /** Split argv into positional operands, honouring `--` and options with values. */
462
+ function operands(args, valueOptions = new Set()) {
463
+ const positional = [];
464
+ const optionValues = [];
465
+ let flags = '';
466
+ for (let index = 0; index < args.length; index += 1) {
467
+ const arg = args[index];
468
+ if (arg.text === '--') {
469
+ positional.push(...args.slice(index + 1));
470
+ break;
471
+ }
472
+ if (isOption(arg.text)) {
473
+ const eq = arg.text.indexOf('=');
474
+ const name = eq < 0 ? arg.text : arg.text.slice(0, eq);
475
+ if (!arg.text.startsWith('--')) flags += arg.text.slice(1);
476
+ if (eq < 0 && valueOptions.has(name) && index + 1 < args.length) {
477
+ optionValues.push({ name, arg: args[index + 1] });
478
+ index += 1;
479
+ } else if (eq >= 0) optionValues.push({ name, arg: { ...arg, values: arg.values.map((item) => ({ ...item, value: item.value.slice(item.value.indexOf('=') + 1) })) } });
480
+ continue;
481
+ }
482
+ positional.push(arg);
483
+ }
484
+ return { positional, optionValues, flags, long: new Set(args.filter((arg) => arg.text.startsWith('--')).map((arg) => arg.text.split('=')[0])) };
485
+ }
486
+
487
+ /** Quoted string literals inside interpreter code (`python -c "open('x')"`). */
488
+ function codeLiterals(code) {
489
+ const literals = [];
490
+ for (const match of code.matchAll(/(['"`])((?:\\.|(?!\1)[^\\\n])*)\1/gu)) literals.push(match[2]);
491
+ for (const match of code.matchAll(/(?:^|[\s(,=])((?:\.{0,2}\/|~\/)?[\w.@-]+(?:\/[\w.@-]+)+)/gu)) literals.push(match[1]);
492
+ return literals;
493
+ }
494
+
495
+ function repoRootOf(dir, exists) {
496
+ let current = dir;
497
+ for (;;) {
498
+ if (exists(join(current, '.git'))) return current;
499
+ const parent = dirname(current);
500
+ if (parent === current) return undefined;
501
+ current = parent;
502
+ }
503
+ }
504
+
505
+ /**
506
+ * References a shell command line makes to files, for the `.picassoignore`
507
+ * guard. Each reference is `{ path, recursive, always, gitTracked, opaque?, command }`:
508
+ * `path` is absolute; `recursive` marks a directory operand the command reads
509
+ * as a tree; `always` marks a target checked even when it does not exist yet
510
+ * (redirections, write commands); `gitTracked` marks a git read whose scope
511
+ * is the repository's tracked files; `opaque` marks a word whose value is
512
+ * only known at run time (its `path` is the working directory).
513
+ *
514
+ * @param {string} commandLine
515
+ * @param {string} cwd - absolute working directory the command starts in.
516
+ * @param {{ home?: string, env?: Record<string, string>, exists?: (path: string) => boolean }} [options]
517
+ */
518
+ export function shellReferences(commandLine, cwd, options = {}) {
519
+ const references = [];
520
+ const exists = options.exists ?? (() => false);
521
+ const root = {
522
+ cwd: resolve(cwd),
523
+ home: options.home ?? homedir(),
524
+ vars: new Map(Object.entries({ HOME: options.home ?? homedir(), PWD: resolve(cwd), ...(options.env ?? {}) })),
525
+ };
526
+ const add = (path, flags, commandName) => {
527
+ if (typeof path !== 'string' || path.length === 0 || path.includes('\0')) return;
528
+ let value = path;
529
+ if (value.startsWith('file://')) {
530
+ try {
531
+ value = fileURLToPath(value);
532
+ } catch {
533
+ return;
534
+ }
535
+ }
536
+ references.push({ path: resolve(flags.cwd, value), recursive: flags.recursive === true, always: flags.always === true, gitTracked: flags.gitTracked === true, command: commandName });
537
+ };
538
+ const run = (script, scope, depth) => {
539
+ if (depth > MAX_DEPTH) return;
540
+ walk(tokenizeShell(script), scope, depth);
541
+ };
542
+ const walk = (tokens, startScope, depth) => {
543
+ const stack = [];
544
+ let scope = startScope;
545
+ let words = [];
546
+ let redirects = [];
547
+ const finish = () => {
548
+ if (words.length > 0 || redirects.length > 0) simple(words, redirects, scope, depth);
549
+ words = [];
550
+ redirects = [];
551
+ };
552
+ for (const token of tokens) {
553
+ if (token.type === 'word') words.push(token);
554
+ else if (token.type === 'redirect') redirects.push(token);
555
+ else if (token.op === '(') {
556
+ finish();
557
+ stack.push(scope);
558
+ scope = { ...scope, vars: new Map(scope.vars) };
559
+ } else if (token.op === ')') {
560
+ finish();
561
+ scope = stack.pop() ?? scope;
562
+ } else finish();
563
+ }
564
+ finish();
565
+ };
566
+ const expand = (word, scope, depth) => {
567
+ const expanded = expandWord(word, scope, (script) => run(script, { ...scope, vars: new Map(scope.vars) }, depth + 1));
568
+ // A word only known at run time: the command may name paths this reading cannot see.
569
+ if (expanded.dynamic) references.push({ path: scope.cwd, recursive: false, always: false, gitTracked: false, opaque: true, command: 'dynamic' });
570
+ return { ...expanded, text: expanded.values[0]?.value ?? expanded.text };
571
+ };
572
+ const simple = (wordTokens, redirectTokens, scope, depth) => {
573
+ for (const redirect of redirectTokens) {
574
+ if (redirect.target === undefined || redirect.op === '<<<') {
575
+ if (redirect.target !== undefined) expand(redirect.target, scope, depth);
576
+ continue;
577
+ }
578
+ const target = expand(redirect.target, scope, depth);
579
+ if ((redirect.op === '>&' || redirect.op === '<&') && /^(?:\d+-?|-)$/u.test(target.text)) continue;
580
+ for (const { value } of target.values) add(value, { cwd: scope.cwd, always: true }, 'redirect');
581
+ }
582
+ let args = wordTokens.map((word) => expand(word, scope, depth));
583
+ // Leading assignments.
584
+ const assignments = [];
585
+ const assignmentLike = (word) => word?.parts[0]?.type === 'lit' && !word.parts[0].quoted && /^[A-Za-z_][A-Za-z0-9_]*\+?=/u.test(word.parts[0].value);
586
+ while (args.length > 0 && assignmentLike(wordTokens[assignments.length])) {
587
+ assignments.push(args[0]);
588
+ args = args.slice(1);
589
+ }
590
+ for (const [position, assignment] of assignments.entries()) {
591
+ const raw = wordTokens[position];
592
+ const name = /^([A-Za-z_][A-Za-z0-9_]*)/u.exec(raw.parts[0].value)[1];
593
+ if (args.length === 0) {
594
+ if (assignment.dynamic) scope.vars.delete(name);
595
+ else scope.vars.set(name, assignment.text.slice(assignment.text.indexOf('=') + 1));
596
+ }
597
+ }
598
+ if (args.length > 0) command(args, scope, depth);
599
+ };
600
+ /** Analyse one argv (after assignments) in `scope`. */
601
+ const command = (args, scope, depth) => {
602
+ if (depth > MAX_DEPTH || args.length === 0) return;
603
+ const head = args[0];
604
+ if (head.dynamic) {
605
+ for (const arg of args.slice(1)) for (const { value } of arg.values) add(value, { cwd: scope.cwd }, '?');
606
+ return;
607
+ }
608
+ const name = basename(head.text);
609
+ const rest = args.slice(1);
610
+ const generic = (list, flags = {}) => {
611
+ for (const arg of list) for (const { value } of arg.values) add(value, { cwd: scope.cwd, ...flags }, name);
612
+ };
613
+ const optionPaths = (optionValues, recursive = false) => {
614
+ for (const { arg } of optionValues) for (const { value } of arg.values) add(value, { cwd: scope.cwd, recursive }, name);
615
+ };
616
+ if (name === '{' || name === '}' || name === '!' || name === 'then' || name === 'do' || name === 'else' || name === 'if' || name === 'while' || name === 'until' || name === 'elif') {
617
+ command(rest, scope, depth);
618
+ return;
619
+ }
620
+ if (name === 'cd' || name === 'pushd' || name === 'chdir') {
621
+ const target = rest.find((arg) => !isOption(arg.text));
622
+ if (target === undefined) scope.cwd = scope.home;
623
+ else if (!target.dynamic && target.text !== '-') scope.cwd = resolve(scope.cwd, target.text);
624
+ return;
625
+ }
626
+ if (name === 'export' || name === 'local' || name === 'declare' || name === 'typeset' || name === 'readonly') {
627
+ for (const arg of rest) {
628
+ const match = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/su.exec(arg.text);
629
+ if (match === null) continue;
630
+ if (arg.dynamic) scope.vars.delete(match[1]);
631
+ else scope.vars.set(match[1], match[2]);
632
+ }
633
+ return;
634
+ }
635
+ if (name === 'eval') {
636
+ run(rest.map((arg) => arg.text).join(' '), scope, depth + 1);
637
+ return;
638
+ }
639
+ if (name === 'source' || name === '.') {
640
+ generic(rest.slice(0, 1), { always: false });
641
+ return;
642
+ }
643
+ if (name === 'env') {
644
+ const { positional, optionValues } = operands(rest, VALUE_OPTIONS.env);
645
+ let inner = { ...scope };
646
+ for (const { name: option, arg } of optionValues) {
647
+ if ((option === '-C' || option === '--chdir') && !arg.dynamic) inner = { ...inner, cwd: resolve(scope.cwd, arg.text) };
648
+ if (option === '-S' || option === '--split-string') run(arg.text, inner, depth + 1);
649
+ }
650
+ const start = positional.findIndex((arg) => !/^[A-Za-z_][A-Za-z0-9_]*=/u.test(arg.text));
651
+ if (start >= 0) command(positional.slice(start), inner, depth + 1);
652
+ return;
653
+ }
654
+ if (WRAPPERS.has(name)) {
655
+ const valueOptions = VALUE_OPTIONS[name] ?? new Set();
656
+ let index = 0;
657
+ let inner = scope;
658
+ while (index < rest.length && isOption(rest[index].text)) {
659
+ const option = rest[index].text.split('=')[0];
660
+ if ((option === '-D' || option === '--chdir') && name === 'sudo' && index + 1 < rest.length) inner = { ...scope, cwd: resolve(scope.cwd, rest[index + 1].text) };
661
+ index += valueOptions.has(option) && !rest[index].text.includes('=') ? 2 : 1;
662
+ }
663
+ // timeout DURATION, nice -n N already consumed; `timeout 5 cmd`.
664
+ if ((name === 'timeout' || name === 'gtimeout') && index < rest.length) index += 1;
665
+ if (name === 'flock' && index < rest.length) index += 1;
666
+ if (name === 'script' && index < rest.length) index += 1;
667
+ command(rest.slice(index), inner, depth + 1);
668
+ return;
669
+ }
670
+ if (name === 'xargs') {
671
+ const { positional, optionValues } = operands(rest, VALUE_OPTIONS.xargs);
672
+ optionPaths(optionValues.filter((item) => item.name === '-a' || item.name === '--arg-file'));
673
+ // The first positional starts the command; everything after it is its argv.
674
+ const start = rest.indexOf(positional[0]);
675
+ if (start >= 0) command(rest.slice(start), scope, depth + 1);
676
+ return;
677
+ }
678
+ if (SHELLS.has(name)) {
679
+ const flag = rest.findIndex((arg) => /^-[a-zA-Z]*c[a-zA-Z]*$/u.test(arg.text));
680
+ if (flag >= 0 && flag + 1 < rest.length) {
681
+ run(rest[flag + 1].text, { ...scope, vars: new Map(scope.vars) }, depth + 1);
682
+ return;
683
+ }
684
+ generic(rest.filter((arg) => !isOption(arg.text)).slice(0, 1));
685
+ return;
686
+ }
687
+ if (INTERPRETERS.has(name)) {
688
+ for (const [index, arg] of rest.entries()) {
689
+ const previous = rest[index - 1]?.text;
690
+ if (previous === '-c' || previous === '-e' || previous === '--eval' || previous === '-p' || previous === '--print' || previous === '-E' || previous === '-r' || previous === '-Command' || previous === '-r') {
691
+ for (const literal of codeLiterals(arg.text)) add(literal, { cwd: scope.cwd }, name);
692
+ } else if (!isOption(arg.text)) {
693
+ for (const { value } of arg.values) add(value, { cwd: scope.cwd }, name);
694
+ if ((name === 'awk' || name === 'gawk' || name === 'mawk' || name === 'jq') && index === rest.findIndex((item) => !isOption(item.text))) {
695
+ for (const literal of codeLiterals(arg.text)) add(literal, { cwd: scope.cwd }, name);
696
+ }
697
+ }
698
+ }
699
+ return;
700
+ }
701
+ if (name === 'git') {
702
+ let index = 0;
703
+ let gitCwd = scope.cwd;
704
+ while (index < rest.length && isOption(rest[index].text)) {
705
+ const option = rest[index].text.split('=')[0];
706
+ if (option === '-C' && index + 1 < rest.length) gitCwd = resolve(gitCwd, rest[index + 1].text);
707
+ if ((option === '--work-tree' || option === '--git-dir') && rest[index].text.includes('=')) add(rest[index].text.slice(rest[index].text.indexOf('=') + 1), { cwd: gitCwd, recursive: true, gitTracked: option === '--git-dir' }, name);
708
+ index += VALUE_OPTIONS.git.has(option) && !rest[index].text.includes('=') ? 2 : 1;
709
+ }
710
+ const sub = rest[index]?.text;
711
+ const subArgs = rest.slice(index + 1);
712
+ const repoRoot = repoRootOf(gitCwd, exists) ?? gitCwd;
713
+ let pathspecs = 0;
714
+ const afterDashDash = subArgs.findIndex((arg) => arg.text === '--');
715
+ for (const [position, arg] of subArgs.entries()) {
716
+ if (arg.dynamic || (isOption(arg.text) && (afterDashDash < 0 || position < afterDashDash))) continue;
717
+ if (arg.text === '--') continue;
718
+ const colon = /^([^:/\s]*):(.+)$/su.exec(arg.text);
719
+ if (colon !== null && (afterDashDash < 0 || position < afterDashDash)) {
720
+ const path = colon[2];
721
+ const base = path.startsWith('./') || path.startsWith('../') ? gitCwd : repoRoot;
722
+ add(path, { cwd: base, recursive: true, always: true }, 'git');
723
+ pathspecs += 1;
724
+ continue;
725
+ }
726
+ for (const { value } of arg.values) {
727
+ const absolute = resolve(gitCwd, value.replace(/^:\(literal\)|^:\/?/u, ''));
728
+ if (afterDashDash >= 0 && position > afterDashDash) {
729
+ add(absolute, { cwd: gitCwd, recursive: GIT_RECURSIVE.has(sub), always: true, gitTracked: true }, 'git');
730
+ pathspecs += 1;
731
+ } else if (exists(absolute)) {
732
+ add(absolute, { cwd: gitCwd, recursive: GIT_RECURSIVE.has(sub), gitTracked: GIT_RECURSIVE.has(sub) }, 'git');
733
+ pathspecs += 1;
734
+ }
735
+ }
736
+ }
737
+ if (GIT_RECURSIVE.has(sub) && pathspecs === 0 && sub !== 'cat-file' && sub !== 'blame' && sub !== 'annotate') {
738
+ add(sub === 'grep' || sub === 'ls-files' ? gitCwd : repoRoot, { cwd: gitCwd, recursive: true, gitTracked: true }, 'git');
739
+ }
740
+ return;
741
+ }
742
+ if (GREP_LIKE.has(name)) {
743
+ const { positional, optionValues, flags, long } = operands(rest, VALUE_OPTIONS.grep);
744
+ const recursive = /[rR]/u.test(flags) || long.has('--recursive') || long.has('--dereference-recursive') || optionValues.some((item) => (item.name === '-d' || item.name === '--directories') && item.arg.text === 'recurse') || name === 'ugrep';
745
+ optionPaths(optionValues.filter((item) => item.name === '-f' || item.name === '--file'));
746
+ const explicitPattern = optionValues.some((item) => ['-e', '-f', '--regexp', '--file'].includes(item.name));
747
+ const files = explicitPattern ? positional : positional.slice(1);
748
+ if (files.length === 0 && recursive) add('.', { cwd: scope.cwd, recursive: true }, name);
749
+ generic(files, { recursive });
750
+ return;
751
+ }
752
+ if (RG_LIKE.has(name)) {
753
+ const { positional, optionValues, long } = operands(rest, VALUE_OPTIONS.rg);
754
+ optionPaths(optionValues.filter((item) => item.name === '-f' || item.name === '--file' || item.name === '--ignore-file'));
755
+ const explicitPattern = long.has('--files') || long.has('--type-list') || optionValues.some((item) => ['-e', '-f', '--regexp', '--file'].includes(item.name));
756
+ const files = explicitPattern ? positional : positional.slice(1);
757
+ if (files.length === 0) add('.', { cwd: scope.cwd, recursive: true }, name);
758
+ generic(files, { recursive: true });
759
+ return;
760
+ }
761
+ if (FIND_LIKE.has(name)) {
762
+ let index = 0;
763
+ while (index < rest.length && /^-[HLPEXOsdfx]/u.test(rest[index].text) && rest[index].text.length <= 3) index += 1;
764
+ const roots = [];
765
+ while (index < rest.length && !rest[index].text.startsWith('-') && rest[index].text !== '(' && rest[index].text !== '!' && rest[index].text !== '\\(') roots.push(rest[index++]);
766
+ if (roots.length === 0) add('.', { cwd: scope.cwd, recursive: true }, name);
767
+ generic(roots, { recursive: true });
768
+ for (; index < rest.length; index += 1) {
769
+ const primary = rest[index].text;
770
+ if (primary === '-exec' || primary === '-execdir' || primary === '-ok' || primary === '-okdir') {
771
+ const end = rest.findIndex((arg, position) => position > index && (arg.text === ';' || arg.text === '+'));
772
+ const inner = rest.slice(index + 1, end < 0 ? rest.length : end).filter((arg) => arg.text !== '{}');
773
+ command(inner, scope, depth + 1);
774
+ index = end < 0 ? rest.length : end;
775
+ } else if (['-fprint', '-fprint0', '-fprintf', '-fls', '-newer', '-anewer', '-cnewer', '-samefile'].includes(primary) && index + 1 < rest.length) {
776
+ generic([rest[index + 1]], { always: primary.startsWith('-f') });
777
+ index += 1;
778
+ }
779
+ }
780
+ return;
781
+ }
782
+ if (FD_LIKE.has(name)) {
783
+ const { positional, optionValues } = operands(rest, VALUE_OPTIONS.fd);
784
+ const dirs = positional.slice(1);
785
+ for (const { name: option, arg } of optionValues) {
786
+ if (option === '--base-directory' || option === '--search-path') dirs.push(arg);
787
+ }
788
+ if (dirs.length === 0) add('.', { cwd: scope.cwd, recursive: true }, name);
789
+ generic(dirs, { recursive: true });
790
+ return;
791
+ }
792
+ if (ARCHIVERS.has(name)) {
793
+ let tarCwd = scope.cwd;
794
+ for (let index = 0; index < rest.length; index += 1) {
795
+ const arg = rest[index];
796
+ // Bundled short flags (`czf out.tgz`, `-xvf in.tar`): a trailing `f` takes the archive, `C` a directory.
797
+ const bundle = /^-?([A-Za-z]{2,})$/u.exec(arg.text);
798
+ if (bundle !== null && (index === 0 || arg.text.startsWith('-')) && !arg.text.startsWith('--') && /^[a-zA-Z]+$/u.test(bundle[1]) && (ARCHIVERS.has(name) && name !== '7z' && name !== '7za')) {
799
+ let consumed = 0;
800
+ for (const flag of bundle[1]) {
801
+ if (flag !== 'f' && flag !== 'C' && flag !== 'T') continue;
802
+ const value = rest[index + 1 + consumed];
803
+ consumed += 1;
804
+ if (value === undefined || value.dynamic) continue;
805
+ if (flag === 'C') tarCwd = resolve(tarCwd, value.text);
806
+ else for (const { value: path } of value.values) add(path, { cwd: tarCwd, always: flag === 'f' }, name);
807
+ }
808
+ index += consumed;
809
+ continue;
810
+ }
811
+ if (arg.text === '-C' || arg.text === '--directory') {
812
+ if (index + 1 < rest.length && !rest[index + 1].dynamic) tarCwd = resolve(tarCwd, rest[index + 1].text);
813
+ index += 1;
814
+ continue;
815
+ }
816
+ if (arg.text.startsWith('--directory=')) {
817
+ tarCwd = resolve(tarCwd, arg.text.slice('--directory='.length));
818
+ continue;
819
+ }
820
+ if (isOption(arg.text)) {
821
+ const option = arg.text.split('=')[0];
822
+ if ((option === '-f' || option === '--file' || option === '-T' || option === '--files-from') && index + 1 < rest.length && !arg.text.includes('=')) {
823
+ for (const { value } of rest[index + 1].values) add(value, { cwd: tarCwd, always: option === '-f' || option === '--file' }, name);
824
+ index += 1;
825
+ } else if (VALUE_OPTIONS.tar.has(option) && !arg.text.includes('=')) index += 1;
826
+ continue;
827
+ }
828
+ for (const { value } of arg.values) add(value, { cwd: tarCwd, recursive: true }, name);
829
+ }
830
+ return;
831
+ }
832
+ if (ZIP_LIKE.has(name)) {
833
+ const { positional, flags, long } = operands(rest, VALUE_OPTIONS.zip);
834
+ const recursive = /r/u.test(flags) || long.has('--recurse-paths');
835
+ generic(positional.slice(0, 1), { always: true });
836
+ generic(positional.slice(1), { recursive });
837
+ return;
838
+ }
839
+ if (COPIERS.has(name) || SYNCERS.has(name) || name === 'diff' || name === 'colordiff' || name === 'mv' || name === 'chmod' || name === 'chown' || name === 'rm' || name === 'ls' || name === 'gls' || name === 'eza' || name === 'exa' || name === 'lsd' || name === 'wc' || name === 'shasum' || name === 'md5sum' || name === 'sha256sum' || name === 'b3sum') {
840
+ const { positional, optionValues, flags, long } = operands(rest, VALUE_OPTIONS[name] ?? VALUE_OPTIONS[SYNCERS.has(name) ? 'rsync' : name === 'colordiff' ? 'diff' : 'cp'] ?? new Set());
841
+ const recursive = SYNCERS.has(name)
842
+ ? /[ra]/u.test(flags) || long.has('--recursive') || long.has('--archive')
843
+ : name === 'mv' || /[rRa]/u.test(flags) || long.has('--recursive') || long.has('--archive');
844
+ optionPaths(optionValues.filter((item) => ['-t', '--target-directory', '--files-from', '--exclude-from', '--include-from', '-X', '--exclude-from', '--from-file', '--to-file'].includes(item.name)), false);
845
+ const recursiveRead = recursive && name !== 'chmod' && name !== 'chown' && name !== 'rm' && name !== 'ls' && name !== 'gls' && name !== 'eza' && name !== 'exa' && name !== 'lsd';
846
+ generic(positional, { recursive: recursiveRead, always: WRITERS.has(name) });
847
+ return;
848
+ }
849
+ if (ALWAYS_RECURSIVE.has(name)) {
850
+ const { positional } = operands(rest);
851
+ if (positional.length === 0 && name !== 'du' && name !== 'tree') add('.', { cwd: scope.cwd, recursive: true }, name);
852
+ generic(positional, { recursive: name !== 'du' && name !== 'tree' });
853
+ return;
854
+ }
855
+ if (name === 'dd') {
856
+ for (const arg of rest) {
857
+ const match = /^(if|of)=(.+)$/su.exec(arg.text);
858
+ if (match !== null) add(match[2], { cwd: scope.cwd, always: match[1] === 'of' }, name);
859
+ }
860
+ return;
861
+ }
862
+ // Any other command: every operand and `--opt=value` value may be a path.
863
+ const { positional, optionValues } = operands(rest);
864
+ optionPaths(optionValues);
865
+ generic(positional, { always: WRITERS.has(name) });
866
+ };
867
+ run(String(commandLine), root, 0);
868
+ return references;
869
+ }