@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
@@ -20,7 +20,7 @@ import { randomUUID } from 'node:crypto';
20
20
  import { renameSync } from 'node:fs';
21
21
  import { homedir } from 'node:os';
22
22
  import { basename, join, resolve } from 'node:path';
23
- import { DEFAULT_MODEL_CHOICE, DIFF_BAD_PATH_ERROR, DIFF_FILE_NOT_FOUND_ERROR, FALLBACK_MODEL_CHOICES, MAX_ANSWER_TEXT_CHARS, MAX_RECENT_PROJECTS, MAX_RECENT_SESSIONS, EXIT_PLAN_MODE_TOOL, MAX_RESUMABLE_SESSIONS, MODEL_CHANGE_WARNING, ULTRACODE_CHANGE_NOTE, WAITING_TEXT_MAX, messageAttachments, } from '@rarog/shared';
23
+ import { DEFAULT_MODEL_CHOICE, DIFF_BAD_PATH_ERROR, DIFF_FILE_NOT_FOUND_ERROR, FALLBACK_MODEL_CHOICES, MAX_ANSWER_TEXT_CHARS, MAX_RECENT_PROJECTS, MAX_RECENT_SESSIONS, EXIT_PLAN_MODE_TOOL, MAX_RESUMABLE_SESSIONS, MODEL_CHANGE_WARNING, ULTRACODE_CHANGE_NOTE, messageAttachments, } from '@rarog/shared';
24
24
  import { foreign, say, sentenceOfArglessRef, } from '@rarog/shared/sentences';
25
25
  import { isFallbackLabel, nextFallbackLabel } from './fallback-label.js';
26
26
  export { isFallbackLabel, nextFallbackLabel };
@@ -28,11 +28,12 @@ import { MAX_TURNS_DETAIL, transition } from './state-machine.js';
28
28
  import { Session, wireStateDetail } from './session.js';
29
29
  import { BadRequestError, BadStateError, NotFoundError, TooManyRequestsError, } from './errors.js';
30
30
  import { createSendRegistry, sendDigest } from './send-registry.js';
31
- import { DECISION_STATES, DRIVER_ERROR_DETAIL, DRIVER_GONE_DETAIL, HERDR_ALLOW_MESSAGE, HERDR_CODEX_CLOSE_MESSAGE, HERDR_CODEX_GIT_MESSAGE, HERDR_FOCUS_MESSAGE, HERDR_GONE_DETAIL, HERDR_HIDDEN_DETAIL, HERDR_LAUNCHING_DETAIL, HERDR_LAUNCH_OFF_MESSAGE, HERDR_LOST_PROMPT_MESSAGE, HERDR_MODEL_MESSAGE, HERDR_MODE_BYPASS_MESSAGE, HERDR_MODE_MESSAGE, HERDR_NOT_OWNED_MESSAGE, HERDR_NO_DRIVER_INTERRUPT_MESSAGE, HERDR_OUT_OF_SCOPE_DIFF_MESSAGE, HERDR_OUT_OF_SCOPE_MESSAGE, HERDR_READ_ONLY_MESSAGE, HERDR_RESUME_MESSAGE, HERDR_TERMINAL_UNAVAILABLE_MESSAGE, HERDR_THROTTLED_MESSAGE, HERDR_TRUST_PROMPT_MESSAGE, INTERRUPT_DETAIL, INTERRUPT_WORKING_GRACE_MS, LATE_TOOL_CALL_MS, LIVE_STATES, MODEL_BUSY_MESSAGE, MODEL_CHANGE_STATES, MODE_BUSY_MESSAGE, PROMPT_BLOCK_MARKER_MS, RESTART_BUSY_MESSAGE, RESTART_CODEX_MESSAGE, RESTART_EXIT_TIMEOUT_MS, RESTART_NO_PANEL_MESSAGE, RESTART_NO_UPDATE_MESSAGE, RESTART_RESEND_STALE_MESSAGE, RESTART_TASKS_MESSAGE, RESTART_UNSUPPORTED_MESSAGE, RESTART_WAITING_AGENT_MESSAGE, RESUME_WITHOUT_ULTRACODE_MESSAGE, SENDABLE_STATES, STREAMING_STATES, TURN_END_STATES, ULTRACODE_CLI_UNKNOWN_MESSAGE, WORKING_STATES, cwdDeniedSentence, herdrLaunchFailedDetail, inTurn, launchThrottledMessage, limitReachedDetail, nextTurnInput, noInputYet, pushStateDetail, restartFailedDetail, restartLaunchingDetail, seedDetailField, startsTurn, tallyTurnInput, toolsDecideSilence, ultracodeCliTooOldMessage, uncertainLaunch, } from './state-sentences.js';
31
+ import { DECISION_STATES, DRIVER_ERROR_DETAIL, DRIVER_GONE_DETAIL, HERDR_ALLOW_MESSAGE, HERDR_CODEX_CLOSE_MESSAGE, HERDR_FOCUS_MESSAGE, HERDR_GONE_DETAIL, HERDR_HIDDEN_DETAIL, HERDR_LAUNCHING_DETAIL, HERDR_LAUNCH_OFF_MESSAGE, HERDR_LOST_PROMPT_MESSAGE, HERDR_MODEL_MESSAGE, HERDR_MODE_BYPASS_MESSAGE, HERDR_MODE_MESSAGE, HERDR_NOT_OWNED_MESSAGE, HERDR_NO_DRIVER_INTERRUPT_MESSAGE, HERDR_OUT_OF_SCOPE_MESSAGE, HERDR_READ_ONLY_MESSAGE, HERDR_RESUME_MESSAGE, HERDR_TERMINAL_UNAVAILABLE_MESSAGE, HERDR_THROTTLED_MESSAGE, HERDR_TRUST_PROMPT_MESSAGE, INTERRUPT_DETAIL, INTERRUPT_WORKING_GRACE_MS, LATE_TOOL_CALL_MS, LIVE_STATES, MODEL_BUSY_MESSAGE, MODEL_CHANGE_STATES, MODE_BUSY_MESSAGE, PROMPT_BLOCK_MARKER_MS, RESTART_BUSY_MESSAGE, RESTART_CODEX_MESSAGE, RESTART_EXIT_TIMEOUT_MS, RESTART_NO_PANEL_MESSAGE, RESTART_NO_UPDATE_MESSAGE, RESTART_RESEND_STALE_MESSAGE, RESTART_TASKS_MESSAGE, RESTART_UNSUPPORTED_MESSAGE, RESTART_WAITING_AGENT_MESSAGE, RESUME_WITHOUT_ULTRACODE_MESSAGE, SENDABLE_STATES, STREAMING_STATES, TURN_END_STATES, ULTRACODE_CLI_UNKNOWN_MESSAGE, WORKING_STATES, cwdDeniedSentence, herdrLaunchFailedDetail, inTurn, launchThrottledMessage, limitReachedDetail, nextTurnInput, noInputYet, pushStateDetail, restartFailedDetail, restartLaunchingDetail, seedDetailField, startsTurn, tallyTurnInput, toolsDecideSilence, ultracodeCliTooOldMessage, uncertainLaunch, } from './state-sentences.js';
32
32
  import { DialogTimings } from './dialog-timing.js';
33
33
  import { ClaimWindows } from './claim-window.js';
34
34
  import * as seenMarks from './seen-marks.js';
35
35
  import * as heldEcho from './held-echo.js';
36
+ import { GIT_DIFF_FILE_LOG, GIT_DIFF_LIST_LOG, measureDiff } from './diff-measure.js';
36
37
  import { heldActivity, holdActivity, stampState } from './activity-clocks.js';
37
38
  import { PendingInteractions } from '../permissions.js';
38
39
  import { classifyRisk } from '../risk.js';
@@ -57,9 +58,13 @@ import { compareCliVersions, runningCliVersion } from '../cli-version.js';
57
58
  import { CliRegistryState } from './cli-registry.js';
58
59
  import { InterruptWindows } from './interrupt-windows.js';
59
60
  import { AttachSlots } from './attach-slots.js';
61
+ import { doneCardsOver, forgetConversation, ownsPaneKey, snapshotIndexes } from './done-retention.js';
60
62
  import { scanProjectRoots } from './project-scan.js';
61
63
  import { recentProjects } from './recent-projects.js';
62
64
  import * as companionScope from './companion-scope.js';
65
+ import * as sessionScope from './session-scope.js';
66
+ import { openSessionDownload } from '../files/session-download.js';
67
+ import { listSessionFiles } from '../files/session-files.js';
63
68
  // Jedyny wartościowy import z `herdr/*` w tym pliku: czysta funkcja sklejająca prompt ze
64
69
  // ścieżkami załączników. Zero gniazda, zero I/O — patrz komentarz przy re-eksporcie niżej.
65
70
  import { appendAttachmentPaths } from '../herdr/uploads.js';
@@ -79,9 +84,9 @@ import { consentStep } from '../herdr/consent-step.js';
79
84
  import { HerdrCommandRefusedError, ULTRACODE_COMMANDS, commandListOf, promptBlockedField, promptBlockedText, registryCatalog, } from '../herdr/commands/index.js';
80
85
  import { cardShowsAll, permissionSemantics, toolInputText } from '../drivers/tool-text.js';
81
86
  import { onlyWaitingAgents, tasksBlockRestart, tasksHoldingDonePush, waitingOnOwnCommand, } from '../herdr/background/work.js';
82
- // Ta sama etykieta, którą dostaje wiersz tool-calla w transkrypcie — patrz `decisionText`.
83
- import { summarizeToolInput } from '../drivers/tool-summary.js';
87
+ import { decisionText, waitingText } from './waiting-line.js';
84
88
  import { ConsentCards, consentRefusal } from './consent-cards.js';
89
+ import { loadDemoModules } from './demo-modules.js';
85
90
  /** Wynik zwykłej wysyłki (bez `clientMessageId` albo pierwsze przyjęcie) */
86
91
  const NOT_REPLAYED = Object.freeze({ replayed: false });
87
92
  // ---------------------------------------------------------------------------
@@ -96,10 +101,8 @@ export { BadRequestError, BadStateError, GoneError, NotFoundError, TooManyReques
96
101
  export const PROMPT_BLOCKED_LOG = 'rarog: prompt blocked by a hook';
97
102
  /** Defined in `held-echo.ts` with the deferred echo; importers keep this path. */
98
103
  export { HELD_FLUSHED_LOG, HELD_QUEUE_LOG } from './held-echo.js';
99
- /** Fraza linii kosztu listy plików gita czytanej od nowa: `git: diff list <ms> ms`. */
100
- export const GIT_DIFF_LIST_LOG = 'git: diff list';
101
- /** Fraza linii kosztu patcha jednego pliku: `git: diff file <ms> ms`. */
102
- export const GIT_DIFF_FILE_LOG = 'git: diff file';
104
+ /** Defined in `diff-measure.ts` with the line of a diff read; importers keep this path. */
105
+ export { GIT_DIFF_FILE_LOG, GIT_DIFF_LIST_LOG } from './diff-measure.js';
103
106
  /*
104
107
  * 409 na zakładanie sesji po osiągnięciu sufitu paneli Raroga.
105
108
  *
@@ -118,19 +121,6 @@ export { HERDR_PANE_CAP_MESSAGE };
118
121
  export { appendAttachmentPaths };
119
122
  /** Re-exported for `index.ts`, which imports it from the manager; defined in `state-sentences.ts`. */
120
123
  export { RESUME_UNREADABLE_MESSAGE } from './state-sentences.js';
121
- /** Dynamiczny import scenariuszy demo — wołany WYŁĄCZNIE przy `config.demo`; treść z podanego zestawu. */
122
- async function loadDemoModules(content) {
123
- const seeds = await import('../demo/seeds.js');
124
- return {
125
- demoSeeds: (now) => seeds.demoSeeds(content, now),
126
- demoBlocks: seeds.demoBlocks,
127
- demoProjects: () => seeds.demoProjects(content),
128
- demoResumable: (cwd, now) => seeds.demoResumable(content, cwd, now),
129
- demoDiff: () => seeds.demoDiff(content),
130
- demoDiffFiles: seeds.demoDiffFiles,
131
- demoDiffFile: (path) => seeds.demoDiffFile(content, path),
132
- };
133
- }
134
124
  // ---------------------------------------------------------------------------
135
125
  // Etykieta sesji (człon `sesja` w tytule `projekt · sesja`)
136
126
  // ---------------------------------------------------------------------------
@@ -1388,9 +1378,9 @@ class RarogManager {
1388
1378
  /**
1389
1379
  * Czy kanał ZAPISU do paneli jest otwarty?
1390
1380
  *
1391
- * Dwa niezależne wyłączniki: `RAROG_HERDR_SEND=0` (decyzja człowieka) i `readOnly`
1392
- * z nadzorcy (nieznany protokół herdr). Oba znaczą to samo dla użytkownika: „widzę,
1393
- * 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.
1394
1384
  */
1395
1385
  #assertHerdrWritable() {
1396
1386
  if (this.#config.herdrSend === false)
@@ -1547,7 +1537,7 @@ class RarogManager {
1547
1537
  if (outcome.kind === 'refused') {
1548
1538
  /*
1549
1539
  * Rozpoznanie WRACA tylko po `send-failed`: to jedyna odmowa, przy której z Raroga nie
1550
- * wyszedł ani jeden bajt, driver karty nie wycofał (`#refuseSend` świadomie nie woła ani
1540
+ * wyszedł ani jeden bajt, driver karty nie wycofał (`refuseSend` świadomie nie woła ani
1551
1541
  * `#clearActive`, ani `#scheduleEvaluate`) i dialog na pewno stoi dalej na ekranie.
1552
1542
  *
1553
1543
  * Pozostałe powody (`screen-changed`, `no-digit`, `multi-select`, `terminal-only`,
@@ -1656,22 +1646,21 @@ class RarogManager {
1656
1646
  return { outcome: 'ok' };
1657
1647
  }
1658
1648
  /**
1659
- * Esc do sesji. Zwraca obietnicę drivera („klawisz poszedł"), a NIE moment przyjęcia
1660
- * żądania.
1649
+ * Esc to the session. Returns the driver's promise ("the key went"), NOT the moment the request was accepted.
1661
1650
  *
1662
- * Kolejność w tej metodzie jest wiążąca i nie wolno jej przesunąć za dostarczenie:
1663
- * `interruptedAtMs` i przejście `interrupt-requested` lecą SYNCHRONICZNIE, bo na tym stoi
1664
- * odpowiedź POST-a ze świeżym `SessionSummary` — jedyna prawda, gdy
1665
- * `EventSource` umarł po cichu. Metoda nie jest `async` z tego samego powodu, co w driverze:
1666
- * odmowy poniżej mają rzucać na wywołaniu, nie odrzuconą obietnicą.
1667
- *
1668
- * Idempotencja stoi TUTAJ, a nie w kliencie: żądania przychodzą też z drugiego urządzenia
1669
- * i z ponowienia sieciowego klienta, których żaden guard w kliencie nie widzi. Okna są
1670
- * dwa i rozłączne — „w locie" (przed dostarczeniem) i debounce (po), każde na swoim polu.
1651
+ * The order in this method is binding: `interruptedAtMs` and the `interrupt-requested` transition run SYNCHRONOUSLY,
1652
+ * because the POST answer with a fresh `SessionSummary` stands on them, the only truth when `EventSource` died
1653
+ * silently. Not `async` for the same reason as in the driver: the refusals below throw on the call. Idempotency
1654
+ * stands HERE, not in the client: requests also come from a second device and from network retries. The two windows
1655
+ * are disjoint: "in flight" (before delivery) and debounce (after), each on its own field.
1671
1656
  */
1672
1657
  interrupt(id) {
1673
1658
  return this.#sessionRestart.track(id, () => this.#interrupt(id));
1674
1659
  }
1660
+ /** {@link ManagerApi.returnedPrompt}: the driver's field read after the last delivered `escape`. */
1661
+ returnedPrompt(id) {
1662
+ return this.#sessions.get(id)?.driver?.returnedPrompt?.() ?? Promise.resolve(null);
1663
+ }
1675
1664
  #interrupt(id) {
1676
1665
  const session = this.#require(id);
1677
1666
  this.#sessionRestart.assertNotRestarting(id);
@@ -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,8 +1925,11 @@ 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
1934
  await this.#launch(opts, slotTaken);
1968
1935
  }
@@ -2332,53 +2299,44 @@ class RarogManager {
2332
2299
  // -------------------------------------------------------------------------
2333
2300
  // Git: diff sesji
2334
2301
  // -------------------------------------------------------------------------
2335
- /**
2336
- * Bramka wspólna WSZYSTKICH tras diffa — starej i obu per plik. Oddaje sesję, z której
2337
- * katalogu wolno czytać, albo `null` w demo: tam diff to stały mock, bez odczytu z dysku.
2338
- */
2339
- #diffSession(id) {
2340
- const session = this.#require(id);
2341
- // Bramka zasięgu: diff roboczy to TREŚĆ katalogu, a wpis Codexa obiecuje sam stan. Klient
2342
- // przycisku dla Codexa nie rysuje — to jest druga linia, dla starego klienta i dla `curl`.
2343
- if (session.engine === 'codex')
2344
- throw new BadRequestError(HERDR_CODEX_GIT_MESSAGE);
2345
- // Panel poza zasięgiem: ta sama granica co transkrypt i wycinek ekranu — treść katalogu zostaje na Macu.
2346
- if (session.outOfScope === true)
2347
- throw new BadRequestError(HERDR_OUT_OF_SCOPE_DIFF_MESSAGE);
2348
- /*
2349
- * Niżej, za gałęzią demo: `outOfScope` mówi o katalogu, w którym panel stoi TERAZ (nadzorca
2350
- * liczy go od nowa po `cd`), a diff czyta `session.cwd` — katalog z chwili pojawienia się
2351
- * panelu, którego reattach nie rusza. Panel, który wystartował poza korzeniami i zrobił `cd` pod korzeń, miał więc zasięg,
2352
- * a diff dalej czytał stary, prywatny katalog. Bramka pyta o TEN
2353
- * katalog, z którego pójdzie odczyt, tą samą funkcją co nadzorca (`scopeOf`).
2354
- */
2355
- // Demo nie ma korzeni ani prawdziwych katalogów: jego diff to stały mock, bez odczytu z dysku.
2356
- if (this.#config.demo)
2357
- return null;
2358
- if (!companionScope.sessionCwdInArea(session, this.#config))
2359
- throw new BadRequestError(HERDR_OUT_OF_SCOPE_DIFF_MESSAGE);
2360
- return session;
2302
+ /** Port of the diff gate (`diffSession` in `session-scope.ts`): the session lookup and the configuration. */
2303
+ #diffSessionPort() {
2304
+ return { require: (id) => this.#require(id), config: this.#config };
2361
2305
  }
2362
2306
  async diff(id) {
2363
- const session = this.#diffSession(id);
2307
+ const session = sessionScope.diffSession(id, this.#diffSessionPort());
2364
2308
  if (session === null)
2365
2309
  return this.#requireDemo().demoDiff();
2366
2310
  const runner = this.#config.diffRunner ?? spawnGitArgs(this.#gitEnv);
2367
2311
  return collectDiff(session.cwd, { run: runner });
2368
2312
  }
2369
2313
  async diffFiles(id) {
2370
- const session = this.#diffSession(id);
2314
+ const session = sessionScope.diffSession(id, this.#diffSessionPort());
2371
2315
  if (session === null)
2372
2316
  return this.#requireDemo().demoDiffFiles();
2373
2317
  const injected = this.#config.diffRunner;
2374
- return this.#measureDiff(GIT_DIFF_LIST_LOG, () => collectDiffList(session.cwd, {
2318
+ return measureDiff(GIT_DIFF_LIST_LOG, this.#diffClock, () => collectDiffList(session.cwd, {
2375
2319
  run: injected ?? spawnGitArgs(this.#gitEnv),
2376
2320
  // Liczniki mają WŁASNY budżet (jak w ramce `git-status`): lista nie czeka na nie dłużej.
2377
2321
  runNumstat: injected ?? spawnGitArgs(this.#gitEnv, GIT_NUMSTAT_BUDGET_MS),
2378
2322
  }));
2379
2323
  }
2324
+ filesPort() {
2325
+ return {
2326
+ ...this.#diffSessionPort(), run: this.#config.diffRunner ?? spawnGitArgs(this.#gitEnv),
2327
+ demoEntries: (rel) => this.#requireDemo().demoFileEntries(rel),
2328
+ };
2329
+ }
2330
+ listFiles(id, dir, maxBytes) {
2331
+ return listSessionFiles(id, dir, maxBytes, this.filesPort());
2332
+ }
2333
+ openFile(id, rel, maxBytes) {
2334
+ return openSessionDownload(id, rel, maxBytes, {
2335
+ ...this.#diffSessionPort(), demoFile: (file) => this.#requireDemo().demoFileBytes(file),
2336
+ });
2337
+ }
2380
2338
  async diffFile(id, path) {
2381
- const session = this.#diffSession(id);
2339
+ const session = sessionScope.diffSession(id, this.#diffSessionPort());
2382
2340
  // Walidacja wstępna stoi PRZED gałęzią demo: `?path=../x` to 400 także tam, jak na produkcji.
2383
2341
  if (validateDiffPath(path) === null)
2384
2342
  throw new DiffError(DIFF_BAD_PATH_ERROR);
@@ -2389,28 +2347,12 @@ class RarogManager {
2389
2347
  return patch;
2390
2348
  }
2391
2349
  const run = this.#config.diffRunner ?? spawnGitArgs(this.#gitEnv);
2392
- return this.#measureDiff(GIT_DIFF_FILE_LOG, () => collectDiffFile(session.cwd, path, { run }));
2393
- }
2394
- /**
2395
- * Linia `git: diff list|file <ms>` w logu: koszt list gita czytanych od nowa przy każdym
2396
- * żądaniu, czyli liczba, po której zapadnie decyzja o pamięci podręcznej. Niesie czas i — przy
2397
- * odmowie — kod z kontraktu; NIGDY ścieżki ani nazwy pliku.
2398
- */
2399
- async #measureDiff(phrase, read) {
2400
- const startedAt = this.#now();
2401
- const line = (suffix) => {
2402
- this.#config.logger?.(`${phrase} ${String(this.#now() - startedAt)} ms${suffix}`);
2403
- };
2404
- try {
2405
- const result = await read();
2406
- line('');
2407
- return result;
2408
- }
2409
- catch (error) {
2410
- line(` (${error instanceof DiffError ? error.code : 'error'})`);
2411
- throw error;
2412
- }
2350
+ return measureDiff(GIT_DIFF_FILE_LOG, this.#diffClock, () => collectDiffFile(session.cwd, path, { run }));
2413
2351
  }
2352
+ /** Clock and logger of the diff read lines (`diff-measure.ts`), read at the time of each line. */
2353
+ #diffClock = {
2354
+ now: () => this.#now(), log: (line) => { this.#config.logger?.(line); },
2355
+ };
2414
2356
  // -------------------------------------------------------------------------
2415
2357
  // Cykl życia procesu
2416
2358
  // -------------------------------------------------------------------------
@@ -2938,6 +2880,7 @@ class RarogManager {
2938
2880
  if (session.launchPending && !this.#startWaits.has(session))
2939
2881
  this.#startExits.add(session);
2940
2882
  this.#dropStartWait(session);
2883
+ this.#trimDoneCards();
2941
2884
  return;
2942
2885
  }
2943
2886
  default: {
@@ -3108,6 +3051,15 @@ class RarogManager {
3108
3051
  }
3109
3052
  this.#herdrLifecycle.rememberGoneIdle(session);
3110
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();
3111
3063
  }
3112
3064
  // --- Kolejka podpięć (5.10: 17 równoległych odczytów historii to skok latencji) ---
3113
3065
  async #attachHerdrDriver(supervisor, session, key) {
@@ -3819,49 +3771,6 @@ class RarogManager {
3819
3771
  function describeError(error) {
3820
3772
  return error instanceof Error ? error.message : String(error);
3821
3773
  }
3822
- /**
3823
- * Treść decyzji do JEDNEJ linii karty listy: pierwsza linia, przycięta do `WAITING_TEXT_MAX`.
3824
- *
3825
- * Pierwsza linia, a nie „pierwsze 120 znaków całości": heredoc, wypisana treść `.env` i plan
3826
- * z trzema akapitami mają się tu nie zmieścić Z DEFINICJI. Cięcie po znakach jest wtedy tylko
3827
- * sufitem na długi jednolinijkowiec, a nie jedyną obroną przed wklejeniem pół pliku w sidebar.
3828
- * Wielokropek dokładamy WYŁĄCZNIE tam, gdzie faktycznie uciął — inaczej linia obiecuje ciąg
3829
- * dalszy, którego nie ma.
3830
- */
3831
- function waitingText(raw) {
3832
- const first = raw.split('\n', 1)[0]?.trim() ?? '';
3833
- /*
3834
- * Cięcie po PUNKTACH KODOWYCH, nie po jednostkach UTF-16: `slice(0, 120)` na linii
3835
- * z emoji na 120. znaku rozcina parę surogatów, `trimEnd()` samotnego surogata nie usuwa
3836
- * (to nie biały znak) i na karcie staje „�…". Grafem z modyfikatorem (flaga, odcień skóry)
3837
- * może się tu jeszcze rozpaść na dwa znaki, ale każdy z nich jest wtedy PEŁNY — żaden
3838
- * nie jest połówką kodu, więc przeglądarka rysuje litery, a nie znak zastępczy.
3839
- */
3840
- const points = [...first];
3841
- if (points.length <= WAITING_TEXT_MAX)
3842
- return first;
3843
- return `${points.slice(0, WAITING_TEXT_MAX).join('').trimEnd()}…`;
3844
- }
3845
- /**
3846
- * Treść ZGODY do jednej linii karty listy — z `displayText`, ale nie zawsze dosłownie.
3847
- *
3848
- * `displayText` jest jednolinijkowy tylko dla narzędzi z polem `command`. Dla całej reszty
3849
- * (`Edit`, `Write`, `Read`, `Task`, `WebFetch`…) `toolInputText` oddaje pretty-printowany JSON,
3850
- * więc PIERWSZĄ linią jest sama klamra — i karta mówiła „zgoda: Edit · {". Z takiego opisu
3851
- * bierzemy dokładnie to, co bierze etykieta tool-calla w transkrypcie (`summarizeToolInput`:
3852
- * `file_path`, `path`, `pattern`, `url`, `query`), a gdy nie ma czego wziąć — nic: „zgoda: Edit"
3853
- * jest uczciwe, klamra nie. Rozpoznanie idzie po PIERWSZEJ LINII, a nie po `startsWith('{')`,
3854
- * bo komenda Basha też umie zacząć się klamrą (`{ echo a; }` — grupa powłoki).
3855
- *
3856
- * Dwa `displayText` nie są treścią decyzji i tu nie wchodzą wcale:
3857
- *
3858
- * - PLAN (`ExitPlanMode`): treścią jest CAŁY plan, a jego nagłówek („# Plan") nie mówi nic
3859
- * ponad samo słowo „plan", które karta i tak stawia. Kanał globalny nie ma powodu wozić
3860
- * danych, których nikt nie rysuje (kontrakt `WaitingFor.text`),
3861
- * - karta ZDEGRADOWANA (`canAllow === false`, `DEGRADED_DISPLAY_TEXT`): tam stoi zdanie
3862
- * O RAROGU („nie potwierdziłem, czego dotyczy ten dialog"), a nie o decyzji. Powód
3863
- * degradacji niesie karta sesji (`herdrDialogReason`), nie wiersz listy.
3864
- */
3865
3774
  /**
3866
3775
  * Przedmiot zgody: wyjście z trybu planu albo zwykłe narzędzie. Jedyne miejsce, w którym
3867
3776
  * nazwa `ExitPlanMode` staje się faktem dla klienta — telefon buduje kartę planu z pola
@@ -3884,27 +3793,6 @@ function withOptionRoles(questions) {
3884
3793
  options: question.options.map((option) => (option.role === undefined ? { ...option, role: 'answer' } : option)),
3885
3794
  }));
3886
3795
  }
3887
- function decisionText(permission) {
3888
- if (permission.toolName === EXIT_PLAN_MODE_TOOL)
3889
- return '';
3890
- if (permission.canAllow === false)
3891
- return '';
3892
- const display = permission.displayText;
3893
- const first = display.split('\n', 1)[0]?.trim() ?? '';
3894
- if (first !== '{' && first !== '{}' && first !== '[')
3895
- return display;
3896
- let parsed;
3897
- try {
3898
- parsed = JSON.parse(display);
3899
- }
3900
- catch {
3901
- // Opis przycięty do 20 kB ma na końcu stopkę, więc nie jest już poprawnym JSON-em.
3902
- return '';
3903
- }
3904
- const summary = summarizeToolInput(permission.toolName, parsed);
3905
- // Bez trafionego klucza `summarizeToolInput` oddaje NAZWĘ narzędzia — a ta stoi już obok.
3906
- return summary === permission.toolName ? '' : summary;
3907
- }
3908
3796
  /**
3909
3797
  * Czy model wolno podać we fladze `--model`?
3910
3798
  *
@@ -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
  }
@@ -36,9 +36,11 @@ export const MAX_MESSAGE_BYTES = 256 * 1024;
36
36
  * i dla tablicy wiadomości (obie struktury trzymają te same wiadomości, obie oddają je
37
37
  * na telefon: ring przez replay `Last-Event-ID`, tablica przez `transcript-snapshot`).
38
38
  *
39
- * 4 MB × 30 paneli (sufit liczby paneli) to pesymistycznie 120 MB — tyle wolno Rarogowi zająć
40
- * transkryptami. Przekroczenie wypycha NAJSTARSZE wpisy, dokładnie tak jak sufit sztuk;
41
- * 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.
42
44
  */
43
45
  export const RING_MAX_BYTES = 4 * 1024 * 1024;
44
46
  /**
@@ -91,20 +91,23 @@ export function markSeen(session, deps, pickUp) {
91
91
  * so a receipt taken there would cover the turn's real result;
92
92
  * - no decision card waits on it: a permission card or a question that comes after the turn end moves no state, so it
93
93
  * can stand over the result in `waiting-input`;
94
- * - the `stateSince` is the session's current one. Equality, not order: a history import can move `stateSince` back,
95
- * and the agent read another result then;
96
94
  * - the session is in the engine conversation the agent read ({@link inReadConversation}): `/clear` and `/resume`
97
95
  * change it with no change of state or `stateSince`. A session without a conversation yet has no result the agent
98
- * could have read.
96
+ * could have read;
97
+ * - the session's memory holds no message newer than the read and its `stateSince` is the one of the read
98
+ * (`Session.readMark` equals the pick-up's). A short turn whose `working` herdr's grace drops ends with no change of
99
+ * state or `stateSince`, and only its messages tell its result from the one the agent read. A turn whose `working`
100
+ * reaches the session can end before its messages reach the memory, and only its state stamps tell it. A turn that
101
+ * adds no message (a context compaction alone) moves the stamp too, so the agent reads the session again.
99
102
  */
100
103
  function pickUpMeetsResult(session, deps, pickUp) {
101
104
  if (session.state !== 'waiting-input' || deps.decisionStands(session))
102
105
  return false;
103
- if (pickUp.stateSince !== session.stateSince)
104
- return false;
105
106
  if (session.engineSessionId === undefined || session.engineSessionId === '')
106
107
  return false;
107
- return inReadConversation(session, pickUp.conversation);
108
+ if (!inReadConversation(session, pickUp.conversation))
109
+ return false;
110
+ return pickUp.readMark === session.readMark;
108
111
  }
109
112
  /**
110
113
  * „Oznacz jako nieprzeczytane" z listy — odwrotność {@link markSeen}, tylko lokalnie.
@@ -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
@@ -0,0 +1,30 @@
1
+ import { sessionCwdInArea } from './companion-scope.js';
2
+ import { BadRequestError } from './errors.js';
3
+ import { HERDR_CODEX_GIT_MESSAGE, HERDR_OUT_OF_SCOPE_DIFF_MESSAGE } from './state-sentences.js';
4
+ /**
5
+ * Bramka wspólna WSZYSTKICH tras diffa — starej i obu per plik. Oddaje sesję, z której
6
+ * katalogu wolno czytać, albo `null` w demo: tam diff to stały mock, bez odczytu z dysku.
7
+ */
8
+ export function diffSession(id, port) {
9
+ const session = port.require(id);
10
+ // Bramka zasięgu: diff roboczy to TREŚĆ katalogu, a wpis Codexa obiecuje sam stan. Klient
11
+ // przycisku dla Codexa nie rysuje — to jest druga linia, dla starego klienta i dla `curl`.
12
+ if (session.engine === 'codex')
13
+ throw new BadRequestError(HERDR_CODEX_GIT_MESSAGE);
14
+ // Panel poza zasięgiem: ta sama granica co transkrypt i wycinek ekranu — treść katalogu zostaje na Macu.
15
+ if (session.outOfScope === true)
16
+ throw new BadRequestError(HERDR_OUT_OF_SCOPE_DIFF_MESSAGE);
17
+ /*
18
+ * Niżej, za gałęzią demo: `outOfScope` mówi o katalogu, w którym panel stoi TERAZ (nadzorca
19
+ * liczy go od nowa po `cd`), a diff czyta `session.cwd` — katalog z chwili pojawienia się
20
+ * panelu, którego reattach nie rusza. Panel, który wystartował poza korzeniami i zrobił `cd` pod korzeń, miał więc zasięg,
21
+ * a diff dalej czytał stary, prywatny katalog. Bramka pyta o TEN
22
+ * katalog, z którego pójdzie odczyt, tą samą funkcją co nadzorca (`scopeOf`).
23
+ */
24
+ // Demo nie ma korzeni ani prawdziwych katalogów: jego diff to stały mock, bez odczytu z dysku.
25
+ if (port.config.demo)
26
+ return null;
27
+ if (!sessionCwdInArea(session, port.config))
28
+ throw new BadRequestError(HERDR_OUT_OF_SCOPE_DIFF_MESSAGE);
29
+ return session;
30
+ }