@alexwkleung/reika 0.2.0 → 0.4.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.
@@ -1269,6 +1269,7 @@ export async function runTurn(opts) {
1269
1269
  return await runTypecheck(opts.bundle.cwd, {
1270
1270
  signal: opts.signal,
1271
1271
  tsconfigPath: typecheckTsconfig,
1272
+ sandbox: opts.config.sandbox,
1272
1273
  });
1273
1274
  }
1274
1275
  finally {
@@ -3,6 +3,7 @@ import { createHash } from 'node:crypto';
3
3
  import { stat } from 'node:fs/promises';
4
4
  import { tmpdir } from 'node:os';
5
5
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
6
+ import { SANDBOX_EXEC_ERROR_PREFIX, sandboxArgv, sandboxPlan } from '../tools/_sandbox.js';
6
7
  const DEFAULT_TIMEOUT_MS = 30_000;
7
8
  // One tsc cascade can be hundreds of lines; a 16k-window model can't absorb that. Cap what the
8
9
  // model sees and tell it how many were elided rather than truncating silently.
@@ -156,7 +157,8 @@ export async function runTypecheck(cwd, opts = {}) {
156
157
  const buildInfo = opts.tsBuildInfoFile ?? defaultBuildInfoFile(cwd);
157
158
  // `--incremental` with an explicit `--tsBuildInfoFile` is what makes the re-check cheap and is
158
159
  // accepted alongside `--noEmit` across TS versions. `--pretty false` forces the stable
159
- // one-line-per-diagnostic format regardless of TTY, which DIAG_RE parses.
160
+ // one-line-per-diagnostic format regardless of TTY, which DIAG_RE parses. One list, used by both
161
+ // spawns below, so the confined and unconfined runs cannot drift apart.
160
162
  const args = [
161
163
  '--noEmit',
162
164
  '--incremental',
@@ -167,34 +169,124 @@ export async function runTypecheck(cwd, opts = {}) {
167
169
  '-p',
168
170
  tsconfig,
169
171
  ];
170
- return runTscProcess(tsc, args, cwd, opts.timeoutMs ?? DEFAULT_TIMEOUT_MS, opts.signal);
172
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
173
+ // Route the project-local `tsc` through the sandbox wrapper so it runs inside confinement — the
174
+ // same profile model-run bash gets (writes confined to cwd, temp and cache dirs, network denied;
175
+ // the temp allow is what lets `--tsBuildInfoFile` land in os.tmpdir()). The wrapper takes a shell
176
+ // command, so the binary has to be part of the line and both it and every argument must be
177
+ // quoted: a bare flag list would be run *as* the command (`/bin/sh -c "--noEmit …"` is an
178
+ // invalid option, exit 2), and tsc would never start — indistinguishable from a clean check, and
179
+ // so a silently dead gate. When the sandbox is unavailable, fall back to the direct spawn
180
+ // (fail-open), which is the gate's standing design.
181
+ //
182
+ // Once a plan exists there is no unconfined retry, even when the wrapper looks like it refused:
183
+ // that verdict is read off the output of the process we just ran, and a planted tsc can print the
184
+ // wrapper's line and exit 65 as easily as sandbox-exec can. A retry would hand it exactly the
185
+ // unconfined run this exists to prevent, so a refusal disables the gate for the turn instead.
186
+ if (opts.sandbox !== false) {
187
+ const plan = sandboxPlan(cwd, { network: false });
188
+ if ('args' in plan) {
189
+ const argv = sandboxArgv(plan, [tsc, ...args].map(shellQuote).join(' '));
190
+ if (argv)
191
+ return runTscProcess(argv.cmd, argv.args, cwd, timeoutMs, opts.signal, true);
192
+ }
193
+ }
194
+ return runTscProcess(tsc, args, cwd, timeoutMs, opts.signal);
195
+ }
196
+ // Whether the sandbox wrapper itself refused to run the command: nonzero exit, the wrapper's own
197
+ // line in the output, and nothing that parses as a diagnostic (so a tsc that really ran — even one
198
+ // whose errors the DIAG_RE cannot parse — is never mistaken for a refusal). A profile the OS
199
+ // rejects, or a param without its `-D` binding, exits 65 having run nothing; `sandboxPlan` probes
200
+ // the real argv for that before tsc runs (#738), so this is the backstop. Undetected, the empty
201
+ // output parses to zero diagnostics and masquerades as a green check. Any nonzero exit in this shape
202
+ // counts rather than bash.ts's exit-65 pin: an apply failure (71) leaves the same nothing-ran
203
+ // signature, and the prefix is required there too. Spoofable by the process inside, which is why a
204
+ // refusal only ever resolves "didn't run" and never buys a retry: the worst a fake one can do is
205
+ // switch the gate off for a turn.
206
+ export function sandboxRefused(code, out) {
207
+ return (code !== null &&
208
+ code !== 0 &&
209
+ out.includes(SANDBOX_EXEC_ERROR_PREFIX) &&
210
+ parseTscOutput(out).length === 0);
171
211
  }
172
- function runTscProcess(bin, args, cwd, timeoutMs, signal) {
212
+ // Single-quote one argument for the `/bin/sh -c` line `sandboxArgv` builds. Every path interpolated
213
+ // into that line is user-controlled — a cwd, tsconfig, or tsbuildinfo path may contain spaces or
214
+ // quotes — so concatenating bare would split one argument into several or let a quote re-parse the
215
+ // rest. `'\''` is the only way to carry a single quote inside a single-quoted string. Exported for
216
+ // tests: the quoting is the security boundary here, and a round-trip through a real /bin/sh is the
217
+ // only proof it holds.
218
+ export function shellQuote(arg) {
219
+ return `'${arg.replace(/'/g, "'\\''")}'`;
220
+ }
221
+ // What `/bin/sh` exits with when it could not run the command it was given: 126 found but not
222
+ // executable (a lost exec bit), 127 not found (a shebang interpreter missing from PATH). The direct
223
+ // spawn reports both as a spawn error; behind the wrapper they are ordinary exits with no tsc
224
+ // output, which would otherwise parse as zero diagnostics — a clean check from a tsc that never ran.
225
+ const SHELL_COULD_NOT_RUN = new Set([126, 127]);
226
+ // The wrapper is `sandbox-exec` → `/bin/sh` → tsc, so a kill aimed at the child pid can stop short
227
+ // of tsc (a shim that runs node without exec). Each spawn gets its own process group and every
228
+ // kill goes to the group, as bash.ts does (#408); the exit sweep covers a reika exit mid-check,
229
+ // since a group of its own is one the terminal's hangup no longer reaches.
230
+ const liveGroups = new Set();
231
+ process.once('exit', () => {
232
+ for (const pid of liveGroups) {
233
+ try {
234
+ process.kill(-pid, 'SIGKILL');
235
+ }
236
+ catch {
237
+ // Already gone.
238
+ }
239
+ }
240
+ });
241
+ // Exported for tests: the refusal branch is this gate's fail-open boundary — the case that used to
242
+ // resolve as a green check — and a real sandbox-exec refusing to load a profile is the only
243
+ // faithful way to drive it.
244
+ export function runTscProcess(bin, args, cwd, timeoutMs, signal, viaSandboxWrapper = false) {
173
245
  return new Promise(resolve => {
174
246
  let child;
175
247
  try {
176
- child = spawn(bin, args, { cwd });
248
+ child = spawn(bin, args, { cwd, detached: process.platform !== 'win32' });
177
249
  }
178
250
  catch (e) {
179
251
  resolve({ ran: false, reason: `spawn failed: ${e.message}` });
180
252
  return;
181
253
  }
254
+ const pid = child.pid;
255
+ if (pid != null && process.platform !== 'win32')
256
+ liveGroups.add(pid);
257
+ const killTree = () => {
258
+ try {
259
+ if (pid == null || process.platform === 'win32')
260
+ throw new Error('no group');
261
+ process.kill(-pid, 'SIGKILL');
262
+ }
263
+ catch {
264
+ try {
265
+ child.kill('SIGKILL');
266
+ }
267
+ catch {
268
+ // Already gone.
269
+ }
270
+ }
271
+ };
182
272
  let out = '';
183
273
  let settled = false;
184
274
  const finish = (r) => {
185
275
  if (settled)
186
276
  return;
187
277
  settled = true;
278
+ if (pid != null)
279
+ liveGroups.delete(pid);
188
280
  clearTimeout(timer);
189
281
  signal?.removeEventListener('abort', onAbort);
190
282
  resolve(r);
191
283
  };
192
284
  const timer = setTimeout(() => {
193
- child.kill('SIGKILL');
285
+ killTree();
194
286
  finish({ ran: false, reason: `timed out after ${timeoutMs}ms` });
195
287
  }, timeoutMs);
196
288
  const onAbort = () => {
197
- child.kill('SIGKILL');
289
+ killTree();
198
290
  finish({ ran: false, reason: 'aborted' });
199
291
  };
200
292
  signal?.addEventListener('abort', onAbort, { once: true });
@@ -203,6 +295,22 @@ function runTscProcess(bin, args, cwd, timeoutMs, signal) {
203
295
  child.stdout?.on('data', d => (out += d.toString()));
204
296
  child.stderr?.on('data', d => (out += d.toString()));
205
297
  child.on('error', e => finish({ ran: false, reason: `process error: ${e.message}` }));
206
- child.on('close', () => finish({ ran: true, diagnostics: parseTscOutput(out) }));
298
+ child.on('close', code => {
299
+ // Only the wrapper spawn gets refusal semantics: a nonzero exit there with the wrapper's own
300
+ // line and no tsc output means the command never ran — read as a clean check, that outcome is
301
+ // the silently-dead gate (see sandboxRefused above).
302
+ if (viaSandboxWrapper && sandboxRefused(code, out)) {
303
+ finish({ ran: false, reason: `sandbox wrapper refused to run tsc (exit ${code})` });
304
+ return;
305
+ }
306
+ if (viaSandboxWrapper &&
307
+ code !== null &&
308
+ SHELL_COULD_NOT_RUN.has(code) &&
309
+ parseTscOutput(out).length === 0) {
310
+ finish({ ran: false, reason: `shell could not run tsc (exit ${code})` });
311
+ return;
312
+ }
313
+ finish({ ran: true, diagnostics: parseTscOutput(out) });
314
+ });
207
315
  });
208
316
  }
package/dist/cli.js CHANGED
@@ -3,6 +3,9 @@ import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { sweepStaleSpills } from './tools/_spill.js';
4
4
  import { USAGE, parseHeadlessArgs } from './headlessargs.js';
5
5
  import { VERSION } from './version.js';
6
+ // Lowercase like the command: ps/top/Activity Monitor otherwise list every session as `node`, and
7
+ // pgrep/pkill match case-sensitively.
8
+ process.title = 'reika';
6
9
  // Spill directories are removed on a normal exit, but SIGHUP (closing the terminal window),
7
10
  // SIGTERM, SIGKILL and hard crashes never reach that handler (#224). The sweep is the cleanup
8
11
  // path for those, and it belongs here rather than in a React effect: it is a property of the
package/dist/config.js CHANGED
@@ -28,7 +28,8 @@ export function isDeniedFromProjectEnv(key) {
28
28
  export function applyProjectEnv(text, env) {
29
29
  const ignored = [];
30
30
  for (const [key, value] of Object.entries(dotenv.parse(text))) {
31
- if (!key.startsWith('REIKA_') || key in env)
31
+ // An empty line sets nothing, but would still claim the key ahead of ~/.config/reika/.env.
32
+ if (!key.startsWith('REIKA_') || key in env || value.trim() === '')
32
33
  continue;
33
34
  if (isDeniedFromProjectEnv(key))
34
35
  ignored.push(key);
@@ -116,7 +117,7 @@ export function loadConfig() {
116
117
  // A termination backstop for the spiral shapes the loop detectors miss, not a cost cap: a
117
118
  // cached round is nearly free on both local and API, so it is sized where a healthy complex
118
119
  // turn never lands and a spiral in headless (no ctrl-c) still ends in hours, not days.
119
- maxTurns: parseInt(process.env.REIKA_MAX_TURNS ?? '200', 10),
120
+ maxTurns: parseInt(process.env.REIKA_MAX_TURNS ?? '400', 10),
120
121
  repoMapBudget: parseIntOrUndef(process.env.REIKA_REPO_MAP_BUDGET),
121
122
  autoApprove: parseAutoApprove(process.env.REIKA_AUTO_APPROVE),
122
123
  autoApproveExplicit: (process.env.REIKA_AUTO_APPROVE ?? '').trim() !== '',
@@ -125,7 +126,7 @@ export function loadConfig() {
125
126
  subagentBaseURL: emptyToUndefined(process.env.REIKA_SUBAGENT_BASE_URL),
126
127
  subagentApiKey: emptyToUndefined(process.env.REIKA_SUBAGENT_API_KEY),
127
128
  // Not a backstop: the last round IS the report round (#340), so this stays tight.
128
- subagentMaxTurns: parseInt(process.env.REIKA_SUBAGENT_MAX_TURNS ?? '8', 10),
129
+ subagentMaxTurns: parseInt(process.env.REIKA_SUBAGENT_MAX_TURNS ?? '10', 10),
129
130
  visionModel: emptyToUndefined(process.env.REIKA_VISION_MODEL),
130
131
  visionBaseURL,
131
132
  visionApiKey: emptyToUndefined(process.env.REIKA_VISION_API_KEY),
package/dist/headless.js CHANGED
@@ -54,6 +54,28 @@ export async function buildHeadlessInput(prompt, config, bundle, mode) {
54
54
  }
55
55
  return { modelText, notices };
56
56
  }
57
+ // `--profile` is the user naming the profile outright, so it outranks a launch REIKA_MODEL and the
58
+ // mode's own model alike (#710). Matched case-insensitively like /model; a name no profile defines
59
+ // keeps the run going on the profile it would have used anyway, and says so — passed through raw,
60
+ // it reached the session as a profile nothing defines and lost the default's probed window.
61
+ export function headlessProfile(config, mode, named) {
62
+ const fallback = startProfiles(config, mode, {}).profile;
63
+ if (named === undefined)
64
+ return { profile: fallback };
65
+ const key = named.toLowerCase();
66
+ if (config.profiles[key])
67
+ return { profile: key };
68
+ const known = Object.keys(config.profiles).join(', ');
69
+ return {
70
+ profile: fallback,
71
+ notice: `no profile named "${named}" (defined: ${known}); using "${fallback}"`,
72
+ };
73
+ }
74
+ // Names the route the turn was on, since with --profile it may not be the default one. Not worded
75
+ // as a fetch failure: an abort, a 400 or a tool throw lands here too.
76
+ export function formatTurnFailure(profile, baseURL, message) {
77
+ return `reika: turn failed (profile "${profile}" at ${baseURL}): ${message}`;
78
+ }
57
79
  export async function runHeadless(args, io) {
58
80
  const prompt = (args.prompt ?? (await io.readStdin())).trim();
59
81
  if (!prompt) {
@@ -67,7 +89,10 @@ export async function runHeadless(args, io) {
67
89
  // with its own model in REIKA_MODE_MODELS runs that one, `--mode` or not. Headless has no /model
68
90
  // and no saved state — its env is the whole answer — so an empty state is the whole of #365 here.
69
91
  const mode = args.mode ?? resolveDefaultMode();
70
- const profile = startProfiles(loaded, mode, {}).profile;
92
+ const chosen = headlessProfile(loaded, mode, args.profile);
93
+ if (chosen.notice)
94
+ io.stderr(`reika: ${chosen.notice}\n`);
95
+ const profile = chosen.profile;
71
96
  const stream = args.stream ? createStreamPrinter(io, args.json) : null;
72
97
  const session = await createSession({
73
98
  cwd: process.cwd(),
@@ -181,7 +206,7 @@ export async function runHeadless(args, io) {
181
206
  }
182
207
  if (failed) {
183
208
  debugLog(`headless: turn failed: ${failed.message}`);
184
- io.stderr(`reika: ${failed.message}\n`);
209
+ io.stderr(`${formatTurnFailure(profile, config.baseURL, failed.message)}\n`);
185
210
  return controller.signal.aborted ? 130 : 1;
186
211
  }
187
212
  if (args.json && !args.stream) {
@@ -2,6 +2,7 @@ export const USAGE = `usage: reika start the interactive TUI in
2
2
  reika -p [prompt] ... run one turn without the TUI and print the reply
3
3
 
4
4
  -p, --prompt [text] run one turn headless; reads stdin when no text is given
5
+ --profile <name> with -p: use this profile (outranks REIKA_MODEL and REIKA_MODE_MODELS)
5
6
  --mode <mode> agent | plan | vibe | minimal | grind | chat (default: REIKA_DEFAULT_MODE, else agent)
6
7
  --json print the turn's messages as a JSON array instead of the reply text
7
8
  --stream print as the turn runs: the reply as it is generated, tool calls on
@@ -47,6 +48,13 @@ export function parseHeadlessArgs(argv) {
47
48
  }
48
49
  args.mode = value;
49
50
  }
51
+ else if (a === '--profile') {
52
+ // A flag-shaped value is a missing name: taking it would swallow the -p or --json after it.
53
+ const value = argv[++i];
54
+ if (!value || value.startsWith('-'))
55
+ throw new Error('--profile needs a profile name');
56
+ args.profile = value;
57
+ }
50
58
  else if (a === '--json') {
51
59
  args.json = true;
52
60
  }
@@ -82,5 +90,9 @@ export function parseHeadlessArgs(argv) {
82
90
  throw new Error(`unexpected argument ${a}\n${USAGE}`);
83
91
  }
84
92
  }
93
+ // The TUI does not read it, so starting one would drop the flag without a word.
94
+ if (!headless && args.profile !== undefined) {
95
+ throw new Error(`--profile applies to a headless run; add -p\n${USAGE}`);
96
+ }
85
97
  return headless ? args : null;
86
98
  }
@@ -119,6 +119,31 @@ export async function loadModelCatalog(path = MODEL_CATALOG_CACHE_PATH) {
119
119
  }
120
120
  return fetchCatalog(path);
121
121
  }
122
+ // Catalog bases on the same host as `baseURL`, other than itself. A provider that moves its API
123
+ // path (models.dev's opencode-go went from /zen/go/v1 to /inference/go/v1) leaves a profile on the
124
+ // old base with no entry, and the new base is what the user needs to see. Named, never used: two
125
+ // bases on one host can be two products, so picking one would be a guess.
126
+ export function sameHostBases(index, baseURL) {
127
+ let host;
128
+ try {
129
+ host = new URL(baseURL).host.toLowerCase();
130
+ }
131
+ catch {
132
+ return [];
133
+ }
134
+ const own = normalizeApiBase(baseURL);
135
+ return Object.keys(index)
136
+ .filter(base => base !== own && hostOf(base) === host)
137
+ .sort();
138
+ }
139
+ function hostOf(base) {
140
+ try {
141
+ return new URL(base).host.toLowerCase();
142
+ }
143
+ catch {
144
+ return undefined;
145
+ }
146
+ }
122
147
  // What startup and a /model switch need to ask about. An explicit window still leaves the output
123
148
  // limit open — the case the catalog exists for — but only a catalog-eligible host can answer it,
124
149
  // so a local server with REIKA_CONTEXT_WINDOW set sees no request at all.
@@ -143,6 +168,12 @@ export async function probeModelLimits(profile, catalog = loadModelCatalog) {
143
168
  return probe;
144
169
  const index = await catalog();
145
170
  const found = index && lookupModelLimits(index, profile.baseURL, profile.model);
171
+ if (index && wantWindow && !found?.window) {
172
+ probe.catalogMiss = {
173
+ baseListed: index[normalizeApiBase(profile.baseURL)] !== undefined,
174
+ sameHost: sameHostBases(index, profile.baseURL),
175
+ };
176
+ }
146
177
  if (!found)
147
178
  return probe;
148
179
  if (wantWindow && found.window) {
package/dist/session.js CHANGED
@@ -95,7 +95,7 @@ export async function createSession(opts) {
95
95
  changed();
96
96
  notices.push({ role: 'system', content: notice });
97
97
  }
98
- const warn = noWindowNotice(probe, before);
98
+ const warn = noWindowNotice(probe, before, name);
99
99
  if (warn)
100
100
  notices.push({ role: 'system', content: warn, tone: 'warn' });
101
101
  return notices;
@@ -286,7 +286,7 @@ export async function createSession(opts) {
286
286
  offline,
287
287
  searchNotice: offline ? undefined : searchPrecedenceNotice(chooseSearchBackend(cfg)),
288
288
  limitsNotice: probed && probedLimitsNotice(probed),
289
- windowNotice: probed && noWindowNotice(probed, startProfile),
289
+ windowNotice: probed && noWindowNotice(probed, startProfile, profile),
290
290
  mcp,
291
291
  // Config errors come first: they explain a server that never even started.
292
292
  mcpNotices: [...(cfg.mcpErrors ?? []), ...mcp.notices],
@@ -361,12 +361,28 @@ export function probedLimitsNotice(probe) {
361
361
  }
362
362
  // A server that answered without a window (Ollama, a router the catalog does not list) leaves the
363
363
  // session with no compaction and per-round payload aging, and nothing on screen would say why.
364
- // Not while the probe is unreached: the retry at the next submit may still find one.
365
- export function noWindowNotice(probe, before) {
364
+ // Not while the probe is unreached: the retry at the next submit may still find one. A hosted
365
+ // endpoint gets the catalog's side of it too: a provider that moved its URL on models.dev reads
366
+ // as "no window" with nothing pointing at the move, and the keys named are this profile's own.
367
+ export function noWindowNotice(probe, before, name = 'default') {
366
368
  if (before.contextWindow != null || !probe.reached || probe.window)
367
369
  return undefined;
368
- return [
369
- `No context window known for ${before.model}, so there is no compaction and older tool output`,
370
- "is dropped from every request. Set REIKA_CONTEXT_WINDOW to the server's context size.",
371
- ].join(' ');
370
+ const lead = `No context window known for ${before.model}, so there is no compaction and older tool output is dropped from every request.`;
371
+ const miss = probe.catalogMiss;
372
+ if (!miss) {
373
+ return `${lead} Set REIKA_CONTEXT_WINDOW to the server's context size.`;
374
+ }
375
+ const group = before.group ?? name;
376
+ const prefix = group === 'default' ? 'REIKA' : `REIKA_${group.toUpperCase()}`;
377
+ const parts = [
378
+ lead,
379
+ miss.baseListed
380
+ ? `models.dev lists ${before.baseURL} but not ${before.model} under it.`
381
+ : `models.dev has no entry for ${before.baseURL}.`,
382
+ ];
383
+ if (!miss.baseListed && miss.sameHost.length > 0) {
384
+ parts.push(`It lists this host at ${miss.sameHost.join(', ')} — if the provider moved, update ${prefix}_BASE_URL.`);
385
+ }
386
+ parts.push(`Or set ${prefix}_CONTEXT_WINDOW to the model's context size.`);
387
+ return parts.join(' ');
372
388
  }
@@ -1,6 +1,7 @@
1
- import { realpathSync } from 'node:fs';
1
+ import { lstatSync, readlinkSync, realpathSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
- import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
+ import { execFileSync } from 'node:child_process';
4
5
  // Resolve a model-supplied path against cwd. Models routinely emit `~/...`
5
6
  // paths, which node's resolve() treats as a literal directory named "~".
6
7
  export function resolveUserPath(cwd, path) {
@@ -66,3 +67,105 @@ export function escapesProject(cwd, full) {
66
67
  // No path in the text: the modal prints the subject directly above it, and repeating it there only
67
68
  // pushed the line past the dialog width and wrapped it.
68
69
  export const OUTSIDE_PROJECT_WARNING = 'Writes outside the project directory';
70
+ // The approval warning for a write that lands in git's metadata. Same shape and mechanism as
71
+ // `OUTSIDE_PROJECT_WARNING`: under `safe` the warning pierces auto-approve and the user sees a
72
+ // modal; under `bypass` (no `requestApproval`) the write is refused outright. The sandbox half of
73
+ // this class refuses the same paths for every sandboxed command (#706); here a deliberately
74
+ // approved write is allowed, exactly as a user-approved bash command runs unsandboxed — the "user
75
+ // asks the agent to repair a hook" case the sandbox's hard deny would otherwise force into bash.
76
+ export const GIT_METADATA_WARNING = 'Writes to git config or hooks (runs code at your next git command)';
77
+ // The names the sandbox profile refuses (src/tools/_sandbox.ts): any entry named `.git`, the
78
+ // metadata files at its top level and under `modules/`/`worktrees/<x>/`, and the `hooks` subtree.
79
+ // Unanchored, so a repo nested anywhere in the project is covered. Paths are normalized to `/` so
80
+ // a Windows separator cannot dodge the `/`-spelled rules. Case-insensitive because macOS's default
81
+ // volume is: `.git/Config` and `.GIT/hooks/x` write the real files, and on a case-sensitive volume
82
+ // the extra matches are only a prompt.
83
+ const GIT_METADATA_NAME_RE = /\/\.git$|\.git\/((modules\/.+\/|worktrees\/[^/]+\/)?(config|config\.worktree|commondir|gitdir))$|\.git\/(modules\/.+\/)?hooks(\/|$)/i;
84
+ // A common git dir NOT named `.git` (`git init --separate-git-dir`, a dotfiles bare repo) escapes
85
+ // the name rules, the same hole the sandbox's GITDIR param exists for. Protected places are the
86
+ // profile's `GITDIR` deny lines, written against the resolved common dir of the session cwd. This
87
+ // is the cwd's repo only — a git dir a target's OWN tree would resolve to is a separate repo whose
88
+ // paths the name rules still cover when it is a plain `.git` entry. The path is regex-escaped: a
89
+ // cwd may itself contain `.`, `+` or `(` (a dotted project name), and an unescaped one would match
90
+ // broader than the git dir.
91
+ const GIT_DIR_DENY_RE = (g) => {
92
+ const dir = g.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
93
+ return new RegExp(`^${dir}$|^${dir}/(config|config\\.worktree|commondir|gitdir)$|^${dir}/hooks(/|$)|^${dir}/worktrees/[^/]+/(config|config\\.worktree|commondir|gitdir)$|^${dir}/modules/.+/(config|config\\.worktree|commondir|gitdir)$|^${dir}/modules/.+/hooks(/|$)`, 'i');
94
+ };
95
+ const commonGitDirs = new Map();
96
+ // The session cwd's common git dir, normalized, or null when there is none. Mirrors the sandbox's
97
+ // `gitDirToBind` (src/tools/_sandbox.ts) minus its "cwd's own `.git`" skip:
98
+ // for the file tools the name rules already cover a `.git`-named dir, and protecting it again here
99
+ // changes nothing, so the skip is a comparison that cannot differ in outcome. A found dir is cached
100
+ // per cwd; a null is not, so a `--separate-git-dir`/bare repo the user creates mid-session is still
101
+ // probed for on the next write.
102
+ function commonGitDir(cwd) {
103
+ const cached = commonGitDirs.get(cwd);
104
+ if (cached !== undefined)
105
+ return cached;
106
+ let dir = null;
107
+ try {
108
+ const out = execFileSync('git', ['rev-parse', '--git-common-dir'], {
109
+ cwd,
110
+ encoding: 'utf8',
111
+ stdio: ['ignore', 'pipe', 'ignore'],
112
+ timeout: 5_000,
113
+ }).trim();
114
+ if (out) {
115
+ // Real path, as the sandbox binds it: git prints a separate git dir already resolved, so a
116
+ // cwd behind a symlink (`/tmp`, `os.tmpdir()`) would otherwise never match it.
117
+ dir = realTarget(resolve(isAbsolute(out) ? out : resolve(cwd, out)));
118
+ }
119
+ }
120
+ catch {
121
+ // not a repo, or no git — nothing to protect beyond the name rules
122
+ }
123
+ if (dir !== null)
124
+ commonGitDirs.set(cwd, dir);
125
+ return dir;
126
+ }
127
+ // Where a write to `full` actually lands: the real path of its deepest existing ancestor plus the
128
+ // rest, with a dangling symlink followed by hand (writeFile creates its target). The sandbox gets
129
+ // this from the kernel; a string check does not, and a sandboxed `ln -s .git/hooks h` is an
130
+ // ordinary in-project write that would turn `write h/pre-commit` into a hook.
131
+ function realTarget(full) {
132
+ let head = full;
133
+ const tail = [];
134
+ for (let hops = 0; hops < 40; hops++) {
135
+ try {
136
+ return join(realpathSync.native(head), ...tail);
137
+ }
138
+ catch {
139
+ // does not exist (yet), or a dangling link — handled below
140
+ }
141
+ try {
142
+ if (lstatSync(head).isSymbolicLink()) {
143
+ head = resolve(dirname(head), readlinkSync(head));
144
+ continue;
145
+ }
146
+ }
147
+ catch {
148
+ // nothing there
149
+ }
150
+ const parent = dirname(head);
151
+ if (parent === head)
152
+ return full;
153
+ tail.unshift(basename(head));
154
+ head = parent;
155
+ }
156
+ return full;
157
+ }
158
+ // Whether a resolved path is git metadata that names a program, and the warning to raise when it
159
+ // is. Undefined for anything else, so the tools' `warnings` arrays stay absent for a normal write.
160
+ // Both the path as written and where it really lands are checked: either one naming git metadata
161
+ // is enough.
162
+ export function gitMetadataWarning(cwd, full) {
163
+ const targets = [...new Set([full, realTarget(full)])].map(p => p.replaceAll('\\', '/'));
164
+ if (targets.some(f => GIT_METADATA_NAME_RE.test(f)))
165
+ return GIT_METADATA_WARNING;
166
+ const g = commonGitDir(cwd);
167
+ if (!g)
168
+ return undefined;
169
+ const deny = GIT_DIR_DENY_RE(g.replaceAll('\\', '/'));
170
+ return targets.some(f => deny.test(f)) ? GIT_METADATA_WARNING : undefined;
171
+ }