@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
@@ -0,0 +1,220 @@
1
+ import { standingConsentDialog } from '../policy/consent.js';
2
+ import { contentEscalates } from '../policy/escalation.js';
3
+ import { optionPolicy } from '../policy/option-policy.js';
4
+ import { matchTerminalDialog } from '../policy/terminal.js';
5
+ import { NOTES_EDITING_MARKER, formFooter, formSubmitMode } from '../screen/form.js';
6
+ import { dialogKind } from '../screen/kinds.js';
7
+ import { OPTION_BOX_GLYPH_PATTERN } from '../screen/options.js';
8
+ import { HORIZONTAL_RULE_PATTERN } from '../screen/region.js';
9
+ import { SCREEN_SIGNATURES } from '../screen/signatures.js';
10
+ import { LIVE_REFUSE, liveEnterWhy, liveKeys } from './policy.js';
11
+ import { LIVE_CURSOR, liveRegion } from './view.js';
12
+ export { LIVE_ENTER_KEY, LIVE_ESCAPE_KEY, LIVE_NAVIGATION_KEYS } from './policy.js';
13
+ const OPTION_ROW = SCREEN_SIGNATURES.dialogOptionRow.pattern;
14
+ const KEY_HINT = SCREEN_SIGNATURES.keyHintLine.pattern;
15
+ const SETS_DEFAULT = SCREEN_SIGNATURES.footerSetsDefault.pattern;
16
+ const CHECKBOX = SCREEN_SIGNATURES.optionCheckbox.pattern;
17
+ const SUBMIT_ROW = SCREEN_SIGNATURES.formSubmitRow.pattern;
18
+ const NEGATIVE = SCREEN_SIGNATURES.negativeOption.pattern;
19
+ const CUSTOM_ANSWER = SCREEN_SIGNATURES.customAnswerOption.pattern;
20
+ /** The checkbox glyphs of the form tab bar (☐ ☒ ☑), all of them: checking a box of the form turns ☐ into ☒. */
21
+ export const LIVE_TAB_GLYPHS = new RegExp(SCREEN_SIGNATURES.tabGlyph.pattern.source, 'gu');
22
+ /**
23
+ * What stands on the phone next to a live card: the three shapes of today's card without buttons (a degraded consent
24
+ * card or one without the approve button, a screen card of a dialog Rarog does not know, a card of a dialog answered in
25
+ * the terminal), or no card for the dialog at all. A closed list: the audit log counts it.
26
+ */
27
+ export const LIVE_CARD_SHAPES = ['degraded', 'screen-dialog', 'terminal', 'no-card'];
28
+ /**
29
+ * What the verify read after a key of the live card saw: the cursor moved to another option (`cursor`), the dialog is
30
+ * gone (`gone`), the same view unchanged (`same`), the same dialog with another print (`changed`), a dialog of another
31
+ * class (`other-dialog`), or a failed read (`unknown`). A closed list: the audit log counts it.
32
+ */
33
+ export const LIVE_VERIFY_OUTCOMES = ['cursor', 'gone', 'same', 'changed', 'other-dialog', 'unknown'];
34
+ const indent = (line) => line.length - line.trimStart().length;
35
+ /**
36
+ * The registry class of the place, which the Enter rule reads and the audit lines carry: in a session the registry's,
37
+ * before the session starts `dialog` for a known start dialog and `permission` for an unknown one (the consent guards).
38
+ */
39
+ export function liveClass(place) {
40
+ if (place.kind === 'session')
41
+ return place.cliDialog;
42
+ return place.startDialog === null ? 'permission' : 'dialog';
43
+ }
44
+ /**
45
+ * Whether row `i` of the option zone continues the label of the option above it: indented to the label column at
46
+ * least, not empty, not an option, a key hint or a rule.
47
+ */
48
+ function continues(region, i) {
49
+ const line = region.rows[i] ?? '';
50
+ const trimmed = line.trim();
51
+ return trimmed !== '' && indent(line) >= region.labelColumn && !region.options.some((option) => option.row === i)
52
+ && !OPTION_ROW.test(line) && !KEY_HINT.test(trimmed) && !HORIZONTAL_RULE_PATTERN.test(trimmed);
53
+ }
54
+ /**
55
+ * The rows of the label under the cursor, from the raw rows (gaps kept), each trimmed. A question form: the cursor row
56
+ * alone, up to the frame of a preview box, because option descriptions stand in the label column under it. Other
57
+ * dialogs: the cursor row and its continuation rows. The card joins them by one space.
58
+ */
59
+ function cursorLabelRows(region, question) {
60
+ const at = region.cursorRow;
61
+ const row = region.rows[at] ?? '';
62
+ const own = region.options.find((option) => option.row === at)?.label
63
+ ?? row.slice(row.indexOf(LIVE_CURSOR) + LIVE_CURSOR.length).trim();
64
+ if (question) {
65
+ const box = own.search(OPTION_BOX_GLYPH_PATTERN);
66
+ return [(box === -1 ? own : own.slice(0, box)).trim()];
67
+ }
68
+ const parts = [own.trim()];
69
+ for (let i = at + 1; i < region.zoneEnd && continues(region, i); i += 1)
70
+ parts.push((region.rows[i] ?? '').trim());
71
+ return parts;
72
+ }
73
+ /**
74
+ * Whether the option under the cursor has a lasting effect: an escalating label, a footer that says Enter saves the
75
+ * default, a standing consent dialog (`standingConsentDialog`), or escalation markers in the dialog content above the
76
+ * options (the operation frame stays out) with the cursor not on a declining option.
77
+ */
78
+ function lasting(region, label) {
79
+ const facts = { label, terminalDialog: null, multiSelect: false, notesEditing: false };
80
+ if (optionPolicy(facts, 'hook').why === 'escalation')
81
+ return true;
82
+ if (region.footer !== null && SETS_DEFAULT.test(region.rows.slice(region.footer).join(' ')))
83
+ return true;
84
+ if (standingConsentDialog(region.rows.join('\n')) !== null)
85
+ return true;
86
+ const firstOption = region.options[0]?.row ?? 0;
87
+ const body = region.rows.slice(region.bodyStart, firstOption).map((line) => line.trim());
88
+ return !NEGATIVE.test(label) && contentEscalates(body);
89
+ }
90
+ /**
91
+ * Numbered options 1..N whose last option declines and, with its continuation rows, ends the screen. These captures
92
+ * have no key footer and end on a declining option: the WebFetch permission (`measured/zgoda-webfetch-2.1.322.txt`),
93
+ * the sandbox network permission (`measured/zgoda-siec-2.1.328.txt`), exit plan mode without a plan
94
+ * (`measured/exitplanmode-bez-planu-2.1.328.txt`), the model switch (`dialog-model-switch.txt`).
95
+ */
96
+ function endsOnDecline(region) {
97
+ const last = region.options.at(-1);
98
+ if (!region.numbered || last === undefined || last.digit === null || !NEGATIVE.test(last.label))
99
+ return false;
100
+ for (let i = last.row + 1; i < region.rows.length; i += 1)
101
+ if (!continues(region, i))
102
+ return false;
103
+ return true;
104
+ }
105
+ /**
106
+ * The option set without a key footer is closed: a dialog of the terminal list matched with its whole option set, or
107
+ * options that end on a declining one at the bottom of the screen.
108
+ */
109
+ function closedSet(region) {
110
+ const title = region.rows.find((row) => row.trim() !== '') ?? '';
111
+ const options = region.options.flatMap((option) => (option.digit === null
112
+ ? []
113
+ : [{ digit: option.digit, label: option.label }]));
114
+ return matchTerminalDialog(title, options) !== null || endsOnDecline(region);
115
+ }
116
+ /**
117
+ * Whether the region is a question form: its key footer names the select and navigation keys of the form. Only the
118
+ * footer counts, because the question and the option descriptions may carry the words of another dialog's footer
119
+ * ("Do you want to proceed?"). The plan dialog's footer ("ctrl+g to edit in …") names neither.
120
+ */
121
+ function questionForm(region) {
122
+ if (region.footer === null)
123
+ return false;
124
+ return dialogKind(region.rows.slice(region.footer).join('\n').toLowerCase()) === 'question';
125
+ }
126
+ /**
127
+ * Whether the cursor stands on the free-text row of a question form: the last numbered option of its block (no
128
+ * numbered option under it above the next rule) whose label, without its checkbox, reads "Type something"
129
+ * (`live/multi-form-free-text-2.1.332.txt`). The row takes typed text, so Enter on it does not answer the form. The
130
+ * preview variant adds no such row, so its last option is the author's even when it reads so.
131
+ */
132
+ function freeTextRow(region, question, cursorRow) {
133
+ if (!question || cursorRow === undefined || previewForm(region))
134
+ return false;
135
+ const option = region.options.find((candidate) => candidate.row === region.cursorRow);
136
+ if (option === undefined || option.digit === null)
137
+ return false;
138
+ const box = CHECKBOX.exec(cursorRow);
139
+ if (!CUSTOM_ANSWER.test((box === null ? cursorRow : box[3] ?? '').trim()))
140
+ return false;
141
+ for (let i = option.row + 1; i < region.zoneEnd; i += 1) {
142
+ if (HORIZONTAL_RULE_PATTERN.test((region.rows[i] ?? '').trim()))
143
+ return true;
144
+ if (region.options.some((candidate) => candidate.row === i && candidate.digit !== null))
145
+ return false;
146
+ }
147
+ return true;
148
+ }
149
+ /**
150
+ * Whether a question form is in notes editing: `ctrl+g` in its footer next to a notes field. The notes field exists
151
+ * only in the preview variant of the form (the notes marker in the footer or a preview frame on an option line,
152
+ * `formSubmitMode`). Without it the phrase is no notes editing: Claude Code 2.1.332 adds "ctrl+g to edit in Vim" to
153
+ * the footer of a multi-select form while the cursor stands on "Type something".
154
+ */
155
+ function notesEditing(region) {
156
+ return formFooter(region.rows).includes(NOTES_EDITING_MARKER) && previewForm(region);
157
+ }
158
+ /** Whether the form is the preview variant: the notes marker in its footer or a preview frame on an option line. */
159
+ function previewForm(region) {
160
+ // `formSubmitMode` reads the rows as the parser keeps them: trimmed, the option line without the cursor.
161
+ const rows = region.rows.map((row) => {
162
+ const trimmed = row.trim();
163
+ return trimmed.startsWith(LIVE_CURSOR) ? trimmed.slice(LIVE_CURSOR.length).trimStart() : trimmed;
164
+ });
165
+ return formSubmitMode(rows) === 'digit-enter';
166
+ }
167
+ /**
168
+ * The live card of a screen, or `null`: level `0`, a dialog with its own card, no dialog with options on the screen,
169
+ * or a question form in notes editing (a key would type into the note).
170
+ */
171
+ export function liveDialogView(screen, input) {
172
+ if (input.level === 0 || input.ownCard)
173
+ return null;
174
+ const region = liveRegion(screen);
175
+ if (region === null)
176
+ return null;
177
+ const question = questionForm(region);
178
+ if (question && notesEditing(region))
179
+ return null;
180
+ const cls = liveClass(input.place);
181
+ const labelRows = region.cursorRow === -1 ? [] : cursorLabelRows(region, question);
182
+ const label = labelRows.join(' ');
183
+ const why = liveEnterWhy({
184
+ level: input.level,
185
+ light: (cls === 'input' || cls === 'dialog') && input.consent.mode !== null,
186
+ consent: input.consent,
187
+ region,
188
+ labelRows,
189
+ closedSet: region.footer === null && closedSet(region),
190
+ freeText: freeTextRow(region, question, labelRows[0]),
191
+ });
192
+ const multiSelect = region.options.some((option) => CHECKBOX.test(option.label));
193
+ const enter = CHECKBOX.test(label)
194
+ ? 'toggle'
195
+ : multiSelect && SUBMIT_ROW.test(label) ? 'submit' : 'choose';
196
+ return {
197
+ text: region.text,
198
+ print: region.print,
199
+ cursorLabel: why === null ? label : null,
200
+ keys: liveKeys(why),
201
+ ...(why === null ? {} : { why, refuse: LIVE_REFUSE[why] }),
202
+ ...(why === null && lasting(region, label) ? { lasting: true } : {}),
203
+ ...(region.hiddenAbove === undefined ? {} : { hiddenAbove: region.hiddenAbove }),
204
+ ...(why === null ? { enter } : {}),
205
+ bind: input.place.kind === 'start' ? 'pane' : 'session',
206
+ };
207
+ }
208
+ /** The wire field `herdrDialogLive` of a view, in the occurrence `id` at revision `rev`. */
209
+ export function liveDialogWire(view, id, rev) {
210
+ return {
211
+ id,
212
+ rev,
213
+ text: view.text,
214
+ cursorLabel: view.cursorLabel,
215
+ keys: [...view.keys],
216
+ ...(view.refuse === undefined ? {} : { refuse: view.refuse }),
217
+ ...(view.lasting === undefined ? {} : { lasting: view.lasting }),
218
+ ...(view.hiddenAbove === undefined ? {} : { hiddenAbove: view.hiddenAbove }),
219
+ };
220
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * The live dialog card, key half: one function decides whether the server takes Enter for a dialog region
3
+ * ({@link liveEnterWhy}), and the keys of the card follow from its answer ({@link liveKeys}). Esc is always there.
4
+ *
5
+ * Every doubt refuses Enter. The consent guards of the emergency approve button (`screenFallbackGuard`) apply to a
6
+ * consent dialog in channel modes `main` and `all`; the guards of the card itself (`card`, `class`, a subagent's
7
+ * dialog in `main`) do not, because the live card shows the dialog as the terminal does. No I/O.
8
+ */
9
+ import { DIALOG_LIVE_KEYS } from '@rarog/shared';
10
+ import { hasCardHiddenChar } from '../../../hidden-chars.js';
11
+ import { screenFallbackGuard } from '../screen-fallback.js';
12
+ import { SCREEN_SIGNATURES } from '../screen/signatures.js';
13
+ /** The keys of the contract, named by their position in `DIALOG_LIVE_KEYS`. */
14
+ const [ESCAPE, UP, DOWN, ENTER] = DIALOG_LIVE_KEYS;
15
+ const LABEL_CUT = SCREEN_SIGNATURES.optionLabelCut.pattern;
16
+ export const LIVE_ESCAPE_KEY = ESCAPE;
17
+ export const LIVE_NAVIGATION_KEYS = [UP, DOWN];
18
+ export const LIVE_ENTER_KEY = ENTER;
19
+ /**
20
+ * Why the server does not take Enter, in the order the rule checks. A closed list: the audit log and the app read
21
+ * the reason, so a new one needs an entry here and in {@link LIVE_REFUSE}.
22
+ */
23
+ export const LIVE_ENTER_WHYS = [
24
+ 'level', 'no-cursor', 'cursors', 'cursor-off-options', 'options-scrolled', 'options-cut', 'hidden-char',
25
+ 'free-text', 'channel-mode', 'unjudged', 'hook-trace', 'hook-waits', 'hook-process', 'foreign-hook',
26
+ 'restart-grace', 'no-tool-use',
27
+ ];
28
+ /** The refusal word of the contract for each reason: the app builds its sentence from it. */
29
+ export const LIVE_REFUSE = {
30
+ level: 'terminal-only',
31
+ 'no-cursor': 'unreadable',
32
+ cursors: 'unreadable',
33
+ 'cursor-off-options': 'unreadable',
34
+ 'options-scrolled': 'unreadable',
35
+ 'options-cut': 'unreadable',
36
+ 'hidden-char': 'unreadable',
37
+ 'free-text': 'terminal-only',
38
+ 'channel-mode': 'consent-dialog',
39
+ unjudged: 'consent-dialog',
40
+ 'hook-trace': 'consent-dialog',
41
+ 'hook-waits': 'consent-dialog',
42
+ 'hook-process': 'consent-dialog',
43
+ 'foreign-hook': 'consent-dialog',
44
+ 'restart-grace': 'consent-dialog',
45
+ 'no-tool-use': 'no-jsonl',
46
+ };
47
+ /** The reason for a consent guard the emergency button refuses on. */
48
+ function consentWhy(guard) {
49
+ switch (guard) {
50
+ case 'judgement': return 'unjudged';
51
+ case 'trace': return 'hook-trace';
52
+ case 'hook': return 'hook-waits';
53
+ case 'hook-running':
54
+ case 'ps': return 'hook-process';
55
+ case 'hook-list': return 'foreign-hook';
56
+ case 'restart': return 'restart-grace';
57
+ // `mode`, and the guards the fixed facts of `liveEnterWhy` rule out: a doubt about the channel refuses.
58
+ default: return 'channel-mode';
59
+ }
60
+ }
61
+ /** The first reason Enter is not taken, or `null` when it is. Esc is taken in every case. */
62
+ export function liveEnterWhy(facts) {
63
+ if (!facts.light && facts.level < 2)
64
+ return 'level';
65
+ const { region } = facts;
66
+ if (region.cursors === 0)
67
+ return 'no-cursor';
68
+ if (region.cursors > 1)
69
+ return 'cursors';
70
+ if (region.cursorRow === -1)
71
+ return 'cursor-off-options';
72
+ if (region.scrolled)
73
+ return 'options-scrolled';
74
+ if (!region.numbered || (region.footer === null && !facts.closedSet))
75
+ return 'options-cut';
76
+ // A label row that ends in the cut mark does not show the option whole; a cut operation above the options does
77
+ // not refuse (the region marks it with `hiddenAbove`).
78
+ if (facts.labelRows.some((row) => LABEL_CUT.test(row)))
79
+ return 'options-cut';
80
+ if (hasCardHiddenChar(region.rows.join('\n')) || facts.labelRows.some((row) => hasCardHiddenChar(row))) {
81
+ return 'hidden-char';
82
+ }
83
+ if (facts.freeText)
84
+ return 'free-text';
85
+ if (facts.light)
86
+ return null;
87
+ const { consent } = facts;
88
+ if (consent.mode === 'off' || consent.mode === 'shadow')
89
+ return null;
90
+ // The facts the live card does not have are fixed so that only the channel guards remain.
91
+ const guard = screenFallbackGuard({ ...consent, cliDialog: 'permission', card: true, thread: 'main' });
92
+ if (guard !== null)
93
+ return consentWhy(guard);
94
+ // The emergency button needs `ps` to answer only for a subagent's dialog; Enter on a consent dialog always does.
95
+ if (consent.hookRunning === null)
96
+ return 'hook-process';
97
+ if (!consent.toolUse)
98
+ return 'no-tool-use';
99
+ return null;
100
+ }
101
+ /** The keys the server takes: all four with Enter, Esc alone on a consent dialog below level 2, else Esc and arrows. */
102
+ export function liveKeys(why) {
103
+ if (why === null)
104
+ return [LIVE_ESCAPE_KEY, ...LIVE_NAVIGATION_KEYS, LIVE_ENTER_KEY];
105
+ if (why === 'level')
106
+ return [LIVE_ESCAPE_KEY];
107
+ return [LIVE_ESCAPE_KEY, ...LIVE_NAVIGATION_KEYS];
108
+ }
@@ -0,0 +1,261 @@
1
+ /**
2
+ * The live dialog card, screen half: the dialog region of a raw pane screen (top rule to the last footer line), its
3
+ * options, the cursor, the cut and scroll marks, the capped text and the fingerprint.
4
+ *
5
+ * It decides nothing: which keys the server takes stands in `policy.ts`, the label under the cursor and the card
6
+ * fields in `model.ts`. No I/O; every screen pattern comes from the signature registry.
7
+ */
8
+ import { createHash } from 'node:crypto';
9
+ import { LAYER2_EXCERPT_MAX_CHARS, LAYER2_EXCERPT_MAX_LINES } from '../layer2/card.js';
10
+ import { withoutAutoDeny } from '../screen/auto-deny.js';
11
+ import { lineBelow } from '../screen/block.js';
12
+ import { headerAboveEdge, operationAbove } from '../screen/operation.js';
13
+ import { HORIZONTAL_RULE_PATTERN, blockTopOf } from '../screen/region.js';
14
+ import { SCREEN_SIGNATURES } from '../screen/signatures.js';
15
+ import { trimmedLines } from '../screen/text.js';
16
+ const KEY_FOOTER = SCREEN_SIGNATURES.dialogKeyFooter.pattern;
17
+ const OPTION_ROW = SCREEN_SIGNATURES.dialogOptionRow.pattern;
18
+ const SESSION_NAME_EDGE = SCREEN_SIGNATURES.sessionNameEdge.pattern;
19
+ const SCROLL_MARK = SCREEN_SIGNATURES.listScrollMarker.pattern;
20
+ const HIDDEN_LINES = SCREEN_SIGNATURES.hiddenLinesMarker.pattern;
21
+ const OPERATION_RULE = SCREEN_SIGNATURES.operationRule.pattern;
22
+ const CHECKBOX = SCREEN_SIGNATURES.optionCheckbox.pattern;
23
+ const SUBMIT_ROW = SCREEN_SIGNATURES.formSubmitRow.pattern;
24
+ const PLAN_TITLE = SCREEN_SIGNATURES.planTitle.pattern;
25
+ /** The cursor glyph of a dialog option. */
26
+ export const LIVE_CURSOR = SCREEN_SIGNATURES.dialogCursorMark.pattern;
27
+ const indent = (line) => line.length - line.trimStart().length;
28
+ /** Lines that are never the content of a dialog: empty lines, horizontal rules, the session name edge. */
29
+ function chrome(line) {
30
+ const trimmed = line.trim();
31
+ return trimmed === '' || HORIZONTAL_RULE_PATTERN.test(trimmed) || SESSION_NAME_EDGE.test(trimmed);
32
+ }
33
+ /** Column of the digit of an option row, from the parts the registry pattern captured. */
34
+ function digitColumn(line, match) {
35
+ return line.length - (match[2] ?? '').length - 2 - (match[1] ?? '').length;
36
+ }
37
+ /**
38
+ * First line of the key footer under the options, or `-1`. The footer is the highest key footer line in the block of
39
+ * non-empty lines that ends on the last line; an option row, a line with the cursor, a rule or an empty line ends
40
+ * the block.
41
+ */
42
+ function footerStart(lines, last) {
43
+ let top = last;
44
+ while (top >= 0) {
45
+ const line = lines[top] ?? '';
46
+ const trimmed = line.trim();
47
+ const ends = trimmed === '' || OPTION_ROW.test(line) || line.includes(LIVE_CURSOR)
48
+ || HORIZONTAL_RULE_PATTERN.test(trimmed);
49
+ if (ends)
50
+ break;
51
+ top -= 1;
52
+ }
53
+ for (let i = top + 1; i <= last; i += 1)
54
+ if (KEY_FOOTER.test((lines[i] ?? '').trim()))
55
+ return i;
56
+ return -1;
57
+ }
58
+ /**
59
+ * Numbered options: the last "1." row above `end` sets the digit column; the options are the rows in that column. A
60
+ * list cut at the top has no "1." row: its lowest option row sets the column and the rows in it from the top of the
61
+ * screen are the options, whose digits then do not run from 1.
62
+ */
63
+ function numberedOptions(lines, end) {
64
+ let one = -1;
65
+ let first = null;
66
+ let lowest = -1;
67
+ let lowestMatch = null;
68
+ for (let i = end - 1; i >= 0 && one === -1; i -= 1) {
69
+ const match = OPTION_ROW.exec(lines[i] ?? '');
70
+ if (match === null)
71
+ continue;
72
+ if (lowestMatch === null) {
73
+ lowest = i;
74
+ lowestMatch = match;
75
+ }
76
+ if (match[1] === '1') {
77
+ one = i;
78
+ first = match;
79
+ }
80
+ }
81
+ const anchor = first ?? lowestMatch;
82
+ if (anchor === null)
83
+ return null;
84
+ const head = lines[first === null ? lowest : one] ?? '';
85
+ const column = digitColumn(head, anchor);
86
+ const options = [];
87
+ for (let i = first === null ? 0 : one; i < end; i += 1) {
88
+ const line = lines[i] ?? '';
89
+ const match = OPTION_ROW.exec(line);
90
+ if (match === null || digitColumn(line, match) !== column)
91
+ continue;
92
+ options.push({ line: i, digit: match[1] ?? '', label: match[2] ?? '' });
93
+ }
94
+ const numbered = options.every((option, k) => option.digit === String(k + 1));
95
+ return { options, column, labelColumn: head.length - (anchor[2] ?? '').length, numbered, digits: true };
96
+ }
97
+ /**
98
+ * Options without digits ("Teach auto mode", the trust dialog): the rows in the label column of the cursor, contiguous
99
+ * around it (empty lines between them included). A choice needs two of them. A numbered option row is never one of
100
+ * them, so a numbered list cut above its "1." row stays a numbered list, and rows right under a numbered option row
101
+ * (no empty line between) that start at its label column or further right continue that option, so they make no
102
+ * choice.
103
+ */
104
+ function digitlessOptions(lines, end) {
105
+ const cursor = lines.slice(0, end).findLastIndex((line) => line.trimStart().startsWith(LIVE_CURSOR));
106
+ if (cursor === -1)
107
+ return null;
108
+ const row = lines[cursor] ?? '';
109
+ if (OPTION_ROW.test(row))
110
+ return null;
111
+ const after = row.slice(row.indexOf(LIVE_CURSOR) + LIVE_CURSOR.length);
112
+ const labelColumn = row.length - after.trimStart().length;
113
+ if (after.trim() === '')
114
+ return null;
115
+ const inColumn = (i) => {
116
+ const line = lines[i] ?? '';
117
+ return line.trim() !== '' && indent(line) === labelColumn && !OPTION_ROW.test(line);
118
+ };
119
+ const walk = (from, step) => {
120
+ const found = [];
121
+ for (let i = from; i >= 0 && i < end; i += step) {
122
+ if (inColumn(i))
123
+ found.push(i);
124
+ else if ((lines[i] ?? '').trim() !== '')
125
+ break;
126
+ }
127
+ return found;
128
+ };
129
+ const at = [...walk(cursor - 1, -1).reverse(), cursor, ...walk(cursor + 1, 1)];
130
+ if (at.length < 2)
131
+ return null;
132
+ const above = lines[(at[0] ?? cursor) - 1] ?? '';
133
+ const option = OPTION_ROW.exec(above);
134
+ if (option !== null && above.length - (option[2] ?? '').length <= labelColumn)
135
+ return null;
136
+ const options = at.map((line) => ({
137
+ line, digit: null, label: line === cursor ? after.trim() : (lines[line] ?? '').trim(),
138
+ }));
139
+ return { options, column: labelColumn, labelColumn, numbered: true, digits: false };
140
+ }
141
+ /**
142
+ * The top rule of the dialog block above the first option, or `null` when it is off screen. The nearest block rule
143
+ * (the operation frame is passed over) is the top, but the plan dialog draws a second rule of the same width between
144
+ * the plan text and its question: the identical rule right above, with the plan title under it, is the top then. An
145
+ * identical rule with anything else under it stands in the scrollback above the dialog. A rule above an operation
146
+ * frame whose own top is cut off belongs to the frame's content or the scrollback, and a rule under an operation frame
147
+ * with no block rule above that frame is the inner rule of a dialog taller than the pane (`measured/exitplanmode.txt`
148
+ * without its first rows): neither counts.
149
+ */
150
+ function topRule(lines, firstOption) {
151
+ let top = blockTopOf(lines, firstOption);
152
+ const higher = top === null ? null : blockTopOf(lines, top.line);
153
+ if (top !== null && higher !== null && lines[higher.line] === lines[top.line]) {
154
+ const title = lineBelow(lines, higher.line, top.line);
155
+ if (PLAN_TITLE.test((lines[title] ?? '').trim()))
156
+ top = higher;
157
+ }
158
+ if (top !== null) {
159
+ const above = blockTopOf(lines, top.line)?.line ?? -1;
160
+ if (lines.slice(above + 1, top.line).some((line) => OPERATION_RULE.test(line.trim())))
161
+ return null;
162
+ }
163
+ const from = top?.line ?? -1;
164
+ for (let frame = firstOption - 1; frame > from; frame -= 1) {
165
+ if (!OPERATION_RULE.test((lines[frame] ?? '').trim()))
166
+ continue;
167
+ return headerAboveEdge(lines, frame + 1, operationAbove(lines, frame + 1)) ? null : top;
168
+ }
169
+ return top;
170
+ }
171
+ /**
172
+ * Whether the cursor row is the Submit or Next row of a multi-select form: the word alone in the label column, with
173
+ * options whose labels start with a checkbox. An option description stands further right or left of that column.
174
+ */
175
+ function submitRow(row, found) {
176
+ const after = row.slice(row.indexOf(LIVE_CURSOR) + LIVE_CURSOR.length);
177
+ return SUBMIT_ROW.test(after.trim()) && row.length - after.trimStart().length === found.labelColumn
178
+ && found.options.some((option) => CHECKBOX.test(option.label));
179
+ }
180
+ /** Rows under the presentation ceiling (60 lines, 4000 characters), cut at the top, and how many were cut. */
181
+ function capped(rows) {
182
+ let cut = Math.max(0, rows.length - LAYER2_EXCERPT_MAX_LINES);
183
+ let text = rows.slice(cut).join('\n');
184
+ while (text.length > LAYER2_EXCERPT_MAX_CHARS && cut < rows.length - 1) {
185
+ cut += 1;
186
+ text = rows.slice(cut).join('\n');
187
+ }
188
+ return { text, cut };
189
+ }
190
+ /** The dialog region of a raw pane screen; `null` = no dialog with options on it. */
191
+ export function liveRegion(screen) {
192
+ const lines = trimmedLines(screen);
193
+ const last = lines.findLastIndex((line) => !chrome(line));
194
+ if (last === -1)
195
+ return null;
196
+ let footer = footerStart(lines, last);
197
+ const numbered = numberedOptions(lines, footer === -1 ? last + 1 : footer);
198
+ const digitless = footer === -1 ? null : digitlessOptions(lines, footer);
199
+ // A choice without digits below the last numbered row: the numbered rows above it are content or scrollback.
200
+ const below = digitless !== null
201
+ && (digitless.options[0]?.line ?? -1) > (numbered?.options.at(-1)?.line ?? -1);
202
+ const found = below ? digitless : numbered;
203
+ if (found === null)
204
+ return null;
205
+ // A key line indented past the options is a hint under an option (the plan's "shift+tab to approve…"), no footer.
206
+ if (footer !== -1 && indent(lines[footer] ?? '') > found.column)
207
+ footer = -1;
208
+ if (footer === -1) {
209
+ if (!found.digits)
210
+ return null;
211
+ const end = lines[last] ?? '';
212
+ const onOption = found.options.some((option) => option.line === last);
213
+ if (!onOption && (indent(end) < found.labelColumn || HORIZONTAL_RULE_PATTERN.test(end.trim())))
214
+ return null;
215
+ }
216
+ const firstOption = found.options[0]?.line ?? last;
217
+ const top = topRule(lines, firstOption);
218
+ const start = top === null ? 0 : top.line + 1;
219
+ const rows = lines.slice(start, last + 1);
220
+ const zoneEnd = (footer === -1 ? last + 1 : footer) - start;
221
+ const first = firstOption - start;
222
+ let marker = null;
223
+ let scrolled = false;
224
+ for (let i = Math.max(0, first - 1); i < zoneEnd; i += 1) {
225
+ const trimmed = (rows[i] ?? '').trim();
226
+ const count = HIDDEN_LINES.exec(trimmed);
227
+ if (count !== null)
228
+ marker ??= Number(count[1]);
229
+ else if (SCROLL_MARK.test(trimmed))
230
+ scrolled = true;
231
+ }
232
+ const cursors = rows.reduce((sum, row) => sum + row.split(LIVE_CURSOR).length - 1, 0);
233
+ const cursorAt = rows.findIndex((row) => row.trimStart().startsWith(LIVE_CURSOR));
234
+ const placed = found.options.some((option) => option.line - start === cursorAt)
235
+ || (cursorAt >= first && cursorAt < zoneEnd && submitRow(rows[cursorAt] ?? '', found));
236
+ const cursorRow = cursors === 1 && placed ? cursorAt : -1;
237
+ const ruleAbove = rows.slice(0, first).findLastIndex((row) => HORIZONTAL_RULE_PATTERN.test(row.trim()));
238
+ const { text, cut } = capped(rows);
239
+ let hidden;
240
+ if (marker !== null)
241
+ hidden = marker + cut;
242
+ else if (top === null)
243
+ hidden = null;
244
+ else
245
+ hidden = cut > 0 ? cut : undefined;
246
+ return {
247
+ rows,
248
+ options: found.options.map((option) => ({ row: option.line - start, digit: option.digit, label: option.label })),
249
+ labelColumn: found.labelColumn,
250
+ footer: footer === -1 ? null : footer - start,
251
+ zoneEnd,
252
+ numbered: found.numbered,
253
+ scrolled,
254
+ cursors,
255
+ cursorRow,
256
+ bodyStart: ruleAbove + 1,
257
+ ...(hidden === undefined ? {} : { hiddenAbove: hidden }),
258
+ text,
259
+ print: createHash('sha256').update(withoutAutoDeny(rows).join('\n')).digest('hex'),
260
+ };
261
+ }
@@ -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';
@@ -24,9 +25,10 @@ export function formFooter(region) {
24
25
  return region.slice(Math.max(0, region.length - FORM_FOOTER_LINES)).join('\n').toLowerCase();
25
26
  }
26
27
  /**
27
- * Sygnatura trybu edycji notatki — stopka rysuje `ctrl+g to edit in Nvim` WYŁĄCZNIE po wejściu
28
- * w pole (`n`). Marker celowo krótki: wąski panel zawija stopkę w środku frazy (zmierzone —
29
- * „ctrl+g to\nedit in Nvim"), a `ctrl+g` poza tym trybem nie występuje na ekranie w ogóle.
28
+ * Signature of notes editing: in the preview variant the footer shows `ctrl+g to edit in Nvim` after `n` enters the
29
+ * notes field. The marker is short on purpose: a narrow pane wraps the footer mid-phrase (measured: "ctrl+g to\nedit in
30
+ * Nvim"). A form without a preview shows the same phrase with the cursor on the free-text row or on Submit (Claude Code
31
+ * 2.1.332), so the marker alone does not prove notes editing there.
30
32
  */
31
33
  export const NOTES_EDITING_MARKER = SCREEN_SIGNATURES.notesEditing.pattern;
32
34
  /**
@@ -145,7 +147,7 @@ export function questionFrom(region, optionsAt) {
145
147
  header = tab;
146
148
  continue;
147
149
  }
148
- lines.push(line);
150
+ lines.push(gutterText(line));
149
151
  }
150
152
  return { header, question: lines.join('\n').trim() };
151
153
  }
@@ -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
  *