@kirkchinese/harness-forge 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/README.md +4 -0
  2. package/docs/DETAIL.zh.md +47 -0
  3. package/lib/agents/presets.d.ts +7 -0
  4. package/lib/agents/presets.js +11 -1
  5. package/lib/agents/profiles.js +3 -2
  6. package/lib/agents/row.js +3 -1
  7. package/lib/client/paths.d.ts +12 -0
  8. package/lib/client/paths.js +68 -0
  9. package/lib/client/typert.d.ts +12 -1
  10. package/lib/client/typert.js +54 -6
  11. package/lib/client.js +1593 -270
  12. package/lib/commands/row.js +1 -1
  13. package/lib/context/instructions.js +5 -5
  14. package/lib/dsh/host.d.ts +3 -0
  15. package/lib/dsh/host.js +3 -0
  16. package/lib/forge/contract.d.ts +42 -2
  17. package/lib/forge/contract.js +3 -1
  18. package/lib/forge/follow.d.ts +30 -0
  19. package/lib/forge/follow.js +73 -0
  20. package/lib/forge/ledger.d.ts +70 -7
  21. package/lib/forge/ledger.js +314 -42
  22. package/lib/forge/projects.d.ts +5 -2
  23. package/lib/forge/projects.js +23 -16
  24. package/lib/forge/remote/archive.d.ts +65 -0
  25. package/lib/forge/remote/archive.js +565 -0
  26. package/lib/forge/remote/code-parts.d.ts +18 -0
  27. package/lib/forge/remote/code-parts.js +76 -0
  28. package/lib/forge/remote/fetch.d.ts +265 -0
  29. package/lib/forge/remote/fetch.js +1133 -0
  30. package/lib/forge/remote/service.d.ts +256 -0
  31. package/lib/forge/remote/service.js +868 -0
  32. package/lib/forge/service.d.ts +19 -9
  33. package/lib/forge/service.js +47 -31
  34. package/lib/forge/settings.d.ts +5 -3
  35. package/lib/forge/settings.js +11 -4
  36. package/lib/forge/state.d.ts +60 -0
  37. package/lib/forge/state.js +174 -58
  38. package/lib/hooks/broker/engine.js +2 -8
  39. package/lib/hooks/broker/session-events.d.ts +5 -0
  40. package/lib/hooks/broker/session-events.js +12 -3
  41. package/lib/hooks/broker/types.d.ts +7 -5
  42. package/lib/hooks/condition.d.ts +78 -2
  43. package/lib/hooks/condition.js +494 -73
  44. package/lib/hooks/config.d.ts +1 -1
  45. package/lib/hooks/config.js +4 -0
  46. package/lib/hooks/glob.d.ts +41 -0
  47. package/lib/hooks/glob.js +114 -0
  48. package/lib/hooks/permissions.d.ts +8 -3
  49. package/lib/hooks/permissions.js +119 -26
  50. package/lib/hooks/powershell-aliases.d.ts +19 -0
  51. package/lib/hooks/powershell-aliases.js +58 -0
  52. package/lib/hooks/process.d.ts +17 -0
  53. package/lib/hooks/process.js +156 -1
  54. package/lib/hooks/row.js +2 -0
  55. package/lib/hooks/runner.d.ts +17 -4
  56. package/lib/hooks/runner.js +42 -13
  57. package/lib/hooks/shell-commands.d.ts +10 -1
  58. package/lib/hooks/shell-commands.js +74 -10
  59. package/lib/hooks/shell.d.ts +3 -2
  60. package/lib/hooks/shell.js +5 -2
  61. package/lib/hooks/vocabulary.js +3 -1
  62. package/lib/mcp/catalog.d.ts +5 -2
  63. package/lib/mcp/catalog.js +18 -10
  64. package/lib/mcp/mount.d.ts +40 -2
  65. package/lib/mcp/mount.js +131 -31
  66. package/lib/mcp/policy.d.ts +42 -0
  67. package/lib/mcp/policy.js +43 -0
  68. package/lib/mcp/remote.js +5 -15
  69. package/lib/mcp/row.js +111 -17
  70. package/lib/mods/loader.js +4 -0
  71. package/lib/mods/service/turns.d.ts +8 -7
  72. package/lib/mods/service/turns.js +10 -35
  73. package/lib/opencode/bun.js +14 -2
  74. package/lib/opencode/row.d.ts +14 -1
  75. package/lib/opencode/row.js +38 -20
  76. package/lib/opencode/runtime/server.js +2 -1
  77. package/lib/porting/adapter-paths.d.ts +13 -0
  78. package/lib/porting/adapter-paths.js +120 -0
  79. package/lib/porting/port-gap.d.ts +10 -4
  80. package/lib/porting/port-gap.js +43 -7
  81. package/lib/porting/prompt.js +9 -7
  82. package/lib/porting/row.js +7 -5
  83. package/lib/porting/verify-port.d.ts +3 -10
  84. package/lib/porting/verify-port.js +12 -34
  85. package/lib/sessions/chat-import.d.ts +48 -0
  86. package/lib/sessions/chat-import.js +44 -0
  87. package/lib/sessions/claude.d.ts +16 -10
  88. package/lib/sessions/claude.js +76 -55
  89. package/lib/sessions/codex-discover.d.ts +34 -0
  90. package/lib/sessions/codex-discover.js +205 -0
  91. package/lib/sessions/codex-meta.d.ts +63 -0
  92. package/lib/sessions/codex-meta.js +148 -0
  93. package/lib/sessions/codex-text.d.ts +9 -0
  94. package/lib/sessions/codex-text.js +44 -0
  95. package/lib/sessions/codex.d.ts +34 -22
  96. package/lib/sessions/codex.js +150 -183
  97. package/lib/sessions/opencode.d.ts +15 -9
  98. package/lib/sessions/opencode.js +77 -58
  99. package/lib/sessions/persist.d.ts +162 -0
  100. package/lib/sessions/persist.js +377 -0
  101. package/lib/sessions/row.d.ts +2 -1
  102. package/lib/sessions/row.js +75 -9
  103. package/lib/sessions/turns.d.ts +31 -0
  104. package/lib/sessions/turns.js +63 -0
  105. package/lib/sessions/zstd.d.ts +15 -0
  106. package/lib/sessions/zstd.js +152 -0
  107. package/lib/shared/render.d.ts +30 -1
  108. package/lib/shared/render.js +813 -48
  109. package/lib/skills/provider.d.ts +2 -0
  110. package/lib/skills/provider.js +8 -2
  111. package/lib/skills/row.js +1 -1
  112. package/lib/workbench/adapter-coverage.d.ts +20 -2
  113. package/lib/workbench/adapter-coverage.js +46 -7
  114. package/lib/workbench/overview.d.ts +77 -27
  115. package/lib/workbench/overview.js +99 -12
  116. package/lib/workbench/remote.d.ts +64 -21
  117. package/lib/workbench/remote.js +181 -42
  118. package/lib/workbench/settings.d.ts +5 -1
  119. package/lib/workbench/settings.js +6 -2
  120. package/lib/workbench/workbench.d.ts +34 -4
  121. package/lib/workbench/workbench.js +147 -46
  122. package/locale/zh.json +2 -1
  123. package/package.json +3 -2
  124. package/lib/forge/marketplace-install.d.ts +0 -3
  125. package/lib/forge/marketplace-install.js +0 -64
@@ -4,26 +4,41 @@
4
4
  * matched against the tool name and its input together.
5
5
  *
6
6
  * - Shell rules match each subcommand (after stripping `VAR=value`), commands
7
- * inside `$(…)` and backticks; when the input cannot be read, or the rule
8
- * names more than the command and the input expands something at run time,
9
- * the hook runs.
10
- * - File rules follow gitignore semantics relative to the working directory:
11
- * a pattern without `/` matches the file name at any depth, `src/**` only
12
- * under `<cwd>/src`, `//abs` an absolute path, `~/x` the home directory.
7
+ * inside `$(…)` and backticks; when the input cannot be read, or a
8
+ * subcommand expands something at run time where it could still become
9
+ * what the rule names, the hook runs.
10
+ * - File rules follow gitignore semantics, anchored as Claude Code anchors
11
+ * them (see `pathRuleMatches`): a pattern without `/` matches the file name
12
+ * at any depth under the working directory, `./x` only `<cwd>/x`, `src/**` only under `<cwd>/src`
13
+ * in an allow rule, `//abs` an absolute path, `~/x` the home directory and
14
+ * `/x` the directory of the settings source.
13
15
  * `Edit` rules cover every file-writing tool and `Read` rules every reader.
14
16
  * @module @kirkchinese/harness-forge
15
17
  */
18
+ import { lstatSync, readlinkSync, realpathSync } from 'node:fs';
16
19
  import { homedir } from 'node:os';
17
- import { isAbsolute, relative, resolve } from 'node:path';
20
+ import { isAbsolute, posix, resolve, win32 } from 'node:path';
21
+ import { linksReachNewShare, reachesNewShare, SYMLINK_HOPS } from '@kirkchinese/harness-forge-core';
22
+ import { Glob, wildcard } from './glob.js';
23
+ import { powershellCommand } from './powershell-aliases.js';
18
24
  import { shellCommands } from './shell-commands.js';
19
25
  import { isShellTool } from './vocabulary.js';
20
26
  const WRITE_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'apply_patch']);
21
27
  const READ_TOOLS = new Set(['Read', 'Glob', 'Grep', 'NotebookRead']);
28
+ /** Whether a call is a file call that `Read(...)`/`Edit(...)` rules match by path. */
29
+ export function isFileCall(tool) {
30
+ const path = tool.input['file_path'] ?? tool.input['path'];
31
+ return typeof path === 'string' && tool.aliases.some(alias => WRITE_TOOLS.has(alias) || READ_TOOLS.has(alias));
32
+ }
22
33
  /**
23
34
  * Whether `rule` selects this tool call.
24
35
  * @param cwd - the session's working directory, for relative file rules.
36
+ * @param unknown - the answer when a wildcard or what it is matched against is
37
+ * too large to match within budget: true (the default) for a hook's `if` (the
38
+ * hook runs) and for deny and ask rules, false for allow rules.
39
+ * @param use - how a permission rule is used, for file rules (see `RuleUse`).
25
40
  */
26
- export function conditionMatches(rule, tool, cwd) {
41
+ export function conditionMatches(rule, tool, cwd, unknown = true, use = {}) {
27
42
  const match = /^\s*([A-Za-z0-9_\-:.*]+?)\s*(?:\((.*)\))?\s*$/su.exec(rule);
28
43
  if (match === null)
29
44
  return false;
@@ -35,17 +50,15 @@ export function conditionMatches(rule, tool, cwd) {
35
50
  return false;
36
51
  if (specifier === undefined || specifier === '' || specifier === '*')
37
52
  return true;
38
- if (isShellTool(tool.dshName) && name !== 'PowerShell')
39
- return shellRuleMatches(specifier, String(tool.input['command'] ?? ''));
40
- if (name === 'PowerShell')
41
- return globRegex(specifier, true).test(String(tool.input['command'] ?? ''));
53
+ if (isShellTool(tool.dshName))
54
+ return shellRuleMatches(specifier, String(tool.input['command'] ?? ''), unknown, shellOf(tool));
42
55
  if (name === 'WebFetch' && specifier.startsWith('domain:'))
43
- return domainMatches(specifier.slice('domain:'.length), String(tool.input['url'] ?? ''));
56
+ return domainMatches(specifier.slice('domain:'.length), String(tool.input['url'] ?? ''), unknown);
44
57
  const path = tool.input['file_path'] ?? tool.input['path'];
45
58
  if (typeof path === 'string' && (WRITE_TOOLS.has(name) || READ_TOOLS.has(name)))
46
- return pathRuleMatches(specifier, path, cwd);
59
+ return fileRuleMatches(specifier, path, cwd, unknown, use);
47
60
  const subject = tool.input['subagent_type'] ?? tool.input['skill'] ?? tool.input['query'] ?? tool.input['url'] ?? tool.input['pattern'] ?? '';
48
- return globRegex(specifier, true).test(String(subject));
61
+ return glob(specifier, true).match(String(subject)) ?? unknown;
49
62
  }
50
63
  function ruleNamesTool(name, tool) {
51
64
  if (tool.aliases.includes(name))
@@ -64,32 +77,270 @@ function mcpRuleMatches(name, specifier, toolName) {
64
77
  const server = name.endsWith('__*') ? name.slice(0, -1) : `${name}__`;
65
78
  return name.split('__').length === 2 || name.endsWith('__*') ? toolName.startsWith(server) : false;
66
79
  }
67
- /** Shell rule: any subcommand matches; unreadable or run-time-expanding input runs the hook. */
68
- function shellRuleMatches(specifier, command) {
69
- const parsed = shellCommands(command);
80
+ /**
81
+ * Shell rule: any subcommand matches; unreadable input runs the hook. The rule
82
+ * and each subcommand are compared as the words the shell reads (quotes and
83
+ * escapes removed, blanks collapsed). A subcommand with a word the shell
84
+ * would expand, or whose syntax the word reader does not read, matches with
85
+ * `unknown` when its words before that one agree with the rule's words.
86
+ * Only the argv is compared: redirections (`> out`, `2>&1`, `<<< x`) are set
87
+ * apart on both sides, so `git status > out` is `git status` to a rule. What a
88
+ * redirection reads or writes is checked against file rules instead (see
89
+ * `redirectFiles` and `ruleVerdict`).
90
+ */
91
+ function shellRuleMatches(specifier, command, unknown, shell) {
92
+ const parsed = shellCommands(command, shell);
70
93
  if (parsed === undefined)
71
94
  return true;
72
- const words = specifier.trim().replace(/:\*$/u, '').split(/\s+/u).filter(word => word !== '*' && word.length > 0);
73
- if (parsed.dynamic && words.length > 1)
74
- return true;
75
- const pattern = shellPattern(specifier);
76
- return parsed.commands.some(sub => pattern.test(sub));
95
+ // PowerShell: the command word on both sides as its cmdlet, through every alias for a restricting answer and
96
+ // only this platform's for an approving one (see `powershellCommand`).
97
+ const canonical = (word) => shell === 'powershell' ? powershellCommand(word, unknown ? 'all' : 'here') : word;
98
+ const rule = shellRule(specifier, shell, canonical);
99
+ if (rule === undefined)
100
+ return unknown;
101
+ return parsed.commands.some((sub) => {
102
+ const read = shellWords(sub, false, shell)?.words;
103
+ if (read === undefined)
104
+ return unknown;
105
+ const words = read.map((word, index) => index === 0 && !word.dynamic ? { ...word, text: canonical(word.text) } : word);
106
+ const dynamicAt = words.findIndex(word => word.dynamic);
107
+ if (dynamicAt === -1)
108
+ return rule.pattern.match(words.map(word => word.text).join(WORD_BREAK)) ?? unknown;
109
+ return unknown && couldExpandInto(rule, words, dynamicAt);
110
+ });
77
111
  }
78
- /** `git *` matches `git` and `git <anything>`; `prefix:*` is the legacy prefix form. */
79
- function shellPattern(specifier) {
112
+ /** What stands between two words when a rule is matched against a command's words: no word holds it (one that does is dynamic). */
113
+ const WORD_BREAK = '\u0000';
114
+ /**
115
+ * `git *` matches `git` and `git <anything>` when that `*` is the rule's only
116
+ * wildcard; `prefix:*` is the legacy prefix form; any other `*` stands for
117
+ * any text, across words. Undefined when the rule's quotes do not close.
118
+ */
119
+ function shellRule(specifier, shell, canonical) {
80
120
  const trimmed = specifier.trim();
81
- if (trimmed.endsWith(':*'))
82
- return new RegExp(`^${escape(trimmed.slice(0, -2))}(\\s.*)?$`, 'su');
83
- if (trimmed.endsWith(' *'))
84
- return new RegExp(`^${globSource(trimmed.slice(0, -2), true)}(\\s.*)?$`, 'su');
85
- return new RegExp(`^${globSource(trimmed, true)}$`, 'su');
121
+ if (Glob.tooLong(trimmed))
122
+ return { words: [], prefix: false, pattern: Glob.refused() };
123
+ const prefix = trimmed.endsWith(':*');
124
+ const read = shellWords(prefix ? trimmed.slice(0, -2) : trimmed, true, shell);
125
+ if (read === undefined)
126
+ return undefined;
127
+ // The command word, unless a wildcard stands in it, read as the command it names.
128
+ const words = read.words.map((word, index) => index === 0 && !/[*?]/u.test(word.text) ? canonical(word.text) : word.text);
129
+ const wildcards = words.filter(word => /[*?]/u.test(word)).length;
130
+ const trailingStar = !prefix && words.at(-1) === '*' && wildcards === 1;
131
+ const pattern = new Glob();
132
+ (trailingStar ? words.slice(0, -1) : words).forEach((word, index) => {
133
+ if (index > 0)
134
+ pattern.literal(WORD_BREAK);
135
+ for (const char of word) {
136
+ if (char === '*')
137
+ pattern.many();
138
+ else if (char === '?')
139
+ pattern.one();
140
+ else
141
+ pattern.literal(char);
142
+ }
143
+ });
144
+ if (prefix || trailingStar)
145
+ pattern.optional(rest => rest.literal(WORD_BREAK).many());
146
+ return { words, prefix, pattern };
147
+ }
148
+ /**
149
+ * Whether a command with a run-time expansion could become one the rule
150
+ * names: its static words agree with the rule's, position by position, up to
151
+ * the first expanding word or the first rule word with a wildcard. The
152
+ * expansion may be empty, so `cat secret.txt $X` could be `cat secret.txt`.
153
+ */
154
+ function couldExpandInto(rule, words, dynamicAt) {
155
+ for (let index = 0; index < dynamicAt; index++) {
156
+ const ruleWord = rule.words[index];
157
+ if (ruleWord === undefined)
158
+ return rule.prefix;
159
+ if (/[*?]/u.test(ruleWord))
160
+ return true;
161
+ if (words[index]?.text !== ruleWord)
162
+ return false;
163
+ }
164
+ return true;
165
+ }
166
+ /** The null device of bash (also Git Bash, which maps it on Windows), and of PowerShell where it is a device (not on Windows). */
167
+ const DEV_NULL = '/dev/null';
168
+ /** PowerShell's null target (https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_redirection). */
169
+ const POWERSHELL_NULL = /^\$null$/iu;
170
+ /** Windows' null device, reserved in every folder whichever shell (bash, PowerShell, cmd) names it. */
171
+ const WINDOWS_NUL = /^nul$/iu;
172
+ /** Whether a redirection target is the null device of `shell` on this platform: no file behind it. */
173
+ function nullDevice(target, shell) {
174
+ const windows = process.platform === 'win32';
175
+ if (windows && WINDOWS_NUL.test(target.text))
176
+ return true;
177
+ // Only the bare variable: quoted, `'$null'` names a file of that name.
178
+ if (shell === 'powershell')
179
+ return (!target.quoted && POWERSHELL_NULL.test(target.text)) || (!windows && target.text === DEV_NULL);
180
+ return target.text === DEV_NULL;
181
+ }
182
+ /**
183
+ * The files the redirections of one simple command of `shell` read or write;
184
+ * undefined when its words cannot be read. Here-documents, here-strings,
185
+ * descriptor copies and closes (`2>&1`, `<&3`, `>&-`) and the shell's null
186
+ * device (see `nullDevice`) name no file.
187
+ */
188
+ export function redirectFiles(command, shell) {
189
+ const read = shellWords(command, false, shell);
190
+ if (read === undefined)
191
+ return undefined;
192
+ return read.redirects.flatMap(({ operator, target }) => {
193
+ // Without its descriptor or stream (`2`, PowerShell's `*`).
194
+ const op = operator.replace(/^(?:\d+|\*)/u, '');
195
+ if (op.startsWith('<<') || nullDevice(target, shell))
196
+ return [];
197
+ if ((op === '<&' || op === '>&') && /^(?:\d+-?|-)$/u.test(target.text))
198
+ return [];
199
+ const reads = op === '<' || op === '<>' || op === '<&';
200
+ const writes = op !== '<' && op !== '<&';
201
+ return [{ path: target.text, reads, writes, plain: !target.dynamic && !target.text.startsWith('~') && !/[*?[]/u.test(target.text) }];
202
+ });
203
+ }
204
+ /**
205
+ * A redirection operator of bash (https://www.gnu.org/software/bash/manual/bash.html#Redirections),
206
+ * longest first: `&>>`/`&>` (stdout and stderr), here-strings `<<<`, here-documents `<<-`/`<<`,
207
+ * `<>` (read and write), descriptor copies `<&`/`>&`, `>>`, `>|` (despite noclobber), `<` and `>`.
208
+ */
209
+ const REDIRECT_OPERATOR = /&>>|&>|<<<|<<-|<<|<>|<&|>>|>\||>&|<|>/uy;
210
+ /**
211
+ * PowerShell's redirection operators (https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_redirection),
212
+ * after an optional stream (see {@link POWERSHELL_STREAM}): `>>`, `>&` (a merge, `2>&1`), `>`, and `<`, which
213
+ * PowerShell 7 reserves and refuses to run; read as an input redirection, it can only make a rule match more.
214
+ */
215
+ const POWERSHELL_REDIRECT_OPERATOR = />>|>&|>|</uy;
216
+ /** The streams a PowerShell redirection names: success (1) to information (6), or `*` for all. */
217
+ const POWERSHELL_STREAM = /^(?:[1-6]|\*)$/u;
218
+ /** A bash redirection's descriptor number. */
219
+ const BASH_DESCRIPTOR = /^\d+$/u;
220
+ /** The shell that reads a shell call's command: PowerShell for DSH's `pwsh` tool, bash otherwise. */
221
+ export function shellOf(tool) {
222
+ return tool.dshName === 'pwsh' ? 'powershell' : 'bash';
223
+ }
224
+ /**
225
+ * The words of a command or a rule, in one pass over the text: blanks
226
+ * separate words; single quotes, double quotes and backslashes quote and are
227
+ * removed. In a command (not a `rule`) an unquoted `#` at a word's start
228
+ * begins a comment, and a word is dynamic when it holds `$` or a backtick,
229
+ * unquoted glob, brace or parenthesis characters, or {@link WORD_BREAK}.
230
+ * An unquoted redirection, with the descriptor number before it and the
231
+ * word after it, is set apart in `redirects` (a process substitution `<(…)`
232
+ * stays a dynamic word). Undefined when a quote does not close or a
233
+ * redirection has no word.
234
+ */
235
+ function shellWords(text, rule, shell) {
236
+ const operators = shell === 'powershell' ? POWERSHELL_REDIRECT_OPERATOR : REDIRECT_OPERATOR;
237
+ const descriptors = shell === 'powershell' ? POWERSHELL_STREAM : BASH_DESCRIPTOR;
238
+ // PowerShell matches without case (https://code.claude.com/docs/en/permissions#powershell).
239
+ const fold = (word) => shell === 'powershell' ? word.toLowerCase() : word;
240
+ const words = [];
241
+ const redirects = [];
242
+ let current = '';
243
+ let started = false;
244
+ let dynamic = false;
245
+ // The current word was written with a quote or an escape: it cannot be a descriptor number.
246
+ let quoted = false;
247
+ // The operator whose target the next word is.
248
+ let pending;
249
+ const end = () => {
250
+ if (started) {
251
+ const word = { text: current, dynamic: dynamic || current.includes(WORD_BREAK), quoted };
252
+ if (pending !== undefined)
253
+ redirects.push({ operator: pending, target: word });
254
+ else
255
+ words.push({ ...word, text: fold(word.text) });
256
+ pending = undefined;
257
+ }
258
+ current = '';
259
+ started = false;
260
+ dynamic = false;
261
+ quoted = false;
262
+ };
263
+ for (let index = 0; index < text.length; index++) {
264
+ const char = text[index] ?? '';
265
+ if (char === ' ' || char === '\t' || char === '\n' || char === '\r') {
266
+ end();
267
+ continue;
268
+ }
269
+ if (char === '#' && !started && !rule)
270
+ break;
271
+ operators.lastIndex = index;
272
+ const opens = char === '<' || char === '>' || (shell === 'bash' && char === '&');
273
+ const operator = opens && text[index + 1] !== '(' ? operators.exec(text)?.[0] : undefined;
274
+ if (operator !== undefined && pending === undefined) {
275
+ // `2>` (PowerShell also `*>`) names a descriptor; any other word before the operator is a word of its own.
276
+ const descriptor = started && !quoted && descriptors.test(current) ? current : '';
277
+ if (descriptor !== '') {
278
+ // The descriptor is no word: what it set (PowerShell's `*` reads as a glob) goes with it.
279
+ current = '';
280
+ started = false;
281
+ dynamic = false;
282
+ }
283
+ else
284
+ end();
285
+ pending = descriptor + operator;
286
+ index += operator.length - 1;
287
+ continue;
288
+ }
289
+ started = true;
290
+ if (char === '\\') {
291
+ quoted = true;
292
+ const next = text[index + 1];
293
+ if (next === undefined)
294
+ dynamic = true;
295
+ // A backslash-newline joins two lines and stands for nothing.
296
+ else if (next !== '\n')
297
+ current += next;
298
+ index++;
299
+ }
300
+ else if (char === "'") {
301
+ quoted = true;
302
+ const close = text.indexOf("'", index + 1);
303
+ if (close === -1)
304
+ return undefined;
305
+ current += text.slice(index + 1, close);
306
+ index = close;
307
+ }
308
+ else if (char === '"') {
309
+ quoted = true;
310
+ let close = index + 1;
311
+ for (; close < text.length && text[close] !== '"'; close++) {
312
+ const inner = text[close] ?? '';
313
+ const next = text[close + 1] ?? '';
314
+ if (inner === '\\' && (next === '$' || next === '`' || next === '"' || next === '\\' || next === '\n')) {
315
+ if (next !== '\n')
316
+ current += next;
317
+ close++;
318
+ }
319
+ else {
320
+ if (!rule && (inner === '$' || inner === '`'))
321
+ dynamic = true;
322
+ current += inner;
323
+ }
324
+ }
325
+ if (close >= text.length)
326
+ return undefined;
327
+ index = close;
328
+ }
329
+ else {
330
+ if (!rule && '$`*?[{()'.includes(char))
331
+ dynamic = true;
332
+ current += char;
333
+ }
334
+ }
335
+ end();
336
+ return pending === undefined ? { words, redirects } : undefined;
86
337
  }
87
338
  /**
88
339
  * `domain:example.com` is that host only, `*.example.com` any subdomain at
89
340
  * any depth but not the domain itself, `*` every host; any other `*` stays
90
341
  * between two dots. Case and a trailing dot are ignored.
91
342
  */
92
- function domainMatches(domain, url) {
343
+ function domainMatches(domain, url, unknown) {
93
344
  try {
94
345
  const host = new URL(url).hostname.toLowerCase().replace(/\.$/u, '');
95
346
  const wanted = domain.trim().toLowerCase().replace(/\.$/u, '');
@@ -97,7 +348,7 @@ function domainMatches(domain, url) {
97
348
  return true;
98
349
  if (wanted.startsWith('*.'))
99
350
  return host.endsWith(wanted.slice(1));
100
- return new RegExp(`^${wanted.split('*').map(escape).join('[^.]*')}$`, 'u').test(host);
351
+ return wildcard(wanted, char => char !== '.').match(host) ?? unknown;
101
352
  }
102
353
  catch {
103
354
  return false;
@@ -105,77 +356,247 @@ function domainMatches(domain, url) {
105
356
  }
106
357
  /**
107
358
  * Whether a gitignore-style pattern, relative to the working directory,
108
- * matches a path (skill `paths`, `Read(...)`/`Edit(...)` rules).
359
+ * matches a path as spelled (skill `paths`): no link is followed.
109
360
  */
110
361
  export function pathPatternMatches(pattern, path, cwd) {
111
- return pathRuleMatches(pattern, path, cwd);
362
+ return pathRuleMatches(pattern, path, cwd, false, {}, spelled);
112
363
  }
113
- /** Gitignore-style path rule, relative to the working directory. */
114
- function pathRuleMatches(specifier, path, cwd) {
115
- const windows = process.platform === 'win32';
116
- const normalize = (value) => {
117
- const posix = value.replace(/\\/gu, '/');
118
- return windows ? posix.toLowerCase() : posix;
364
+ /** A path as spelled. */
365
+ const spelled = (path) => path;
366
+ const SYSTEM = {
367
+ get platform() { return process.platform; },
368
+ lstat: lstatSync,
369
+ readlink: readlinkSync,
370
+ realpath: path => realpathSync.native(path),
371
+ };
372
+ /**
373
+ * The real path of an absolute path, or undefined when it cannot be known (a
374
+ * link loop, more than {@link SYMLINK_HOPS} links, a link or folder that
375
+ * cannot be read, or, on Windows, a path or link that leads to a network share
376
+ * or device `base` is not on). What exists is resolved by the system; a part
377
+ * that does not exist yet is followed link by link (`readlink`), so a dangling
378
+ * link leads where a write through it would create its file. The one resolver
379
+ * file rules and redirection targets use; nothing else follows links.
380
+ *
381
+ * On Windows, opening, resolving or reading a link on `\\server\share` makes
382
+ * the system connect to that server and sign in with the person's credentials,
383
+ * and `realpath` follows links by itself. So before any call that could follow
384
+ * one, `linksReachNewShare` walks the path with `lstat` and `readlink` only;
385
+ * realpath runs only for a path that stays local (it is what expands a short
386
+ * name such as `RUNNER~1`).
387
+ * @param base - the working directory: a share it is on is not new.
388
+ */
389
+ export function realPathOf(path, base, system = SYSTEM) {
390
+ return resolveReal(path, base, system, { hops: 0 });
391
+ }
392
+ function resolveReal(path, base, system, followed) {
393
+ if (linksReachNewShare(path, base, system.platform, system))
394
+ return undefined;
395
+ const paths = system.platform === 'win32' ? win32 : posix;
396
+ try {
397
+ return system.realpath(path);
398
+ }
399
+ catch (error) {
400
+ // Only a missing part is followed by hand; a loop or an unreadable folder stays unknown.
401
+ if (error.code !== 'ENOENT')
402
+ return undefined;
403
+ }
404
+ const parent = paths.dirname(path);
405
+ if (parent === path)
406
+ return undefined;
407
+ const folder = resolveReal(parent, base, system, followed);
408
+ if (folder === undefined)
409
+ return undefined;
410
+ const candidate = paths.join(folder, paths.basename(path));
411
+ try {
412
+ if (!system.lstat(candidate).isSymbolicLink())
413
+ return undefined;
414
+ }
415
+ catch (error) {
416
+ // Nothing there: a write creates the file here.
417
+ return error.code === 'ENOENT' ? candidate : undefined;
418
+ }
419
+ if (++followed.hops > SYMLINK_HOPS)
420
+ return undefined;
421
+ let target;
422
+ try {
423
+ target = system.readlink(candidate);
424
+ }
425
+ catch {
426
+ return undefined;
427
+ }
428
+ return resolveReal(paths.resolve(folder, target), base, system, followed);
429
+ }
430
+ /**
431
+ * A `Read(...)`/`Edit(...)` rule, checked on the path as spelled and on its
432
+ * real path (anchors resolved the same way), or on the one `use.path` names:
433
+ * a restricting answer (`unknown` true: deny, ask, a hook's `if`) matches
434
+ * when either does, so a link cannot hide a denied file; an approving one
435
+ * (allow) only when both do, so a link inside an allowed folder cannot reach
436
+ * a file outside it (`ruleVerdict` lets two allow rules cover the two paths).
437
+ */
438
+ function fileRuleMatches(specifier, path, cwd, unknown, use) {
439
+ const real = (absolute) => realPathOf(absolute, cwd);
440
+ if (use.path !== undefined)
441
+ return pathRuleMatches(specifier, path, cwd, unknown, use, use.path === 'real' ? real : spelled);
442
+ const asSpelled = pathRuleMatches(specifier, path, cwd, unknown, use, spelled);
443
+ if (asSpelled === unknown)
444
+ return asSpelled;
445
+ // A path whose real form cannot be known matches a restricting rule and no approving one.
446
+ return pathRuleMatches(specifier, path, cwd, unknown, use, real);
447
+ }
448
+ /**
449
+ * A file rule, anchored as Claude Code anchors it
450
+ * (https://code.claude.com/docs/en/permissions#how-path-patterns-match):
451
+ * `//path` at the filesystem root, `~/path` at the home directory, `/path` at
452
+ * `root` (the directory of the settings source; the working directory when
453
+ * there is none), `path` and `./path` at the working directory. A rule
454
+ * matches only files under its anchor. The docs apply gitignore semantics
455
+ * (https://code.claude.com/docs/en/permissions#how-deep-a-pattern-matches):
456
+ * a bare pattern without a `/` ("bare filenames ... match at any depth")
457
+ * matches at any depth below its anchor, and so does a bare single-directory
458
+ * `dir/**` in a deny or ask rule (`restricts`); any other slash anchors, the
459
+ * leading one of `./x` too (https://git-scm.com/docs/gitignore#_pattern_format:
460
+ * a separator at the beginning or middle makes the pattern relative to its
461
+ * base), so `./x` is `<cwd>/x` only. In a deny or ask rule a pattern that
462
+ * matches a directory also matches everything in it, as in gitignore.
463
+ */
464
+ function pathRuleMatches(specifier, path, cwd, unknown, { root, restricts = false }, locate) {
465
+ const located = locate(isAbsolute(path) ? resolve(path) : resolve(cwd, path));
466
+ // Where a path or an anchor cannot be known, the answer is `unknown`: a restricting rule matches, an approving one does not.
467
+ if (located === undefined)
468
+ return unknown;
469
+ const target = rulePath(located);
470
+ let unresolved = false;
471
+ const anchor = (directory) => {
472
+ const real = locate(resolve(directory));
473
+ if (real === undefined)
474
+ unresolved = true;
475
+ return rulePath(real ?? directory);
119
476
  };
120
- const target = isAbsolute(path) ? resolve(path) : resolve(cwd, path);
121
477
  let pattern = specifier.trim();
122
- let base = cwd;
478
+ let base;
479
+ // A bare relative pattern (no leading `./`, `/`, `~/` or `//`): the only form that may match below its anchor.
480
+ let bare = false;
123
481
  if (pattern.startsWith('//')) {
124
- pattern = pattern.slice(1);
125
- base = '';
482
+ base = '/';
483
+ pattern = pattern.slice(2);
126
484
  }
127
485
  else if (pattern.startsWith('~/')) {
128
- base = homedir();
486
+ base = anchor(homedir());
129
487
  pattern = pattern.slice(2);
130
488
  }
489
+ else if (pattern.startsWith('/')) {
490
+ base = anchor(root ?? cwd);
491
+ pattern = pattern.slice(1);
492
+ }
131
493
  else if (pattern.startsWith('./')) {
494
+ // `./x` contains a slash, so gitignore anchors it: `<cwd>/x` only, never `<cwd>/sub/x`.
495
+ base = anchor(cwd);
132
496
  pattern = pattern.slice(2);
133
497
  }
134
- else if (pattern.startsWith('/') && !windows) {
135
- pattern = pattern.slice(1);
498
+ else {
499
+ base = anchor(cwd);
500
+ bare = true;
136
501
  }
137
- const anchored = pattern.replace(/\/$/u, '').includes('/');
138
- if (base === '')
139
- return globRegex(normalize(pattern), false).test(normalize(target));
140
- const rel = normalize(relative(base, target));
141
- if (!anchored) {
142
- const name = rel.split('/').at(-1) ?? rel;
143
- return globRegex(normalize(pattern), false).test(name) || globRegex(`**/${normalize(pattern)}`, false).test(rel);
502
+ if (process.platform === 'win32')
503
+ pattern = pattern.toLowerCase();
504
+ pattern = pattern.replace(/\/+$/u, '');
505
+ // An anchored rule's literal folders (before the last part or the first wildcard) are resolved as the path is, so
506
+ // `//etc/hosts` also covers macOS's `/private/etc/hosts`, and a Windows short name its long one.
507
+ if (!bare && locate !== spelled) {
508
+ const parts = pattern.split('/');
509
+ const literal = parts.findIndex(part => /[*?[]/u.test(part));
510
+ const folders = Math.min(literal === -1 ? parts.length - 1 : literal, parts.length - 1);
511
+ const prefix = nativePath(`${base.endsWith('/') ? base : `${base}/`}${parts.slice(0, folders).join('/')}`);
512
+ // A rule's folders on a share stay as written: nothing local resolves onto one (such a path is unknown), and
513
+ // resolving them would connect to it.
514
+ if (folders > 0 && !reachesNewShare(prefix, cwd)) {
515
+ const real = locate(prefix);
516
+ if (real === undefined)
517
+ unresolved = true;
518
+ else {
519
+ base = rulePath(real);
520
+ pattern = parts.slice(folders).join('/');
521
+ }
522
+ }
144
523
  }
145
- return globRegex(normalize(pattern), false).test(rel);
524
+ if (unresolved)
525
+ return unknown;
526
+ const rel = below(base, target);
527
+ if (rel === undefined)
528
+ return false;
529
+ const anyDepth = bare && (!pattern.includes('/') || (restricts && /^[^/]+\/\*\*$/u.test(pattern)));
530
+ const compiled = glob(anyDepth ? `**/${pattern}` : pattern, false);
531
+ // The path and, for a deny or ask rule, each directory above it.
532
+ const candidates = restricts ? [...[...rel.matchAll(/\//gu)].map(slash => rel.slice(0, slash.index)), rel] : [rel];
533
+ return candidates.some(candidate => compiled.match(candidate) ?? unknown);
534
+ }
535
+ /** A path in the form rules match (on Windows see `windowsRulePath`). */
536
+ function rulePath(path) {
537
+ return process.platform === 'win32' ? windowsRulePath(path) : path;
146
538
  }
147
- function globRegex(pattern, shell) {
148
- return new RegExp(`^${globSource(pattern, shell)}$`, 'su');
539
+ /** A path in rule form back to one the system resolves (on Windows see `windowsNativePath`). */
540
+ function nativePath(path) {
541
+ return process.platform === 'win32' ? windowsNativePath(path) : path;
149
542
  }
150
- /** Glob → regex source. In shell rules `*` spans anything; in path rules it stays within a segment. */
151
- function globSource(pattern, shell) {
152
- let source = '';
153
- for (let index = 0; index < pattern.length; index++) {
154
- const char = pattern[index] ?? '';
543
+ /** Windows' long-path prefixes: `\\?\UNC\server\share` and `\\?\C:\…`. */
544
+ const WINDOWS_LONG_UNC = /^\\\\\?\\UNC\\/iu;
545
+ const WINDOWS_LONG = /^\\\\\?\\/u;
546
+ /**
547
+ * A Windows path in the form rules match, as Claude Code writes them
548
+ * (https://code.claude.com/docs/en/permissions#where-a-pattern-anchors: "`C:\Users\alice` becomes `/c/Users/alice`"):
549
+ * either separator becomes `/`, the long-path prefix goes, a drive `C:` becomes `/c` and a share `\\server` stays
550
+ * `//server`. The whole path is compared without case, as Windows' file systems compare names by default, so the
551
+ * rule, the working directory and every path, spelled or real, go through this one function.
552
+ */
553
+ export function windowsRulePath(path) {
554
+ return path.replace(WINDOWS_LONG_UNC, '\\\\').replace(WINDOWS_LONG, '').replace(/\\/gu, '/').toLowerCase().replace(/^([a-z]):/u, '/$1');
555
+ }
556
+ /** A rule-form Windows path (`/c/users/x`, `//server/share/x`) as Windows names it (`c:\users\x`). */
557
+ export function windowsNativePath(path) {
558
+ const drive = /^\/([a-z])(?:\/(.*))?$/u.exec(path);
559
+ if (drive !== null)
560
+ return `${drive[1] ?? ''}:\\${(drive[2] ?? '').replace(/\//gu, '\\')}`;
561
+ return path.replace(/\//gu, '\\');
562
+ }
563
+ /** `target` relative to `base` (both from `rulePath`), or undefined when it lies outside. */
564
+ function below(base, target) {
565
+ if (target === base)
566
+ return '';
567
+ const prefix = base.endsWith('/') ? base : `${base}/`;
568
+ return target.startsWith(prefix) ? target.slice(prefix.length) : undefined;
569
+ }
570
+ /** A glob. In shell rules `*` spans anything; in path rules it stays within a segment. */
571
+ function glob(pattern, shell) {
572
+ if (Glob.tooLong(pattern))
573
+ return Glob.refused();
574
+ const segment = (char) => shell || char !== '/';
575
+ const result = new Glob();
576
+ const chars = [...pattern];
577
+ for (let index = 0; index < chars.length; index++) {
578
+ const char = chars[index] ?? '';
155
579
  if (char === '*') {
156
- if (pattern[index + 1] === '*') {
580
+ if (chars[index + 1] === '*') {
157
581
  index++;
158
- if (pattern[index + 1] === '/') {
582
+ if (chars[index + 1] === '/') {
159
583
  index++;
160
- source += '(?:.*/)?';
584
+ result.optional(dirs => dirs.many().literal('/'));
161
585
  }
162
586
  else {
163
- source += '.*';
587
+ result.many();
164
588
  }
165
589
  }
166
590
  else {
167
- source += shell ? '.*' : '[^/]*';
591
+ result.many(segment);
168
592
  }
169
593
  }
170
594
  else if (char === '?') {
171
- source += shell ? '.' : '[^/]';
595
+ result.one(segment);
172
596
  }
173
597
  else {
174
- source += escape(char);
598
+ result.literal(char);
175
599
  }
176
600
  }
177
- return source;
178
- }
179
- function escape(text) {
180
- return text.replace(/[.+^${}()|[\]\\]/gu, '\\$&');
601
+ return result;
181
602
  }