@rarog/server 1.1.1 → 1.1.2-beta.2

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 (161) hide show
  1. package/node_modules/@rarog/shared/package.json +1 -1
  2. package/node_modules/@rarog/shared/src/decode.js +46 -1
  3. package/node_modules/@rarog/shared/src/notify-copy.js +2 -0
  4. package/node_modules/@rarog/shared/src/protocol/background.js +7 -0
  5. package/node_modules/@rarog/shared/src/protocol/context.js +57 -0
  6. package/node_modules/@rarog/shared/src/protocol/coordination.js +42 -0
  7. package/node_modules/@rarog/shared/src/protocol/dialog-live.js +117 -0
  8. package/node_modules/@rarog/shared/src/protocol/files.js +1 -1
  9. package/node_modules/@rarog/shared/src/protocol/inbox.js +6 -0
  10. package/node_modules/@rarog/shared/src/protocol/presence.js +47 -0
  11. package/node_modules/@rarog/shared/src/protocol.js +14 -146
  12. package/node_modules/@rarog/shared/src/rest.js +16 -1
  13. package/node_modules/@rarog/shared/src/sentences/dialogs.js +10 -0
  14. package/node_modules/@rarog/shared/src/sentences/push.js +9 -0
  15. package/node_modules/@rarog/shared/src/sentences/rest.js +9 -0
  16. package/node_modules/@rarog/shared/src/sentences/restart.js +1 -0
  17. package/node_modules/@rarog/shared/src/sentences/session.js +24 -0
  18. package/package.json +2 -2
  19. package/plugin/rarog/.claude-plugin/plugin.json +4 -0
  20. package/plugin/rarog/bin/rarog-coordinator +7 -0
  21. package/plugin/rarog/hooks/hooks.json +18 -0
  22. package/plugin/rarog/hooks/recipient.mjs +95 -0
  23. package/plugin/rarog/lib/coordinator.mjs +1340 -0
  24. package/plugin/rarog/lib/threads.mjs +350 -0
  25. package/plugin/rarog/skills/coordinator/SKILL.md +111 -0
  26. package/plugin/rarog/skills/coordinator/check-and-merge.md +46 -0
  27. package/plugin/rarog/skills/coordinator/close-thread.md +15 -0
  28. package/plugin/rarog/skills/coordinator/role.md +61 -0
  29. package/plugin/rarog/skills/coordinator/send-back.md +39 -0
  30. package/plugin/rarog/skills/coordinator/start-thread.md +43 -0
  31. package/server/src/bootstrap/coordination.js +49 -0
  32. package/server/src/bootstrap/coordinator-start.js +27 -0
  33. package/server/src/bootstrap/inbox.js +4 -0
  34. package/server/src/bootstrap/pr-status.js +15 -7
  35. package/server/src/bootstrap/push.js +59 -5
  36. package/server/src/cli/doctor-pr-status.js +10 -6
  37. package/server/src/companion/catalog.js +1 -1
  38. package/server/src/companion/index.js +2 -4
  39. package/server/src/config/flags.js +4 -0
  40. package/server/src/config-env.js +15 -0
  41. package/server/src/config.js +17 -3
  42. package/server/src/coordination/merge-events.js +86 -0
  43. package/server/src/coordination/merge-prompt.js +244 -0
  44. package/server/src/coordination/registry.js +289 -0
  45. package/server/src/coordination/state.js +94 -0
  46. package/server/src/coordination/summary.js +422 -0
  47. package/server/src/coordination/thread-file.js +245 -0
  48. package/server/src/coordination/thread-git.js +110 -0
  49. package/server/src/coordination/watch.js +237 -0
  50. package/server/src/demo/content/coordinator.js +89 -0
  51. package/server/src/demo/content/en.js +57 -1
  52. package/server/src/demo/content/pl.js +57 -1
  53. package/server/src/demo/control.js +4 -2
  54. package/server/src/demo/inbox.js +12 -0
  55. package/server/src/demo/mock-herdr.js +5 -4
  56. package/server/src/demo/review-routes.js +2 -2
  57. package/server/src/demo/scenarios.js +31 -17
  58. package/server/src/demo/seeds.js +82 -40
  59. package/server/src/drivers/herdr/live-dialog.js +412 -0
  60. package/server/src/drivers/herdr/live-step.js +261 -0
  61. package/server/src/drivers/herdr/pause-gate.js +60 -0
  62. package/server/src/drivers/herdr/pull-request-poll.js +5 -5
  63. package/server/src/drivers/herdr/queue-take-back.js +4 -0
  64. package/server/src/drivers/herdr/returned-prompt.js +4 -1
  65. package/server/src/drivers/herdr/screen-fallback.js +50 -0
  66. package/server/src/drivers/herdr/start-dialog-gate.js +136 -0
  67. package/server/src/drivers/herdr-driver.js +159 -77
  68. package/server/src/files/refusals.js +9 -2
  69. package/server/src/files/session-gate.js +5 -4
  70. package/server/src/git-branch-diff.js +194 -0
  71. package/server/src/herdr/argv.js +34 -3
  72. package/server/src/herdr/audit.js +32 -1
  73. package/server/src/herdr/background/cli-shapes.js +35 -15
  74. package/server/src/herdr/background/index.js +7 -7
  75. package/server/src/herdr/background/merge.js +17 -5
  76. package/server/src/herdr/background/notification.js +0 -4
  77. package/server/src/herdr/background/pull-request-files.js +53 -161
  78. package/server/src/herdr/background/pull-requests.js +54 -632
  79. package/server/src/herdr/background/queued-prompt.js +46 -0
  80. package/server/src/herdr/background/work.js +96 -0
  81. package/server/src/herdr/client.js +22 -46
  82. package/server/src/herdr/commands/catalog.js +11 -7
  83. package/server/src/herdr/commands/discover.js +33 -1
  84. package/server/src/herdr/commands/index.js +3 -2
  85. package/server/src/herdr/dialogs/copy.js +7 -0
  86. package/server/src/herdr/dialogs/index.js +13 -1
  87. package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +4 -56
  88. package/server/src/herdr/dialogs/live/model.js +220 -0
  89. package/server/src/herdr/dialogs/live/policy.js +108 -0
  90. package/server/src/herdr/dialogs/live/view.js +261 -0
  91. package/server/src/herdr/dialogs/screen/form.js +6 -4
  92. package/server/src/herdr/dialogs/screen/option-run.js +25 -3
  93. package/server/src/herdr/dialogs/screen/parse.js +3 -3
  94. package/server/src/herdr/dialogs/screen/signatures.js +78 -0
  95. package/server/src/herdr/dialogs/screen/start-dialog.js +72 -0
  96. package/server/src/herdr/dialogs/screen/trust-arrow.js +46 -9
  97. package/server/src/herdr/engines.js +96 -0
  98. package/server/src/herdr/history-steps.js +9 -4
  99. package/server/src/herdr/identity.js +20 -5
  100. package/server/src/herdr/jsonl-follow.js +26 -3
  101. package/server/src/herdr/label-code.js +104 -0
  102. package/server/src/herdr/label-migration.js +142 -0
  103. package/server/src/herdr/launcher.js +30 -5
  104. package/server/src/herdr/plugin-copy.js +281 -0
  105. package/server/src/herdr/provenance.js +80 -40
  106. package/server/src/herdr/session-index.js +19 -0
  107. package/server/src/herdr/start-dialog-wait.js +96 -0
  108. package/server/src/herdr/supervisor.js +49 -23
  109. package/server/src/herdr/types.js +1 -0
  110. package/server/src/herdr/workspace-resolver.js +5 -4
  111. package/server/src/inbox/card.js +31 -8
  112. package/server/src/inbox/heads.js +1 -0
  113. package/server/src/inbox/inbox.js +21 -4
  114. package/server/src/inbox/removals.js +10 -1
  115. package/server/src/index.js +45 -8
  116. package/server/src/notify/apns-payload.js +5 -3
  117. package/server/src/notify/content.js +64 -0
  118. package/server/src/notify/index.js +11 -3
  119. package/server/src/notify/live-activity-state.js +19 -6
  120. package/server/src/notify/live-activity.js +5 -2
  121. package/server/src/notify/policy.js +53 -13
  122. package/server/src/notify/ready-to-merge.js +148 -0
  123. package/server/src/notify/stalled-wait.js +213 -0
  124. package/server/src/pr-status/facts.js +87 -0
  125. package/server/src/pr-status/gh.js +76 -9
  126. package/server/src/pr-status/index.js +1 -10
  127. package/server/src/pr-status/source.js +20 -6
  128. package/server/src/pr-status/tracker.js +32 -9
  129. package/server/src/project-root.js +233 -0
  130. package/server/src/routes/sessions.js +68 -2
  131. package/server/src/sessions/branch-diff.js +57 -0
  132. package/server/src/sessions/cli-registry.js +17 -3
  133. package/server/src/sessions/companion-scope.js +2 -1
  134. package/server/src/sessions/consent-cards.js +49 -2
  135. package/server/src/sessions/conversation-lists.js +11 -2
  136. package/server/src/sessions/coordinator-start.js +172 -0
  137. package/server/src/sessions/demo-modules.js +1 -0
  138. package/server/src/sessions/demo-seeds.js +100 -0
  139. package/server/src/sessions/driver-events.js +68 -14
  140. package/server/src/sessions/herdr-lifecycle.js +11 -4
  141. package/server/src/sessions/interrupt-windows.js +28 -4
  142. package/server/src/sessions/launch-gate.js +36 -11
  143. package/server/src/sessions/live-dialog.js +69 -0
  144. package/server/src/sessions/manager.js +138 -287
  145. package/server/src/sessions/owner-turn.js +36 -0
  146. package/server/src/sessions/pr-status-link.js +64 -16
  147. package/server/src/sessions/seen-marks.js +31 -12
  148. package/server/src/sessions/session-dialog.js +82 -0
  149. package/server/src/sessions/session-git.js +1 -0
  150. package/server/src/sessions/session-scope.js +6 -5
  151. package/server/src/sessions/session-take-back.js +5 -0
  152. package/server/src/sessions/session.js +82 -10
  153. package/server/src/sessions/state-machine.js +13 -0
  154. package/server/src/sessions/state-sentences.js +87 -30
  155. package/server/src/sessions/test-session.js +50 -0
  156. package/server/src/sessions/waiting-line.js +49 -0
  157. package/server/src/term/herdr-backend.js +15 -12
  158. package/server/src/term/lifecycle.js +4 -6
  159. package/server/src/transcript-import.js +20 -2
  160. package/server/src/version.js +4 -0
  161. /package/server/src/{companion/asks-owner.js → asks-owner.js} +0 -0
@@ -1,48 +1,20 @@
1
1
  import { asRecord } from '../../drivers/tool-text.js';
2
- import { clipUnits, stripControlChars } from '../../text.js';
3
2
  import { parseJsonlEntry } from '../jsonl-pending.js';
4
- import { harnessNoticeText } from './artifacts.js';
5
3
  import { CLI_SHAPES } from './cli-shapes.js';
6
- import { isBackgroundTaskId } from './ids.js';
7
- import { isTaskNotification, parseTaskNotification } from './notification.js';
8
- const BASH = CLI_SHAPES.taskTools.literals.bash;
9
- const TOOL_RESULT = CLI_SHAPES.toolResult.literals.field;
10
- const BACKGROUND_TASK_ID = CLI_SHAPES.taskStart.literals.backgroundTaskId;
11
- /** Ile PR-ów najwyżej stoi na liście; lista jedzie w każdej ramce snapshotu, jak artefakty. */
12
- export const PULL_REQUESTS_MAX = 20;
13
- /** Ile jednostek UTF-16 tytułu jedzie na telefon — tyle co tytuł artefaktu. */
14
- export const PULL_REQUEST_TITLE_MAX = 120;
15
- /**
16
- * Ile wywołań `gh pr create` bez wyniku pamięta jeden plik. Wynik stoi zwykle w następnym wpisie; sufit chroni
17
- * pamięć przed plikiem, w którym wyniki nie przychodzą (przerwane wywołania).
18
- */
19
- export const PULL_REQUEST_CALLS_MAX = 64;
4
+ const LINK = CLI_SHAPES.prLink.literals;
5
+ /** How many linked URLs one conversation keeps; above it the oldest goes. */
6
+ export const LINKED_PULL_REQUESTS_MAX = 100;
20
7
  /**
21
8
  * Adres PR w gramatyce GitHuba: właściciel z liter, cyfr i łączników (do 39 znaków), nazwa repo z liter, cyfr,
22
9
  * kropki, podkreślenia i łącznika, numer dodatni bez zer wiodących (do 9 cyfr, bezpieczna liczba całkowita).
23
10
  * Jedna definicja: tę samą gramatykę czyta moduł stanu PR-ów (`pr-status/source.ts`, `parsePrUrl`).
24
11
  */
25
12
  export const PR_URL = /^https:\/\/github\.com\/([A-Za-z0-9][A-Za-z0-9-]{0,38})\/([A-Za-z0-9._-]{1,100})\/pull\/([1-9][0-9]{0,8})$/;
26
- /**
27
- * Koniec linii, po której `gh pr create` podaje adres PR, który JUŻ istniał (wyjście z błędem, zmierzone
28
- * w dokumentacji `gh`: `a pull request for branch "x" into branch "main" already exists:`).
29
- */
30
- const ALREADY_EXISTS = 'already exists:';
31
- /**
32
- * Igły prefiltra: wywołanie niesie `create` (między `pr` i `create` parser dopuszcza dowolne białe znaki, w JSON
33
- * tabulator stoi jako `\t`), wynik `/pull/`. Bajty, bo porównujemy porcje pliku.
34
- * A result moved to the background carries `backgroundTaskId`, its end notification the harness origin value.
35
- */
36
- const NEEDLES = [
37
- 'create', '/pull/', BACKGROUND_TASK_ID, CLI_SHAPES.notificationOrigin.literals.kind,
38
- ].map((needle) => Buffer.from(needle, 'utf8'));
39
- /**
40
- * Czy linia pliku MOŻE nieść wywołanie `gh pr create` albo wynik z adresem PR. Tani prefiltr przed
41
- * `JSON.parse`: fałszywe „tak” kosztuje jedno parsowanie. `/` w napisie JSON nie jest ucieczką, więc adres
42
- * stoi w linii dosłownie.
43
- */
44
- export function mayCarryPullRequest(line) {
45
- return NEEDLES.some((needle) => line.includes(needle));
13
+ /** Prefilter needle: the entry type stands in the line literally. Bytes, because the reader compares file chunks. */
14
+ const NEEDLE = Buffer.from(LINK.type, 'utf8');
15
+ /** Whether a file line MAY carry a link entry. A cheap prefilter before `JSON.parse`; a false "yes" costs one parse. */
16
+ export function mayCarryPullRequestLink(line) {
17
+ return line.includes(NEEDLE);
46
18
  }
47
19
  /** Adres PR rozłożony na części; `null` = linia nie jest DOKŁADNIE adresem PR. */
48
20
  export function parsePullRequestUrl(text) {
@@ -55,630 +27,80 @@ export function parsePullRequestUrl(text) {
55
27
  return null;
56
28
  return { url: text, repo: `${owner}/${repo}`, number: Number(hit[3]) };
57
29
  }
58
- /**
59
- * Polecenie powłoki → segmenty łańcucha, każdy jako lista słów. Leksyka na tyle, na ile trzeba, żeby poznać
60
- * pierwsze słowa segmentu: cudzysłowy pojedyncze i podwójne, ucieczka `\`, podstawienie `$(…)` i odwrotne
61
- * apostrofy (z zagnieżdżeniem), heredoc (`<<EOF`, `<<'EOF'`, `<<-EOF`; treść do linii z ogranicznikiem jest
62
- * pomijana) i komentarz `#` na początku słowa. Separatory segmentów tylko na najwyższym poziomie: `;`, `&`, `|`,
63
- * nowa linia i nawias podpowłoki. Słowo z podstawieniem albo `$` poza apostrofami nie jest dosłowne.
64
- * Niedomknięty cudzysłów kończy polecenie tym, co zebrano.
65
- */
66
- export function shellSegments(command) {
67
- const segments = [];
68
- const stack = [];
69
- /** Ograniczniki heredoców czekających na koniec bieżącej linii. */
70
- const heredocs = [];
71
- let words = [];
72
- let text = '';
73
- let literal = true;
74
- let inWord = false;
75
- let quotedStart = false;
76
- let runs = false;
77
- const endWord = () => {
78
- if (inWord) {
79
- words.push({ text, literal, ...(quotedStart ? { quotedStart: true } : {}), ...(runs ? { runs: true } : {}) });
80
- }
81
- text = '';
82
- literal = true;
83
- inWord = false;
84
- quotedStart = false;
85
- runs = false;
86
- };
87
- const endSegment = () => {
88
- endWord();
89
- if (words.length > 0)
90
- segments.push(words);
91
- words = [];
92
- };
93
- const append = (chars) => {
94
- text += chars;
95
- inWord = true;
96
- };
97
- /** Pomija treść czekających heredoców od pozycji `from` (początek linii); oddaje pozycję za nimi. */
98
- const skipHeredocs = (from) => {
99
- let at = from;
100
- while (heredocs.length > 0) {
101
- const { delimiter, tabs } = heredocs.shift() ?? { delimiter: '', tabs: false };
102
- for (;;) {
103
- if (at >= command.length)
104
- return at;
105
- const end = command.indexOf('\n', at);
106
- const line = command.slice(at, end === -1 ? command.length : end);
107
- at = end === -1 ? command.length : end + 1;
108
- if ((tabs ? line.replace(/^\t+/, '') : line) === delimiter)
109
- break;
110
- }
111
- }
112
- return at;
113
- };
114
- /** Ogranicznik heredoca od pozycji za `<<`; oddaje pozycję za nim. */
115
- const readHeredoc = (from) => {
116
- let at = from;
117
- const tabs = command[at] === '-';
118
- if (tabs)
119
- at += 1;
120
- while (command[at] === ' ' || command[at] === '\t')
121
- at += 1;
122
- let delimiter = '';
123
- while (at < command.length && !/[\s;&|<>()]/.test(command[at] ?? '')) {
124
- const ch = command[at] ?? '';
125
- if (ch === '\'' || ch === '"') {
126
- const close = command.indexOf(ch, at + 1);
127
- const end = close === -1 ? command.length : close;
128
- delimiter += command.slice(at + 1, end);
129
- at = end + 1;
130
- }
131
- else {
132
- if (ch !== '\\')
133
- delimiter += ch;
134
- at += 1;
135
- }
136
- }
137
- if (delimiter !== '')
138
- heredocs.push({ delimiter, tabs });
139
- return at;
140
- };
141
- let i = 0;
142
- while (i < command.length) {
143
- const ch = command[i] ?? '';
144
- const next = command[i + 1] ?? '';
145
- const top = stack.at(-1);
146
- if (top === 'sq') {
147
- if (ch === '\'')
148
- stack.pop();
149
- else
150
- append(ch);
151
- i += 1;
152
- continue;
153
- }
154
- if (top === 'dq') {
155
- if (ch === '"') {
156
- stack.pop();
157
- }
158
- else if (ch === '\\' && '$`"\\\n'.includes(next) && next !== '') {
159
- if (next !== '\n')
160
- append(next);
161
- i += 1;
162
- }
163
- else if (ch === '$' && next === '(') {
164
- stack.push('sub');
165
- literal = false;
166
- runs = true;
167
- append('$(');
168
- i += 1;
169
- }
170
- else if (ch === '`') {
171
- stack.push('bt');
172
- literal = false;
173
- runs = true;
174
- append(ch);
175
- }
176
- else {
177
- if (ch === '$')
178
- literal = false;
179
- append(ch);
180
- }
181
- i += 1;
182
- continue;
183
- }
184
- if (top === 'bt') {
185
- if (ch === '\\' && next !== '') {
186
- append(ch + next);
187
- i += 2;
188
- continue;
189
- }
190
- if (ch === '`')
191
- stack.pop();
192
- append(ch);
193
- i += 1;
194
- continue;
195
- }
196
- if (top === 'sub') {
197
- // Wnętrze podstawienia: słowa nie są potrzebne, tylko jego granice.
198
- if (ch === '\\' && next !== '') {
199
- append(ch + next);
200
- i += 2;
201
- continue;
202
- }
203
- if (ch === ')')
204
- stack.pop();
205
- else if (ch === '(')
206
- stack.push('sub');
207
- else if (ch === '\'')
208
- stack.push('sq');
209
- else if (ch === '"')
210
- stack.push('dq');
211
- else if (ch === '`')
212
- stack.push('bt');
213
- else if (ch === '<' && next === '<' && command[i + 2] !== '<') {
214
- append('<<');
215
- i = readHeredoc(i + 2);
216
- continue;
217
- }
218
- else if (ch === '\n' && heredocs.length > 0) {
219
- append(ch);
220
- i = skipHeredocs(i + 1);
221
- continue;
222
- }
223
- append(ch);
224
- i += 1;
225
- continue;
226
- }
227
- // Najwyższy poziom.
228
- if (ch === '\\') {
229
- if (next === '\n')
230
- i += 2;
231
- else {
232
- if (next !== '') {
233
- if (!inWord)
234
- quotedStart = true;
235
- append(next);
236
- }
237
- i += 2;
238
- }
239
- continue;
240
- }
241
- if (ch === ' ' || ch === '\t' || ch === '\r') {
242
- endWord();
243
- i += 1;
244
- continue;
245
- }
246
- if (ch === '\n') {
247
- endSegment();
248
- i = skipHeredocs(i + 1);
249
- continue;
250
- }
251
- // `&` w przekierowaniu (`2>&1`, `>&2`, `&>plik`) należy do słowa, nie rozdziela segmentów.
252
- if (ch === '&' && (command[i - 1] === '>' || command[i - 1] === '<' || next === '>')) {
253
- append(ch);
254
- i += 1;
255
- continue;
256
- }
257
- if (ch === ';' || ch === '&' || ch === '|' || ch === '(' || ch === ')') {
258
- endSegment();
259
- i += 1;
260
- continue;
261
- }
262
- if (ch === '#' && !inWord) {
263
- const end = command.indexOf('\n', i);
264
- i = end === -1 ? command.length : end;
265
- continue;
266
- }
267
- if (ch === '<' && next === '<' && command[i + 2] !== '<') {
268
- endWord();
269
- i = readHeredoc(i + 2);
270
- continue;
271
- }
272
- if (ch === '\'' || ch === '"') {
273
- stack.push(ch === '\'' ? 'sq' : 'dq');
274
- if (!inWord)
275
- quotedStart = true;
276
- inWord = true;
277
- }
278
- else if (ch === '$' && next === '(') {
279
- stack.push('sub');
280
- literal = false;
281
- runs = true;
282
- append('$(');
283
- i += 1;
284
- }
285
- else if (ch === '`') {
286
- stack.push('bt');
287
- literal = false;
288
- runs = true;
289
- append(ch);
290
- }
291
- else {
292
- if (ch === '$')
293
- literal = false;
294
- append(ch);
295
- }
296
- i += 1;
297
- }
298
- endSegment();
299
- return segments;
300
- }
301
- const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
302
- /** Słowa, po których polecenie dalej stoi w tym samym segmencie. */
303
- const PREFIX_COMMANDS = ['env', 'command'];
304
- /** Tytuł z argumentów `gh pr create`; `undefined` = brak albo nie dosłowny. */
305
- function titleOf(args) {
306
- for (let at = 0; at < args.length; at += 1) {
307
- const word = args[at];
308
- if (word === undefined)
309
- break;
310
- let value;
311
- if (word.text === '--title' || word.text === '-t')
312
- value = args[at + 1];
313
- else if (word.text.startsWith('--title='))
314
- value = { text: word.text.slice('--title='.length), literal: word.literal };
315
- if (value === undefined)
316
- continue;
317
- if (!value.literal)
318
- return undefined;
319
- const title = clipUnits(stripControlChars(value.text).trim(), PULL_REQUEST_TITLE_MAX);
320
- return title === '' ? undefined : title;
321
- }
322
- return undefined;
323
- }
324
- /**
325
- * Programy, które obok `gh pr create` w tym samym poleceniu nie wypiszą adresu PR linią samą w sobie: przejście do
326
- * katalogu, git (komunikat `remote:` o PR stoi z przedrostkiem), ustawienia powłoki i filtry wyjścia `create`
327
- * w potoku. Każdy inny program (także `gh pr view`, `cat` bez przekierowania do pliku, testy) czyni wynik
328
- * niejednoznacznym, poza wyjątkami niżej: adres mógł przyjść od niego, a nie od `create`. Lista słów, nie
329
- * wywołań: jednym napisem, bo strażnik (`pliki-zwykle-guard.test.ts`) dopuszcza literał nazwy gita tylko
330
- * na linii spawnu runnera.
331
- */
332
- const QUIET_PROGRAMS = 'cd pushd popd git export unset set true false sleep test [ tail head tee grep wc'
333
- .split(' ');
334
- /** `echo` i `printf` są ciche, gdy wszystkie słowa są dosłowne i żadne nie niesie adresu PR. */
335
- const PRINT_PROGRAMS = ['echo', 'printf'];
336
- const PR_URL_ANYWHERE = /github\.com\/[^/\s]+\/[^/\s]+\/pull\/[1-9]/;
337
- /**
338
- * Programs that are quiet when their stdout goes to a file: an agent writes the PR body this way in the same call
339
- * (`cat > body.txt <<'EOF'`), measured as the most common reason a created PR went unrecognized. Their stderr
340
- * carries only error messages, never a bare PR URL line.
341
- */
342
- const TO_FILE_PROGRAMS = ['cat', 'echo', 'printf'];
343
- /** File tools that print nothing to stdout unless asked to be verbose. */
344
- const FILE_PROGRAMS = 'rm mkdir cp mv ln touch chmod mktemp'.split(' ');
345
- const VERBOSE_FLAG = /^(-[A-Za-z]*v[A-Za-z]*|--verbose)$/;
346
- /** The Markdown line-length check (`awk 'length > 120 {print NR": "length}' body.txt`): lines start with a number. */
347
- const AWK_LINE_LENGTH = /^length(\(\))?\s*>\s*[0-9]+\s*\{\s*print\s+F?NR\s*": "\s*length(\(\))?\s*\}$/;
348
- /** A redirect of stdout (`>`, `>>`, `1>`, `&>`), with its target in the same word or in the next one. */
349
- const STDOUT_REDIRECT = /^(?:1|&)?>>?(.*)$/;
350
- /**
351
- * Whether the segment's stdout ends in a regular file: the last stdout redirect points to a path that is not
352
- * a descriptor (`>&2`) and not a device other than `/dev/null` (`/dev/stdout` lands in the result).
353
- */
354
- function stdoutToFile(words) {
355
- let target = null;
356
- for (let at = 1; at < words.length; at += 1) {
357
- if (words[at]?.quotedStart === true)
358
- continue;
359
- const hit = STDOUT_REDIRECT.exec(words[at]?.text ?? '');
360
- if (hit === null)
361
- continue;
362
- const inline = hit[1] ?? '';
363
- target = inline === '' ? (words[at + 1]?.text ?? '') : inline;
364
- if (inline === '')
365
- at += 1;
366
- }
367
- if (target === null || target === '' || target.startsWith('&'))
368
- return false;
369
- return !target.startsWith('/dev/') || target === '/dev/null';
370
- }
371
- /** Whether a file tool, `sed -i` or the `awk` line-length check stays silent on stdout. */
372
- function isSilentTool(program, args) {
373
- if (FILE_PROGRAMS.includes(program))
374
- return !args.some((word) => VERBOSE_FLAG.test(word.text));
375
- if (program === 'sed') {
376
- const inPlace = args.some((word) => /^(-[A-Za-z]*i|--in-place)/.test(word.text));
377
- return inPlace && !args.some((word) => word.text.includes('/dev/'));
378
- }
379
- if (program === 'awk') {
380
- const [script, ...files] = args;
381
- // An operand `ORS=…` is a variable assignment, not a file, and changes what awk prints.
382
- return script !== undefined && script.literal && AWK_LINE_LENGTH.test(script.text.trim())
383
- && !files.some((word) => word.text.startsWith('-') || ASSIGNMENT.test(word.text));
384
- }
385
- return false;
386
- }
387
- /** `timeout` from GNU coreutils (`gtimeout` from Homebrew): runs the program that follows its options and duration. */
388
- const TIMEOUT_PROGRAMS = ['timeout', 'gtimeout'];
389
- const TIMEOUT_FLAGS = ['--preserve-status', '--foreground', '-v', '--verbose'];
390
- /** Options of `timeout` whose value is the next word. */
391
- const TIMEOUT_VALUE_OPTIONS = ['-s', '--signal', '-k', '--kill-after'];
392
- /** Options of `timeout` with the value in the same word. */
393
- const TIMEOUT_JOINED_OPTION = /^(?:-[sk].|--signal=.|--kill-after=.)/;
394
- const TIMEOUT_DURATION = /^[0-9]+(?:\.[0-9]+)?[smhd]?$/;
395
- /**
396
- * Index of the program after `timeout` at `at`: options, then the duration. `null` = another shape, so `timeout`
397
- * stays the program (neither `create` nor quiet).
398
- */
399
- function afterTimeout(segment, at) {
400
- let next = at + 1;
401
- for (;;) {
402
- const word = segment[next];
403
- if (word === undefined || !word.literal)
404
- return null;
405
- if (word.text === '--') {
406
- next += 1;
407
- break;
408
- }
409
- if (TIMEOUT_FLAGS.includes(word.text) || TIMEOUT_JOINED_OPTION.test(word.text))
410
- next += 1;
411
- else if (TIMEOUT_VALUE_OPTIONS.includes(word.text)) {
412
- if (segment[next + 1]?.literal !== true)
413
- return null;
414
- next += 2;
415
- }
416
- else
417
- break;
418
- }
419
- return TIMEOUT_DURATION.test(segment[next]?.text ?? '') ? next + 1 : null;
420
- }
421
- /** Słowa segmentu od programu (po przypisaniach `X=1`, `env`/`command` i `timeout` z czasem). */
422
- function commandWords(segment) {
423
- let at = 0;
424
- for (;;) {
425
- const word = segment[at];
426
- if (word === undefined)
427
- break;
428
- if (ASSIGNMENT.test(word.text) || (word.literal && PREFIX_COMMANDS.includes(word.text)))
429
- at += 1;
430
- else if (word.literal && TIMEOUT_PROGRAMS.includes(word.text)) {
431
- const program = afterTimeout(segment, at);
432
- if (program === null)
433
- break;
434
- at = program;
435
- }
436
- else
437
- break;
438
- }
439
- return segment.slice(at);
440
- }
441
- /** Czy segment to `gh pr create` (program `gh` albo ścieżka do niego, słowa dosłowne). */
442
- function isCreate(words) {
443
- const [program, group, action] = words;
444
- if (program === undefined || group === undefined || action === undefined)
445
- return false;
446
- if (!program.literal || !group.literal || !action.literal)
447
- return false;
448
- return (program.text === 'gh' || program.text.endsWith('/gh')) && group.text === 'pr' && action.text === 'create';
449
- }
450
- /** Czy segment obok `create` na pewno nie dostarczy adresu PR do wyniku (segment bez słów też). */
451
- function isQuiet(words) {
452
- const [program] = words;
453
- if (program === undefined)
454
- return true;
455
- if (!program.literal)
456
- return false;
457
- if (QUIET_PROGRAMS.includes(program.text))
458
- return true;
459
- if (words.some((word) => PR_URL_ANYWHERE.test(word.text)))
460
- return false;
461
- // A command substitution prints to stderr whatever the redirects of the program say.
462
- if (words.some((word) => word.runs === true))
463
- return false;
464
- if (TO_FILE_PROGRAMS.includes(program.text) && stdoutToFile(words))
465
- return true;
466
- if (isSilentTool(program.text, words.slice(1)))
467
- return true;
468
- if (!PRINT_PROGRAMS.includes(program.text))
469
- return false;
470
- return words.every((word) => word.literal);
471
- }
472
- /**
473
- * Czy polecenie `Bash` wykonuje `gh pr create`; `null` = nie albo wynik niejednoznaczny. Adres PR w wyniku należy
474
- * do `create` tylko wtedy, gdy pozostałe segmenty polecenia są ciche ({@link isQuiet}): `gh pr view … || gh pr
475
- * create` albo `printf` z adresem dałyby adres PR, którego to polecenie nie utworzyło. Wynik niesie tytuł
476
- * z `--title`/`-t`, gdy polecenie podało go dosłownie (bez rozwinięć powłoki) i niepusty.
477
- * Several `gh pr create` segments in one call all count, but then no title: the result does not say which URL
478
- * belongs to which create (the first one may have failed).
479
- */
480
- export function pullRequestCommand(command) {
481
- const creates = [];
482
- for (const segment of shellSegments(command)) {
483
- const words = commandWords(segment);
484
- if (isCreate(words)) {
485
- creates.push(words);
486
- continue;
487
- }
488
- if (!isQuiet(words))
489
- return null;
490
- }
491
- const [create] = creates;
492
- if (create === undefined)
30
+ /** A valid top-level `timestamp` of a PARSED entry (`parseJsonlEntry`), or `null`. */
31
+ export function entryTimeOf(value) {
32
+ const entry = asRecord(value);
33
+ if (entry === null || Array.isArray(value))
493
34
  return null;
494
- if (creates.length > 1)
495
- return {};
496
- const title = titleOf(create.slice(3));
497
- return title === undefined ? {} : { title };
498
- }
499
- export function createPullRequestCalls() {
500
- return { pending: new Map(), background: new Map() };
501
- }
502
- /** Adds to a map with a ceiling: `Map` keeps insertion order, so the first key is the oldest call. */
503
- function remember(map, id, value) {
504
- map.set(id, value);
505
- if (map.size > PULL_REQUEST_CALLS_MAX) {
506
- const [oldest] = map.keys();
507
- if (oldest !== undefined)
508
- map.delete(oldest);
509
- }
510
- }
511
- /** Bloki treści wpisu; nie-tablica = brak bloków (ta sama reguła co w `artifacts.ts`). */
512
- function blocksOf(entry) {
513
- const content = asRecord(entry['message'])?.['content'];
514
- if (!Array.isArray(content))
515
- return [];
516
- return content.flatMap((item) => {
517
- const block = asRecord(item);
518
- return block === null || Array.isArray(item) ? [] : [block];
519
- });
520
- }
521
- /** Treść bloku `tool_result`: napis albo tablica bloków tekstu (sklejone nową linią). */
522
- function resultText(block) {
523
- const content = block['content'];
524
- if (typeof content === 'string')
525
- return content;
526
- if (!Array.isArray(content))
527
- return '';
528
- return content.flatMap((item) => {
529
- const part = asRecord(item);
530
- return part?.['type'] === 'text' && typeof part['text'] === 'string' ? [part['text']] : [];
531
- }).join('\n');
532
- }
533
- /** Adresy PR z treści wyniku: linie dokładnie adresem, bez tych po „already exists:”. */
534
- function urlsOf(text) {
535
- const found = [];
536
- let previous = '';
537
- for (const raw of text.split('\n')) {
538
- const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw;
539
- const pr = parsePullRequestUrl(line);
540
- if (pr !== null && !previous.trimEnd().endsWith(ALREADY_EXISTS))
541
- found.push(pr);
542
- if (line.trim() !== '')
543
- previous = line;
544
- }
545
- return found;
546
- }
547
- /** Task id of a result that went to the background (`toolUseResult.backgroundTaskId`); `null` = none or bad shape. */
548
- function backgroundTaskIdOf(entry) {
549
- const result = asRecord(entry[TOOL_RESULT]);
550
- const taskId = result?.[BACKGROUND_TASK_ID];
551
- return typeof taskId === 'string' && isBackgroundTaskId(taskId) ? taskId : null;
552
- }
553
- /** A valid entry time, or `null`. */
554
- function timeOf(entry) {
555
35
  const at = entry['timestamp'];
556
36
  return typeof at === 'string' && !Number.isNaN(Date.parse(at)) ? at : null;
557
37
  }
558
- /**
559
- * The end notification of a call waiting in the background → a read request. Only a harness notification
560
- * (`origin`), with a status (an event without one is not the end), the `tool_use_id` of a waiting call and its
561
- * task id. The waiting call leaves the memory, so a second copy of the notification asks nothing.
562
- */
563
- function outputOf(entry, calls) {
564
- const text = harnessNoticeText(entry);
565
- if (!isTaskNotification(text))
566
- return null;
567
- const notification = parseTaskNotification(text);
568
- if (notification.status === '')
38
+ /** Whether a PARSED entry is a link entry, valid or not (the follower's read signal). */
39
+ export function isPullRequestLinkEntry(value) {
40
+ return !Array.isArray(value) && asRecord(value)?.['type'] === LINK.type;
41
+ }
42
+ /** One PARSED link entry → the linked PR with the entry time as `createdAt`; `null` = not a valid link entry. */
43
+ export function pullRequestLinkOf(value) {
44
+ if (!isPullRequestLinkEntry(value))
569
45
  return null;
570
- const waiting = calls.background.get(notification.toolUseId);
571
- if (waiting === undefined || waiting.taskId !== notification.id)
46
+ const entry = asRecord(value) ?? {};
47
+ const url = entry[LINK.url];
48
+ const createdAt = entryTimeOf(value);
49
+ if (typeof url !== 'string' || createdAt === null)
572
50
  return null;
573
- calls.background.delete(notification.toolUseId);
574
- const createdAt = timeOf(entry);
575
- if (createdAt === null)
51
+ const pr = parsePullRequestUrl(url);
52
+ if (pr === null || entry[LINK.number] !== pr.number || entry[LINK.repository] !== pr.repo)
576
53
  return null;
577
- const output = { path: notification.outputFile, taskId: waiting.taskId, createdAt };
578
- return waiting.title === undefined ? output : { ...output, title: waiting.title };
579
- }
580
- /**
581
- * Jeden SPARSOWANY wpis pliku (wynik `parseJsonlEntry`) → PR-y, które z niego wyszły. Wywołanie
582
- * `gh pr create` trafia do `calls`; wynik zdejmuje swoje wywołanie z `calls`, także wtedy, gdy adresu nie ma.
583
- * A result without a URL that went to the background moves the call to the background memory; its end
584
- * notification gives a read request in `outputs`.
585
- */
586
- export function pullRequestsOf(value, calls) {
587
- const entry = asRecord(value);
588
- if (entry === null || Array.isArray(value))
589
- return { pullRequests: [], outputs: [] };
590
- const found = [];
591
- const output = outputOf(entry, calls);
592
- for (const block of blocksOf(entry)) {
593
- if (block['type'] === 'tool_use') {
594
- const input = asRecord(block['input']);
595
- const command = input?.['command'];
596
- const id = block['id'];
597
- if (block['name'] !== BASH || typeof command !== 'string' || typeof id !== 'string')
598
- continue;
599
- const recognized = pullRequestCommand(command);
600
- if (recognized !== null)
601
- remember(calls.pending, id, recognized);
602
- continue;
603
- }
604
- if (block['type'] !== 'tool_result')
605
- continue;
606
- const id = block['tool_use_id'];
607
- if (typeof id !== 'string')
608
- continue;
609
- const known = calls.pending.get(id);
610
- if (known === undefined)
611
- continue;
612
- calls.pending.delete(id);
613
- const urls = urlsOf(resultText(block));
614
- const taskId = urls.length === 0 ? backgroundTaskIdOf(entry) : null;
615
- if (taskId !== null) {
616
- remember(calls.background, id, known.title === undefined ? { taskId } : { taskId, title: known.title });
617
- continue;
618
- }
619
- const createdAt = timeOf(entry);
620
- if (createdAt === null)
621
- continue;
622
- for (const pr of urls) {
623
- found.push(known.title === undefined ? { ...pr, createdAt } : { ...pr, createdAt, title: known.title });
624
- }
625
- }
626
- return { pullRequests: found, outputs: output === null ? [] : [output] };
54
+ return { ...pr, createdAt };
627
55
  }
628
- /** Text of a background call's output file → its PRs, by the same line rule as a `tool_result`. */
629
- export function pullRequestsFromOutput(text, output) {
630
- const { createdAt, title } = output;
631
- return urlsOf(text).map((pr) => (title === undefined ? { ...pr, createdAt } : { ...pr, createdAt, title }));
632
- }
633
- /** Kolejność: czas utworzenia malejąco, przy remisie numer malejąco (stała kolejność). */
634
- function newestFirst(a, b) {
56
+ /** Order: time descending, on a tie number descending, then URL (a stable order). */
57
+ export function newestFirst(a, b) {
635
58
  return Date.parse(b.createdAt) - Date.parse(a.createdAt) || b.number - a.number || (a.url < b.url ? -1 : 1);
636
59
  }
637
- /**
638
- * Lista PR-ów sesji ze wszystkich jej plików. Ten sam adres raz: najwcześniejszy czas (PR powstał przy
639
- * pierwszym wyniku), tytuł z pierwszego, który go niesie. Mapa ma ten sam sufit co lista: po przekroczeniu
640
- * wypada najstarszy PR (i tak stoi poza listą).
641
- */
642
- export function createPullRequestList() {
60
+ /** The linked set of one conversation: one item per URL, the earliest time, the oldest out above the ceiling. */
61
+ export function createLinkedPullRequests() {
643
62
  const known = new Map();
644
63
  return {
645
64
  add(pr) {
646
65
  const current = known.get(pr.url);
647
66
  if (current === undefined) {
648
67
  known.set(pr.url, { ...pr });
649
- if (known.size > PULL_REQUESTS_MAX) {
68
+ if (known.size > LINKED_PULL_REQUESTS_MAX) {
650
69
  const [oldest] = [...known.values()].sort((a, b) => newestFirst(b, a));
651
70
  if (oldest !== undefined)
652
71
  known.delete(oldest.url);
653
72
  }
654
73
  return known.has(pr.url);
655
74
  }
656
- const earlier = Date.parse(pr.createdAt) < Date.parse(current.createdAt);
657
- const title = current.title ?? pr.title;
658
- const createdAt = earlier ? pr.createdAt : current.createdAt;
659
- if (createdAt === current.createdAt && title === current.title)
75
+ if (Date.parse(pr.createdAt) >= Date.parse(current.createdAt))
660
76
  return false;
661
- known.set(pr.url, title === undefined ? { ...current, createdAt } : { ...current, createdAt, title });
77
+ known.set(pr.url, { ...current, createdAt: pr.createdAt });
662
78
  return true;
663
79
  },
664
- get pullRequests() {
665
- return [...known.values()].sort(newestFirst).slice(0, PULL_REQUESTS_MAX).map((pr) => ({ ...pr }));
80
+ get linked() {
81
+ return [...known.values()].sort(newestFirst).map((pr) => ({ ...pr }));
666
82
  },
667
83
  };
668
84
  }
669
- /** Podpis listy — po nim driver poznaje ZMIANĘ. Pusta lista ma podpis `[]`. */
670
- export function pullRequestsSignature(list) {
671
- return JSON.stringify(list.map((pr) => [pr.url, pr.createdAt, pr.title ?? null]));
672
- }
673
85
  /**
674
- * Lista PR-ów z linii JEDNEGO pliku (kolejność zapisu) — ta sama maszyna co w czytniku, dla testów. Output files
675
- * of background calls are not read here.
86
+ * Signature of what the driver paid out: the linked set and the window. An empty set has the signature `[]` whatever
87
+ * the window, so a conversation without links pays nothing out after attach.
676
88
  */
677
- export function sessionPullRequests(lines) {
678
- const calls = createPullRequestCalls();
679
- const list = createPullRequestList();
680
- for (const line of lines)
681
- for (const pr of pullRequestsOf(parseJsonlEntry(line), calls).pullRequests)
682
- list.add(pr);
683
- return list.pullRequests;
89
+ export function pullRequestLinksSignature(links) {
90
+ if (links.linked.length === 0)
91
+ return '[]';
92
+ return JSON.stringify([links.windowStart, ...links.linked.map((pr) => [pr.url, pr.createdAt, pr.title ?? null])]);
93
+ }
94
+ /** Links and window from the lines of ONE main file (write order): the reader's rule, for tests and demo data. */
95
+ export function pullRequestLinks(lines) {
96
+ const set = createLinkedPullRequests();
97
+ let windowStart = null;
98
+ for (const line of lines) {
99
+ const entry = parseJsonlEntry(line);
100
+ windowStart ??= entryTimeOf(entry);
101
+ const pr = pullRequestLinkOf(entry);
102
+ if (pr !== null)
103
+ set.add(pr);
104
+ }
105
+ return { linked: set.linked, windowStart };
684
106
  }