@rarog/server 1.0.1 → 1.1.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 (140) hide show
  1. package/README.md +18 -5
  2. package/node_modules/@rarog/shared/package.json +1 -1
  3. package/node_modules/@rarog/shared/src/decode.js +64 -3
  4. package/node_modules/@rarog/shared/src/protocol/files.js +33 -0
  5. package/node_modules/@rarog/shared/src/protocol/folders.js +27 -0
  6. package/node_modules/@rarog/shared/src/protocol/herdr.js +23 -0
  7. package/node_modules/@rarog/shared/src/protocol/inbox.js +38 -0
  8. package/node_modules/@rarog/shared/src/protocol/notes.js +7 -1
  9. package/node_modules/@rarog/shared/src/protocol.js +20 -47
  10. package/node_modules/@rarog/shared/src/rest.js +106 -12
  11. package/node_modules/@rarog/shared/src/sentences/herdr.js +0 -4
  12. package/node_modules/@rarog/shared/src/sentences/index.js +7 -1
  13. package/node_modules/@rarog/shared/src/sentences/rest.js +21 -0
  14. package/package.json +3 -3
  15. package/server/src/auth/admin.js +3 -1
  16. package/server/src/bootstrap/consent.js +99 -2
  17. package/server/src/bootstrap/folder-gate.js +55 -0
  18. package/server/src/bootstrap/http.js +3 -2
  19. package/server/src/bootstrap/inbox.js +29 -4
  20. package/server/src/bootstrap/sse.js +2 -1
  21. package/server/src/cli/doctor-no-hook.js +162 -0
  22. package/server/src/cli/doctor.js +2 -0
  23. package/server/src/cli/service-log.js +27 -0
  24. package/server/src/cli/service.js +5 -2
  25. package/server/src/cli/templates/launchd.plist +1 -1
  26. package/server/src/cli/templates/rarog.service +1 -1
  27. package/server/src/cli/update-channel.js +100 -0
  28. package/server/src/cli/update-provenance.js +37 -19
  29. package/server/src/cli/update-registry.js +160 -62
  30. package/server/src/cli/update.js +13 -3
  31. package/server/src/companion/turns-settle.js +4 -1
  32. package/server/src/companion/turns.js +36 -5
  33. package/server/src/config/files.js +32 -0
  34. package/server/src/config/flags.js +10 -1
  35. package/server/src/config/protected-dirs.js +2 -0
  36. package/server/src/config/roots.js +13 -8
  37. package/server/src/config/work-area.js +36 -12
  38. package/server/src/config-env.js +33 -0
  39. package/server/src/config.js +22 -2
  40. package/server/src/demo/control.js +9 -1
  41. package/server/src/demo/files.js +49 -0
  42. package/server/src/demo/inbox.js +73 -0
  43. package/server/src/demo/review-routes.js +6 -1
  44. package/server/src/device-effects.js +3 -1
  45. package/server/src/drivers/herdr/consent-no-hook-io.js +89 -0
  46. package/server/src/drivers/herdr/consent-no-hook.js +411 -0
  47. package/server/src/drivers/herdr/refusals.js +226 -0
  48. package/server/src/drivers/herdr/returned-prompt.js +172 -0
  49. package/server/src/drivers/herdr/screen-fallback.js +246 -0
  50. package/server/src/drivers/herdr-driver.js +193 -295
  51. package/server/src/files/file-index.js +248 -0
  52. package/server/src/files/ignored.js +119 -0
  53. package/server/src/files/listing.js +82 -0
  54. package/server/src/files/path-rule.js +199 -0
  55. package/server/src/files/refusals.js +50 -0
  56. package/server/src/files/send-file.js +115 -0
  57. package/server/src/files/session-download.js +51 -0
  58. package/server/src/files/session-files.js +38 -0
  59. package/server/src/files/session-gate.js +53 -0
  60. package/server/src/folder-gate/client.js +314 -0
  61. package/server/src/folder-gate/disk.js +455 -0
  62. package/server/src/folder-gate/folders.js +23 -0
  63. package/server/src/folder-gate/gate.js +220 -0
  64. package/server/src/folder-gate/helper.js +118 -0
  65. package/server/src/folder-gate/install.js +27 -0
  66. package/server/src/folder-gate/relay-worker.js +147 -0
  67. package/server/src/folder-gate/types.js +115 -0
  68. package/server/src/folder-gate/wire.js +170 -0
  69. package/server/src/fs-browse.js +55 -23
  70. package/server/src/fs-mkdir.js +3 -1
  71. package/server/src/git-status.js +16 -7
  72. package/server/src/git-watch.js +130 -19
  73. package/server/src/git-work-tree.js +3 -3
  74. package/server/src/herdr/audit.js +1 -1
  75. package/server/src/herdr/client.js +2 -2
  76. package/server/src/herdr/commands/discover.js +21 -9
  77. package/server/src/herdr/dialogs/consent-gate.js +28 -8
  78. package/server/src/herdr/dialogs/decide/sources.js +5 -2
  79. package/server/src/herdr/dialogs/hook/contract.js +16 -9
  80. package/server/src/herdr/dialogs/index.js +12 -2
  81. package/server/src/herdr/dialogs/layer1/cycle.js +43 -7
  82. package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +166 -86
  83. package/server/src/herdr/dialogs/layer1/hook-list/session-facts.js +135 -0
  84. package/server/src/herdr/dialogs/layer1/screen-key.js +52 -0
  85. package/server/src/herdr/dialogs/layer1/version-gate.js +13 -5
  86. package/server/src/herdr/dialogs/no-hook.js +63 -0
  87. package/server/src/herdr/dialogs/router.js +21 -6
  88. package/server/src/herdr/dialogs/screen/block.js +10 -0
  89. package/server/src/herdr/dialogs/screen/parse.js +33 -3
  90. package/server/src/herdr/dialogs/screen/resolve.js +9 -7
  91. package/server/src/herdr/dialogs/screen-fallback.js +55 -0
  92. package/server/src/herdr/dialogs/shadow/alive.js +9 -8
  93. package/server/src/herdr/jsonl-follow.js +55 -14
  94. package/server/src/herdr/jsonl-pending.js +25 -1
  95. package/server/src/herdr/provenance.js +3 -3
  96. package/server/src/herdr/socket.js +25 -28
  97. package/server/src/herdr/supervisor.js +13 -10
  98. package/server/src/herdr/transcript-path.js +36 -0
  99. package/server/src/herdr/trust.js +11 -8
  100. package/server/src/herdr/uploads-registry.js +3 -2
  101. package/server/src/herdr/uploads.js +170 -47
  102. package/server/src/inbox/card.js +18 -9
  103. package/server/src/inbox/dialogs.js +40 -12
  104. package/server/src/inbox/heads.js +55 -0
  105. package/server/src/inbox/inbox.js +24 -2
  106. package/server/src/inbox/index.js +3 -1
  107. package/server/src/index.js +44 -21
  108. package/server/src/install/repair.js +8 -0
  109. package/server/src/iroh/listener.js +3 -0
  110. package/server/src/iroh/log-budget.js +1 -0
  111. package/server/src/iroh/socket.js +2 -1
  112. package/server/src/log-timestamps.js +9 -4
  113. package/server/src/notes/store.js +3 -2
  114. package/server/src/router.js +20 -2
  115. package/server/src/routes/devices.js +2 -2
  116. package/server/src/routes/inbox.js +91 -0
  117. package/server/src/routes/projects.js +5 -1
  118. package/server/src/routes/sessions.js +145 -18
  119. package/server/src/routes/system.js +9 -4
  120. package/server/src/safe-read.js +86 -1
  121. package/server/src/sessions/companion-scope.js +16 -7
  122. package/server/src/sessions/demo-modules.js +16 -0
  123. package/server/src/sessions/diff-measure.js +30 -0
  124. package/server/src/sessions/done-retention.js +57 -0
  125. package/server/src/sessions/launch-gate.js +2 -2
  126. package/server/src/sessions/manager.js +78 -190
  127. package/server/src/sessions/project-scan.js +9 -3
  128. package/server/src/sessions/ring-buffer.js +5 -3
  129. package/server/src/sessions/seen-marks.js +9 -6
  130. package/server/src/sessions/session-git.js +31 -2
  131. package/server/src/sessions/session-scope.js +30 -0
  132. package/server/src/sessions/session.js +19 -0
  133. package/server/src/sessions/state-sentences.js +1 -1
  134. package/server/src/sessions/waiting-line.js +72 -0
  135. package/server/src/sse.js +143 -10
  136. package/server/src/term/herdr-backend.js +2 -2
  137. package/server/src/term/index.js +2 -15
  138. package/server/src/term/registry.js +4 -3
  139. package/server/src/term/ws.js +9 -1
  140. package/server/src/version.js +30 -0
@@ -0,0 +1,170 @@
1
+ /**
2
+ * The line codec between the server and a folder helper: one JSON object per line, a request `{id, op, args}` and an
3
+ * answer `{id, ok: true, value}` or `{id, ok: false, error}`. Values JSON cannot carry travel as one-key tags:
4
+ * `Buffer` as `{"$b64": …}`, `bigint` as `{"$big": "…"}`, a file system error as `{"$err": …}` with `code`,
5
+ * `errno`, `syscall`, `path` and `dest`, and the port's `DiskStats` and `DiskDirent` snapshots. A plain object key
6
+ * that starts with `$` is refused, so data cannot pose as a tag. The module never touches the disk or a process.
7
+ */
8
+ import { DiskDirent, DiskStats, STATS_FIELDS, } from './types.js';
9
+ /** Every operation a request may name; the record keeps the list complete against `DiskOp`. */
10
+ const OPS = {
11
+ lstat: true, stat: true, readlink: true, realpath: true, realpathNative: true, readdir: true, readdirNames: true,
12
+ readHead: true, readdirByIdentity: true, openRead: true, read: true, close: true, mkdir: true, writeFile: true,
13
+ appendRegular: true, chmod: true, unlink: true, check: true,
14
+ };
15
+ const ENTRY_TYPES = new Set(['file', 'dir', 'link', 'fifo', 'socket', 'block', 'char', 'unknown']);
16
+ const ERROR_FIELDS = ['code', 'errno', 'syscall', 'path', 'dest'];
17
+ const isPlainObject = (value) => {
18
+ const proto = Object.getPrototypeOf(value);
19
+ return proto === Object.prototype || proto === null;
20
+ };
21
+ /** `value` as a JSON-safe tree; `undefined` drops out of objects. Throws on a value the wire cannot carry. */
22
+ export function toWire(value) {
23
+ if (value === undefined)
24
+ return undefined;
25
+ if (value === null || typeof value === 'boolean' || typeof value === 'string')
26
+ return value;
27
+ if (typeof value === 'number') {
28
+ if (!Number.isFinite(value))
29
+ throw new TypeError('folder gate wire: a number must be finite');
30
+ return value;
31
+ }
32
+ if (typeof value === 'bigint')
33
+ return { $big: value.toString() };
34
+ if (typeof value !== 'object')
35
+ throw new TypeError(`folder gate wire: cannot carry a ${typeof value}`);
36
+ if (Buffer.isBuffer(value))
37
+ return { $b64: value.toString('base64') };
38
+ if (value instanceof DiskStats) {
39
+ const fields = {};
40
+ for (const field of STATS_FIELDS)
41
+ fields[field] = value[field].toString();
42
+ return { $stats: fields };
43
+ }
44
+ if (value instanceof DiskDirent) {
45
+ return { $dirent: { name: toWire(value.name) ?? null, parentPath: value.parentPath, type: value.type } };
46
+ }
47
+ if (value instanceof Error) {
48
+ const error = { message: value.message };
49
+ for (const field of ERROR_FIELDS) {
50
+ const one = value[field];
51
+ if (typeof one === 'string' || typeof one === 'number')
52
+ error[field] = one;
53
+ }
54
+ return { $err: error };
55
+ }
56
+ if (Array.isArray(value))
57
+ return value.map((item) => toWire(item) ?? null);
58
+ if (!isPlainObject(value))
59
+ throw new TypeError('folder gate wire: cannot carry a class instance');
60
+ const out = {};
61
+ for (const [key, item] of Object.entries(value)) {
62
+ if (key.startsWith('$'))
63
+ throw new TypeError(`folder gate wire: the key ${key} is reserved for tags`);
64
+ const encoded = toWire(item);
65
+ if (encoded !== undefined)
66
+ out[key] = encoded;
67
+ }
68
+ return out;
69
+ }
70
+ function record(value, what) {
71
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
72
+ throw new TypeError(`folder gate wire: ${what} must be an object`);
73
+ }
74
+ return value;
75
+ }
76
+ function text(value, what) {
77
+ if (typeof value !== 'string')
78
+ throw new TypeError(`folder gate wire: ${what} must be a string`);
79
+ return value;
80
+ }
81
+ function decodeTag(tag, body) {
82
+ switch (tag) {
83
+ case '$b64':
84
+ return Buffer.from(text(body, '$b64'), 'base64');
85
+ case '$big':
86
+ return BigInt(text(body, '$big'));
87
+ case '$stats': {
88
+ const fields = record(body, '$stats');
89
+ const values = {};
90
+ for (const field of STATS_FIELDS)
91
+ values[field] = BigInt(text(fields[field], `$stats.${field}`));
92
+ return new DiskStats(values);
93
+ }
94
+ case '$dirent': {
95
+ const entry = record(body, '$dirent');
96
+ const name = fromWire(entry.name);
97
+ if (typeof name !== 'string' && !Buffer.isBuffer(name)) {
98
+ throw new TypeError('folder gate wire: $dirent.name must be a string or bytes');
99
+ }
100
+ const type = text(entry.type, '$dirent.type');
101
+ if (!ENTRY_TYPES.has(type))
102
+ throw new TypeError(`folder gate wire: unknown entry type ${type}`);
103
+ return new DiskDirent(name, text(entry.parentPath, '$dirent.parentPath'), type);
104
+ }
105
+ case '$err': {
106
+ const fields = record(body, '$err');
107
+ const error = new Error(text(fields.message, '$err.message'));
108
+ const target = error;
109
+ for (const field of ERROR_FIELDS) {
110
+ const one = fields[field];
111
+ if (typeof one === 'string' || typeof one === 'number')
112
+ target[field] = one;
113
+ }
114
+ return error;
115
+ }
116
+ default:
117
+ throw new TypeError(`folder gate wire: unknown tag ${tag}`);
118
+ }
119
+ }
120
+ /** The value a tree from {@link toWire} stands for. Throws on a malformed tree. */
121
+ export function fromWire(tree) {
122
+ if (tree === null || typeof tree !== 'object')
123
+ return tree;
124
+ if (Array.isArray(tree))
125
+ return tree.map(fromWire);
126
+ const entries = Object.entries(tree);
127
+ const [first] = entries;
128
+ if (entries.length === 1 && first !== undefined && first[0].startsWith('$'))
129
+ return decodeTag(first[0], first[1]);
130
+ const out = {};
131
+ for (const [key, item] of entries) {
132
+ if (key.startsWith('$'))
133
+ throw new TypeError(`folder gate wire: the key ${key} is reserved for tags`);
134
+ out[key] = fromWire(item);
135
+ }
136
+ return out;
137
+ }
138
+ /** JSON never writes a raw newline, so the result is one line; the caller adds the `\n`. */
139
+ const line = (message) => JSON.stringify(toWire(message));
140
+ function parsed(input) {
141
+ const message = record(JSON.parse(input), 'a message');
142
+ if (!Number.isSafeInteger(message.id))
143
+ throw new TypeError('folder gate wire: id must be an integer');
144
+ return message;
145
+ }
146
+ export function encodeRequest(id, op, args) {
147
+ return line({ id, op, args });
148
+ }
149
+ export function decodeRequest(input) {
150
+ const message = parsed(input);
151
+ const op = message.op;
152
+ if (typeof op !== 'string' || !Object.hasOwn(OPS, op))
153
+ throw new TypeError('folder gate wire: unknown op');
154
+ return { id: message.id, op: op, args: fromWire(message.args) };
155
+ }
156
+ export function encodeResponse(id, answer) {
157
+ return answer.ok ? line({ id, ok: true, value: answer.value }) : line({ id, ok: false, error: answer.error });
158
+ }
159
+ export function decodeResponse(input) {
160
+ const message = parsed(input);
161
+ const id = message.id;
162
+ if (message.ok === true)
163
+ return { id, ok: true, value: fromWire(message.value) };
164
+ if (message.ok !== false)
165
+ throw new TypeError('folder gate wire: ok must be a boolean');
166
+ const error = fromWire(message.error);
167
+ if (!(error instanceof Error))
168
+ throw new TypeError('folder gate wire: an error answer must carry an error');
169
+ return { id, ok: false, error: error };
170
+ }
@@ -22,12 +22,15 @@
22
22
  * korzeni; filtr `isDirectory()` w wierszach chronił listę, nie parametr żądania; then `stat` (not a
23
23
  * directory → 404) and `readdir` (no permission → an empty list).
24
24
  *
25
+ * A guarded folder of home that the folder gate holds closed (`FolderGateError` from the walk or the port) is a 404
26
+ * with the sentence of the folder's state, the status of a path that cannot be read, never an empty listing.
27
+ *
25
28
  * A row is shown only for a folder in the work area, so with the root `~` the protected folders of home neither
26
29
  * appear nor get the `stat` of their `.git`. The listing of a directory carries `git` and `history` of the
27
30
  * directory itself, and `canCreate` when the route gives it; the roots level carries none of them. Creating a
28
31
  * directory is `fs-mkdir.ts`, which reuses the parent steps and the row rule below.
29
32
  */
30
- import { readdir, realpath, stat } from 'node:fs/promises';
33
+ import { stat } from 'node:fs/promises';
31
34
  import os from 'node:os';
32
35
  import path from 'node:path';
33
36
  import { MAX_DIR_ENTRIES } from '@rarog/shared';
@@ -35,6 +38,8 @@ import { say } from '@rarog/shared/sentences';
35
38
  import { expandTilde, isInsideAnyRoot } from './config.js';
36
39
  import { insideWorkArea, resolveInWorkArea } from './config/work-area.js';
37
40
  import { defaultStoreRoot, projectSlug } from './cli-store.js';
41
+ import { DIRECT_DISK } from './folder-gate/disk.js';
42
+ import { FolderGateError } from './folder-gate/types.js';
38
43
  /** Katalogi, których nigdy nie pokazujemy — szum, nie projekty. */
39
44
  const SKIPPED_DIRS = new Set(['node_modules']);
40
45
  /** Kod błędu odpowiedzi 400 (kontrakt UI: inline błąd pod polem ścieżki). */
@@ -42,8 +47,26 @@ export const PATH_NOT_ALLOWED = 'path-not-allowed';
42
47
  function deny(sentence) {
43
48
  return { ok: false, status: 400, error: PATH_NOT_ALLOWED, sentence };
44
49
  }
50
+ /** A closed guarded folder: the status of a path that cannot be read, with the sentence of the folder's state. */
51
+ function closedFolder(error) {
52
+ return { ok: false, status: 404, error: 'not-found', sentence: error.sentence };
53
+ }
54
+ /** The value of a port call, or the refusal of a closed folder; any other error gives `fallback`. */
55
+ async function orClosed(call, fallback) {
56
+ return call.catch((error) => (error instanceof FolderGateError ? error : fallback));
57
+ }
45
58
  /** Czy katalog istnieje? Każdy błąd (ENOENT, EACCES, ELOOP) znaczy „nie ma znacznika". */
46
- async function exists(candidate) {
59
+ async function exists(candidate, disk) {
60
+ try {
61
+ await disk.call('stat', { path: candidate });
62
+ return true;
63
+ }
64
+ catch {
65
+ return false;
66
+ }
67
+ }
68
+ /** The same question in the CLI store under `~/.claude`, which never lies in the work area. */
69
+ async function inStore(candidate) {
47
70
  try {
48
71
  await stat(candidate);
49
72
  return true;
@@ -53,20 +76,20 @@ async function exists(candidate) {
53
76
  }
54
77
  }
55
78
  /** Znaczniki wiersza: repo gita i historia sesji CLI dla tego katalogu. */
56
- async function markers(dir, storeRoot) {
79
+ async function markers(dir, storeRoot, disk) {
57
80
  const [git, history] = await Promise.all([
58
- exists(path.join(dir, '.git')),
59
- exists(path.join(storeRoot, projectSlug(dir))),
81
+ exists(path.join(dir, '.git'), disk),
82
+ inStore(path.join(storeRoot, projectSlug(dir))),
60
83
  ]);
61
84
  return { git, history };
62
85
  }
63
- export async function toEntry(dir, name, storeRoot) {
64
- return { name, path: dir, ...await markers(dir, storeRoot) };
86
+ export async function toEntry(dir, name, storeRoot, disk = DIRECT_DISK) {
87
+ return { name, path: dir, ...await markers(dir, storeRoot, disk) };
65
88
  }
66
- async function toEntries(dirs, storeRoot) {
89
+ async function toEntries(dirs, storeRoot, disk) {
67
90
  // Podkatalogi jednego katalogu mają z definicji unikalne nazwy — tu basename WYSTARCZA
68
91
  // i ujednoznacznianie z `rootNames()` byłoby tylko szumem („willow" → „Projects/willow").
69
- return Promise.all(dirs.map((dir) => toEntry(dir, path.basename(dir), storeRoot)));
92
+ return Promise.all(dirs.map((dir) => toEntry(dir, path.basename(dir), storeRoot, disk)));
70
93
  }
71
94
  /**
72
95
  * Nazwy korzeni — jedyne miejsce, w którym basename może się POWTÓRZYĆ.
@@ -102,13 +125,13 @@ function rootNames(roots) {
102
125
  * Kolejność jest ta z konfiguracji, a nie alfabetyczna: korzenie wpisuje człowiek i to ON
103
126
  * decyduje, co jest pierwsze. Duplikaty odsiewamy po ścieżce.
104
127
  */
105
- async function rootListing(roots, storeRoot) {
128
+ async function rootListing(roots, storeRoot, disk) {
106
129
  const unique = [...new Set(roots.map((root) => path.resolve(root)))];
107
130
  const names = rootNames(unique);
108
131
  return {
109
132
  path: null,
110
133
  parent: null,
111
- entries: await Promise.all(unique.map((dir, index) => toEntry(dir, names[index] ?? path.basename(dir), storeRoot))),
134
+ entries: await Promise.all(unique.map((dir, index) => toEntry(dir, names[index] ?? path.basename(dir), storeRoot, disk))),
112
135
  truncated: false,
113
136
  };
114
137
  }
@@ -118,6 +141,7 @@ async function rootListing(roots, storeRoot) {
118
141
  */
119
142
  export async function resolveListedDir(raw, opts) {
120
143
  const home = opts.home ?? os.homedir();
144
+ const disk = opts.disk ?? DIRECT_DISK;
121
145
  const roots = opts.roots.map((root) => path.resolve(expandTilde(root, home)));
122
146
  const expanded = expandTilde(raw, home);
123
147
  if (!path.isAbsolute(expanded)) {
@@ -141,21 +165,24 @@ export async function resolveListedDir(raw, opts) {
141
165
  * (klasyk: `/tmp` na macOS) odcinałby własne, legalne podkatalogi. The directory itself is resolved by the walk,
142
166
  * one segment at a time, which stops before an excluded folder; only home and the roots go through `realpath`.
143
167
  */
144
- const realHome = await realpath(home).catch(() => home);
145
- const realRoots = await Promise.all(roots.map(async (root) => realpath(root).catch(() => root)));
168
+ const realHome = await disk.call('realpathNative', { path: home }).catch(() => home);
169
+ const realRoots = await Promise.all(roots.map(async (root) => disk.call('realpathNative', { path: root }).catch(() => root)));
146
170
  const walked = resolveInWorkArea(dir, realRoots, realHome, opts.walk);
147
171
  if (walked.kind === 'missing') {
148
172
  return { ok: false, status: 404, error: 'not-found', sentence: say('rest.cwd-not-found') };
149
173
  }
150
- if (walked.kind === 'excluded')
151
- return deny(say('rest.cwd-symlink-escape'));
174
+ if (walked.kind === 'excluded') {
175
+ return walked.closed === undefined ? deny(say('rest.cwd-symlink-escape')) : closedFolder(walked.closed);
176
+ }
152
177
  /*
153
178
  * The walk keeps the letter case of the request, while `realpath` gives the roots in the case stored on disk, so on
154
179
  * the default macOS disk a root written in another case refused its own folders. The walked path has no symlink
155
180
  * left and no excluded folder on it, so the same `realpath` as for the roots reads nothing new and gives the case
156
181
  * the comparison needs.
157
182
  */
158
- const realDir = await realpath(walked.path).catch(() => null);
183
+ const realDir = await orClosed(disk.call('realpathNative', { path: walked.path }), null);
184
+ if (realDir instanceof FolderGateError)
185
+ return closedFolder(realDir);
159
186
  if (realDir === null) {
160
187
  return { ok: false, status: 404, error: 'not-found', sentence: say('rest.cwd-not-found') };
161
188
  }
@@ -192,26 +219,31 @@ export async function browseDirectory(rawPath, opts) {
192
219
  const home = opts.home ?? os.homedir();
193
220
  const storeRoot = opts.storeRoot ?? defaultStoreRoot();
194
221
  const maxEntries = opts.maxEntries ?? MAX_DIR_ENTRIES;
222
+ const disk = opts.disk ?? DIRECT_DISK;
195
223
  const roots = opts.roots.map((root) => path.resolve(expandTilde(root, home)));
196
224
  const raw = (rawPath ?? '').trim();
197
225
  if (raw === '')
198
- return { ok: true, listing: await rootListing(roots, storeRoot) };
226
+ return { ok: true, listing: await rootListing(roots, storeRoot, disk) };
199
227
  const ctx = await resolveListedDir(raw, opts);
200
228
  if (!ctx.ok)
201
229
  return ctx;
202
230
  const { dir, realDir } = ctx;
203
- const info = await stat(realDir).catch(() => null);
231
+ const info = await orClosed(disk.call('stat', { path: realDir }), null);
232
+ if (info instanceof FolderGateError)
233
+ return closedFolder(info);
204
234
  if (info === null || !info.isDirectory()) {
205
235
  return { ok: false, status: 404, error: 'not-found', sentence: say('rest.cwd-not-found') };
206
236
  }
207
237
  // Brak uprawnień do odczytu katalogu NIE jest błędem żądania: użytkownik ma zobaczyć pusty
208
- // katalog i móc się z niego cofnąć, a nie czerwony komunikat.
209
- const dirents = await readdir(dir, { withFileTypes: true }).catch(() => []);
238
+ // katalog i móc się z niego cofnąć, a nie czerwony komunikat. A closed guarded folder is a refusal.
239
+ const dirents = await orClosed(disk.call('readdir', { path: dir, encoding: 'utf8' }), []);
240
+ if (dirents instanceof FolderGateError)
241
+ return closedFolder(dirents);
210
242
  const names = dirents
211
243
  // `isDirectory()` jest fałszem dla dowiązania — symlinków świadomie NIE rozwijamy, bo
212
244
  // dowiązanie do `/` wyprowadziłoby przeglądarkę poza korzenie jednym tapnięciem.
213
245
  .filter((entry) => entry.isDirectory())
214
- .map((entry) => entry.name)
246
+ .map((entry) => String(entry.name))
215
247
  .filter((name) => isListedChild(ctx, name))
216
248
  .sort((a, b) => a.localeCompare(b, 'pl', { sensitivity: 'base' }));
217
249
  const truncated = names.length > maxEntries;
@@ -223,9 +255,9 @@ export async function browseDirectory(rawPath, opts) {
223
255
  path: dir,
224
256
  // Korzeń → `null`: cofnięcie wraca na poziom korzeni, a nie do katalogu nad korzeniem.
225
257
  parent: isRoot ? null : path.dirname(dir),
226
- ...await markers(dir, storeRoot),
258
+ ...await markers(dir, storeRoot, disk),
227
259
  ...(opts.canCreate === undefined ? {} : { canCreate: opts.canCreate }),
228
- entries: await toEntries(shown.map((name) => path.join(dir, name)), storeRoot),
260
+ entries: await toEntries(shown.map((name) => path.join(dir, name)), storeRoot, disk),
229
261
  truncated,
230
262
  },
231
263
  };
@@ -108,7 +108,9 @@ export async function makeDirectory(body, deps) {
108
108
  }
109
109
  }
110
110
  async function inSlot(parent, name, deps) {
111
- const ctx = await resolveListedDir(parent, { roots: deps.config.projectRoots, home: deps.home, walk: deps.walk });
111
+ const ctx = await resolveListedDir(parent, {
112
+ roots: deps.config.projectRoots, home: deps.home, walk: deps.walk, disk: deps.disk,
113
+ });
112
114
  if (!ctx.ok)
113
115
  return refused(deps, ctx);
114
116
  // From here to the start of the child: no `fs` call and no `await`, so the child gets `realDir` as checked.
@@ -15,10 +15,10 @@
15
15
  * timera z trailing edge, bo event `git-status` jest kosmetyczny, a nie transakcyjny.
16
16
  */
17
17
  import { spawn } from 'node:child_process';
18
- import { lstat, readlink, realpath } from 'node:fs/promises';
19
18
  import { dirname, join, sep } from 'node:path';
20
19
  import { MAX_DIFF_PATCH_BYTES } from '@rarog/shared';
21
20
  import { CONFIG_NAMES_ENCODING, CONFIG_NAMES_READ_CAP_BYTES, filterDriverNames, withFilterDriversOff, } from './git-config-guard.js';
21
+ import { DIRECT_DISK, closedFolderOf } from './folder-gate/disk.js';
22
22
  import { SANDBOX_EXEC, gitSandboxLogLine, probeGitSandbox } from './git-sandbox.js';
23
23
  import { gitWorkTree } from './git-work-tree.js';
24
24
  export const DEFAULT_THROTTLE_MS = 3_000;
@@ -201,7 +201,7 @@ const GIT_GLOBAL_OPTIONS = ['--literal-pathspecs'];
201
201
  * git czyta jeszcze jako opcję globalną, więc „podkomenda” `-c` z `rest` = `['core.fsmonitor=…', …]` stałaby
202
202
  * po osłonach i je nadpisała. Wbudowanych podkomend nie zasłoni też alias z konfiguracji repo.
203
203
  */
204
- export const GIT_SUBCOMMANDS = ['status', 'log', 'diff', 'ls-files', 'rev-parse'];
204
+ export const GIT_SUBCOMMANDS = ['status', 'log', 'diff', 'ls-files', 'rev-parse', 'check-ignore'];
205
205
  /**
206
206
  * The two options that pin a git process to the repository of a read:
207
207
  *
@@ -325,7 +325,8 @@ function guardedGitEnv(env) {
325
325
  }
326
326
  /**
327
327
  * Oldest git the runner starts `diff` with: `GIT_NO_LAZY_FETCH` works from git 2.44. With an older git `diff` is
328
- * refused, because a lazy fetch was measured on `diff` only; `status`, `log`, `ls-files` and `rev-parse` still run.
328
+ * refused, because a lazy fetch was measured on `diff` only; `status`, `log`, `ls-files`, `rev-parse` and
329
+ * `check-ignore` still run.
329
330
  */
330
331
  const MIN_GIT_VERSION = { major: 2, minor: 44 };
331
332
  /** Read cap of `git version` and `git --exec-path` (one line each). */
@@ -460,12 +461,17 @@ export function spawnGitArgs(env, timeoutMs = DEFAULT_TIMEOUT_MS, maxBytes = DIF
460
461
  * - no directory up from `cwd` has `.git`: exit code 128, what git answers outside a repository. Git does not run,
461
462
  * because a `.git` created between the lookup and its start would come with its own `core.worktree`;
462
463
  * - `cwd` cannot be resolved, or the command is not one the runner takes ({@link gitArgv} throws): `spawnFailed`,
463
- * as for a process that did not start.
464
+ * as for a process that did not start;
465
+ * - `cwd` or its work tree lies in a guarded folder the folder gate holds closed: `spawnFailed` with `EFOLDERGATE`.
464
466
  * The config names read ({@link filterDriversOff}) runs in the same `cwd` with the same pin.
465
467
  */
466
468
  async function bindWorkTree(command, cwd) {
467
469
  try {
468
470
  const workTree = await gitWorkTree(cwd);
471
+ // Git in a guarded folder the folder gate holds closed would wait for the consent window; it does not start.
472
+ const closed = closedFolderOf(cwd) ?? (workTree === null ? null : closedFolderOf(workTree));
473
+ if (closed !== null)
474
+ return { refused: { ok: false, stdout: '', spawnFailed: closed.code } };
469
475
  if (workTree === null)
470
476
  return { refused: { ok: false, stdout: '', exitCode: 128 } };
471
477
  // Built field by field: a `workTree` or a `probe` in the caller's object does not reach the argv.
@@ -789,12 +795,15 @@ export async function probeUntracked(cwd, path) {
789
795
  const full = join(cwd, path);
790
796
  // Katalog nadrzędny po rozwiązaniu dowiązań ma leżeć w katalogu sesji: `ls-files` nie schodzi
791
797
  // w dowiązania, więc katalog podmieniony na dowiązanie PO wypisaniu listy odpada tutaj.
792
- const [root, parent] = await Promise.all([realpath(cwd), realpath(dirname(full))]);
798
+ const [root, parent] = await Promise.all([
799
+ DIRECT_DISK.call('realpathNative', { path: cwd }),
800
+ DIRECT_DISK.call('realpathNative', { path: dirname(full) }),
801
+ ]);
793
802
  if (parent !== root && !parent.startsWith(root + sep))
794
803
  return { kind: 'other' };
795
- const info = await lstat(full);
804
+ const info = await DIRECT_DISK.call('lstat', { path: full });
796
805
  if (info.isSymbolicLink())
797
- return { kind: 'symlink', target: await readlink(full) };
806
+ return { kind: 'symlink', target: await DIRECT_DISK.call('readlink', { path: full }) };
798
807
  return info.isFile() ? { kind: 'file' } : { kind: 'other' };
799
808
  }
800
809
  catch {
@@ -30,11 +30,17 @@
30
30
  * Awaria watchera (EMFILE w piaskownicy, katalog zniknął) jest CICHA: schodzimy do
31
31
  * dotychczasowych wyzwalaczy, bez logu przy każdym zdarzeniu. Ponowna próba dopiero wtedy,
32
32
  * gdy repo zostanie zwolnione (ostatni `unwatch`) i ktoś je znów zarejestruje.
33
+ *
34
+ * `fs.watch` runs in the server process and, in a macOS-guarded folder of home, waits for the consent window. So a
35
+ * repo whose watched directories lie in such a folder, in any spelling of home or through a symlink, is watched only
36
+ * while the folder gate holds every one of those folders `open`: an unknown folder is checked first, a closed one
37
+ * pauses the repo (counts and directories stay), and `open` starts the watchers again with one read, because changes
38
+ * made meanwhile were not seen.
33
39
  */
34
40
  import { watch } from 'node:fs';
35
- import { statSync } from 'node:fs';
36
41
  import { dirname, isAbsolute, resolve } from 'node:path';
37
- import { readRegularFileSync } from './safe-read.js';
42
+ import { DIRECT_DISK, guardedFolderOf } from './folder-gate/disk.js';
43
+ import { folderGate } from './folder-gate/install.js';
38
44
  /** Zwłoka między pierwszym zdarzeniem burzy a odczytem (ms) — patrz reguła 2 w nagłówku. */
39
45
  export const DEFAULT_GIT_WATCH_DEBOUNCE_MS = 750;
40
46
  /** Najkrótszy odstęp między dwoma odczytami TEGO SAMEGO repo (ms). */
@@ -83,7 +89,7 @@ export function findGitDirs(cwd) {
83
89
  */
84
90
  function readPointer(path) {
85
91
  try {
86
- const read = readRegularFileSync(path, { maxBytes: GIT_POINTER_MAX_BYTES, followSymlink: false });
92
+ const read = DIRECT_DISK.sync('readHead', { path, maxBytes: GIT_POINTER_MAX_BYTES, followSymlink: false });
87
93
  return read === null || read.truncated ? null : read.bytes.toString('utf8');
88
94
  }
89
95
  catch {
@@ -97,7 +103,7 @@ function readPointer(path) {
97
103
  */
98
104
  function isDirectory(path) {
99
105
  try {
100
- return statSync(path).isDirectory();
106
+ return DIRECT_DISK.sync('stat', { path }).isDirectory();
101
107
  }
102
108
  catch {
103
109
  return false;
@@ -106,7 +112,7 @@ function isDirectory(path) {
106
112
  function resolveGitDir(candidate, base) {
107
113
  let stat;
108
114
  try {
109
- stat = statSync(candidate);
115
+ stat = DIRECT_DISK.sync('stat', { path: candidate });
110
116
  }
111
117
  catch {
112
118
  return null;
@@ -148,6 +154,8 @@ export class GitRepoWatcher {
148
154
  #repos = new Map();
149
155
  /** cwd → klucz repo (`gitDir`); `null` = katalog bez gita (też liczony, żeby `unwatch` był symetryczny). */
150
156
  #byCwd = new Map();
157
+ #gate;
158
+ #offGate;
151
159
  #closed = false;
152
160
  constructor(opts) {
153
161
  this.#onChange = opts.onChange;
@@ -156,6 +164,8 @@ export class GitRepoWatcher {
156
164
  this.#minIntervalMs = opts.minIntervalMs ?? DEFAULT_GIT_WATCH_MIN_INTERVAL_MS;
157
165
  this.#watchFn = opts.watchFn ?? watch;
158
166
  this.#now = opts.now ?? (() => Date.now());
167
+ this.#gate = opts.gate ?? folderGate();
168
+ this.#offGate = this.#gate.onChange((folder) => { this.#folderChanged(folder); });
159
169
  }
160
170
  /** Repozytoria pod obserwacją (diagnostyka i testy). */
161
171
  get repoCount() {
@@ -167,7 +177,7 @@ export class GitRepoWatcher {
167
177
  if (entry === undefined || entry.gitDir === null)
168
178
  return false;
169
179
  const repo = this.#repos.get(entry.gitDir);
170
- return repo !== undefined && !repo.failed;
180
+ return repo !== undefined && !repo.failed && !repo.paused;
171
181
  }
172
182
  watch(cwd) {
173
183
  if (this.#closed)
@@ -182,24 +192,42 @@ export class GitRepoWatcher {
182
192
  * a `git init` przyszedł później z terminala. Każdy kolejny `watch` takiego cwd pyta
183
193
  * dysk od nowa (tani `stat`) i dopiero znalezione repo dostaje watcher.
184
194
  */
185
- const dirs = findGitDirs(cwd);
186
- const gitDir = dirs?.gitDir ?? null;
187
- if (known !== undefined) {
188
- known.count += 1;
189
- known.gitDir = gitDir;
195
+ let entry = known;
196
+ if (entry !== undefined) {
197
+ entry.count += 1;
190
198
  }
191
199
  else {
192
- this.#byCwd.set(cwd, { gitDir, count: 1 });
200
+ entry = { gitDir: null, count: 1 };
201
+ this.#byCwd.set(cwd, entry);
193
202
  }
194
- if (dirs === null || gitDir === null)
195
- return;
203
+ this.#attach(cwd, entry);
204
+ }
205
+ /**
206
+ * Finds the repo of `cwd` and joins it, making and starting the repo when it is new; `null` without a repo. A pointer
207
+ * file (`.git` of a worktree, `commondir`) in a guarded folder that is not open cannot be read, so the folder's
208
+ * `open` asks again ({@link #folderChanged}).
209
+ */
210
+ #attach(cwd, entry) {
211
+ const dirs = findGitDirs(cwd);
212
+ entry.gitDir = dirs?.gitDir ?? null;
213
+ if (dirs === null)
214
+ return null;
215
+ const gitDir = dirs.gitDir;
196
216
  let repo = this.#repos.get(gitDir);
197
217
  if (repo === undefined) {
198
- repo = { watchers: [], cwds: new Set(), timer: null, lastFiredAt: null, failed: false };
218
+ const targets = dirs.commonDir === null ? [gitDir] : [gitDir, dirs.commonDir];
219
+ repo = {
220
+ watchers: [], cwds: new Set(), timer: null, lastFiredAt: null, failed: false, targets,
221
+ folders: this.#foldersOf(targets), paused: false,
222
+ };
199
223
  this.#repos.set(gitDir, repo);
200
- this.#start(gitDir, dirs, repo);
224
+ if (this.#allOpen(repo))
225
+ this.#start(gitDir, repo);
226
+ else
227
+ repo.paused = true;
201
228
  }
202
229
  repo.cwds.add(cwd);
230
+ return repo;
203
231
  }
204
232
  unwatch(cwd) {
205
233
  const known = this.#byCwd.get(cwd);
@@ -222,14 +250,97 @@ export class GitRepoWatcher {
222
250
  }
223
251
  close() {
224
252
  this.#closed = true;
253
+ this.#offGate();
225
254
  for (const repo of this.#repos.values())
226
255
  this.#stop(repo);
227
256
  this.#repos.clear();
228
257
  this.#byCwd.clear();
229
258
  }
230
- #start(gitDir, dirs, repo) {
231
- const targets = dirs.commonDir === null ? [gitDir] : [gitDir, dirs.commonDir];
232
- for (const dir of targets) {
259
+ /**
260
+ * The guarded folders `targets` lie in, as written or where they resolve (`realpath`, and `realpathNative` in the
261
+ * letter case of the disk): `fs.watch` follows a symlink, and the gate judges text only. Each form is judged by the
262
+ * port's rule, which knows every spelling of home (as written, on disk, another letter case), not only home as the
263
+ * gate was given it. Both are metadata, which never waits for a consent window; when neither resolves, the text
264
+ * alone decides.
265
+ */
266
+ #foldersOf(targets) {
267
+ if (!this.#gate.enabled)
268
+ return [];
269
+ const folders = new Set();
270
+ for (const target of targets) {
271
+ const forms = [target];
272
+ for (const op of ['realpath', 'realpathNative']) {
273
+ try {
274
+ forms.push(DIRECT_DISK.sync(op, { path: target }));
275
+ }
276
+ catch {
277
+ // The other forms decide.
278
+ }
279
+ }
280
+ for (const form of forms) {
281
+ const folder = this.#gate.stateOf(form)?.folder ?? guardedFolderOf(form)?.folder;
282
+ if (folder !== undefined)
283
+ folders.add(folder);
284
+ }
285
+ }
286
+ return [...folders];
287
+ }
288
+ /** Whether every guarded folder of the repo is open; an unknown one gets a check, whose `open` starts the repo. */
289
+ #allOpen(repo) {
290
+ let ready = true;
291
+ for (const folder of repo.folders) {
292
+ const state = this.#gate.stateOf(folder)?.state;
293
+ if (state === 'open')
294
+ continue;
295
+ ready = false;
296
+ if (state === 'unknown')
297
+ void this.#gate.check(folder, 0);
298
+ }
299
+ return ready;
300
+ }
301
+ /**
302
+ * A folder changed state: repos in it pause when it closes and start again, with one read, when all their folders
303
+ * are open. On `open` the pointer files there can be read: a directory in the folder that found no repo looks again,
304
+ * and a paused repo reads its `commondir` again, so a worktree whose shared refs lie in the folder watches them too.
305
+ */
306
+ #folderChanged(folder) {
307
+ if (this.#closed)
308
+ return;
309
+ if (this.#gate.stateOf(folder)?.state === 'open') {
310
+ for (const [cwd, entry] of this.#byCwd) {
311
+ if (entry.gitDir !== null || !this.#foldersOf([cwd]).includes(folder))
312
+ continue;
313
+ const repo = this.#attach(cwd, entry);
314
+ if (repo !== null && entry.gitDir !== null && !repo.paused)
315
+ this.#bump(entry.gitDir, repo);
316
+ }
317
+ }
318
+ for (const [gitDir, repo] of [...this.#repos]) {
319
+ if (repo.failed)
320
+ continue;
321
+ // The `commondir` file lies in `gitDir`; read only while its folder is open, so no read waits here.
322
+ if (repo.paused && this.#foldersOf([gitDir]).every((one) => this.#gate.stateOf(one)?.state === 'open')) {
323
+ const commonDir = readCommonDir(gitDir);
324
+ repo.targets = commonDir === null ? [gitDir] : [gitDir, commonDir];
325
+ repo.folders = this.#foldersOf(repo.targets);
326
+ }
327
+ if (!repo.folders.includes(folder))
328
+ continue;
329
+ if (this.#allOpen(repo)) {
330
+ if (!repo.paused)
331
+ continue;
332
+ repo.paused = false;
333
+ this.#start(gitDir, repo);
334
+ this.#bump(gitDir, repo);
335
+ }
336
+ else if (!repo.paused) {
337
+ repo.paused = true;
338
+ this.#stop(repo);
339
+ }
340
+ }
341
+ }
342
+ #start(gitDir, repo) {
343
+ for (const dir of repo.targets) {
233
344
  try {
234
345
  // `persistent: false` — obserwator gita nie ma prawa trzymać procesu przy życiu.
235
346
  const watcher = this.#watchFn(dir, { recursive: true, persistent: false }, (_event, name) => {