@rarog/server 1.1.0-beta.1 → 1.1.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 (95) hide show
  1. package/README.md +14 -2
  2. package/node_modules/@rarog/shared/package.json +1 -1
  3. package/node_modules/@rarog/shared/src/decode.js +16 -1
  4. package/node_modules/@rarog/shared/src/protocol/folders.js +27 -0
  5. package/node_modules/@rarog/shared/src/protocol/herdr.js +23 -0
  6. package/node_modules/@rarog/shared/src/protocol/notes.js +7 -1
  7. package/node_modules/@rarog/shared/src/protocol.js +5 -31
  8. package/node_modules/@rarog/shared/src/sentences/herdr.js +0 -4
  9. package/node_modules/@rarog/shared/src/sentences/index.js +7 -1
  10. package/node_modules/@rarog/shared/src/sentences/rest.js +8 -0
  11. package/package.json +2 -2
  12. package/server/src/auth/admin.js +3 -1
  13. package/server/src/bootstrap/consent.js +11 -0
  14. package/server/src/bootstrap/folder-gate.js +55 -0
  15. package/server/src/cli/service-log.js +27 -0
  16. package/server/src/cli/service.js +5 -2
  17. package/server/src/cli/templates/launchd.plist +1 -1
  18. package/server/src/cli/templates/rarog.service +1 -1
  19. package/server/src/cli/update-provenance.js +37 -19
  20. package/server/src/cli/update-registry.js +31 -1
  21. package/server/src/cli/update.js +128 -6
  22. package/server/src/config/protected-dirs.js +2 -0
  23. package/server/src/config/roots.js +13 -8
  24. package/server/src/config/work-area.js +36 -12
  25. package/server/src/config-env.js +9 -0
  26. package/server/src/config.js +17 -1
  27. package/server/src/demo/control.js +9 -1
  28. package/server/src/drivers/herdr/consent-no-hook.js +103 -8
  29. package/server/src/drivers/herdr/screen-fallback.js +246 -0
  30. package/server/src/drivers/herdr-driver.js +78 -9
  31. package/server/src/files/file-index.js +5 -3
  32. package/server/src/files/listing.js +8 -2
  33. package/server/src/files/path-rule.js +95 -41
  34. package/server/src/files/refusals.js +14 -0
  35. package/server/src/files/session-gate.js +11 -6
  36. package/server/src/folder-gate/client.js +314 -0
  37. package/server/src/folder-gate/disk.js +455 -0
  38. package/server/src/folder-gate/folders.js +23 -0
  39. package/server/src/folder-gate/gate.js +220 -0
  40. package/server/src/folder-gate/helper.js +118 -0
  41. package/server/src/folder-gate/install.js +27 -0
  42. package/server/src/folder-gate/relay-worker.js +147 -0
  43. package/server/src/folder-gate/types.js +115 -0
  44. package/server/src/folder-gate/wire.js +170 -0
  45. package/server/src/fs-browse.js +55 -23
  46. package/server/src/fs-mkdir.js +3 -1
  47. package/server/src/git-status.js +13 -5
  48. package/server/src/git-watch.js +130 -19
  49. package/server/src/git-work-tree.js +3 -3
  50. package/server/src/herdr/client.js +2 -2
  51. package/server/src/herdr/commands/discover.js +21 -9
  52. package/server/src/herdr/dialogs/consent-gate.js +28 -8
  53. package/server/src/herdr/dialogs/decide/sources.js +5 -2
  54. package/server/src/herdr/dialogs/hook/contract.js +1 -1
  55. package/server/src/herdr/dialogs/index.js +7 -2
  56. package/server/src/herdr/dialogs/layer1/cycle.js +43 -7
  57. package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +34 -27
  58. package/server/src/herdr/dialogs/layer1/screen-key.js +52 -0
  59. package/server/src/herdr/dialogs/router.js +21 -6
  60. package/server/src/herdr/dialogs/screen/parse.js +23 -2
  61. package/server/src/herdr/dialogs/screen/resolve.js +9 -7
  62. package/server/src/herdr/dialogs/screen-fallback.js +55 -0
  63. package/server/src/herdr/dialogs/shadow/alive.js +9 -8
  64. package/server/src/herdr/jsonl-follow.js +55 -14
  65. package/server/src/herdr/provenance.js +3 -3
  66. package/server/src/herdr/socket.js +25 -28
  67. package/server/src/herdr/supervisor.js +13 -10
  68. package/server/src/herdr/transcript-path.js +36 -0
  69. package/server/src/herdr/trust.js +11 -8
  70. package/server/src/herdr/uploads-registry.js +3 -2
  71. package/server/src/herdr/uploads.js +170 -47
  72. package/server/src/index.js +22 -3
  73. package/server/src/iroh/listener.js +3 -0
  74. package/server/src/iroh/log-budget.js +1 -0
  75. package/server/src/iroh/socket.js +2 -1
  76. package/server/src/notes/store.js +3 -2
  77. package/server/src/router.js +13 -1
  78. package/server/src/routes/projects.js +5 -1
  79. package/server/src/routes/sessions.js +10 -4
  80. package/server/src/routes/system.js +4 -0
  81. package/server/src/safe-read.js +12 -12
  82. package/server/src/sessions/companion-scope.js +10 -5
  83. package/server/src/sessions/done-retention.js +57 -0
  84. package/server/src/sessions/launch-gate.js +2 -2
  85. package/server/src/sessions/manager.js +35 -59
  86. package/server/src/sessions/project-scan.js +9 -3
  87. package/server/src/sessions/ring-buffer.js +8 -21
  88. package/server/src/sessions/session-git.js +31 -2
  89. package/server/src/sessions/session.js +1 -1
  90. package/server/src/sessions/state-sentences.js +1 -1
  91. package/server/src/sse.js +121 -22
  92. package/server/src/term/herdr-backend.js +2 -2
  93. package/server/src/term/index.js +2 -15
  94. package/server/src/term/registry.js +4 -3
  95. package/server/src/term/ws.js +9 -1
@@ -10,7 +10,8 @@
10
10
  * `update-provenance.ts` checks that one file, and npm installs exactly that file with `--ignore-scripts`. It finishes
11
11
  * nothing: `update.ts` hands a new version to that version's own `rarog update --finish`. After npm has replaced the
12
12
  * package files this process only reads one file and starts a child, so it never loads a module from the new files
13
- * (no dynamic import).
13
+ * (no dynamic import). `nodeInstallsHere` tells `update.ts` whether the npm of another node (the service's) installs
14
+ * into this installation.
14
15
  */
15
16
  import { spawn } from 'node:child_process';
16
17
  import { mkdirSync, mkdtempSync, realpathSync, rmSync } from 'node:fs';
@@ -295,6 +296,35 @@ function npmPrefixOf(root) {
295
296
  const binDir = npmBinDir(root);
296
297
  return binDir === null ? null : path.dirname(binDir);
297
298
  }
299
+ /**
300
+ * `node` is the node of the npm prefix of the installation at `root` (`<prefix>/bin`), and `npm prefix -g` of the npm
301
+ * next to it, in the environment `env`, is that prefix: a user `prefix=` in `.npmrc` can move it away from the node's
302
+ * own directory. Only then a whole `rarog update` on `node` installs into this installation and finishes on that node.
303
+ * Each reason for `false` is a line to `line`; Ctrl-C during npm = {@link SetupInterrupted}.
304
+ */
305
+ export async function nodeInstallsHere(input) {
306
+ const { node, root, line } = input;
307
+ const prefix = packageManagerOf(root) === 'npm' ? npmPrefixOf(root) : null;
308
+ if (prefix === null || !sameDir(path.dirname(node), path.join(prefix, 'bin'))) {
309
+ line(` ${node} is not the node of the npm prefix of ${root}`);
310
+ return false;
311
+ }
312
+ const found = npmCliOf(node);
313
+ if ('failure' in found) {
314
+ line(` ${found.failure}`);
315
+ return false;
316
+ }
317
+ const run = await runNpm({
318
+ execPath: node, npmCli: found.file, env: npmEnv(input.env, NPM_AGE_GATE_CONFIG), cwd: input.cwd,
319
+ }, PREFIX_ARGS, line);
320
+ if (run.interrupted)
321
+ throw new SetupInterrupted('npm prefix was interrupted (Ctrl-C)');
322
+ const said = run.stdout.trim();
323
+ if (run.code === 0 && said !== '' && sameDir(said, prefix))
324
+ return true;
325
+ line(` npm prefix -g of ${node}: ${run.code === 0 ? said : `exit ${String(run.code)}`}`);
326
+ return false;
327
+ }
298
328
  /**
299
329
  * The Download step on `view`: the header with the versions, then one step line. Ctrl-C during npm =
300
330
  * {@link SetupInterrupted}.
@@ -2,6 +2,8 @@
2
2
  * `rarog update`: the newest version of the npm package from the registry (the Download step, `update-registry.ts`),
3
3
  * then `rarog update --finish` of the version installed: a new version finishes in its own process (this one only
4
4
  * started it, so a fault in the old version's finish cannot block the new one), the same version finishes here.
5
+ * Started on another node than the service's, when that node is the one of this prefix, it first runs again on the
6
+ * service's node, so the finish never moves the service to the terminal's node.
5
7
  *
6
8
  * `rarog update --finish` finishes the installed version without the registry. In order: the Claude SDK it pins
7
9
  * (downloaded without a question), the service pointed at this installation when the run that has just installed it
@@ -16,11 +18,11 @@
16
18
  * launchctl does not tell is refused before any step.
17
19
  */
18
20
  import { spawn } from 'node:child_process';
19
- import { realpathSync } from 'node:fs';
21
+ import { accessSync, constants, realpathSync } from 'node:fs';
20
22
  import path from 'node:path';
21
23
  import { INSTALL_MODE, INSTALL_ROOT } from '../install/mode.js';
22
- import { rarogCli, repairCommands, shellQuote } from '../install/repair.js';
23
- import { transientInstall } from '../install/service-target.js';
24
+ import { installationCli, rarogCli, repairCommands, shellQuote } from '../install/repair.js';
25
+ import { serviceArgvNode, transientInstall } from '../install/service-target.js';
24
26
  import { readPackageVersion } from '../version.js';
25
27
  import { trackChild } from './child-output.js';
26
28
  import { EXIT_INTERRUPTED, EXIT_OK, EXIT_REFUSED, Refusal, Usage, err, homeOf, out, platformOf } from './io.js';
@@ -33,7 +35,7 @@ import { closingCheck, setupCliTarget } from './setup-check.js';
33
35
  import { SCREEN_TITLE, SERVICE_UNDETERMINED, entry, serviceStateFix } from './setup-context.js';
34
36
  import { SetupView } from './setup-screen.js';
35
37
  import { unitFilePath } from './systemd-unit.js';
36
- import { downloadStep } from './update-registry.js';
38
+ import { downloadStep, nodeInstallsHere } from './update-registry.js';
37
39
  import { UPDATE_LOCK_TOKEN, markInstalled, takeUpdateLock, updateLockOf } from './update-lock.js';
38
40
  import { sentenceFor, usageFor } from './screen/prose.js';
39
41
  export const UPDATE_USAGE = ` rarog update [--beta] [--data-dir <dir>] [--verbose]
@@ -51,6 +53,11 @@ export const UPDATE_USAGE = ` rarog update [--beta] [--data-dir <dir>] [--verbo
51
53
  project folders and leaves config.json as it is.
52
54
  --data-dir: the installation's data directory from rarog serve --data-dir.
53
55
  --verbose: every detail line on the screen.`;
56
+ /**
57
+ * Set in the environment of `rarog update` run again on the service's node: that run never switches again, so a
58
+ * node that still differs ends in a refusal, not in a loop.
59
+ */
60
+ export const UPDATE_NODE_GUARD = 'RAROG_UPDATE_ON_SERVICE_NODE';
54
61
  /** Command name of the run log (`<dataDir>/logs/update-….log`). */
55
62
  export const UPDATE_LOG_COMMAND = 'update';
56
63
  /** Step lines of a finish: four steps and the closing Check. */
@@ -166,6 +173,107 @@ function serviceAgainst(io, platform, root) {
166
173
  ? { kind: 'unloaded', what: `the service file ${file} is there, but launchd has no ${SERVICE_LABEL} loaded` }
167
174
  : HERE;
168
175
  }
176
+ /**
177
+ * The node the service starts when it starts this installation on another node than this process's: every source
178
+ * names the same executable node (macOS: the definition launchd has loaded and the plist; Linux: the unit file).
179
+ * `null` otherwise: no service, an unreadable one, sources that disagree, another installation, this process's node,
180
+ * or a load state launchctl does not tell. The Download step offers it only when it is the node of this prefix.
181
+ */
182
+ function otherServiceNode(io, platform, root) {
183
+ const current = { node: process.execPath, bin: path.join(root, 'bin', 'rarog.mjs') };
184
+ const home = homeOf(io.env);
185
+ const sources = [];
186
+ if (platform === 'linux') {
187
+ if (entry(unitFilePath(home)) !== 'present')
188
+ return null;
189
+ const found = unitArgv(io);
190
+ if ('issue' in found)
191
+ return null;
192
+ sources.push(found.argv);
193
+ }
194
+ else {
195
+ const loaded = loadedDefinition(SERVICE_LABEL, io, platform);
196
+ if (loaded.kind === 'unknown')
197
+ return null;
198
+ if (loaded.kind === 'loaded')
199
+ sources.push(loaded.argv);
200
+ if (entry(servicePlistPath(home)) === 'present') {
201
+ const found = servicePlistArgv(io);
202
+ if ('issue' in found)
203
+ return null;
204
+ sources.push(found.argv);
205
+ }
206
+ }
207
+ const nodes = new Set();
208
+ for (const argv of sources) {
209
+ if (serviceInstallationMismatch(argv, 'package', current)?.kind !== 'node')
210
+ return null;
211
+ nodes.add(serviceArgvNode(argv) ?? '');
212
+ }
213
+ const [node] = nodes;
214
+ if (nodes.size !== 1 || node === undefined || node === '')
215
+ return null;
216
+ try {
217
+ accessSync(node, constants.X_OK);
218
+ }
219
+ catch {
220
+ return null;
221
+ }
222
+ return node;
223
+ }
224
+ /**
225
+ * The service's node when this installation's update has to run on it: the service starts this installation on
226
+ * another node ({@link otherServiceNode}), that node is the one of this installation's npm prefix, and its npm installs
227
+ * there (`nodeInstallsHere`). `null` otherwise; `line` gets the reason.
228
+ */
229
+ async function updateNodeOfService(io, platform, root, line) {
230
+ const node = otherServiceNode(io, platform, root);
231
+ if (node === null)
232
+ return null;
233
+ return await nodeInstallsHere({ node, root, env: io.env, cwd: homeOf(io.env), line }) ? node : null;
234
+ }
235
+ /** The arguments of a command as the user types them: the words bare, the value of `--data-dir` quoted. */
236
+ function typed(args) {
237
+ return args.map((arg, i) => (args[i - 1] === '--data-dir' ? shellQuote(arg) : arg)).join(' ');
238
+ }
239
+ /**
240
+ * `rarog update` (`argv` starts with `update`) on another node than the service's, when the update has to run on the
241
+ * service's node ({@link updateNodeOfService}): this process becomes the same command with the same arguments on that
242
+ * node (`process.execve`, the same PID), so its npm installs and the new version's finish runs on the node the service
243
+ * starts (a finish on this node would move the service here). One line says so; that run takes the update lock
244
+ * itself and gets {@link UPDATE_NODE_GUARD}. A run with the guard that still sees another node refuses instead of
245
+ * switching again. `null` = this run goes on.
246
+ */
247
+ async function onServiceNode(argv, io, platform, root, replaceWith) {
248
+ let node;
249
+ try {
250
+ node = await updateNodeOfService(io, platform, root, () => { });
251
+ }
252
+ catch (failure) {
253
+ if (failure instanceof SetupInterrupted)
254
+ return EXIT_INTERRUPTED;
255
+ throw failure;
256
+ }
257
+ if (node === null)
258
+ return null;
259
+ const bin = path.join(root, 'bin', 'rarog.mjs');
260
+ const command = installationCli({ node, bin }, typed(argv));
261
+ if (io.env[UPDATE_NODE_GUARD] !== undefined) {
262
+ throw new Refusal(`the service starts ${node}, but this run on it runs on ${process.execPath}; nothing was`
263
+ + ` changed; run ${command}.`);
264
+ }
265
+ const replace = replaceWith ?? (typeof process.execve === 'function' ? process.execve : null);
266
+ if (replace === null) {
267
+ // `bin/rarog.mjs` lets only a Node with `process.execve` in; a second process would not stop with this one.
268
+ throw new Refusal(`the service starts ${node}, and this Node (v${process.versions.node}) has no process.execve`
269
+ + ` to run the update on it; nothing was changed; run ${command}.`);
270
+ }
271
+ out(io, `rarog update: the service starts ${node}, so this update runs on it.`);
272
+ // The same process becomes the run on the service's node: every signal reaches it as it would reach `rarog update`
273
+ // started there, and no process is left behind that could exit while the update goes on.
274
+ const code = replace(node, [node, bin, ...argv], { ...withoutToken(io.env), [UPDATE_NODE_GUARD]: '1' });
275
+ return typeof code === 'number' ? code : EXIT_REFUSED;
276
+ }
169
277
  /** `rarog update` and `rarog update --finish` — `argv` starts with `update`; tests give `deps`. */
170
278
  export async function updateCommand(argv, io, deps = DEFAULT_DEPS) {
171
279
  if (argv.includes('--help') || argv.includes('-h')) {
@@ -200,6 +308,12 @@ export async function updateCommand(argv, io, deps = DEFAULT_DEPS) {
200
308
  throw new Refusal(`${what}: no ${path.join(rarogConfigDir(io.env), 'config.json')}, so there is no installation`
201
309
  + ` to ${flags.finish ? 'finish' : 'update'}; run ${rarogCli('setup', mode)} first.`);
202
310
  }
311
+ // Before the lock: the run on the service's node takes it itself.
312
+ if (!flags.finish) {
313
+ const code = await onServiceNode(argv, io, platform, root, deps.replaceProcess);
314
+ if (code !== null)
315
+ return code;
316
+ }
203
317
  // `rarog update` installs, so it always takes the lock itself; a finish inherits the lock of a run that installed.
204
318
  const dir = rarogConfigDir(io.env);
205
319
  const lock = flags.finish ? updateLockOf(dir, io.env, what) : takeUpdateLock(dir, what);
@@ -364,8 +478,16 @@ async function runSteps(io, view, steps, run, deps, at) {
364
478
  // The update lock does not name this installation as the one just installed: the refusal of rarog restart.
365
479
  start('service', 'Service', false);
366
480
  view.detail(` ${service.what}`);
367
- // The command of this installation (the absolute form outside `PATH`, `screenFix`); the step line says why.
368
- show(view, 'fail', `starts another ${service.other}; nothing was changed`, rarogCli('service install', 'package'));
481
+ // A service on the node of this prefix whose npm installs here: this command again on that node, which the service
482
+ // already starts (`rarog service install` here would move the service to this process's node).
483
+ const node = service.other === 'node'
484
+ ? await updateNodeOfService(io, run.platform, run.root, (text) => { view.detail(text); }) : null;
485
+ const again = [...(run.flags.finish ? ['update', '--finish'] : ['update']),
486
+ ...(run.flags.dataDir === null ? [] : ['--data-dir', run.flags.dataDir])];
487
+ // Otherwise the command of this installation (the absolute form outside `PATH`, `screenFix`); the step line says why.
488
+ show(view, 'fail', `starts another ${service.other}; nothing was changed`, node === null
489
+ ? rarogCli('service install', 'package')
490
+ : installationCli({ node, bin: path.join(run.root, 'bin', 'rarog.mjs') }, typed(again)));
369
491
  return EXIT_REFUSED;
370
492
  }
371
493
  const results = [];
@@ -10,6 +10,8 @@ import path from 'node:path';
10
10
  export const PROTECTED_HOME_DIRS = [
11
11
  'Desktop', 'Documents', 'Downloads', 'Library', 'Movies', 'Music', 'Pictures',
12
12
  ];
13
+ /** The protected folders where projects usually live: the part of {@link PROTECTED_HOME_DIRS} a folder gate opens. */
14
+ export const OPEN_HOME_DIRS = ['Desktop', 'Documents', 'Downloads'];
13
15
  /**
14
16
  * A name or path folded the way the default macOS disk (APFS, case-insensitive) compares names, so spellings that disk
15
17
  * reads as one name fold alike: decomposed form (NFD), then lower, upper and lower case, then composed form (NFC).
@@ -3,11 +3,11 @@
3
3
  * that every caller uses before Rarog runs anything in a directory. `loadConfig` (`server/src/config.ts`) passes in
4
4
  * the values it read through `readEnv`.
5
5
  */
6
- import { realpathSync, statSync } from 'node:fs';
7
6
  import os from 'node:os';
8
7
  import path from 'node:path';
9
8
  import { say } from '@rarog/shared/sentences';
10
9
  import { ConfigError, HERDR_ROOTS_ENV, PROJECT_ROOTS_ENV } from '../config-env.js';
10
+ import { DIRECT_DISK } from '../folder-gate/disk.js';
11
11
  import { insideWorkArea, isExcludedPath, resolveInWorkArea } from './work-area.js';
12
12
  // ---------------------------------------------------------------------------
13
13
  // Korzenie projektów i walidacja cwd
@@ -85,9 +85,11 @@ export function isInsideAnyRoot(candidate, roots) {
85
85
  return false;
86
86
  return roots.some((root) => isInside(candidate, root));
87
87
  }
88
+ /** `realpathSync` of the work-area disk port: the JavaScript walk, letter case as written. */
89
+ const realpathOnDisk = (candidate) => DIRECT_DISK.sync('realpath', { path: candidate });
88
90
  function realIsDirectory(candidate) {
89
91
  try {
90
- return statSync(candidate).isDirectory();
92
+ return DIRECT_DISK.sync('stat', { path: candidate }).isDirectory();
91
93
  }
92
94
  catch {
93
95
  return false;
@@ -110,7 +112,7 @@ function realIsDirectory(candidate) {
110
112
  * nadrzędnym), odpada. Korzeń, którego nie da się rozwiązać, zostaje w postaci leksykalnej —
111
113
  * nieistniejący korzeń nie może rozszerzać granicy, więc jego „zawężenie" byłoby tylko szumem.
112
114
  */
113
- export function isInsideAnyRootReal(candidate, roots, realPath = realpathSync) {
115
+ export function isInsideAnyRootReal(candidate, roots, realPath = realpathOnDisk) {
114
116
  if (!isInsideAnyRoot(candidate, roots))
115
117
  return false;
116
118
  let resolved;
@@ -172,7 +174,8 @@ function realPathEntersHidden(resolved, realRoots) {
172
174
  * 5. the work area, still text only: a macOS-protected folder of home is refused unless a root lies in it
173
175
  * (`config/work-area.ts`); a read there makes macOS ask for access, and this check is synchronous,
174
176
  * 6. the symlink walk (`resolveInWorkArea`) as the first disk access: it stops before an excluded folder, so
175
- * `<root>/link -> ~/Desktop/x` is refused without a read in `Desktop`; a missing segment is "not found",
177
+ * `<root>/link -> ~/Desktop/x` is refused without a read in `Desktop`; a missing segment is "not found", and a
178
+ * guarded folder the folder gate holds closed gives the sentence of its state (metadata only, no helper call),
176
179
  * 7. musi istnieć i być katalogiem,
177
180
  * 8. i dopiero teraz to samo pytanie po ROZWIĄZANIU dowiązań — kroki 4 i 7 same
178
181
  * przepuszczały `<korzeń>/skrót -> /gdziekolwiek`; the resolved path must also lie outside the excluded folders,
@@ -217,7 +220,7 @@ export function validateProjectCwd(input, roots, opts = {}) {
217
220
  if (!insideWorkArea(cwd, roots, home)) {
218
221
  return { ok: false, sentence: say('rest.cwd-protected') };
219
222
  }
220
- const resolveOne = opts.realPath ?? realpathSync;
223
+ const resolveOne = opts.realPath ?? realpathOnDisk;
221
224
  const onDisk = (entry) => {
222
225
  try {
223
226
  return resolveOne(entry);
@@ -234,8 +237,10 @@ export function validateProjectCwd(input, roots, opts = {}) {
234
237
  const walked = resolveInWorkArea(cwd, realRoots, realHome, opts.walk);
235
238
  if (walked.kind === 'missing')
236
239
  return { ok: false, sentence: say('rest.cwd-not-found') };
237
- if (walked.kind === 'excluded')
238
- return { ok: false, sentence: say('rest.cwd-symlink-escape') };
240
+ if (walked.kind === 'excluded') {
241
+ // A guarded folder the folder gate holds closed: the sentence of its state, not a link that leads out.
242
+ return { ok: false, sentence: walked.closed?.sentence ?? say('rest.cwd-symlink-escape') };
243
+ }
239
244
  resolved = walked.path;
240
245
  }
241
246
  if (!isDirectory(cwd)) {
@@ -243,7 +248,7 @@ export function validateProjectCwd(input, roots, opts = {}) {
243
248
  }
244
249
  if (resolved === null) {
245
250
  try {
246
- resolved = opts.realPath === undefined ? realpathSync(cwd) : opts.realPath(cwd);
251
+ resolved = opts.realPath === undefined ? realpathOnDisk(cwd) : opts.realPath(cwd);
247
252
  }
248
253
  catch {
249
254
  return { ok: false, sentence: say('rest.cwd-symlink-escape') };
@@ -5,10 +5,13 @@
5
5
  * unless a root lies in that folder (`protected-dirs.ts`). `insideWorkArea` judges text only; `resolveInWorkArea`
6
6
  * resolves symlinks one segment at a time and stops before it would touch an excluded folder; `inWorkAreaOnDisk`
7
7
  * puts the two together for a directory that already exists, and `inExcludedOnDisk` asks only about the excluded
8
- * folders, for a directory that may lie outside the roots. The module never lists a directory and never reads a file.
8
+ * folders, for a directory that may lie outside the roots. A guarded folder the folder gate holds closed is out of the
9
+ * work area too, unless the caller asks to ignore the gate (`WalkOptions`). The module never lists a directory and
10
+ * never reads a file.
9
11
  */
10
- import { lstatSync, readlinkSync, realpathSync } from 'node:fs';
11
12
  import path from 'node:path';
13
+ import { DIRECT_DISK, closedFolderOf } from '../folder-gate/disk.js';
14
+ import { FolderGateError } from '../folder-gate/types.js';
12
15
  import { PROTECTED_HOME_DIRS, foldCase, inProtectedFolder, openedByRoot } from './protected-dirs.js';
13
16
  const lower = (value) => value.toLowerCase();
14
17
  /** Whether `candidate` is `root` or lies inside it, by path segments. */
@@ -58,7 +61,14 @@ export function insideWorkArea(cwd, roots, home) {
58
61
  });
59
62
  return inRoot && !isExcludedPath(resolved, roots, home);
60
63
  }
61
- const DISK = { lstat: (file) => lstatSync(file), readlink: (file) => readlinkSync(file) };
64
+ /** The walk's view of the work-area disk port. */
65
+ export function walkDiskOf(disk) {
66
+ return {
67
+ lstat: (file) => disk.sync('lstat', { path: file }),
68
+ readlink: (file) => disk.sync('readlink', { path: file }),
69
+ };
70
+ }
71
+ const DISK = walkDiskOf(DIRECT_DISK);
62
72
  /** Symlinks followed in one walk before it gives up, as `ELOOP` of the system. */
63
73
  const MAX_LINKS = 40;
64
74
  /**
@@ -66,9 +76,13 @@ const MAX_LINKS = 40;
66
76
  * built so far is checked, and one in an excluded folder ends the walk (`excluded`) without a read there. A
67
77
  * symlink's target is walked the same way, so `<root>/link -> ~/Desktop/x` never reaches `Desktop`. An excluded
68
78
  * folder that holds a root (`~/Documents` on the way to the root `~/Documents/Projects`) may be passed.
69
- * `missing`: a segment does not exist, cannot be checked, or the links loop. `roots` and `home` in on-disk form.
79
+ * `missing`: a segment does not exist, cannot be checked, or the links loop. A segment in a guarded folder the folder
80
+ * gate holds closed ends the walk as `excluded` with the refusal in `closed`, before its `lstat`: the folder cannot be
81
+ * entered now, and a missing segment would keep the verdict of the text. The walk asks the port for it
82
+ * (`closedFolderOf`), because metadata passes a closed folder; a disk that refuses a segment with `FolderGateError`
83
+ * ends the walk the same way. With `gate: 'ignore'` the walk does not ask the gate. `roots` and `home` in on-disk form.
70
84
  */
71
- export function resolveInWorkArea(candidate, roots, home, disk = DISK) {
85
+ export function resolveInWorkArea(candidate, roots, home, disk = DISK, options = {}) {
72
86
  if (!path.isAbsolute(candidate))
73
87
  return { kind: 'missing' };
74
88
  // The way to a root compares in lower case, like a root opening a path (`isExcludedPath`).
@@ -90,13 +104,16 @@ export function resolveInWorkArea(candidate, roots, home, disk = DISK) {
90
104
  const next = path.join(current, part);
91
105
  if (blocked(next))
92
106
  return { kind: 'excluded' };
107
+ const closed = options.gate === 'ignore' ? null : closedFolderOf(next);
108
+ if (closed !== null)
109
+ return { kind: 'excluded', closed };
93
110
  let link = null;
94
111
  try {
95
112
  if (disk.lstat(next).isSymbolicLink())
96
113
  link = disk.readlink(next);
97
114
  }
98
- catch {
99
- return { kind: 'missing' };
115
+ catch (error) {
116
+ return error instanceof FolderGateError ? { kind: 'excluded', closed: error } : { kind: 'missing' };
100
117
  }
101
118
  if (link === null) {
102
119
  current = next;
@@ -111,7 +128,11 @@ export function resolveInWorkArea(candidate, roots, home, disk = DISK) {
111
128
  }
112
129
  return { kind: 'resolved', path: current };
113
130
  }
114
- const AREA_DISK = { ...DISK, realpath: (file) => realpathSync(file) };
131
+ /** The area's view of the work-area disk port: `realpath` is the JavaScript walk of `realpathSync`. */
132
+ export function areaDiskOf(disk) {
133
+ return { ...walkDiskOf(disk), realpath: (file) => disk.sync('realpath', { path: file }) };
134
+ }
135
+ const AREA_DISK = areaDiskOf(DIRECT_DISK);
115
136
  /**
116
137
  * Roots and home in on-disk form, the reference points of a walk: a root that is a symlink (`/srv/home -> ~`) counts
117
138
  * where it leads. Only they go through `realpath`, never a folder inside them; one that does not resolve stays as given.
@@ -136,13 +157,15 @@ export function onDiskForms(roots, home, realpath = AREA_DISK.realpath) {
136
157
  * meets the whole rule once more there, so `<root>/link -> ~/Desktop/x`, `<root ~>/visible -> ~/.cache/x` and a root
137
158
  * that is a symlink to home (`/srv/home/Desktop`) stay out without a read in the excluded folder. A path the walk
138
159
  * cannot resolve (deleted, unreadable, a loop of links) keeps the verdict of its text, because nothing can be read
139
- * through it; a link that leads out of every root keeps it too, unless it ends in an excluded folder.
160
+ * through it; a link that leads out of every root keeps it too, unless it ends in an excluded folder. A guarded folder
161
+ * the folder gate holds closed on the way puts the path out of the work area until the folder opens, unless `options`
162
+ * ignore the gate ({@link WalkOptions}).
140
163
  */
141
- export function inWorkAreaOnDisk(cwd, roots, home, disk = AREA_DISK) {
164
+ export function inWorkAreaOnDisk(cwd, roots, home, disk = AREA_DISK, options = {}) {
142
165
  const real = onDiskForms(roots, home, disk.realpath);
143
166
  if (!insideWorkArea(cwd, [...roots, ...real.roots], home))
144
167
  return false;
145
- const walked = resolveInWorkArea(cwd, real.roots, real.home, disk);
168
+ const walked = resolveInWorkArea(cwd, real.roots, real.home, disk, options);
146
169
  if (walked.kind !== 'resolved')
147
170
  return walked.kind === 'missing';
148
171
  const inRoots = real.roots.some((root) => path.isAbsolute(root) && isWithin(walked.path, path.resolve(root)));
@@ -156,7 +179,8 @@ export function inWorkAreaOnDisk(cwd, roots, home, disk = AREA_DISK) {
156
179
  * resolve before the text check, never `cwd`, and a root counts in both forms: one that is a symlink into a protected
157
180
  * folder (`/srv/code -> ~/Desktop/project`) opens the physical path a pane reports. Then the walk
158
181
  * ({@link resolveInWorkArea}), which stops before an excluded folder, and the excluded folders once more on the path
159
- * it resolves to. A path the walk cannot resolve is not excluded: nothing can be read through it.
182
+ * it resolves to. A path the walk cannot resolve is not excluded: nothing can be read through it. A guarded folder
183
+ * the folder gate holds closed on the way counts as excluded, so git does not run there.
160
184
  */
161
185
  export function inExcludedOnDisk(cwd, roots, home, disk = AREA_DISK) {
162
186
  const real = onDiskForms(roots, home, disk.realpath);
@@ -182,6 +182,14 @@ export const CONSENT_RESTART_GRACE_ENV = 'RAROG_CONSENT_RESTART_GRACE';
182
182
  * wysyła, więc to NIE jest szósty killswitch. Flaga kanału zgody jej nie zmienia i odwrotnie.
183
183
  */
184
184
  export const DIALOG_LAYER2_ENV = 'RAROG_DIALOG_LAYER2';
185
+ /**
186
+ * Folder gate kill switch (`docs/macos-folders.md`): missing or empty = on on macOS and off elsewhere, `1` = on,
187
+ * `0` = off; any other value is a config error at start, also in the demo, which never runs the gate. On, a disk call
188
+ * of the work area in Desktop, Documents or Downloads (and any other guarded folder of home) runs in a helper
189
+ * process the server can kill, so a macOS consent window waits there instead of in the server. Off = every call in
190
+ * the server process, without helpers or the relay thread. It approves and sends nothing.
191
+ */
192
+ export const FOLDER_GATE_ENV = 'RAROG_FOLDER_GATE';
185
193
  /**
186
194
  * SSE STREAM COMPRESSION flag: missing, empty or `1` = the server gzips the stream when the client sent
187
195
  * `Accept-Encoding` with `gzip` at a weight above zero; `0` = no compression for any client; any other value is a
@@ -392,6 +400,7 @@ export const SERVER_ENV = {
392
400
  [CONSENT_ALWAYS_ENV]: 'plain',
393
401
  [CONSENT_RESTART_GRACE_ENV]: 'plain',
394
402
  [DIALOG_LAYER2_ENV]: 'plain',
403
+ [FOLDER_GATE_ENV]: 'plain',
395
404
  [SSE_GZIP_ENV]: 'plain',
396
405
  [COMPANION_ENV]: 'plain',
397
406
  [COMPANION_SESSIONS_ENV]: 'plain',
@@ -15,7 +15,7 @@ import path from 'node:path';
15
15
  import { MAX_TRANSCRIPT_MESSAGES } from '@rarog/shared';
16
16
  import { BUNDLE_ID_RE } from '@rarog/shared/rest';
17
17
  import { dataDirConflictMessage, resolveDataDir } from '@rarog/shared/data-dir';
18
- import { AGENT_FILES_ENV, APNS_ENV_NAMES, APNS_KEY_ID_ENV, APNS_KEY_PATH_ENV, APNS_TEAM_ID_ENV, APNS_TOPIC_ENV, CLAUDE_ENV_CLEAR_ENV, ConfigError, CLI_WAITING_ENV, CODEX_STATUS_ENV, COMPANION_ENV, COMPANION_MODEL_ENV, COMPANION_SESSIONS_ENV, COMPANION_ENV_PASSTHROUGH, CONSENT_CHANNEL_ENV, CONSENT_PROOF_ENV, CONSENT_ALWAYS_ENV, CONSENT_RESTART_GRACE_ENV, DEMO_CONTENT_ENV, DEMO_LANG_ENV, DEMO_REVIEW_CODE_ENV, DIALOG_LAYER2_ENV, GIT_ENV_PASSTHROUGH, GIT_ENV_PREFIX, GIT_FILE_DETAILS_ENV, HERDR_BIN_ENV, HERDR_LAUNCH_ENV, HERDR_ROOTS_ENV, HERDR_SEEN_FOCUS_ENV, HERDR_SEND_ENV, HERDR_SOCKET_ENV, HERDR_TAB_LABELS_ENV, INBOX_ENV, FILES_ENV, FILES_MAX_MB_ENV, IROH_ENV, IROH_KEY_ENV, IROH_PORT_ENV, IROH_RELAY_ENV, MAX_PANES_ENV, MIN_CLIENT_BUILD_ENV, NOTES_ENV, PROJECT_ROOTS_ENV, PROMPT_BLOCK_ENV, PUSH_E2E_ENV, PUSH_ENV, PR_STATUS_ENV, PR_STATUS_ENV_PASSTHROUGH, PUSH_RELAY_URL_ENV, QUEUE_ECHO_ENV, REFUSAL_DUMPS_ENV, SONIOX_API_HOST_ENV, SONIOX_API_KEY_ENV, OPENAI_API_KEY_ENV, SSE_GZIP_ENV, TALL_DIALOG_GUARD_ENV, TERM_ENV, TERM_ENV_PASSTHROUGH, TERM_IDLE_DAYS_ENV, TERM_MAX_ENV, VOICE_ENV, YOLO_ROOTS_ENV, readEnv, } from './config-env.js';
18
+ import { AGENT_FILES_ENV, APNS_ENV_NAMES, APNS_KEY_ID_ENV, APNS_KEY_PATH_ENV, APNS_TEAM_ID_ENV, APNS_TOPIC_ENV, CLAUDE_ENV_CLEAR_ENV, ConfigError, CLI_WAITING_ENV, CODEX_STATUS_ENV, COMPANION_ENV, COMPANION_MODEL_ENV, COMPANION_SESSIONS_ENV, COMPANION_ENV_PASSTHROUGH, CONSENT_CHANNEL_ENV, CONSENT_PROOF_ENV, CONSENT_ALWAYS_ENV, CONSENT_RESTART_GRACE_ENV, DEMO_CONTENT_ENV, DEMO_LANG_ENV, DEMO_REVIEW_CODE_ENV, DIALOG_LAYER2_ENV, FOLDER_GATE_ENV, GIT_ENV_PASSTHROUGH, GIT_ENV_PREFIX, GIT_FILE_DETAILS_ENV, HERDR_BIN_ENV, HERDR_LAUNCH_ENV, HERDR_ROOTS_ENV, HERDR_SEEN_FOCUS_ENV, HERDR_SEND_ENV, HERDR_SOCKET_ENV, HERDR_TAB_LABELS_ENV, INBOX_ENV, FILES_ENV, FILES_MAX_MB_ENV, IROH_ENV, IROH_KEY_ENV, IROH_PORT_ENV, IROH_RELAY_ENV, MAX_PANES_ENV, MIN_CLIENT_BUILD_ENV, NOTES_ENV, PROJECT_ROOTS_ENV, PROMPT_BLOCK_ENV, PUSH_E2E_ENV, PUSH_ENV, PR_STATUS_ENV, PR_STATUS_ENV_PASSTHROUGH, PUSH_RELAY_URL_ENV, QUEUE_ECHO_ENV, REFUSAL_DUMPS_ENV, SONIOX_API_HOST_ENV, SONIOX_API_KEY_ENV, OPENAI_API_KEY_ENV, SSE_GZIP_ENV, TALL_DIALOG_GUARD_ENV, TERM_ENV, TERM_ENV_PASSTHROUGH, TERM_IDLE_DAYS_ENV, TERM_MAX_ENV, VOICE_ENV, YOLO_ROOTS_ENV, readEnv, } from './config-env.js';
19
19
  import { RAROG_VERSION } from './version.js';
20
20
  import { INSTALL_MODE } from './install/mode.js';
21
21
  import { DEVICES_FILENAME, activeDeviceEpochs } from './auth/devices-store.js';
@@ -528,6 +528,20 @@ export function parseDialogLayer2(raw) {
528
528
  return true;
529
529
  throw new ConfigError(`${DIALOG_LAYER2_ENV} takes 1 or 0 (got: ${value}).`);
530
530
  }
531
+ /**
532
+ * The folder gate flag: missing or empty = the platform decides (on on macOS, where the consent windows are), `1` = on,
533
+ * `0` = off; any other value stops the start, so a typo never leaves the server in another mode than the owner meant.
534
+ */
535
+ export function parseFolderGate(raw, platform) {
536
+ const value = raw?.trim() ?? '';
537
+ if (value === '')
538
+ return platform === 'darwin';
539
+ if (value === '1')
540
+ return true;
541
+ if (value === '0')
542
+ return false;
543
+ throw new ConfigError(`${FOLDER_GATE_ENV} takes 1 or 0 (got: ${value}).`);
544
+ }
531
545
  /** Strażnik wysokości dialogu; brak wartości = WŁĄCZONY, `0`/`false` wyłącza. */
532
546
  export function parseTallDialogGuard(raw) {
533
547
  if (raw === undefined || raw.trim() === '')
@@ -707,6 +721,8 @@ export function loadConfig(env = process.env, mode = INSTALL_MODE) {
707
721
  consentRestartGraceMs: parseConsentRestartGrace(readEnv(env, CONSENT_RESTART_GRACE_ENV)),
708
722
  // W demo bez skutku (mock nie ma drivera herdr), ale zła wartość zatrzymuje start tak samo.
709
723
  dialogLayer2: parseDialogLayer2(readEnv(env, DIALOG_LAYER2_ENV)),
724
+ // Off in demo unconditionally: the demo reads nothing of the host's folders; a wrong value stops the start there.
725
+ folderGate: parseFolderGate(readEnv(env, FOLDER_GATE_ENV), process.platform) && !demo,
710
726
  sseGzip: parseSseGzip(readEnv(env, SSE_GZIP_ENV)),
711
727
  // Off in demo unconditionally; a wrong value still stops the start there.
712
728
  companionEnabled: parseCompanionEnabled(readEnv(env, COMPANION_ENV)) && !demo,
@@ -546,7 +546,15 @@ export function createDemoControl(router, config, manager, panels, notes) {
546
546
  return true;
547
547
  }
548
548
  const handler = (req, res) => {
549
- const url = new URL(req.url ?? '/', 'http://127.0.0.1');
549
+ let url;
550
+ try {
551
+ url = new URL(req.url ?? '/', 'http://127.0.0.1');
552
+ }
553
+ catch {
554
+ // A target `URL` rejects would end the process here; the router answers it with its 400.
555
+ router(req, res);
556
+ return;
557
+ }
550
558
  const pathname = url.pathname;
551
559
  if (pathname === '/api/demo/control') {
552
560
  controlChain = controlChain.then(() => control(req, res)).catch(() => {