@rarog/server 1.1.0-beta.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 (93) 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/config/protected-dirs.js +2 -0
  21. package/server/src/config/roots.js +13 -8
  22. package/server/src/config/work-area.js +36 -12
  23. package/server/src/config-env.js +9 -0
  24. package/server/src/config.js +17 -1
  25. package/server/src/demo/control.js +9 -1
  26. package/server/src/drivers/herdr/consent-no-hook.js +103 -8
  27. package/server/src/drivers/herdr/screen-fallback.js +246 -0
  28. package/server/src/drivers/herdr-driver.js +78 -9
  29. package/server/src/files/file-index.js +5 -3
  30. package/server/src/files/listing.js +8 -2
  31. package/server/src/files/path-rule.js +95 -41
  32. package/server/src/files/refusals.js +14 -0
  33. package/server/src/files/session-gate.js +11 -6
  34. package/server/src/folder-gate/client.js +314 -0
  35. package/server/src/folder-gate/disk.js +455 -0
  36. package/server/src/folder-gate/folders.js +23 -0
  37. package/server/src/folder-gate/gate.js +220 -0
  38. package/server/src/folder-gate/helper.js +118 -0
  39. package/server/src/folder-gate/install.js +27 -0
  40. package/server/src/folder-gate/relay-worker.js +147 -0
  41. package/server/src/folder-gate/types.js +115 -0
  42. package/server/src/folder-gate/wire.js +170 -0
  43. package/server/src/fs-browse.js +55 -23
  44. package/server/src/fs-mkdir.js +3 -1
  45. package/server/src/git-status.js +13 -5
  46. package/server/src/git-watch.js +130 -19
  47. package/server/src/git-work-tree.js +3 -3
  48. package/server/src/herdr/client.js +2 -2
  49. package/server/src/herdr/commands/discover.js +21 -9
  50. package/server/src/herdr/dialogs/consent-gate.js +28 -8
  51. package/server/src/herdr/dialogs/decide/sources.js +5 -2
  52. package/server/src/herdr/dialogs/hook/contract.js +1 -1
  53. package/server/src/herdr/dialogs/index.js +7 -2
  54. package/server/src/herdr/dialogs/layer1/cycle.js +43 -7
  55. package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +34 -27
  56. package/server/src/herdr/dialogs/layer1/screen-key.js +52 -0
  57. package/server/src/herdr/dialogs/router.js +21 -6
  58. package/server/src/herdr/dialogs/screen/parse.js +23 -2
  59. package/server/src/herdr/dialogs/screen/resolve.js +9 -7
  60. package/server/src/herdr/dialogs/screen-fallback.js +55 -0
  61. package/server/src/herdr/dialogs/shadow/alive.js +9 -8
  62. package/server/src/herdr/jsonl-follow.js +55 -14
  63. package/server/src/herdr/provenance.js +3 -3
  64. package/server/src/herdr/socket.js +25 -28
  65. package/server/src/herdr/supervisor.js +13 -10
  66. package/server/src/herdr/transcript-path.js +36 -0
  67. package/server/src/herdr/trust.js +11 -8
  68. package/server/src/herdr/uploads-registry.js +3 -2
  69. package/server/src/herdr/uploads.js +170 -47
  70. package/server/src/index.js +22 -3
  71. package/server/src/iroh/listener.js +3 -0
  72. package/server/src/iroh/log-budget.js +1 -0
  73. package/server/src/iroh/socket.js +2 -1
  74. package/server/src/notes/store.js +3 -2
  75. package/server/src/router.js +13 -1
  76. package/server/src/routes/projects.js +5 -1
  77. package/server/src/routes/sessions.js +10 -4
  78. package/server/src/routes/system.js +4 -0
  79. package/server/src/safe-read.js +12 -12
  80. package/server/src/sessions/companion-scope.js +10 -5
  81. package/server/src/sessions/done-retention.js +57 -0
  82. package/server/src/sessions/launch-gate.js +2 -2
  83. package/server/src/sessions/manager.js +35 -59
  84. package/server/src/sessions/project-scan.js +9 -3
  85. package/server/src/sessions/ring-buffer.js +8 -21
  86. package/server/src/sessions/session-git.js +31 -2
  87. package/server/src/sessions/session.js +1 -1
  88. package/server/src/sessions/state-sentences.js +1 -1
  89. package/server/src/sse.js +121 -22
  90. package/server/src/term/herdr-backend.js +2 -2
  91. package/server/src/term/index.js +2 -15
  92. package/server/src/term/registry.js +4 -3
  93. package/server/src/term/ws.js +9 -1
@@ -204,11 +204,14 @@ export async function routeSessions(ctx, req, res, rq) {
204
204
  return true;
205
205
  }
206
206
  // Diff jest READ-ONLY, więc jest GET-em — i musi być obsłużony PRZED strażnikiem POST-a.
207
+ // Git may outlast a revocation, so the device is checked again before the answer, as on all three diff routes.
207
208
  if (action === 'diff' && segments.length === 4) {
208
209
  if (method !== 'GET')
209
210
  return methodNotAllowed(res, 'GET');
210
211
  return runManagerAction(res, log, secrets, async () => {
211
- sendJson(res, 200, await manager.diff(sessionId));
212
+ const diff = await manager.diff(sessionId);
213
+ if (recheckDevice(req, res, 'while reading the diff of'))
214
+ sendJson(res, 200, diff);
212
215
  });
213
216
  }
214
217
  /*
@@ -223,10 +226,9 @@ export async function routeSessions(ctx, req, res, rq) {
223
226
  return methodNotAllowed(res, 'GET');
224
227
  const list = segments[4] === 'files';
225
228
  const filePath = url.searchParams.get('path') ?? '';
229
+ let answer;
226
230
  try {
227
- sendJson(res, 200, list
228
- ? await manager.diffFiles(sessionId)
229
- : await manager.diffFile(sessionId, filePath));
231
+ answer = list ? await manager.diffFiles(sessionId) : await manager.diffFile(sessionId, filePath);
230
232
  }
231
233
  catch (err) {
232
234
  const status = diffErrorStatus(err);
@@ -234,7 +236,11 @@ export async function routeSessions(ctx, req, res, rq) {
234
236
  log.error(`manager action failed: ${redact(err, secrets)}`);
235
237
  if (!res.headersSent)
236
238
  sendFailure(res, status, err, 'diff');
239
+ return true;
237
240
  }
241
+ if (!recheckDevice(req, res, 'while reading the diff of'))
242
+ return true;
243
+ sendJson(res, 200, answer);
238
244
  return true;
239
245
  }
240
246
  /*
@@ -120,6 +120,8 @@ export async function routeSystem(ctx, req, res, rq) {
120
120
  * Endpoint nie przyjmuje żadnych parametrów i nigdy ich nie przyjmie: wszystko, co
121
121
  * konfiguruje strumień (region, model, format, limity), jest decyzją serwera. Ciało
122
122
  * czytamy wyłącznie po to, żeby domknąć żądanie i utrzymać limit 64 kB.
123
+ * After the key arrives the device is checked again: a device revoked meanwhile gets 401 and the key is dropped (it
124
+ * expires on its own).
123
125
  */
124
126
  if (pathname === '/api/voice/token') {
125
127
  if (method !== 'POST')
@@ -132,6 +134,8 @@ export async function routeSystem(ctx, req, res, rq) {
132
134
  sendError(res, result.status, result.error, result.sentence);
133
135
  return true;
134
136
  }
137
+ if (!recheckDevice(req, res, 'while minting a dictation key for'))
138
+ return true;
135
139
  // `sendJson` ustawia `Cache-Control: no-store` na KAŻDEJ odpowiedzi API — dla tej
136
140
  // jednej to nie jest higiena, tylko wymóg: w ciele jedzie klucz.
137
141
  sendJson(res, 200, result.token);
@@ -19,8 +19,8 @@
19
19
  * od pliku, którego nie wolno ruszyć. Pilnuje tego strażnik `server/test/pliki-zwykle-guard.test.ts`: odczyt
20
20
  * z `node:fs` poza tym modułem stoi na jego liście wyjątków z powodem.
21
21
  *
22
- * A file sent on in pieces opens with {@link openRegularFile} and is read with {@link exactReader}: exactly the bytes
23
- * of its `fstat`, from that one descriptor.
22
+ * A file sent on in pieces opens with {@link openRegularFile} (the `openRead` of the work-area port) and is read with
23
+ * {@link exactReader} through the port's handle: exactly the bytes of its `fstat`, from that one descriptor.
24
24
  *
25
25
  * Besides regular files, one directory read lives here, because on Linux it opens the directory:
26
26
  * {@link readDirectoryByIdentity} lists a directory through its `dev` and `ino` rather than its path. On Linux that
@@ -121,23 +121,23 @@ export async function openRegularFile(path, opts) {
121
121
  /** Bytes per piece of {@link exactReader} by default. */
122
122
  export const EXACT_PIECE_BYTES = 64 * 1024;
123
123
  /**
124
- * Reads the first `size` bytes of a file open on `handle` (the `fstat` size of {@link openRegularFile}), one piece
125
- * of at most `pieceBytes` per call, each at its own offset: the position of the descriptor does not matter, and bytes
126
- * appended past `size` are never read. `short`: the file ended before `size` bytes, so it was cut since its `fstat`
127
- * and what was read is not the file. The caller calls it one step at a time, owns the handle and closes it; an error
128
- * of the read rejects.
124
+ * Reads the first `size` bytes of an open file (the `fstat` size taken at its open), one piece of at most
125
+ * `pieceBytes` per call, each at its own offset: the position of the descriptor does not matter, and bytes appended
126
+ * past `size` are never read. `short`: the file ended before `size` bytes, so it was cut since its `fstat` and what
127
+ * was read is not the file. The reader is the handle of the work-area port, so a file in a guarded folder is read in
128
+ * that folder's helper; this function touches no disk itself. The caller calls it one step at a time, owns the handle
129
+ * and closes it; an error of the read rejects.
129
130
  */
130
131
  export function exactReader(handle, size, pieceBytes = EXACT_PIECE_BYTES) {
131
132
  let position = 0;
132
133
  return async () => {
133
134
  if (position >= size)
134
135
  return { kind: 'done' };
135
- const buffer = Buffer.allocUnsafe(Math.min(pieceBytes, size - position));
136
- const { bytesRead } = await handle.read(buffer, 0, buffer.length, position);
137
- if (bytesRead === 0)
136
+ const bytes = await handle.read(Math.min(pieceBytes, size - position), position);
137
+ if (bytes.length === 0)
138
138
  return { kind: 'short', read: position };
139
- position += bytesRead;
140
- return { kind: 'piece', bytes: bytesRead === buffer.length ? buffer : buffer.subarray(0, bytesRead) };
139
+ position += bytes.length;
140
+ return { kind: 'piece', bytes };
141
141
  };
142
142
  }
143
143
  const DIRECTORY_FLAGS = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW | constants.O_NONBLOCK;
@@ -15,10 +15,10 @@ import { BadStateError } from './errors.js';
15
15
  * root), as for the diff, because the list carries the names and descriptions of skills from `.claude/` of that
16
16
  * directory. A card without a pane is in scope with its directory; demo mode reads the registry only.
17
17
  */
18
- export function inCommandScope(session, config) {
18
+ export function inCommandScope(session, config, options = {}) {
19
19
  if (session.engine === 'codex' || session.outOfScope === true)
20
20
  return false;
21
- return config.demo || sessionCwdInArea(session, config);
21
+ return config.demo || sessionCwdInArea(session, config, options);
22
22
  }
23
23
  /**
24
24
  * Whether the directory a read of this session will use lies in the work area of `RAROG_HERDR_ROOTS`. A pane
@@ -27,9 +27,9 @@ export function inCommandScope(session, config) {
27
27
  * as written and on disk ({@link inWorkAreaOnDisk}): a link into a protected folder of home, or a root that is a
28
28
  * symlink to home, does not open that folder to a read.
29
29
  */
30
- export function sessionCwdInArea(session, config) {
30
+ export function sessionCwdInArea(session, config, options = {}) {
31
31
  return session.herdrKey === undefined
32
- || inWorkAreaOnDisk(session.cwd, config.herdrRoots ?? [], config.home ?? homedir());
32
+ || inWorkAreaOnDisk(session.cwd, config.herdrRoots ?? [], config.home ?? homedir(), undefined, options);
33
33
  }
34
34
  /**
35
35
  * Session the voice agent may ask about: its directory and the engine conversation it writes now (`init` of the
@@ -37,7 +37,12 @@ export function sessionCwdInArea(session, config) {
37
37
  * own sentence instead of the 400 of the commands list.
38
38
  */
39
39
  export function companionTargetOf(session, config) {
40
- return inCommandScope(session, config) ? { cwd: session.cwd, agentSessionId: session.engineSessionId } : null;
40
+ // The target names a transcript in the engine's store outside the session directory, so a macOS folder the gate
41
+ // holds closed does not take the session from the Inbox or the voice agent; the commands list and the diff,
42
+ // which read the directory itself, keep the gate.
43
+ return inCommandScope(session, config, { gate: 'ignore' })
44
+ ? { cwd: session.cwd, agentSessionId: session.engineSessionId }
45
+ : null;
41
46
  }
42
47
  /**
43
48
  * {@link companionTargetOf} with the newest message of the session's transcript in memory, for the voice agent's
@@ -0,0 +1,57 @@
1
+ /** Closed cards the server keeps for resuming; each holds up to two transcript budgets (`ring-buffer.ts`). */
2
+ export const DONE_CARDS_MAX = 100;
3
+ /** `true` when the pane index (`HerdrAgent.key` → card id) still points at this card: its pane is alive. */
4
+ export function ownsPaneKey(herdrByKey, card) {
5
+ return card.herdrKey !== undefined && herdrByKey.get(card.herdrKey) === card.id;
6
+ }
7
+ /**
8
+ * Closed cards over the cap, the oldest `lastActivityAt` first. A card with a driver or a live pane and a card whose
9
+ * restart is in progress neither counts nor goes; a `resumable` card is not closed.
10
+ */
11
+ export function doneCardsOver(sessions, herdrByKey, restarts, max = DONE_CARDS_MAX) {
12
+ const closed = [...sessions.values()].filter((card) => card.state === 'done' && card.driver === null
13
+ && !ownsPaneKey(herdrByKey, card) && !restarts.has(card.id));
14
+ if (closed.length <= max)
15
+ return [];
16
+ closed.sort((a, b) => Date.parse(a.lastActivityAt) - Date.parse(b.lastActivityAt));
17
+ return closed.slice(0, closed.length - max);
18
+ }
19
+ /**
20
+ * The card was forgotten while its conversation has no live process and no other card: the consent cycle may drop
21
+ * the conversation's entries (`forgotten`). Called after the card left `sessions`.
22
+ */
23
+ export function forgetConversation(card, sessions, forgotten) {
24
+ const engine = card.engineSessionId;
25
+ if (forgotten === undefined || engine === undefined || engine === '')
26
+ return;
27
+ for (const other of sessions.values())
28
+ if (other.engineSessionId === engine)
29
+ return;
30
+ forgotten(engine);
31
+ }
32
+ /**
33
+ * Zapamiętuje, w których indeksach stoi ta karta, i oddaje funkcję COFAJĄCĄ `#forget…`.
34
+ *
35
+ * Odtwarzamy dokładnie to, co było — a nie „co powinno być": `#indexEngineSession` pomija
36
+ * sesje `done`, więc bezwarunkowe wołanie go po rollbacku dokładałoby wpis, którego przed
37
+ * kasowaniem nie było. Jedyne, czego nie wskrzeszamy, to czekający z `AttachSlots`: to obietnice
38
+ * czekających na podpięcie drivera, a po nieudanym wznowieniu nie ma do czego ich podpiąć.
39
+ * Nowa karta pod tym samym id (gdyby `create()` zdążył ją wstawić) ma pierwszeństwo.
40
+ */
41
+ export function snapshotIndexes(port, session) {
42
+ const key = session.herdrKey;
43
+ const engineSessionId = session.engineSessionId;
44
+ const hadKey = ownsPaneKey(port.herdrByKey, session);
45
+ const hadEngine = engineSessionId !== undefined
46
+ && port.byEngineSession.get(engineSessionId) === session.id;
47
+ return () => {
48
+ if (port.sessions.has(session.id))
49
+ return;
50
+ port.sessions.set(session.id, session);
51
+ port.watch(session);
52
+ if (hadKey && key !== undefined)
53
+ port.herdrByKey.set(key, session.id);
54
+ if (hadEngine && engineSessionId !== undefined)
55
+ port.byEngineSession.set(engineSessionId, session.id);
56
+ };
57
+ }
@@ -37,8 +37,8 @@ export class LaunchGate {
37
37
  /*
38
38
  * Sufit paneli sprawdzamy PRZED `canLaunch`, choć logicznie jest węższy.
39
39
  *
40
- * Powód jest czysto ludzki: nadzorca gasi `canLaunch` z TRZECH różnych powodów (killswitch,
41
- * nieznany protokół, osiągnięty sufit), a komunikat może być tylko jeden. Przy odwrotnej
40
+ * Powód jest czysto ludzki: the supervisor turns `canLaunch` off for several reasons (killswitches,
41
+ * unavailable herdr, reached cap), a komunikat może być tylko jeden. Przy odwrotnej
42
42
  * kolejności siódmy panel dostawał odpowiedź „zakładanie wyłączone” z nazwą killswitcha zakładania
43
43
  * — zdanie nieprawdziwe i prowadzące donikąd, zamiast „zamknij któryś panel".
44
44
  */
@@ -58,6 +58,7 @@ import { compareCliVersions, runningCliVersion } from '../cli-version.js';
58
58
  import { CliRegistryState } from './cli-registry.js';
59
59
  import { InterruptWindows } from './interrupt-windows.js';
60
60
  import { AttachSlots } from './attach-slots.js';
61
+ import { doneCardsOver, forgetConversation, ownsPaneKey, snapshotIndexes } from './done-retention.js';
61
62
  import { scanProjectRoots } from './project-scan.js';
62
63
  import { recentProjects } from './recent-projects.js';
63
64
  import * as companionScope from './companion-scope.js';
@@ -140,7 +141,6 @@ class RarogManager {
140
141
  #pending = new PendingInteractions();
141
142
  #sessions = new Map();
142
143
  #listeners = [];
143
- #transcriptResets = [];
144
144
  #conversations = new companionScope.ConversationListeners((line) => { this.#config.logger?.(line); });
145
145
  /** Git row of cards: reader, `.git` watcher, `git-status` frames and the cost window in the log. */
146
146
  #git;
@@ -619,9 +619,6 @@ class RarogManager {
619
619
  onEvent(cb) {
620
620
  this.#listeners.push(cb);
621
621
  }
622
- onTranscriptReset(cb) {
623
- this.#transcriptResets.push(cb);
624
- }
625
622
  projects() {
626
623
  const configured = this.#config.projects;
627
624
  if (configured !== undefined) {
@@ -871,19 +868,11 @@ class RarogManager {
871
868
  paneId: handle.paneId,
872
869
  herdrKey: handle.key,
873
870
  launchedByRarog: true,
874
- ringStartSeq: opts.continuesRing?.lastSeq,
875
871
  });
876
872
  // Etykieta karty → etykieta taba w herdr. Launcher założył tab z nazwą katalogu;
877
873
  // nadzorca przemianuje go, gdy panel dostanie etykietę pochodzenia.
878
874
  this.#setLabel(session, label);
879
875
  this.#sessions.set(session.id, session);
880
- // A card under an existing id: the open transcript streams get a snapshot before the first frame of the new card.
881
- for (const listener of opts.continuesRing === undefined ? [] : this.#transcriptResets) {
882
- try {
883
- listener(session.id);
884
- }
885
- catch { /* A broken listener must not fail the launch. */ }
886
- }
887
876
  this.#herdrByKey.set(handle.key, session.id);
888
877
  this.#indexEngineSession(session);
889
878
  this.#git.watch(session);
@@ -1389,9 +1378,9 @@ class RarogManager {
1389
1378
  /**
1390
1379
  * Czy kanał ZAPISU do paneli jest otwarty?
1391
1380
  *
1392
- * Dwa niezależne wyłączniki: `RAROG_HERDR_SEND=0` (decyzja człowieka) i `readOnly`
1393
- * z nadzorcy (nieznany protokół herdr). Oba znaczą to samo dla użytkownika: „widzę,
1394
- * nie ruszam" — i oba mają odmówić TUTAJ, a nie dopiero na gnieździe.
1381
+ * Two checks: `RAROG_HERDR_SEND=0` in the config and `readOnly` from the supervisor (the same flag at
1382
+ * the socket, also true while a missing or too old herdr protocol keeps integration off). Both mean
1383
+ * "I see, I do not touch" for the user, and both refuse HERE, not only at the socket.
1395
1384
  */
1396
1385
  #assertHerdrWritable() {
1397
1386
  if (this.#config.herdrSend === false)
@@ -1847,63 +1836,38 @@ class RarogManager {
1847
1836
  * (bez żywego panelu), gdzie nie ma czemu wracać.
1848
1837
  */
1849
1838
  #hideHerdrSession(session) {
1850
- const key = session.herdrKey;
1851
1839
  // Tylko WŁASNY wpis indeksu: po zmianie silnika w panelu klucz
1852
1840
  // trzyma już karta następcy, a ślepe `delete` zdejmowałoby ją z indeksu — z nadzorcy
1853
1841
  // przyszedłby wtedy drugi `appeared` na ten sam panel i lista miałaby dwie karty.
1854
- if (key !== undefined && this.#herdrByKey.get(key) === session.id) {
1855
- this.#herdrByKey.delete(key);
1856
- }
1842
+ const live = ownsPaneKey(this.#herdrByKey, session);
1843
+ if (live)
1844
+ this.#herdrByKey.delete(session.herdrKey);
1857
1845
  // `closed` → `done` jest tu jedynym sposobem powiedzenia klientowi „tej karty już nie ma":
1858
1846
  // protokół nie zna zdarzenia „sesja usunięta", a milczenie zostawiłoby kartę do restartu.
1859
1847
  this.#applyTransition(session, { type: 'closed' }, HERDR_HIDDEN_DETAIL);
1860
- this.#forgetHerdrSession(session);
1848
+ this.#forgetHerdrSession(session, !live); // A hidden live pane keeps its conversation in the consent cycle.
1861
1849
  }
1862
1850
  /**
1863
- * Zapamiętuje, w których indeksach stoi ta karta, i oddaje funkcję COFAJĄCĄ `#forget…`.
1864
- *
1865
- * Odtwarzamy dokładnie to, co było — a nie „co powinno być": `#indexEngineSession` pomija
1866
- * sesje `done`, więc bezwarunkowe wołanie go po rollbacku dokładałoby wpis, którego przed
1867
- * kasowaniem nie było. Jedyne, czego nie wskrzeszamy, to czekający z `AttachSlots`: to obietnice
1868
- * czekających na podpięcie drivera, a po nieudanym wznowieniu nie ma do czego ich podpiąć.
1869
- * Nowa karta pod tym samym id (gdyby `create()` zdążył ją wstawić) ma pierwszeństwo.
1851
+ * Usuwa sesję herdr z RAM i ze wszystkich indeksów (ukrycie albo zniknięcie panelu).
1852
+ * `ends`: the conversation is over and the consent cycle may forget it (`done-retention.ts`).
1870
1853
  */
1871
- #snapshotIndexes(session) {
1872
- const key = session.herdrKey;
1873
- const engineSessionId = session.engineSessionId;
1874
- const hadKey = key !== undefined && this.#herdrByKey.get(key) === session.id;
1875
- const hadEngine = engineSessionId !== undefined
1876
- && this.#byEngineSession.get(engineSessionId) === session.id;
1877
- return () => {
1878
- if (this.#sessions.has(session.id))
1879
- return;
1880
- this.#sessions.set(session.id, session);
1881
- this.#prStatus.sync(session);
1882
- this.#git.watch(session);
1883
- if (hadKey && key !== undefined)
1884
- this.#herdrByKey.set(key, session.id);
1885
- if (hadEngine && engineSessionId !== undefined)
1886
- this.#byEngineSession.set(engineSessionId, session.id);
1887
- };
1888
- }
1889
- /** Usuwa sesję herdr z RAM i ze wszystkich indeksów (ukrycie albo zniknięcie panelu). */
1890
- #forgetHerdrSession(session) {
1854
+ #forgetHerdrSession(session, ends = true) {
1891
1855
  // Karta zamknięta albo ukryta w czasie dialogu startowego: zdanie do transkryptu, zanim karta zniknie z RAM.
1892
1856
  this.#dropStartWait(session);
1893
1857
  this.#unindexEngineSession(session);
1894
- const key = session.herdrKey;
1895
- if (key !== undefined && this.#herdrByKey.get(key) === session.id) {
1896
- this.#herdrByKey.delete(key);
1897
- }
1858
+ if (ownsPaneKey(this.#herdrByKey, session))
1859
+ this.#herdrByKey.delete(session.herdrKey);
1898
1860
  this.#attach.dropAttachWaiter(session.id);
1899
1861
  // Okna przerwania są RAM-owe i per karta — karta znika, więc znikają razem z nią.
1900
- // Bez tego rollback `#snapshotIndexes` wskrzeszałby sesję ze stęchłym oknem debounce'u.
1862
+ // Bez tego rollback `snapshotIndexes` wskrzeszałby sesję ze stęchłym oknem debounce'u.
1901
1863
  this.#interrupts.resetInterruptWindows(session.id);
1902
1864
  this.#herdrLifecycle.herdrRestoreQuiet.delete(session.id);
1903
1865
  this.#herdrBlocked.delete(session.id);
1904
1866
  this.#timing.forget(session.id);
1905
1867
  this.#claimWindows.forget(session.id);
1906
1868
  this.#sessions.delete(session.id);
1869
+ if (ends)
1870
+ forgetConversation(session, this.#sessions, this.#config.consentForgotten);
1907
1871
  this.#prStatus.forget(session.id);
1908
1872
  this.#git.unwatch(session);
1909
1873
  /*
@@ -1961,11 +1925,13 @@ class RarogManager {
1961
1925
  * zostawiłby w indeksach wpisy wskazujące na obiekt, którego nikt już nie czyta.
1962
1926
  */
1963
1927
  async #recreate(session, opts, slotTaken) {
1964
- const restore = this.#snapshotIndexes(session);
1965
- this.#forgetHerdrSession(session);
1928
+ const restore = snapshotIndexes({
1929
+ sessions: this.#sessions, herdrByKey: this.#herdrByKey, byEngineSession: this.#byEngineSession,
1930
+ watch: (s) => { this.#prStatus.sync(s); this.#git.watch(s); },
1931
+ }, session);
1932
+ this.#forgetHerdrSession(session, false);
1966
1933
  try {
1967
- // The new card numbers on after the old one; `#launch` sends the open streams of this id a snapshot.
1968
- await this.#launch({ ...opts, continuesRing: session.ring }, slotTaken);
1934
+ await this.#launch(opts, slotTaken);
1969
1935
  }
1970
1936
  catch (error) {
1971
1937
  /*
@@ -1990,9 +1956,9 @@ class RarogManager {
1990
1956
  this.#sessionRestart.assertNotRestarting(id);
1991
1957
  /*
1992
1958
  * „Uruchom ponownie i wyślij”: `seq` i `id` z ciała mają wskazywać blokadę, której przycisk
1993
- * działa — inaczej 409 PRZED rezerwacją i slotem. The `seq` alone is not enough: numbering starts from 1 again
1994
- * in a new server process, so a late tap from before a server restart could name a new notice under the same
1995
- * number. The block `id` decides.
1959
+ * działa — inaczej 409 PRZED rezerwacją i slotem. Sam `seq` nie wystarcza: karta po restarcie numeruje
1960
+ * transkrypt od zera, więc spóźnione tapnięcie spod notki sprzed restartu trafiłoby w nową notkę o tym samym
1961
+ * numerze.
1996
1962
  * Ładunek (tekst dla CLI, dymek, wizytówki) bierzemy z serwera, nigdy z ciała: klient podaje wyłącznie,
1997
1963
  * KTÓRĄ blokadę tapnięto.
1998
1964
  */
@@ -2914,6 +2880,7 @@ class RarogManager {
2914
2880
  if (session.launchPending && !this.#startWaits.has(session))
2915
2881
  this.#startExits.add(session);
2916
2882
  this.#dropStartWait(session);
2883
+ this.#trimDoneCards();
2917
2884
  return;
2918
2885
  }
2919
2886
  default: {
@@ -3084,6 +3051,15 @@ class RarogManager {
3084
3051
  }
3085
3052
  this.#herdrLifecycle.rememberGoneIdle(session);
3086
3053
  this.#applyTransition(session, { type: 'closed' }, HERDR_GONE_DETAIL);
3054
+ this.#trimDoneCards();
3055
+ }
3056
+ /** Closed cards over the cap leave by the Hide path, with one fresh list to all phones. */
3057
+ #trimDoneCards() {
3058
+ const over = doneCardsOver(this.#sessions, this.#herdrByKey, this.#sessionRestart.restarts);
3059
+ for (const session of over)
3060
+ this.#forgetHerdrSession(session);
3061
+ if (over.length > 0)
3062
+ this.#emitSessionsSnapshot();
3087
3063
  }
3088
3064
  // --- Kolejka podpięć (5.10: 17 równoległych odczytów historii to skok latencji) ---
3089
3065
  async #attachHerdrDriver(supervisor, session, key) {
@@ -3,10 +3,10 @@
3
3
  * a configured `projects` list. Reads one directory level per root and nothing else; the allow-list check
4
4
  * of a launch directory lives in `validateProjectCwd`, not here. This module does not import `manager.ts`.
5
5
  */
6
- import { readdirSync } from 'node:fs';
7
6
  import { homedir } from 'node:os';
8
7
  import { join } from 'node:path';
9
8
  import { insideWorkArea, onDiskForms } from '../config/work-area.js';
9
+ import { DIRECT_DISK, closedFolderOf } from '../folder-gate/disk.js';
10
10
  /**
11
11
  * Skan korzeni projektów — lista w pickerze „Nowa sesja" poza trybem demo.
12
12
  *
@@ -18,7 +18,8 @@ import { insideWorkArea, onDiskForms } from '../config/work-area.js';
18
18
  * and by its path on disk, from the roots and home in on-disk form: a root that is a symlink to home
19
19
  * (`/srv/home -> ~`) lists the folders of home under its own prefix, and the text alone would let `Desktop` through.
20
20
  * A folder is a real directory, never a symlink, so its path on disk is its name under the resolved root; the entry
21
- * keeps the path as written.
21
+ * keeps the path as written. A guarded folder of home that the folder gate holds closed stays off, and so does every
22
+ * folder of a root inside it: the port refuses that listing without the disk.
22
23
  */
23
24
  export function scanProjectRoots(roots, home = homedir()) {
24
25
  const real = onDiskForms(roots, home);
@@ -26,7 +27,8 @@ export function scanProjectRoots(roots, home = homedir()) {
26
27
  for (const [index, root] of roots.entries()) {
27
28
  let entries;
28
29
  try {
29
- entries = readdirSync(root, { withFileTypes: true });
30
+ // `utf8` gives every name as a string.
31
+ entries = DIRECT_DISK.sync('readdir', { path: root, encoding: 'utf8' });
30
32
  }
31
33
  catch {
32
34
  continue;
@@ -40,6 +42,10 @@ export function scanProjectRoots(roots, home = homedir()) {
40
42
  continue;
41
43
  if (!insideWorkArea(join(realRoot, entry.name), real.roots, real.home))
42
44
  continue;
45
+ // A start there would be refused: the folder gate holds its guarded folder closed (a root inside it, whose
46
+ // listing the port refused, is left out already).
47
+ if (closedFolderOf(path) !== null || closedFolderOf(join(realRoot, entry.name)) !== null)
48
+ continue;
43
49
  if (!found.has(path))
44
50
  found.set(path, { path, name: entry.name });
45
51
  }
@@ -4,10 +4,6 @@
4
4
  * Kontrakt ze speca: pojemność 500, `push(t) → seq` monotoniczny od 1, `since(seq) → T[]`,
5
5
  * `tooOld(seq) → boolean`.
6
6
  *
7
- * A new card under an existing id (restart, "Resume") continues the old card's numbering with `startSeq`: the first
8
- * push gets `startSeq + 1`, and a cursor at or below `startSeq` is too old, because the events it counts belong to the
9
- * old card and none of them are in this ring.
10
- *
11
7
  * Semantyka kursora (taka sama jak w SSE): kursor to `seq` OSTATNIEGO odebranego eventu,
12
8
  * więc `since(seq)` zwraca elementy o `seq > kursor`. Kursor `0` = „nic jeszcze nie widziałem".
13
9
  * `seq` żyje w ramach jednego `serverStartId` — po restarcie backendu kursor jest z definicji
@@ -40,9 +36,11 @@ export const MAX_MESSAGE_BYTES = 256 * 1024;
40
36
  * i dla tablicy wiadomości (obie struktury trzymają te same wiadomości, obie oddają je
41
37
  * na telefon: ring przez replay `Last-Event-ID`, tablica przez `transcript-snapshot`).
42
38
  *
43
- * 4 MB × 30 paneli (sufit liczby paneli) to pesymistycznie 120 MB — tyle wolno Rarogowi zająć
44
- * transkryptami. Przekroczenie wypycha NAJSTARSZE wpisy, dokładnie tak jak sufit sztuk;
45
- * sztuki zostają drugim limitem, bo 500 malutkich eventów też ma się kiedyś skończyć.
39
+ * Both hold the same message objects, so one card keeps up to 4 MiB of messages plus up to 4 MiB of other ring
40
+ * events: 8 MiB at worst, usually far less. Closed cards are capped at `DONE_CARDS_MAX` (`done-retention.ts`), so at
41
+ * worst 100 × 8 MiB. Cards with a live pane have no count cap: `RAROG_MAX_PANES` limits only the panes Rarog starts.
42
+ * Going over the byte cap pushes out the OLDEST entries, like the count cap; the count stays a second limit, because
43
+ * 500 tiny events must end somewhere too.
46
44
  */
47
45
  export const RING_MAX_BYTES = 4 * 1024 * 1024;
48
46
  /**
@@ -73,10 +71,8 @@ export class RingBuffer {
73
71
  #size = 0;
74
72
  /** Suma wag elementów aktualnie przechowywanych. */
75
73
  #bytes = 0;
76
- /** Ostatnio przydzielony `seq`; `#floor` = nic jeszcze nie wrzucono. */
77
- #lastSeq;
78
- /** The last seq of the ring this one continues; a cursor at or below it is too old (0 = a fresh ring). */
79
- #floor;
74
+ /** Ostatnio przydzielony `seq`; 0 = nic jeszcze nie wrzucono. */
75
+ #lastSeq = 0;
80
76
  constructor(capacity = DEFAULT_RING_CAPACITY, opts = {}) {
81
77
  if (!Number.isInteger(capacity) || capacity < 1) {
82
78
  throw new RangeError(`RingBuffer: pojemność musi być dodatnią liczbą całkowitą, jest ${capacity}`);
@@ -86,12 +82,6 @@ export class RingBuffer {
86
82
  this.#weights = new Array(capacity).fill(0);
87
83
  this.#maxBytes = opts.maxBytes ?? null;
88
84
  this.#weigh = opts.weigh ?? jsonBytes;
89
- const startSeq = opts.startSeq ?? 0;
90
- if (!Number.isInteger(startSeq) || startSeq < 0) {
91
- throw new RangeError(`RingBuffer: startSeq must be a non-negative integer, is ${String(startSeq)}`);
92
- }
93
- this.#floor = startSeq;
94
- this.#lastSeq = startSeq;
95
85
  }
96
86
  get capacity() {
97
87
  return this.#capacity;
@@ -157,16 +147,13 @@ export class RingBuffer {
157
147
  *
158
148
  * `true`, gdy:
159
149
  * - część eventów po kursorze została już wyparta z bufora (kursor za stary), albo
160
- * - kursor wskazuje na `seq` z przyszłości / z innego `serverStartId` (kursor niespójny), albo
161
- * - the cursor counts events of the ring this one continues (`startSeq`).
150
+ * - kursor wskazuje na `seq` z przyszłości / z innego `serverStartId` (kursor niespójny).
162
151
  */
163
152
  tooOld(seq) {
164
153
  if (!Number.isFinite(seq))
165
154
  return true;
166
155
  if (seq > this.#lastSeq)
167
156
  return true;
168
- if (this.#floor > 0 && seq <= this.#floor)
169
- return true;
170
157
  return seq < this.oldestServableCursor;
171
158
  }
172
159
  /**
@@ -4,12 +4,14 @@
4
4
  * The manager owns one {@link SessionGit}, gives it a narrow {@link SessionGitPort} (sessions, clock, the environment
5
5
  * of git processes, emission) and calls it after a tool call, at the end of a turn, on opening a transcript and on
6
6
  * a `git-status` event of a driver. Git runs only through the runners of `git-status.ts`, and never in a protected
7
- * folder of home that no root opens: neither `git status` nor the `.git` watcher. This module does not
7
+ * folder of home that no root opens, nor in a guarded folder the folder gate holds closed: neither `git status` nor
8
+ * the `.git` watcher. A session refused only for a closed folder gets both when the folder opens. This module does not
8
9
  * import `manager.ts`.
9
10
  */
10
11
  import { homedir } from 'node:os';
11
12
  import { HERDR_GIT_MIN_INTERVAL_MS } from '../config.js';
12
13
  import { inExcludedOnDisk } from '../config/work-area.js';
14
+ import { folderGate } from '../folder-gate/install.js';
13
15
  import { GIT_NUMSTAT_BUDGET_MS, GIT_NUMSTAT_READ_CAP_BYTES, GitStatusWatcher, spawnGitArgs, spawnGitLog, spawnGitStatus, } from '../git-status.js';
14
16
  import { GitReadStats } from '../git-stats.js';
15
17
  import { GitRepoWatcher } from '../git-watch.js';
@@ -24,6 +26,9 @@ export class SessionGit {
24
26
  #gitStats;
25
27
  /** Sessions whose directory {@link watch} registered: {@link unwatch} releases exactly these. */
26
28
  #watched = new WeakSet();
29
+ /** Sessions {@link watch} refused; a guarded folder that opens may admit them, so `open` asks again. */
30
+ #refused = new Set();
31
+ #offGate;
27
32
  constructor(config, port) {
28
33
  this.#config = config;
29
34
  this.#port = port;
@@ -55,6 +60,10 @@ export class SessionGit {
55
60
  console.warn(`rarog: git-watch without a watcher for ${gitDir}: ${describeError(error)}`);
56
61
  },
57
62
  }));
63
+ this.#offGate = folderGate().onChange((_folder, state) => {
64
+ if (state === 'open')
65
+ this.#admitRefused();
66
+ });
58
67
  }
59
68
  /**
60
69
  * Registers the session's directory in the `.git` watcher, unless git may not run there ({@link #gitAllowed}). The
@@ -62,20 +71,40 @@ export class SessionGit {
62
71
  */
63
72
  watch(session) {
64
73
  const watcher = this.#gitWatch;
65
- if (watcher === null || this.#watched.has(session) || !this.#gitAllowed(session.cwd))
74
+ if (watcher === null || this.#watched.has(session))
75
+ return;
76
+ if (!this.#gitAllowed(session.cwd)) {
77
+ this.#refused.add(session);
66
78
  return;
79
+ }
80
+ this.#refused.delete(session);
67
81
  this.#watched.add(session);
68
82
  watcher.watch(session.cwd);
69
83
  }
70
84
  /** Releases the session's directory in the `.git` watcher, when {@link watch} registered it. */
71
85
  unwatch(session) {
86
+ this.#refused.delete(session);
72
87
  if (this.#watched.delete(session))
73
88
  this.#gitWatch?.unwatch(session.cwd);
74
89
  }
75
90
  /** Stops the `.git` watcher (manager `dispose`). */
76
91
  close() {
92
+ this.#offGate();
93
+ this.#refused.clear();
77
94
  this.#gitWatch?.close();
78
95
  }
96
+ /** A guarded folder opened: each refused session that git may now run for gets its watcher and one fresh read. */
97
+ #admitRefused() {
98
+ for (const session of [...this.#refused]) {
99
+ if (this.#port.sessions.get(session.id) !== session) {
100
+ this.#refused.delete(session);
101
+ continue;
102
+ }
103
+ this.watch(session);
104
+ if (this.#watched.has(session))
105
+ this.requestGitStatus(session, true);
106
+ }
107
+ }
79
108
  /**
80
109
  * Whether git may run in `cwd`: not in a macOS-protected folder of home that no root opens, as written or
81
110
  * through a symlink. A read there waits for a privacy prompt nobody sees and hangs the server. A pane outside the
@@ -560,7 +560,7 @@ export class Session {
560
560
  this.lastGitSignature = undefined;
561
561
  this.lastGitEvent = undefined;
562
562
  // Ring ma sufit BAJTÓW obok sufitu sztuk — patrz `ring-buffer.ts`.
563
- this.ring = new RingBuffer(init.ringCapacity, { maxBytes: RING_MAX_BYTES, startSeq: init.ringStartSeq });
563
+ this.ring = new RingBuffer(init.ringCapacity, { maxBytes: RING_MAX_BYTES });
564
564
  }
565
565
  /** Kształt wysyłany do klienta (pola serwerowe zostają na serwerze). */
566
566
  summary() {
@@ -413,7 +413,7 @@ export const HERDR_OUT_OF_SCOPE_MESSAGE = say('session.out-of-scope');
413
413
  * bramki zasięgu (patrz {@link HERDR_CODEX_GIT_MESSAGE}).
414
414
  */
415
415
  export const HERDR_OUT_OF_SCOPE_DIFF_MESSAGE = say('session.out-of-scope-diff');
416
- /** 400 na wysyłkę przy zamkniętym kanale zapisu (`RAROG_HERDR_SEND=0` albo nieznany protokół). */
416
+ /** 400 for a send while the write channel is closed (`RAROG_HERDR_SEND=0`). */
417
417
  export const HERDR_READ_ONLY_MESSAGE = say('session.herdr-read-only');
418
418
  /** 429 na wysyłkę odrzuconą przez throttle. */
419
419
  export const HERDR_THROTTLED_MESSAGE = say('session.send-throttled');