@rarog/server 1.1.1 → 1.1.2-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/node_modules/@rarog/shared/package.json +1 -1
  2. package/node_modules/@rarog/shared/src/decode.js +3 -0
  3. package/node_modules/@rarog/shared/src/notify-copy.js +1 -0
  4. package/node_modules/@rarog/shared/src/protocol/background.js +7 -0
  5. package/node_modules/@rarog/shared/src/sentences/dialogs.js +10 -0
  6. package/node_modules/@rarog/shared/src/sentences/push.js +3 -0
  7. package/package.json +2 -2
  8. package/server/src/bootstrap/pr-status.js +15 -7
  9. package/server/src/bootstrap/push.js +36 -5
  10. package/server/src/cli/doctor-pr-status.js +10 -6
  11. package/server/src/demo/control.js +4 -2
  12. package/server/src/demo/mock-herdr.js +2 -2
  13. package/server/src/demo/scenarios.js +31 -17
  14. package/server/src/demo/seeds.js +62 -38
  15. package/server/src/drivers/herdr/pull-request-poll.js +5 -5
  16. package/server/src/drivers/herdr/queue-take-back.js +4 -0
  17. package/server/src/drivers/herdr/start-dialog-gate.js +132 -0
  18. package/server/src/drivers/herdr-driver.js +75 -15
  19. package/server/src/herdr/background/cli-shapes.js +16 -15
  20. package/server/src/herdr/background/index.js +7 -7
  21. package/server/src/herdr/background/merge.js +17 -5
  22. package/server/src/herdr/background/notification.js +0 -4
  23. package/server/src/herdr/background/pull-request-files.js +53 -161
  24. package/server/src/herdr/background/pull-requests.js +54 -632
  25. package/server/src/herdr/background/work.js +84 -0
  26. package/server/src/herdr/dialogs/copy.js +7 -0
  27. package/server/src/herdr/dialogs/index.js +4 -1
  28. package/server/src/herdr/dialogs/screen/form.js +2 -1
  29. package/server/src/herdr/dialogs/screen/option-run.js +25 -3
  30. package/server/src/herdr/dialogs/screen/parse.js +3 -3
  31. package/server/src/herdr/dialogs/screen/signatures.js +55 -0
  32. package/server/src/herdr/dialogs/screen/start-dialog.js +72 -0
  33. package/server/src/herdr/dialogs/screen/trust-arrow.js +46 -9
  34. package/server/src/herdr/jsonl-follow.js +6 -2
  35. package/server/src/herdr/label-code.js +104 -0
  36. package/server/src/herdr/label-migration.js +142 -0
  37. package/server/src/herdr/launcher.js +30 -5
  38. package/server/src/herdr/provenance.js +80 -40
  39. package/server/src/herdr/start-dialog-wait.js +96 -0
  40. package/server/src/herdr/supervisor.js +33 -10
  41. package/server/src/herdr/workspace-resolver.js +5 -4
  42. package/server/src/index.js +8 -3
  43. package/server/src/notify/apns-payload.js +5 -3
  44. package/server/src/notify/content.js +37 -0
  45. package/server/src/notify/index.js +4 -0
  46. package/server/src/notify/live-activity-state.js +9 -5
  47. package/server/src/notify/live-activity.js +5 -2
  48. package/server/src/notify/policy.js +4 -2
  49. package/server/src/notify/stalled-wait.js +213 -0
  50. package/server/src/pr-status/facts.js +87 -0
  51. package/server/src/pr-status/gh.js +76 -9
  52. package/server/src/pr-status/index.js +1 -10
  53. package/server/src/pr-status/source.js +20 -6
  54. package/server/src/pr-status/tracker.js +32 -9
  55. package/server/src/sessions/conversation-lists.js +8 -2
  56. package/server/src/sessions/driver-events.js +7 -3
  57. package/server/src/sessions/interrupt-windows.js +28 -4
  58. package/server/src/sessions/manager.js +14 -5
  59. package/server/src/sessions/pr-status-link.js +64 -16
  60. package/server/src/sessions/session.js +10 -3
  61. package/server/src/sessions/state-machine.js +11 -0
  62. package/server/src/sessions/test-session.js +50 -0
  63. package/server/src/term/herdr-backend.js +15 -12
  64. package/server/src/term/lifecycle.js +4 -6
@@ -1,53 +1,31 @@
1
1
  /**
2
- * Czytnik plików rozmowy pod kątem pull requestów: plik główny `<uuid>.jsonl`, pliki subagentów
3
- * `subagents/agent-<id>.jsonl` i agentów workflow `subagents/workflows/wf_<id>/agent-<id>.jsonl`.
4
- * Rozpoznanie i lista: `pull-requests.ts`; opis całości: `docs/pull-requests.md`.
2
+ * Reader of the MAIN conversation file `<uuid>.jsonl` for pull requests: the linked set and the window's lower bound
3
+ * (`pull-requests.ts`), bound to one conversation. Whole picture: `docs/pull-requests.md`.
5
4
  *
6
- * Dlaczego osobny czytnik, a nie follower pliku głównego i czytnik pliku subagenta (`agent-file.ts`):
7
- * tamte patrzą na wybrane pliki (okno ogona, otwarci agenci), a PR powstaje w dowolnym agencie, także takim,
8
- * który dawno skończył, i ma być widoczny po restarcie serwera. Ten moduł czyta więc WSZYSTKIE pliki rozmowy
9
- * sesji, przyrostowo, z prefiltrem przed `JSON.parse` ({@link mayCarryPullRequest}). Plik główny czyta drugi
10
- * raz (follower czyta go po swojemu): to cena jednego mechanizmu dla trzech źródeł.
5
+ * Why a reader of its own and not the follower: the follower reads a tail window, and the linked set covers the whole
6
+ * file and must hold after a server restart. The reader goes through the file incrementally with a prefilter before
7
+ * `JSON.parse` ({@link mayCarryPullRequestLink}); until the window is known it parses every line. Subagent and
8
+ * workflow agent files are not read: the link entry stands in the main file.
11
9
  *
12
- * Granica odczytu: z pliku agenta workflow ten moduł czyta TREŚĆ (wywołania `Bash` i ich wyniki), nie tylko
13
- * tag z pierwszej linii jak `workflow-run.ts`. Dalej wychodzi wyłącznie adres PR, numer, repo, czas i tytuł
14
- * z `--title`. Pliki subagentów i agentów workflow czyta tylko za zgodą `RAROG_AGENT_FILES` (opcja `subagents`).
15
- *
16
- * Koszt (pomiar na magazynie plików rozmów CLI 2.1.216–2.1.319, 313 sesji z katalogiem `subagents/`): pliki
17
- * agentów jednej sesji mają w medianie 1,1 MiB, p90 63 MiB, p99 418 MiB, najwięcej 976 MiB w 356 plikach. Dlatego
18
- * jeden odczyt bierze najwyżej {@link PULL_REQUEST_SCAN_BUDGET_BYTES}, a reszta czeka na następny (`backlog`);
19
- * nic nie jest pomijane, offset każdego pliku idzie dalej. Odczyt od {@link PULL_REQUEST_SCAN_LOG_BYTES}
20
- * zostawia w logu linię z kosztem.
21
- *
22
- * One file's read (byte chunks, lines through `jsonl-lines.ts` with an over-ceiling line skipped whole, a file
23
- * shorter than the offset or with another inode read from the start) is `incremental-read.ts`. Pliki trzymane są
24
- * pod nazwą względną wobec katalogu sesji, więc przeniesienie katalogu (`EnterWorktree`) zachowuje
25
- * offsety. Moduł nigdy nie rzuca; brak pliku albo katalogu to normalny stan.
26
- *
27
- * Output files: a recognized `gh pr create` that ran in the background ends with a CLI notification naming its
28
- * output file (`<tmp>/claude-<uid>/<slug>/<session uuid>/tasks/<task id>.output`). The reader reads that one file,
29
- * after a shape check of the path ({@link isTaskOutputPath}), through `safe-read.ts` without following a symlink and
30
- * up to {@link PULL_REQUEST_OUTPUT_MAX_BYTES}; a longer file gives nothing. The agent in the sandbox can write that
31
- * directory, so a FIFO or a symlink there is expected and gives nothing. Only the PR URL leaves the file.
10
+ * One read takes at most {@link PULL_REQUEST_SCAN_BUDGET_BYTES}; the rest waits for the next one (`backlog`), nothing
11
+ * is skipped. A read from {@link PULL_REQUEST_SCAN_LOG_BYTES} leaves a cost line in the log. One file's read (byte
12
+ * chunks, lines through `jsonl-lines.ts` with an over-ceiling line skipped whole, a file shorter than the offset or
13
+ * with another inode read from the start) is `incremental-read.ts`. The module never throws; a missing file is a
14
+ * normal state.
32
15
  */
33
- import { readdir } from 'node:fs/promises';
34
- import { basename, dirname, isAbsolute, join, normalize } from 'node:path';
35
16
  import { defaultStoreRoot } from '../../cli-store.js';
36
- import { readRegularFile } from '../../safe-read.js';
37
- import { TRANSCRIPT_EXT, locateTranscript } from '../transcript-path.js';
17
+ import { locateTranscript } from '../transcript-path.js';
38
18
  import { parseJsonlEntry } from '../jsonl-pending.js';
39
- import { CLI_SHAPES } from './cli-shapes.js';
40
- import { isAgentId, isBackgroundTaskId, isRunId } from './ids.js';
41
19
  import { cursorAt, readIncrement } from './incremental-read.js';
42
- import { createPullRequestCalls, createPullRequestList, mayCarryPullRequest, pullRequestsFromOutput, pullRequestsOf, } from './pull-requests.js';
20
+ import { createLinkedPullRequests, entryTimeOf, mayCarryPullRequestLink, pullRequestLinkOf, } from './pull-requests.js';
43
21
  /**
44
- * Co ile driver czyta pliki rozmowy po sygnale (przyrost pliku głównego, zmiana listy zadań w tle). Sygnały
45
- * w tym oknie składają się w jeden odczyt.
22
+ * How long after a signal the driver reads the conversation file (the main file grew, a PR link entry). Signals in
23
+ * this window fold into one read.
46
24
  */
47
25
  export const PULL_REQUESTS_POLL_MS = 5_000;
48
26
  /** Przerwa między odczytami, gdy poprzedni zostawił zaległość (budżet się skończył). */
49
27
  export const PULL_REQUESTS_BACKLOG_MS = 1_000;
50
- /** Ile bajtów najwyżej czyta jeden odczyt, łącznie ze wszystkich plików. */
28
+ /** How many bytes one read takes at most. */
51
29
  export const PULL_REQUEST_SCAN_BUDGET_BYTES = 256 * 1024 * 1024;
52
30
  /** Jedna porcja odczytu. */
53
31
  export const PULL_REQUEST_CHUNK_BYTES = 1024 * 1024;
@@ -57,43 +35,9 @@ export const PULL_REQUEST_LINE_MAX_BYTES = 8 * 1024 * 1024;
57
35
  export const PULL_REQUEST_SCAN_LOG_BYTES = 8 * 1024 * 1024;
58
36
  /** Fraza linii logu z kosztem odczytu. */
59
37
  export const PULL_REQUEST_SCAN_LOG = 'pull request scan';
60
- /** Ceiling of one background output file; `gh pr create` prints a few lines. A longer file gives no PR. */
61
- export const PULL_REQUEST_OUTPUT_MAX_BYTES = 64 * 1024;
62
- const NOTIFICATION = CLI_SHAPES.notification.literals;
63
- /** The session directory that holds `tasks/`: a conversation uuid. */
64
- const SESSION_DIR = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
65
- /**
66
- * Whether `path` from a notification has the shape of the task's output file: absolute and already normal (no `..`,
67
- * `.`, `//` or trailing `/`), named `<taskId>.output`, in a `tasks` directory whose parent is a session uuid.
68
- */
69
- export function isTaskOutputPath(path, taskId) {
70
- if (!isBackgroundTaskId(taskId) || !isAbsolute(path) || normalize(path) !== path || path.endsWith('/'))
71
- return false;
72
- if (basename(path) !== `${taskId}${NOTIFICATION.outputExtension}`)
73
- return false;
74
- const tasks = dirname(path);
75
- return basename(tasks) === NOTIFICATION.outputDir && SESSION_DIR.test(basename(dirname(tasks)));
76
- }
77
- /** PRs from a background call's output file; nothing on a refused path, a missing or odd file, or an error. */
78
- async function outputPullRequests(output) {
79
- if (!isTaskOutputPath(output.path, output.taskId))
80
- return [];
81
- try {
82
- const read = await readRegularFile(output.path, { maxBytes: PULL_REQUEST_OUTPUT_MAX_BYTES, followSymlink: false });
83
- if (read === null || read.truncated)
84
- return [];
85
- return pullRequestsFromOutput(read.bytes.toString('utf8'), output);
86
- }
87
- catch {
88
- return [];
89
- }
90
- }
91
- /** Nazwa względna pliku głównego w mapie stanów (pliki agentów mają ścieżkę względną wobec katalogu sesji). */
92
- const MAIN = '';
93
38
  class Reader {
94
39
  #root;
95
40
  #cwd;
96
- #subagents;
97
41
  #budgetBytes;
98
42
  #chunkBytes;
99
43
  #lineMaxBytes;
@@ -103,8 +47,10 @@ class Reader {
103
47
  #uuid;
104
48
  /** Ścieżka pliku głównego; `null` = trzeba jej szukać (pierwszy odczyt, `repoint`, `relocated`). */
105
49
  #mainPath = null;
106
- #files = new Map();
107
- #list = createPullRequestList();
50
+ #cursor;
51
+ #set = createLinkedPullRequests();
52
+ /** The window's lower bound; found again when the file is read from the start. */
53
+ #windowStart = null;
108
54
  /** Rośnie przy `repoint()` i `relocated()`; odczyt rozpoczęty wcześniej niczego nie oddaje. */
109
55
  #generation = 0;
110
56
  #closed = false;
@@ -113,13 +59,15 @@ class Reader {
113
59
  this.#cwd = opts.cwd;
114
60
  this.#uuid = opts.agentSessionId;
115
61
  this.#locate = opts.locate;
116
- this.#subagents = opts.subagents;
117
62
  this.#chunkBytes = Math.max(1, opts.chunkBytes ?? PULL_REQUEST_CHUNK_BYTES);
118
63
  this.#budgetBytes = Math.max(this.#chunkBytes, opts.budgetBytes ?? PULL_REQUEST_SCAN_BUDGET_BYTES);
119
64
  this.#lineMaxBytes = Math.max(1, opts.lineMaxBytes ?? PULL_REQUEST_LINE_MAX_BYTES);
120
65
  this.#now = opts.now ?? Date.now;
121
66
  this.#log = opts.logger ?? ((message) => { console.warn(message); });
122
67
  }
68
+ get #links() {
69
+ return { linked: this.#set.linked, windowStart: this.#windowStart };
70
+ }
123
71
  async read() {
124
72
  if (this.#closed)
125
73
  return null;
@@ -135,40 +83,24 @@ class Reader {
135
83
  }
136
84
  const mainPath = this.#mainPath;
137
85
  if (mainPath === null)
138
- return { pullRequests: this.#list.pullRequests, backlog: false };
139
- const dir = mainPath.slice(0, mainPath.length - TRANSCRIPT_EXT.length);
140
- const names = [MAIN, ...(this.#subagents ? await agentFiles(dir) : [])];
86
+ return { links: this.#links, backlog: false };
87
+ const startedAt = this.#now();
88
+ const outcome = await this.#advance(mainPath, stale);
141
89
  if (stale())
142
90
  return null;
143
- const startedAt = this.#now();
144
- let budget = this.#budgetBytes;
145
- let read = 0;
146
- let backlog = false;
147
- for (const name of names) {
148
- if (budget <= 0) {
149
- backlog = true;
150
- break;
151
- }
152
- const outcome = await this.#advance(name === MAIN ? mainPath : join(dir, name), name, budget, stale);
153
- if (stale())
154
- return null;
155
- budget -= outcome.bytes;
156
- read += outcome.bytes;
157
- if (outcome.more)
158
- backlog = true;
91
+ if (outcome.bytes >= PULL_REQUEST_SCAN_LOG_BYTES) {
92
+ this.#log(`rarog: ${PULL_REQUEST_SCAN_LOG} ${this.#uuid}: ${String(outcome.bytes)} B `
93
+ + `in ${String(Math.round(this.#now() - startedAt))} ms${outcome.more ? ', more in the next read' : ''}`);
159
94
  }
160
- if (read >= PULL_REQUEST_SCAN_LOG_BYTES) {
161
- this.#log(`rarog: ${PULL_REQUEST_SCAN_LOG} ${this.#uuid}: ${String(read)} B from ${String(names.length)} files `
162
- + `in ${String(Math.round(this.#now() - startedAt))} ms${backlog ? ', more in the next read' : ''}`);
163
- }
164
- return { pullRequests: this.#list.pullRequests, backlog };
95
+ return { links: this.#links, backlog: outcome.more };
165
96
  }
166
97
  repoint(agentSessionId) {
167
98
  this.#generation += 1;
168
99
  this.#uuid = agentSessionId;
169
100
  this.#mainPath = null;
170
- this.#files = new Map();
171
- this.#list = createPullRequestList();
101
+ this.#cursor = undefined;
102
+ this.#set = createLinkedPullRequests();
103
+ this.#windowStart = null;
172
104
  }
173
105
  relocated() {
174
106
  this.#generation += 1;
@@ -176,82 +108,42 @@ class Reader {
176
108
  }
177
109
  close() {
178
110
  this.#closed = true;
179
- this.#files = new Map();
111
+ this.#cursor = undefined;
180
112
  }
181
113
  /**
182
- * Doczytuje jeden plik najwyżej o `budget` bajtów. `bytes` = ile przeczytano, `more` = plik ma jeszcze
183
- * nieprzeczytaną część. Błąd w połowie zostawia offset za ostatnią przerobioną porcją.
114
+ * Reads the file on by at most the byte budget. `bytes` = how much was read, `more` = the file has an unread part.
115
+ * An error midway leaves the offset after the last handled chunk.
184
116
  */
185
- #advance(path, name, budget, stale) {
186
- const list = this.#list;
117
+ #advance(path, stale) {
118
+ const set = this.#set;
187
119
  return readIncrement(path, {
188
- cursor: this.#files.get(name),
189
- // Inna zawartość pod tą samą nazwą albo plik krótszy: czytamy od początku (lista PR-ów zostaje,
190
- // ten sam adres drugi raz niczego nie dodaje).
120
+ cursor: this.#cursor,
121
+ // Other content under the same name, or a shorter file: read from the start. The set stays (the same URL again
122
+ // adds nothing); the window is found again from the first lines.
191
123
  restart: (identity) => {
192
- const state = { ...cursorAt(identity), calls: createPullRequestCalls() };
193
- this.#files.set(name, state);
194
- return state;
124
+ const cursor = cursorAt(identity);
125
+ this.#cursor = cursor;
126
+ this.#windowStart = null;
127
+ return cursor;
195
128
  },
196
- budgetBytes: budget,
129
+ budgetBytes: this.#budgetBytes,
197
130
  chunkBytes: this.#chunkBytes,
198
131
  lineMaxBytes: this.#lineMaxBytes,
199
132
  stale,
200
- onLines: (lines, state) => {
201
- const outputs = [];
133
+ onLines: (lines) => {
202
134
  for (const line of lines) {
203
- if (!mayCarryPullRequest(line))
135
+ if (this.#windowStart !== null && !mayCarryPullRequestLink(line))
204
136
  continue;
205
- const found = pullRequestsOf(parseJsonlEntry(line.toString('utf8')), state.calls);
206
- for (const pr of found.pullRequests)
207
- list.add(pr);
208
- outputs.push(...found.outputs);
137
+ const entry = parseJsonlEntry(line.toString('utf8'));
138
+ this.#windowStart ??= entryTimeOf(entry);
139
+ const pr = pullRequestLinkOf(entry);
140
+ if (pr !== null)
141
+ set.add(pr);
209
142
  }
210
- if (outputs.length === 0)
211
- return undefined;
212
- // The offset is already past these lines and the waiting calls left the memory, so every output read here
213
- // lands in the list it was asked for, even when the read went stale meanwhile: `relocated()` keeps that
214
- // list, `repoint()` and `close()` drop it.
215
- return (async () => {
216
- for (const output of outputs)
217
- for (const pr of await outputPullRequests(output))
218
- list.add(pr);
219
- })();
220
143
  },
221
144
  });
222
145
  }
223
146
  }
224
- /**
225
- * Pliki agentów sesji jako ścieżki względne wobec katalogu sesji, posortowane: `subagents/agent-<id>.jsonl`
226
- * i `subagents/workflows/wf_<id>/agent-<id>.jsonl`. Nazwy przechodzą przez strażniki `ids.ts`, zanim staną
227
- * się ścieżką. Brak katalogu = pusta lista.
228
- */
229
- async function agentFiles(dir) {
230
- const agents = async (sub) => {
231
- try {
232
- return (await readdir(join(dir, sub), { withFileTypes: true }))
233
- .filter((entry) => entry.isFile() && entry.name.startsWith('agent-') && entry.name.endsWith(TRANSCRIPT_EXT)
234
- && isAgentId(entry.name.slice('agent-'.length, -TRANSCRIPT_EXT.length)))
235
- .map((entry) => join(sub, entry.name));
236
- }
237
- catch {
238
- return [];
239
- }
240
- };
241
- const found = await agents('subagents');
242
- let runs = [];
243
- try {
244
- runs = (await readdir(join(dir, 'subagents', 'workflows'), { withFileTypes: true }))
245
- .filter((entry) => entry.isDirectory() && isRunId(entry.name))
246
- .map((entry) => entry.name);
247
- }
248
- catch {
249
- runs = [];
250
- }
251
- for (const run of runs)
252
- found.push(...await agents(join('subagents', 'workflows', run)));
253
- return found.sort();
254
- }
255
147
  export function createPullRequestFilesReader(opts) {
256
148
  return new Reader(opts);
257
149
  }