@rarog/server 1.1.0 → 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 (66) 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/cli/update-registry.js +31 -1
  12. package/server/src/cli/update.js +128 -6
  13. package/server/src/demo/control.js +4 -2
  14. package/server/src/demo/mock-herdr.js +2 -2
  15. package/server/src/demo/scenarios.js +31 -17
  16. package/server/src/demo/seeds.js +62 -38
  17. package/server/src/drivers/herdr/pull-request-poll.js +5 -5
  18. package/server/src/drivers/herdr/queue-take-back.js +4 -0
  19. package/server/src/drivers/herdr/start-dialog-gate.js +132 -0
  20. package/server/src/drivers/herdr-driver.js +75 -15
  21. package/server/src/herdr/background/cli-shapes.js +16 -15
  22. package/server/src/herdr/background/index.js +7 -7
  23. package/server/src/herdr/background/merge.js +17 -5
  24. package/server/src/herdr/background/notification.js +0 -4
  25. package/server/src/herdr/background/pull-request-files.js +53 -161
  26. package/server/src/herdr/background/pull-requests.js +54 -632
  27. package/server/src/herdr/background/work.js +84 -0
  28. package/server/src/herdr/dialogs/copy.js +7 -0
  29. package/server/src/herdr/dialogs/index.js +4 -1
  30. package/server/src/herdr/dialogs/screen/form.js +2 -1
  31. package/server/src/herdr/dialogs/screen/option-run.js +25 -3
  32. package/server/src/herdr/dialogs/screen/parse.js +3 -3
  33. package/server/src/herdr/dialogs/screen/signatures.js +55 -0
  34. package/server/src/herdr/dialogs/screen/start-dialog.js +72 -0
  35. package/server/src/herdr/dialogs/screen/trust-arrow.js +46 -9
  36. package/server/src/herdr/jsonl-follow.js +6 -2
  37. package/server/src/herdr/label-code.js +104 -0
  38. package/server/src/herdr/label-migration.js +142 -0
  39. package/server/src/herdr/launcher.js +30 -5
  40. package/server/src/herdr/provenance.js +80 -40
  41. package/server/src/herdr/start-dialog-wait.js +96 -0
  42. package/server/src/herdr/supervisor.js +33 -10
  43. package/server/src/herdr/workspace-resolver.js +5 -4
  44. package/server/src/index.js +8 -3
  45. package/server/src/notify/apns-payload.js +5 -3
  46. package/server/src/notify/content.js +37 -0
  47. package/server/src/notify/index.js +4 -0
  48. package/server/src/notify/live-activity-state.js +9 -5
  49. package/server/src/notify/live-activity.js +5 -2
  50. package/server/src/notify/policy.js +4 -2
  51. package/server/src/notify/stalled-wait.js +213 -0
  52. package/server/src/pr-status/facts.js +87 -0
  53. package/server/src/pr-status/gh.js +76 -9
  54. package/server/src/pr-status/index.js +1 -10
  55. package/server/src/pr-status/source.js +20 -6
  56. package/server/src/pr-status/tracker.js +32 -9
  57. package/server/src/sessions/conversation-lists.js +8 -2
  58. package/server/src/sessions/driver-events.js +7 -3
  59. package/server/src/sessions/interrupt-windows.js +28 -4
  60. package/server/src/sessions/manager.js +14 -5
  61. package/server/src/sessions/pr-status-link.js +64 -16
  62. package/server/src/sessions/session.js +10 -3
  63. package/server/src/sessions/state-machine.js +11 -0
  64. package/server/src/sessions/test-session.js +50 -0
  65. package/server/src/term/herdr-backend.js +15 -12
  66. package/server/src/term/lifecycle.js +4 -6
@@ -1,3 +1,7 @@
1
+ /** From this age of a wait on an own command (`waitingSince` to now) the stage is `long`. */
2
+ export const WAIT_LONG_MS = 30 * 60_000;
3
+ /** From this age of a wait on an own command the stage is `stuck`. */
4
+ export const WAIT_STUCK_MS = 60 * 60_000;
1
5
  /**
2
6
  * Subagent w POSTOJU: rodzaj `agent` z polem `waitingSince`. Skończył turę i czeka na własne
3
7
  * zadanie w tle — nie pracuje i nie skończył.
@@ -49,6 +53,84 @@ export function tasksHoldingDonePush(tasks) {
49
53
  export function waitingOnOwnCommand(tasks) {
50
54
  return (tasks ?? []).some((task) => waitingAgent(task) && (task.ownTasks?.length ?? 0) > 0);
51
55
  }
56
+ /**
57
+ * One task: a subagent in standby ({@link waitingAgent}) with a known open own command (`ownTasks` not empty), the
58
+ * same condition as {@link waitingOnOwnCommand} for a single task.
59
+ */
60
+ function waitsOnOwnCommand(task) {
61
+ return waitingAgent(task) && (task.ownTasks?.length ?? 0) > 0;
62
+ }
63
+ /**
64
+ * The wait stage of one task (`BackgroundTask.ownCommandWait`) at `nowMs`, or `undefined` when the task does not wait
65
+ * on a known own command ({@link waitsOnOwnCommand}).
66
+ *
67
+ * The age runs from `waitingSince`, not from the start of the command or the agent: a command meant to run long (a dev
68
+ * server started before the standby) must not count, and a new standby starts a new wait. This is the only rule that
69
+ * reads the clock; `merge.ts` calls it on every emission, so the list goes out again on the first tick past a
70
+ * threshold. An unreadable `waitingSince` or a clock behind it gives `short`: no proof of a long wait.
71
+ */
72
+ export function ownCommandWaitOf(task, nowMs) {
73
+ if (!waitsOnOwnCommand(task))
74
+ return undefined;
75
+ const age = nowMs - Date.parse(task.waitingSince ?? '');
76
+ if (age >= WAIT_STUCK_MS)
77
+ return 'stuck';
78
+ if (age >= WAIT_LONG_MS)
79
+ return 'long';
80
+ return 'short';
81
+ }
82
+ /**
83
+ * Opaque key of one wait: the agent and the start of its standby. Present only on a task that carries
84
+ * `ownCommandWait`, so it names the same wait across emissions while the stage grows, and a wake followed by a new
85
+ * standby gives a new key. Callers compare keys and never read the two fields themselves.
86
+ */
87
+ export function waitKey(task) {
88
+ if (task.ownCommandWait === undefined || !waitingAgent(task))
89
+ return undefined;
90
+ return JSON.stringify([task.id, task.waitingSince]);
91
+ }
92
+ /** A session that ended (`done`) or waits for a resume: an agent still on its list is a phantom for the rules. */
93
+ function phantomState(state) {
94
+ return state === 'done' || state === 'resumable';
95
+ }
96
+ /**
97
+ * Live Activity counter "waiting": a session after a turn (`waiting-input`) whose list has a wait at `stuck`. Such a
98
+ * session counts as waiting, not as finished or working, and is not the tap target (`aggregateState` in
99
+ * `notify/live-activity-state.ts`). Other states keep their own counter: a decision already waits, a turn works, and
100
+ * `done` or `resumable` has a phantom agent. The stage is read from the field only (`ownCommandWaitOf` set it).
101
+ */
102
+ export function stuckWait(state, tasks) {
103
+ return state === 'waiting-input' && (tasks ?? []).some((task) => task.ownCommandWait === 'stuck');
104
+ }
105
+ /**
106
+ * The edge of the stalled wait alarm between two lists of one session: a wait whose key was below `stuck` on `before`
107
+ * and is `stuck` on `after`. `short` → `stuck` is an edge (a sleeping Mac can skip `long`); a key absent from
108
+ * `before`, or without a stage there (first list after a Rarog restart or a driver swap, an agent before its file was
109
+ * read), is not, so a restart never repeats the alarm. Any session state gives the edge except a phantom one (`done`,
110
+ * `resumable`), which also has nothing at `stuck`; its waits keep their keys in `waitKeys`.
111
+ */
112
+ export function stuckWaits(state, before, after) {
113
+ const below = new Set((before ?? []).flatMap((task) => {
114
+ const key = waitKey(task);
115
+ return key !== undefined && task.ownCommandWait !== 'stuck' ? [key] : [];
116
+ }));
117
+ const waitKeys = [];
118
+ const stuckKeys = [];
119
+ const newly = [];
120
+ for (const task of after ?? []) {
121
+ const key = waitKey(task);
122
+ if (key === undefined)
123
+ continue;
124
+ waitKeys.push(key);
125
+ if (task.ownCommandWait !== 'stuck' || phantomState(state))
126
+ continue;
127
+ stuckKeys.push(key);
128
+ if (below.has(key)) {
129
+ newly.push({ key, agentId: task.id, ...(task.description === undefined ? {} : { description: task.description }) });
130
+ }
131
+ }
132
+ return { newly, stuckKeys, waitKeys };
133
+ }
52
134
  /**
53
135
  * Zaległe „gotowe": czy lista je WSTRZYMUJE — coś pracuje ({@link tasksHoldingDonePush}) albo
54
136
  * subagent w postoju czeka na własną komendę ({@link waitingOnOwnCommand}).
@@ -111,6 +193,8 @@ function openWorkflow(task) {
111
193
  * Kafel Live Activity, licznik „pracuje": na liście jest zadanie, które jeszcze mieli
112
194
  * ({@link liveTask}). Sesja po turze, której wszystkie zadania to czekający subagenci, do
113
195
  * „pracuje" się nie liczy; z nieodebranym wynikiem liczy się do „skończyły".
196
+ * Exception: a session after a turn with a wait at `stuck` ({@link stuckWait}) counts as waiting, neither as working
197
+ * nor as finished.
114
198
  */
115
199
  export function hasBackgroundWork(tasks) {
116
200
  return (tasks ?? []).some(liveTask);
@@ -24,6 +24,13 @@ export const TERMINAL_DIALOG_MESSAGE = say('dialogs.terminal-dialog');
24
24
  * celowo, żeby go zmierzyć (mechanizm bezpieczeństwa modelu) — driver go więc nie wysyła.
25
25
  */
26
26
  export const PAUSE_ESCAPE_MESSAGE = say('dialogs.pause-escape');
27
+ /**
28
+ * A Claude Code start dialog herdr reads as ready: the card's sentence for the external imports dialog (the answer is
29
+ * kept for the project for good) and for an unknown one, and the refusal of a key or text sent to either.
30
+ */
31
+ export const START_DIALOG_IMPORTS_MESSAGE = say('dialogs.start-dialog.imports');
32
+ export const START_DIALOG_UNKNOWN_MESSAGE = say('dialogs.start-dialog.unknown');
33
+ export const START_DIALOG_REFUSED_MESSAGE = say('dialogs.start-dialog.refused');
27
34
  /** Odpowiedź z nieświeżej karty: dialog na ekranie jest już inny niż ten, w który tapnięto. */
28
35
  export const STALE_DECISION_MESSAGE = say('dialogs.stale-decision');
29
36
  /**
@@ -138,6 +138,8 @@
138
138
  * - `screen/confirm.ts` — potwierdzenie ustawień CLI rozpoznane po kształcie (`confirmFrom`).
139
139
  * - `screen/resolve.ts` — cross-check ekranu z jsonl i hookiem (`resolveOptions`).
140
140
  * - `screen/trust-arrow.ts` — dialog zaufania bez cyfr: pełny render, folder, `❯`, odcisk bloku.
141
+ * - `screen/start-dialog.ts` — start dialog herdr reads as ready: no prompt field, and the external imports dialog
142
+ * recognised from its option pair and key footer (`startDialogOf`).
141
143
  * - `screen/mode-footer.ts` — tryb uprawnień ze stopki ekranu (nie dialog: nadzorca, `mode-cycle.ts`).
142
144
  * - `screen/operation.ts` — operacja dialogu zgody (ramka komendy).
143
145
  * - `screen/edit-frame.ts` — dowód wywołania `Edit` i `Write`: ścieżka z nagłówka i diff albo treść z ramki.
@@ -178,7 +180,7 @@
178
180
  * też transkryptu ani modułów drivera herdr (`drivers/herdr/`), a tryb cienia (`shadow/`) nie zna warstwy 1
179
181
  * (strażnik: `server/test/layer1-granica.test.ts`).
180
182
  */
181
- export { FORM_SUBMIT_GONE_MESSAGE, MULTI_SELECT_MESSAGE, NOTE_NOT_ALLOWED_MESSAGE, NOTE_NO_CHANNEL_MESSAGE, NOTE_WRITE_FAILED_MESSAGE, NO_ANSWER_ON_SCREEN_MESSAGE, NO_DIGIT_MESSAGE, PAUSE_ESCAPE_MESSAGE, SCREEN_CHANGED_MESSAGE, STALE_DECISION_MESSAGE, TERMINAL_DIALOG_MESSAGE, TERMINAL_ONLY_MESSAGE, formSubmitAbortMessage, hookAnswerPartialMessage, noteNotDeliveredMessage, } from './copy.js';
183
+ export { FORM_SUBMIT_GONE_MESSAGE, MULTI_SELECT_MESSAGE, NOTE_NOT_ALLOWED_MESSAGE, NOTE_NO_CHANNEL_MESSAGE, NOTE_WRITE_FAILED_MESSAGE, NO_ANSWER_ON_SCREEN_MESSAGE, NO_DIGIT_MESSAGE, PAUSE_ESCAPE_MESSAGE, SCREEN_CHANGED_MESSAGE, STALE_DECISION_MESSAGE, START_DIALOG_IMPORTS_MESSAGE, START_DIALOG_REFUSED_MESSAGE, START_DIALOG_UNKNOWN_MESSAGE, TERMINAL_DIALOG_MESSAGE, TERMINAL_ONLY_MESSAGE, formSubmitAbortMessage, hookAnswerPartialMessage, noteNotDeliveredMessage, } from './copy.js';
182
184
  export { ANSWERED_HOOK_SHIELD_MS, CLI_HOLD_MISSES, CLI_WAITING_PROBES, DECIDED_SHIELD_MS, FORM_FALLBACK_MISSES, FORM_FALLBACK_RETRY_DELAYS_MS, FORM_SUBMIT_CONFIRM_DELAY_MS, HOOK_ANSWER_POLL_MS, HOOK_ANSWER_WAIT_MS, SCREEN_ANSWER_REARM_DELAYS_MS, SHADOW_DEADLINE_MS, } from './timing.js';
183
185
  export { askFormOnScreen, cliDialogOnScreen } from './presence.js';
184
186
  export { DIALOG_ROUTES, DIALOG_ROUTE_REASONS, routeAllowsDigit, routeDialog, routeHookOf, routeScreenOf, } from './router.js';
@@ -202,6 +204,7 @@ export { dialogThreadOnScreen, parseOptions, subagentDialogOnScreen } from './sc
202
204
  export { blockVisible } from './screen/block-visible.js';
203
205
  export { SANDBOX_NETWORK_TOOL } from './screen/kinds.js';
204
206
  export { matchKnownDialog } from './screen/known.js';
207
+ export { startDialogOf } from './screen/start-dialog.js';
205
208
  export { sameDialogIdentity } from './screen/identity.js';
206
209
  export { SESSION_PAUSED_DIALOG, sessionPausedDialog } from './policy/pause.js';
207
210
  export { TERMINAL_DIALOG_IDS } from './policy/terminal.js';
@@ -3,6 +3,7 @@
3
3
  * pytania spod paska zakładek, sygnatury formularza wielokrotnego wyboru.
4
4
  */
5
5
  import { BOX_EDGE_PATTERN, OPTION_BOX_GLYPH_PATTERN, OPTION_LINE_PATTERN } from './options.js';
6
+ import { gutterText } from './option-run.js';
6
7
  import { HORIZONTAL_RULE_PATTERN } from './region.js';
7
8
  import { isReviewScreen } from './review.js';
8
9
  import { SCREEN_SIGNATURES } from './signatures.js';
@@ -145,7 +146,7 @@ export function questionFrom(region, optionsAt) {
145
146
  header = tab;
146
147
  continue;
147
148
  }
148
- lines.push(line);
149
+ lines.push(gutterText(line));
149
150
  }
150
151
  return { header, question: lines.join('\n').trim() };
151
152
  }
@@ -1,15 +1,37 @@
1
1
  /**
2
2
  * Which numbered run of a region is the option list: the one that stands directly above the key footer.
3
3
  *
4
- * A dialog body can carry its own numbered list above the options (a plan's phases, a summary). Two rules keep that
5
- * list off the buttons. Pure functions over region lines; they know no dialog titles or tool names, the CLI look
6
- * comes from `SCREEN_SIGNATURES`. `optionRegion` (`parse.ts`) calls them; nothing else does.
4
+ * A dialog body can carry its own numbered list above the options (a plan's phases, a summary), and a wrapped
5
+ * question can start a line with a digit and a dot. Three rules keep those lines off the buttons. Pure functions over
6
+ * region lines; they know no dialog titles or tool names, the CLI look comes from `SCREEN_SIGNATURES`. `optionRegion`
7
+ * (`parse.ts`) calls them; `questionFrom` (`form.ts`) calls `gutterText` for the card text.
7
8
  */
8
9
  import { OPTION_LINE_PATTERN, inOptionDescription, optionsCloseRegion, unbox, unframe } from './options.js';
9
10
  import { SCREEN_SIGNATURES } from './signatures.js';
10
11
  const KEY_FOOTER_PATTERN = SCREEN_SIGNATURES.dialogKeyFooter.pattern;
11
12
  const DIGITLESS_FOCUS_PATTERN = SCREEN_SIGNATURES.digitlessFocusLine.pattern;
12
13
  const OPTION_NUMBER_PATTERN = SCREEN_SIGNATURES.optionNumber.pattern;
14
+ const LEFT_EDGE_PATTERN = SCREEN_SIGNATURES.boxEdgeStart.pattern;
15
+ const RIGHT_EDGE_PATTERN = SCREEN_SIGNATURES.boxEdgeEnd.pattern;
16
+ /**
17
+ * A region line for shape recognition: `unbox`, except that a numbered line behind a left edge with no right edge
18
+ * keeps that edge and so is not an option line. The CLI draws a wrapped question behind such a gutter (fixture
19
+ * `dialog-askuserquestion-multiq-pytanie-w-ramce.txt`), and the wrap can start a line with a digit and a dot
20
+ * ("…restores" / "1. The banner…"); read as an option it would repeat a digit and void the form, or add a button the
21
+ * form does not have. Options inside a dialog frame carry both edges.
22
+ */
23
+ export function regionLine(line) {
24
+ const text = unbox(line);
25
+ const trimmed = line.trim();
26
+ if (!OPTION_LINE_PATTERN.test(text))
27
+ return text;
28
+ return LEFT_EDGE_PATTERN.test(trimmed) && !RIGHT_EDGE_PATTERN.test(trimmed) ? trimmed : text;
29
+ }
30
+ /** The text of a region line for the card: a numbered line that kept its gutter ({@link regionLine}) loses it here. */
31
+ export function gutterText(line) {
32
+ const text = line.replace(LEFT_EDGE_PATTERN, '').trim();
33
+ return text !== line && OPTION_LINE_PATTERN.test(text) ? text : line;
34
+ }
13
35
  /**
14
36
  * Start (index in the region) of the last numbered run, when that run ends the dialog; `-1` otherwise.
15
37
  *
@@ -22,7 +22,7 @@ import { withoutAutoDeny } from './auto-deny.js';
22
22
  import { headerAboveEdge, operationAbove } from './operation.js';
23
23
  import { trimmedLines } from './text.js';
24
24
  import { DIALOG_TAIL_LINES, blockTopOf, dialogRegions, framedDialogText } from './region.js';
25
- import { OPTION_LINE_PATTERN, guideMap, isCompleteOptionSet, optionsCloseRegion, optionsIn, selectedOptionIn, selectedWithLabel, unbox, unframe, } from './options.js';
25
+ import { OPTION_LINE_PATTERN, guideMap, isCompleteOptionSet, optionsCloseRegion, optionsIn, selectedOptionIn, selectedWithLabel, unframe, } from './options.js';
26
26
  import { contentEscalates } from '../policy/escalation.js';
27
27
  import { blockFromSubagent, dialogBlock, fileDialogTitle, lineBelow, regionCallTrace, toolNaming, } from './block.js';
28
28
  import { PLAN_DIALOG_PATTERN, PLAN_EXIT_CONFIRM_PATTERN, SANDBOX_NETWORK_TOOL, dialogKind } from './kinds.js';
@@ -32,7 +32,7 @@ import { planFooterFile } from './plan-file.js';
32
32
  import { NOTES_EDITING_MARKER, formFooter, formMultiSelect, formSubmitMode, questionFrom } from './form.js';
33
33
  import { confirmFrom } from './confirm.js';
34
34
  import { fileDialogShown } from './file-dialog.js';
35
- import { digitlessChoiceBelow, lastRunStart } from './option-run.js';
35
+ import { digitlessChoiceBelow, lastRunStart, regionLine } from './option-run.js';
36
36
  /** Czy na ekranie stoi dialog, który z definicji NIE MA wpisu w jsonl ani zrzutu hooka? */
37
37
  export function screenOnlyDialog(text) {
38
38
  const dialog = parseOptions(text);
@@ -77,7 +77,7 @@ export function dialogThreadOnScreen(text) {
77
77
  */
78
78
  export function optionRegion(lines, labels) {
79
79
  for (const candidate of dialogRegions(lines)) {
80
- const region = candidate.lines.map(unbox);
80
+ const region = candidate.lines.map(regionLine);
81
81
  const raw = candidate.lines.map(unframe);
82
82
  // Tryb zatwierdzania liczymy PRZED opcjami: wariant `preview` wyłącza czytanie opisów
83
83
  // (ramka podglądu stoi dokładnie tam, gdzie w drugim wariancie stoi opis).
@@ -400,12 +400,67 @@ export const SCREEN_SIGNATURES = {
400
400
  pattern: /^ (\S.*)$/,
401
401
  cli: '2.1.319',
402
402
  },
403
+ trustArrowWarningOpen: {
404
+ what: 'start of the pre-approved permissions warning in the trust dialog block, without the margin',
405
+ // `dialog-trust-preapproved-2.1.332.txt`. The count and the settings file names vary with the folder, and a
406
+ // narrow pane wraps the line, so the pattern takes the start only.
407
+ pattern: /^⚠ This folder pre-approves /,
408
+ cli: '2.1.332',
409
+ },
410
+ trustArrowWarningClose: {
411
+ what: 'sentence that ends the pre-approved permissions warning in the trust dialog block, without the margin',
412
+ // `dialog-trust-preapproved-2.1.332.txt`
413
+ pattern: /^These will apply without asking\./,
414
+ cli: '2.1.332',
415
+ },
416
+ trustArrowWarningListLine: {
417
+ what: 'permission list line of the warning: a three-space margin, the same shape as an option line without `❯`',
418
+ // `dialog-trust-preapproved-2.1.332.txt`: the first list line has this margin, a wrapped rest has one space.
419
+ pattern: /^ {3}(\S.*)$/,
420
+ cli: '2.1.332',
421
+ },
403
422
  trustArrowFooter: {
404
423
  what: 'stopka dialogu zaufania bez cyfr — ostatnia linia bloku',
405
424
  // `kontrolny/zaufanie-2.1.319.txt`
406
425
  pattern: /^Enter to confirm · Esc to cancel$/,
407
426
  cli: '2.1.319',
408
427
  },
428
+ /*
429
+ * Start dialog about external imports: it stands before the prompt field when a memory file of the project (or its
430
+ * `.claude/rules`) imports a file outside the project, and herdr reads it as `idle` (its blocked rules look for
431
+ * "esc to cancel"). Captures `kontrolny/importy-zewnetrzne-*-2.1.332.txt` at 139 columns.
432
+ */
433
+ startDialogImportsTitle: {
434
+ what: 'title line of the external imports start dialog, the first line under the bare rule of its block',
435
+ // `kontrolny/importy-zewnetrzne-2.1.332.txt`
436
+ pattern: /^Allow external CLAUDE\.md file imports\?$/,
437
+ cli: '2.1.332',
438
+ },
439
+ startDialogImportsNoOption: {
440
+ what: 'decline option of the external imports start dialog (no digit), the label without the cursor column',
441
+ // `kontrolny/importy-zewnetrzne-2.1.332.txt` (cursor on it), `kontrolny/importy-zewnetrzne-po-down-2.1.332.txt`
442
+ pattern: /^No, disable external imports$/,
443
+ cli: '2.1.332',
444
+ },
445
+ startDialogImportsYesOption: {
446
+ what: 'allow option of the external imports start dialog (no digit), the label without the cursor column',
447
+ // `kontrolny/importy-zewnetrzne-po-down-2.1.332.txt` (cursor on it after `down`)
448
+ pattern: /^Yes, allow external imports$/,
449
+ cli: '2.1.332',
450
+ },
451
+ startDialogImportsOptionLine: {
452
+ what: 'option line of the external imports start dialog: two-space margin, cursor column (`❯` or a space), a '
453
+ + 'space, the label',
454
+ // `kontrolny/importy-zewnetrzne-2.1.332.txt`, `kontrolny/importy-zewnetrzne-po-down-2.1.332.txt`
455
+ pattern: /^ {2}(?:(❯)| ) (\S.*)$/,
456
+ cli: '2.1.332',
457
+ },
458
+ startDialogImportsFooter: {
459
+ what: 'key footer of the external imports start dialog, the last line of the screen',
460
+ // `kontrolny/importy-zewnetrzne-2.1.332.txt`, also under the cut top of `…-dluga-lista-2.1.332.txt`
461
+ pattern: /^Enter to confirm · Esc to disable$/,
462
+ cli: '2.1.332',
463
+ },
409
464
  knownDialogModel: {
410
465
  what: 'tytuł bloku dialogu zmiany modelu („Switch model?”), nie zdanie gdziekolwiek na ekranie',
411
466
  pattern: /^Switch model\?$/,
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Start dialog: a screen herdr reads as ready (`idle`, `interactive_ready`) while Claude Code has not reached its
3
+ * prompt field, because a dialog stands before it. The predicate says whether such a screen stands and, for the
4
+ * measured external imports dialog, which one. It is pure: what the launcher does with the answer (the wait, the
5
+ * stable screen over time) lives in `herdr/start-dialog-wait.ts`; no key ever comes from here.
6
+ *
7
+ * The external imports dialog is proven from the bottom of the screen: its key footer as the last line and, above
8
+ * it, the closed pair of its two options with exactly one `❯`. A long import list pushes the block's rule, title and
9
+ * first paths above the pane edge, so neither the rule nor the title is required; when the rule is on the screen,
10
+ * the line under it must be the measured title.
11
+ */
12
+ import { composerRegionState } from '../../../drivers/herdr/commands.js';
13
+ import { blockTopOf } from './region.js';
14
+ import { SCREEN_SIGNATURES } from './signatures.js';
15
+ import { MEANINGFUL_PATTERN, trimmedLines } from './text.js';
16
+ const TITLE = SCREEN_SIGNATURES.startDialogImportsTitle.pattern;
17
+ const NO_OPTION = SCREEN_SIGNATURES.startDialogImportsNoOption.pattern;
18
+ const YES_OPTION = SCREEN_SIGNATURES.startDialogImportsYesOption.pattern;
19
+ const OPTION_LINE = SCREEN_SIGNATURES.startDialogImportsOptionLine.pattern;
20
+ const FOOTER = SCREEN_SIGNATURES.startDialogImportsFooter.pattern;
21
+ const blank = (line) => (line ?? '').trim() === '';
22
+ /** The first non-blank line under the nearest bare block rule above line `end`, trimmed; `null` without a rule. */
23
+ function blockTitle(lines, end) {
24
+ const top = blockTopOf(lines, end, { kinds: ['bare'] });
25
+ if (top === null)
26
+ return null;
27
+ for (let at = top.line + 1; at < end; at += 1) {
28
+ if (!blank(lines[at]))
29
+ return (lines[at] ?? '').trim();
30
+ }
31
+ return null;
32
+ }
33
+ /**
34
+ * Index of the "No" line of the external imports option pair, or `null`: the footer is the last line, only blank
35
+ * lines stand between it and the pair, the pair is "No" then "Yes" with the measured margin and exactly one `❯`, and
36
+ * the line above the pair is blank (or above the pane edge), so no third option hides there.
37
+ */
38
+ function importsPairAt(lines) {
39
+ const footer = lines.length - 1;
40
+ if (footer < 0 || !FOOTER.test((lines[footer] ?? '').trim()))
41
+ return null;
42
+ let at = footer - 1;
43
+ while (at >= 0 && blank(lines[at]))
44
+ at -= 1;
45
+ const yes = OPTION_LINE.exec(lines[at] ?? '');
46
+ const no = OPTION_LINE.exec(lines[at - 1] ?? '');
47
+ if (yes === null || no === null || !blank(lines[at - 2]))
48
+ return null;
49
+ if (!NO_OPTION.test(no[2] ?? '') || !YES_OPTION.test(yes[2] ?? ''))
50
+ return null;
51
+ return (no[1] === undefined) === (yes[1] === undefined) ? null : at - 1;
52
+ }
53
+ /**
54
+ * The start dialog on `screenText`, or `null` when the screen shows no start dialog: the prompt field is visible
55
+ * (Claude Code reached its prompt) or the screen has no text at all (nothing was drawn or read).
56
+ *
57
+ * @param screenText raw pane screen (ANSI allowed)
58
+ */
59
+ export function startDialogOf(screenText) {
60
+ const lines = trimmedLines(screenText);
61
+ if (!lines.some((line) => MEANINGFUL_PATTERN.test(line)))
62
+ return null;
63
+ if (composerRegionState(screenText) !== 'unknown')
64
+ return null;
65
+ const pair = importsPairAt(lines);
66
+ if (pair !== null) {
67
+ const title = blockTitle(lines, pair);
68
+ if (title === null || TITLE.test(title))
69
+ return { id: 'external-imports', title };
70
+ }
71
+ return { id: null, title: blockTitle(lines, lines.length) };
72
+ }
@@ -10,6 +10,12 @@
10
10
  * kolumny kursora, etykieta opcji, cyfra), także oddzielonej pustą linią. Każdy inny kształt (trzecia opcja, ucięta
11
11
  * góra albo dół, cyfry, zawinięty folder) daje `null`, czyli kartę bez przycisku. Moduł jest czysty: decyzję
12
12
  * o klawiszu podejmuje `send/trust-step.ts`.
13
+ *
14
+ * One exception to the option-shaped line rule: the warning about permissions the folder pre-approves (Claude Code
15
+ * 2.1.332). Between its opening line "⚠ This folder pre-approves …:" and its closing sentence "These will apply
16
+ * without asking." a line may carry the three-space margin of the permission list, which is the indent of an option
17
+ * line. The folder's settings write that list, so it still may not hold `❯`, an option label or a numbered option,
18
+ * and a warning without its closing sentence gives `null`.
13
19
  */
14
20
  import { createHash } from 'node:crypto';
15
21
  import path from 'node:path';
@@ -24,6 +30,9 @@ const CURSOR_MARK = SCREEN_SIGNATURES.trustArrowCursorMark.pattern;
24
30
  const CONTENT_LINE = SCREEN_SIGNATURES.trustArrowContentLine.pattern;
25
31
  const DIGIT_OPTION = SCREEN_SIGNATURES.optionLine.pattern;
26
32
  const FOOTER = SCREEN_SIGNATURES.trustArrowFooter.pattern;
33
+ const WARNING_OPEN = SCREEN_SIGNATURES.trustArrowWarningOpen.pattern;
34
+ const WARNING_CLOSE = SCREEN_SIGNATURES.trustArrowWarningClose.pattern;
35
+ const WARNING_LIST_LINE = SCREEN_SIGNATURES.trustArrowWarningListLine.pattern;
27
36
  const blank = (line) => (line ?? '').trim() === '';
28
37
  /** Opcja z dokładnym wcięciem z pomiaru albo `null`: linia bez kolumny kursora opcją nie jest. */
29
38
  function optionOf(line) {
@@ -37,12 +46,42 @@ function optionOf(line) {
37
46
  * bez `❯` i bez etykiety opcji (z cyfrą albo bez).
38
47
  */
39
48
  function plainLine(line) {
40
- if (blank(line))
41
- return true;
42
- const text = CONTENT_LINE.exec(line)?.[1];
49
+ return blank(line) || textOf(line, CONTENT_LINE) !== null;
50
+ }
51
+ /** Text of a block line with the given margin, or `null`: no such margin, `❯`, an option label or a numbered option. */
52
+ function textOf(line, margin) {
53
+ const text = margin.exec(line)?.[1];
43
54
  if (text === undefined || CURSOR_MARK.test(line))
44
- return false;
45
- return !NO_OPTION.test(text) && !YES_OPTION.test(text) && !DIGIT_OPTION.test(text);
55
+ return null;
56
+ return NO_OPTION.test(text) || YES_OPTION.test(text) || DIGIT_OPTION.test(text) ? null : text;
57
+ }
58
+ /**
59
+ * Whether the block lines outside the option pair hold no further list position. A line is blank or block text with
60
+ * the one-space margin. Inside the pre-approved permissions warning a line is never blank and may carry the
61
+ * three-space margin of the permission list instead; the warning must close before the option pair.
62
+ */
63
+ function onlyPlainLines(lines, from, to, first, last) {
64
+ let inWarning = false;
65
+ for (let index = from; index < to; index += 1) {
66
+ const line = lines[index] ?? '';
67
+ if (index === first || index === last) {
68
+ if (inWarning)
69
+ return false;
70
+ }
71
+ else if (inWarning) {
72
+ const text = textOf(line, CONTENT_LINE);
73
+ if (text === null && textOf(line, WARNING_LIST_LINE) === null)
74
+ return false;
75
+ if (text !== null && WARNING_CLOSE.test(text))
76
+ inWarning = false;
77
+ }
78
+ else {
79
+ if (!plainLine(line))
80
+ return false;
81
+ inWarning = WARNING_OPEN.test(textOf(line, CONTENT_LINE) ?? '');
82
+ }
83
+ }
84
+ return !inWarning;
46
85
  }
47
86
  /**
48
87
  * Dialog zaufania bez cyfr albo `null`, gdy ekran nie pokazuje go w całości.
@@ -78,10 +117,8 @@ export function parseTrustArrowDialog(screenText) {
78
117
  if (block.ambiguous || block.top === -1 || block.title?.kind !== 'known' || block.title.id !== 'trust')
79
118
  return null;
80
119
  // Od kreski do stopki jedyną listą jest para opcji: pusta linia nie chowa dodatkowej pozycji.
81
- for (let index = block.top + 1; index < footer; index += 1) {
82
- if (index !== first && index !== last && !plainLine(lines[index] ?? ''))
83
- return null;
84
- }
120
+ if (!onlyPlainLines(lines, block.top + 1, footer, first, last))
121
+ return null;
85
122
  const content = lines.slice(block.top + 1, first).map(unbox).join(' ');
86
123
  if (!SCREEN_SIGNATURES.knownDialogTrust.pattern.test(content))
87
124
  return null;
@@ -45,7 +45,7 @@ import { ENGINE_SESSION_ID_PATTERN, IMAGE_PLACEHOLDER, isHiddenTurnInput, parseI
45
45
  import { FileEchoPairing } from './commands/index.js';
46
46
  import { historyMessages, readHistoryTail, readRange, sizeOf } from './history-steps.js';
47
47
  import { compactPostTokensFrom, compactPreTokensFrom, createUsageTracker, isMainCompactBoundary, usageFrom, } from './jsonl-usage.js';
48
- import { artifactsSignature, createArtifactsTracker, createBackgroundTasksTracker, scanMainFileBefore, } from './background/index.js';
48
+ import { artifactsSignature, createArtifactsTracker, createBackgroundTasksTracker, isPullRequestLinkEntry, scanMainFileBefore, } from './background/index.js';
49
49
  import { emptyCarry, takeLines } from './background/jsonl-lines.js';
50
50
  import { toolActivity, toolEndActivity, toolInputsByName } from './jsonl-activity.js';
51
51
  import { MAIN_SCAN_MAX_BYTES } from './background/main-scan.js';
@@ -92,6 +92,8 @@ export const ARTIFACTS_RESCAN_LOG = 'artifact scan after a file truncation or sk
92
92
  export const ARTIFACTS_RESCAN_SKIPPED_LOG = 'artifacts before the file truncation or skip are not visible';
93
93
  /** Okno batchowania emisji — 100 ms wystarczy telefonowi, a ratuje SSE przy 17 panelach. */
94
94
  export const FOLLOW_BATCH_MS = 100;
95
+ /** Events without content: they do not take the last place of a batch from the activity indicator. */
96
+ const CONTENTLESS = new Set(['turn-input', 'echo-dropped', 'pull-request-entry']);
95
97
  /** Siatka bezpieczeństwa: `fs.watch` gubi zdarzenia na części systemów plików. */
96
98
  export const FOLLOW_STAT_TICK_MS = 2_000;
97
99
  /** Plik jeszcze nie istnieje: gęsty poll przez pierwszą minutę… */
@@ -1697,6 +1699,8 @@ class Follower {
1697
1699
  this.#push({ type: 'turn-input' });
1698
1700
  else if (isMainCompactBoundary(raw))
1699
1701
  this.#push({ type: 'turn-input', kind: 'compaction' });
1702
+ else if (isPullRequestLinkEntry(raw))
1703
+ this.#push({ type: 'pull-request-entry' });
1700
1704
  return;
1701
1705
  }
1702
1706
  const message = entry.message;
@@ -2321,7 +2325,7 @@ class Follower {
2321
2325
  let last = events.length - 1;
2322
2326
  // Zdarzenia bez treści (wejście tury, wypadnięty wpis echa) nie odbierają wskaźnikowi aktywności
2323
2327
  // miejsca ostatniego w partii.
2324
- while (last >= 0 && (events[last]?.type === 'turn-input' || events[last]?.type === 'echo-dropped'))
2328
+ while (last >= 0 && CONTENTLESS.has(events[last]?.type ?? ''))
2325
2329
  last -= 1;
2326
2330
  for (let i = 0; i < events.length; i += 1) {
2327
2331
  const event = events[i];
@@ -0,0 +1,104 @@
1
+ /**
2
+ * The provenance suffix of a Rarog pane label: `rt:<code>` for a terminal, `rc:<code><code>` for a
3
+ * Claude pane, hex values written in Crockford base32 (lowercase, most significant bit first, the
4
+ * last character padded with zero bits). Pure functions over strings, the writers and the closed
5
+ * patterns side by side. What the values mean (terminal id, project key, tab label trace) lives in
6
+ * `herdr/provenance.ts`, which reads and writes every pane label through this module.
7
+ */
8
+ /** Crockford base32 in lowercase: digits and letters without `i`, `l`, `o`, `u`. */
9
+ const ALPHABET = '0123456789abcdefghjkmnpqrstvwxyz';
10
+ const CODE_CHAR = '[0-9a-hjkmnp-tv-z]';
11
+ const HEX_RE = /^[0-9a-f]+$/;
12
+ /** Hex digits of a terminal id and of a tab label trace. */
13
+ const TERM_ID_HEX = 16;
14
+ const TRACE_HEX = 8;
15
+ /** Characters of a project key code: the first 35 bits of the 64-bit key. */
16
+ export const PROJECT_KEY_CODE_LENGTH = 7;
17
+ const KEY_CODE_RE = new RegExp(`^${CODE_CHAR}{${String(PROJECT_KEY_CODE_LENGTH)}}$`);
18
+ /** Between the description and the suffix. */
19
+ const SEPARATOR = ' · ';
20
+ /** Characters of a code for `hexLength` hex digits: whole 5-bit characters. */
21
+ function codeLength(hexLength) {
22
+ return Math.ceil((hexLength * 4) / 5);
23
+ }
24
+ /** Lowercase hex → code; the last character is padded with zero bits. */
25
+ export function encodeHex(hex) {
26
+ if (!HEX_RE.test(hex))
27
+ throw new Error('Label code input is not lowercase hex.');
28
+ const length = codeLength(hex.length);
29
+ let value = BigInt(`0x${hex}`) << BigInt(length * 5 - hex.length * 4);
30
+ const chars = [];
31
+ for (let i = 0; i < length; i += 1) {
32
+ chars.unshift(ALPHABET.charAt(Number(value & 31n)));
33
+ value >>= 5n;
34
+ }
35
+ return chars.join('');
36
+ }
37
+ /**
38
+ * Code → `hexLength` lowercase hex digits, or `null` for a code of another length, a character
39
+ * outside the alphabet or padding bits other than zero (so a value has exactly one code).
40
+ */
41
+ export function decodeCode(code, hexLength) {
42
+ const length = codeLength(hexLength);
43
+ if (code.length !== length)
44
+ return null;
45
+ let value = 0n;
46
+ for (const char of code) {
47
+ const digit = ALPHABET.indexOf(char);
48
+ if (digit < 0)
49
+ return null;
50
+ value = (value << 5n) | BigInt(digit);
51
+ }
52
+ const padding = BigInt(length * 5 - hexLength * 4);
53
+ if ((value & ((1n << padding) - 1n)) !== 0n)
54
+ return null;
55
+ return (value >> padding).toString(16).padStart(hexLength, '0');
56
+ }
57
+ /** The code of a 16-hex project key as a Claude label carries it. */
58
+ export function keyCodeOf(key) {
59
+ return encodeHex(key).slice(0, PROJECT_KEY_CODE_LENGTH);
60
+ }
61
+ /** `rt:<13 characters>` — the whole terminal id, lossless. */
62
+ export function termLabelSuffix(id) {
63
+ if (id.length !== TERM_ID_HEX)
64
+ throw new Error('Terminal id is not 16 hex digits.');
65
+ return `rt:${encodeHex(id)}`;
66
+ }
67
+ /** `rc:<7 characters of the key><7 characters of the trace>` — the trace is lossless. */
68
+ export function claudeLabelSuffix(keyCode, trace) {
69
+ if (!KEY_CODE_RE.test(keyCode))
70
+ throw new Error('Project key code is not 7 label code characters.');
71
+ if (trace.length !== TRACE_HEX)
72
+ throw new Error('Tab label trace is not 8 hex digits.');
73
+ return `rc:${keyCode}${encodeHex(trace)}`;
74
+ }
75
+ /** A captured description is valid when absent (bare format) or not blank. */
76
+ export function descriptionOk(description) {
77
+ return description === undefined || /\S/u.test(description);
78
+ }
79
+ /** `<description> · <suffix>`, or the bare suffix when the description is empty. */
80
+ export function joinLabel(description, suffix) {
81
+ return description === '' ? suffix : `${description}${SEPARATOR}${suffix}`;
82
+ }
83
+ /*
84
+ * Closed patterns anchored at the end, with an optional leading description. The description is
85
+ * captured and checked in code (at least one non-whitespace character), so a separator alone
86
+ * stays foreign; one greedy group keeps the match linear on long labels.
87
+ */
88
+ const TERM_LABEL_RE = new RegExp(`^(?:(.+)${SEPARATOR})?rt:(${CODE_CHAR}{${String(codeLength(TERM_ID_HEX))}})$`);
89
+ const CLAUDE_LABEL_RE = new RegExp(`^(?:(.+)${SEPARATOR})?rc:(${CODE_CHAR}{${String(PROJECT_KEY_CODE_LENGTH)}})`
90
+ + `(${CODE_CHAR}{${String(codeLength(TRACE_HEX))}})$`);
91
+ /** A pane label in the current format → its suffix, or `null` for anything outside the patterns. */
92
+ export function readLabelSuffix(label) {
93
+ const term = TERM_LABEL_RE.exec(label);
94
+ if (term?.[2] !== undefined) {
95
+ const id = descriptionOk(term[1]) ? decodeCode(term[2], TERM_ID_HEX) : null;
96
+ return id === null ? null : { kind: 'term', id };
97
+ }
98
+ const claude = CLAUDE_LABEL_RE.exec(label);
99
+ if (claude?.[2] !== undefined && claude[3] !== undefined) {
100
+ const trace = descriptionOk(claude[1]) ? decodeCode(claude[3], TRACE_HEX) : null;
101
+ return trace === null ? null : { kind: 'claude', keyCode: claude[2], trace };
102
+ }
103
+ return null;
104
+ }