@rarog/server 1.1.1 → 1.1.2-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/node_modules/@rarog/shared/package.json +1 -1
  2. package/node_modules/@rarog/shared/src/decode.js +3 -0
  3. package/node_modules/@rarog/shared/src/notify-copy.js +1 -0
  4. package/node_modules/@rarog/shared/src/protocol/background.js +7 -0
  5. package/node_modules/@rarog/shared/src/sentences/dialogs.js +10 -0
  6. package/node_modules/@rarog/shared/src/sentences/push.js +3 -0
  7. package/package.json +2 -2
  8. package/server/src/bootstrap/pr-status.js +15 -7
  9. package/server/src/bootstrap/push.js +36 -5
  10. package/server/src/cli/doctor-pr-status.js +10 -6
  11. package/server/src/demo/control.js +4 -2
  12. package/server/src/demo/mock-herdr.js +2 -2
  13. package/server/src/demo/scenarios.js +31 -17
  14. package/server/src/demo/seeds.js +62 -38
  15. package/server/src/drivers/herdr/pull-request-poll.js +5 -5
  16. package/server/src/drivers/herdr/queue-take-back.js +4 -0
  17. package/server/src/drivers/herdr/start-dialog-gate.js +132 -0
  18. package/server/src/drivers/herdr-driver.js +75 -15
  19. package/server/src/herdr/background/cli-shapes.js +16 -15
  20. package/server/src/herdr/background/index.js +7 -7
  21. package/server/src/herdr/background/merge.js +17 -5
  22. package/server/src/herdr/background/notification.js +0 -4
  23. package/server/src/herdr/background/pull-request-files.js +53 -161
  24. package/server/src/herdr/background/pull-requests.js +54 -632
  25. package/server/src/herdr/background/work.js +84 -0
  26. package/server/src/herdr/dialogs/copy.js +7 -0
  27. package/server/src/herdr/dialogs/index.js +4 -1
  28. package/server/src/herdr/dialogs/screen/form.js +2 -1
  29. package/server/src/herdr/dialogs/screen/option-run.js +25 -3
  30. package/server/src/herdr/dialogs/screen/parse.js +3 -3
  31. package/server/src/herdr/dialogs/screen/signatures.js +55 -0
  32. package/server/src/herdr/dialogs/screen/start-dialog.js +72 -0
  33. package/server/src/herdr/dialogs/screen/trust-arrow.js +46 -9
  34. package/server/src/herdr/jsonl-follow.js +6 -2
  35. package/server/src/herdr/label-code.js +104 -0
  36. package/server/src/herdr/label-migration.js +142 -0
  37. package/server/src/herdr/launcher.js +30 -5
  38. package/server/src/herdr/provenance.js +80 -40
  39. package/server/src/herdr/start-dialog-wait.js +96 -0
  40. package/server/src/herdr/supervisor.js +33 -10
  41. package/server/src/herdr/workspace-resolver.js +5 -4
  42. package/server/src/index.js +8 -3
  43. package/server/src/notify/apns-payload.js +5 -3
  44. package/server/src/notify/content.js +37 -0
  45. package/server/src/notify/index.js +4 -0
  46. package/server/src/notify/live-activity-state.js +9 -5
  47. package/server/src/notify/live-activity.js +5 -2
  48. package/server/src/notify/policy.js +4 -2
  49. package/server/src/notify/stalled-wait.js +213 -0
  50. package/server/src/pr-status/facts.js +87 -0
  51. package/server/src/pr-status/gh.js +76 -9
  52. package/server/src/pr-status/index.js +1 -10
  53. package/server/src/pr-status/source.js +20 -6
  54. package/server/src/pr-status/tracker.js +32 -9
  55. package/server/src/sessions/conversation-lists.js +8 -2
  56. package/server/src/sessions/driver-events.js +7 -3
  57. package/server/src/sessions/interrupt-windows.js +28 -4
  58. package/server/src/sessions/manager.js +14 -5
  59. package/server/src/sessions/pr-status-link.js +64 -16
  60. package/server/src/sessions/session.js +10 -3
  61. package/server/src/sessions/state-machine.js +11 -0
  62. package/server/src/sessions/test-session.js +50 -0
  63. package/server/src/term/herdr-backend.js +15 -12
  64. package/server/src/term/lifecycle.js +4 -6
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Pane labels in the old provenance format, the only code that knows it:
3
+ * `<description> · rarog-term <16 hex terminal id>` and
4
+ * `<description> · rarog-claude <16 hex project key> <8 hex tab label trace>`, the description optional.
5
+ *
6
+ * Two parts. {@link legacyToCurrent} is a pure normalizer: `parsePaneLabel` reads every label
7
+ * through it, so a pane with an old label is Rarog's for every reader. {@link createLabelMigration}
8
+ * is the pass that rewrites old labels in herdr to the current format, called by the supervisor
9
+ * whenever herdr answers. It writes nothing but `pane.rename` on a pane whose old label a fresh read
10
+ * has just confirmed, so it never meets another writer on the same label: every other writer
11
+ * confirms a label in the current format or no label at all.
12
+ */
13
+ import { HerdrUnavailableError } from './socket.js';
14
+ import { HerdrReadOnlyError } from './types.js';
15
+ import { claudeLabelSuffix, descriptionOk, joinLabel, keyCodeOf, termLabelSuffix, } from './label-code.js';
16
+ const LEGACY_TERM_RE = /^(?:(.+) · )?rarog-term ([0-9a-f]{16})$/;
17
+ const LEGACY_CLAUDE_RE = /^(?:(.+) · )?rarog-claude ([0-9a-f]{16}) ([0-9a-f]{8})$/;
18
+ /**
19
+ * An old-format label → the same provenance in the current format, the description verbatim; any
20
+ * other label comes back unchanged. The terminal id and the trace stay whole, the project key
21
+ * becomes its code (the current format carries no more of it).
22
+ */
23
+ export function legacyToCurrent(label) {
24
+ const term = LEGACY_TERM_RE.exec(label);
25
+ if (term?.[2] !== undefined && descriptionOk(term[1])) {
26
+ return joinLabel(term[1] ?? '', termLabelSuffix(term[2]));
27
+ }
28
+ const claude = LEGACY_CLAUDE_RE.exec(label);
29
+ if (claude?.[2] !== undefined && claude[3] !== undefined && descriptionOk(claude[1])) {
30
+ return joinLabel(claude[1] ?? '', claudeLabelSuffix(keyCodeOf(claude[2]), claude[3]));
31
+ }
32
+ return label;
33
+ }
34
+ /** The label is in the old format: the migration pass is the one to rewrite it. */
35
+ export function isLegacyPaneLabel(label) {
36
+ return label !== null && legacyToCurrent(label) !== label;
37
+ }
38
+ const messageOf = (err) => (err instanceof Error ? err.message : String(err));
39
+ export function createLabelMigration(config) {
40
+ const { client, writable, log } = config;
41
+ let due = true;
42
+ let disposed = false;
43
+ let inFlight = null;
44
+ /** `pane|label` that herdr refused to rename (pane gone, a label the socket rejects): not retried. */
45
+ const refused = new Set();
46
+ const logged = new Set();
47
+ const logOnce = (tag, line) => {
48
+ if (logged.has(tag))
49
+ return;
50
+ logged.add(tag);
51
+ log(line);
52
+ };
53
+ const pass = async () => {
54
+ if (!writable()) {
55
+ logOnce('read-only', 'herdr: pane label migration on hold — write channel closed (RAROG_HERDR_SEND=0)');
56
+ return;
57
+ }
58
+ due = false;
59
+ let panes;
60
+ try {
61
+ panes = await client.listPanes();
62
+ }
63
+ catch (err) {
64
+ due = true;
65
+ log(`herdr: pane label migration could not read the panes (${messageOf(err)})`);
66
+ return;
67
+ }
68
+ const old = panes.filter((pane) => isLegacyPaneLabel(pane.label)
69
+ && !refused.has(`${pane.paneId}|${pane.label ?? ''}`));
70
+ if (old.length === 0)
71
+ return;
72
+ let rewritten = 0;
73
+ for (const pane of old) {
74
+ if (disposed)
75
+ return;
76
+ if (!writable()) {
77
+ due = true;
78
+ break;
79
+ }
80
+ const label = pane.label ?? '';
81
+ let current;
82
+ try {
83
+ current = (await client.listPanes()).find((candidate) => candidate.paneId === pane.paneId)?.label;
84
+ }
85
+ catch (err) {
86
+ due = true;
87
+ log(`herdr: pane ${pane.paneId} not confirmed before its label rewrite (${messageOf(err)})`);
88
+ break;
89
+ }
90
+ if (disposed)
91
+ return;
92
+ // Addresses are positional and a human may rename a pane: only the label read above is rewritten.
93
+ if (current !== label) {
94
+ // A pane gone from its address may live on under another one: the next pass reads the whole list again.
95
+ if (current === undefined || isLegacyPaneLabel(current))
96
+ due = true;
97
+ log(`herdr: pane ${pane.paneId} changed before its label rewrite — skipping`);
98
+ continue;
99
+ }
100
+ try {
101
+ await client.renamePane(pane.paneId, legacyToCurrent(label));
102
+ rewritten += 1;
103
+ }
104
+ catch (err) {
105
+ if (err instanceof HerdrReadOnlyError || err instanceof HerdrUnavailableError) {
106
+ // The write gate, or a timeout that does not say whether the rename landed: the next pass reads again.
107
+ due = true;
108
+ log(`herdr: label rewrite of pane ${pane.paneId} — not done or result unknown (${messageOf(err)})`);
109
+ break;
110
+ }
111
+ refused.add(`${pane.paneId}|${label}`);
112
+ log(`herdr: label rewrite of pane ${pane.paneId} failed (${messageOf(err)})`);
113
+ }
114
+ }
115
+ log(`herdr: pane label migration — ${String(rewritten)} of ${String(old.length)} old-format pane labels rewritten`);
116
+ };
117
+ return {
118
+ run() {
119
+ if (inFlight !== null)
120
+ return inFlight;
121
+ if (disposed || !due)
122
+ return Promise.resolve();
123
+ const current = pass()
124
+ .catch((err) => {
125
+ due = true;
126
+ log(`herdr: pane label migration threw an error — ${messageOf(err)}`);
127
+ })
128
+ .finally(() => {
129
+ if (inFlight === current)
130
+ inFlight = null;
131
+ });
132
+ inFlight = current;
133
+ return current;
134
+ },
135
+ requestPass() {
136
+ due = true;
137
+ },
138
+ dispose() {
139
+ disposed = true;
140
+ },
141
+ };
142
+ }
@@ -20,6 +20,7 @@
20
20
  * 6. `agent.start`, etykieta pochodzenia panelu (`pane.rename`) i sygnał „etykieta gotowa"
21
21
  * dla nadzorcy (`paneLabelled` — od niego rusza synchronizacja etykiety taba z kartą), tytuł
22
22
  * (`pane.report_metadata`), poll `agent.get` — w TLE, rozstrzygają `ready`.
23
+ * A start dialog herdr reads as ready ends the poll as `blocked` (`start-dialog-wait.ts`).
23
24
  *
24
25
  * Launcher nie emituje żadnych zdarzeń cyklu życia i nie zna managera.
25
26
  */
@@ -29,8 +30,9 @@ import { foreign, say } from '@rarog/shared/sentences';
29
30
  import { DEFAULT_CLAUDE_ENV_CLEAR, HERDR_LAUNCH_POLL_MS, HERDR_LAUNCH_READY_TIMEOUT_MS, HERDR_LAUNCH_SHELL_WAIT_MS, PANE_SHELL_ENV, } from '../config.js';
30
31
  import { assertAllowedArgs, buildClaudeArgs } from './argv.js';
31
32
  import { decideProjectWorkspace, sharedProjectPlacement } from './project-workspace.js';
32
- import { claudePaneLabel, labelTrace, newRarogAgentName, projectKey, realProjectPath, sanitizePaneTitle, } from './provenance.js';
33
+ import { claudePaneLabelFrom, newClaudeProvenance, newRarogAgentName, realProjectPath, sanitizePaneTitle, } from './provenance.js';
33
34
  import { snippet } from './dialogs/screen/snippet.js';
35
+ import { createStartDialogWatch, startDialogSample, watchStartDialogSession } from './start-dialog-wait.js';
34
36
  // `HerdrUntrustedCwdError` NIE jest tu importowany: brak zaufania katalogu jest
35
37
  // ostrzeżeniem (`trustPrompt`), a nie odmową startu. Klasa zostaje w `types.ts` razem
36
38
  // z tłumaczeniem na kod `herdr-untrusted` w routerze — patrz jej docstring.
@@ -305,6 +307,7 @@ export function createHerdrLauncher(deps) {
305
307
  */
306
308
  const waitReady = async (paneId, sessionId, start) => {
307
309
  const deadline = now() + readyTimeoutMs;
310
+ const startDialogs = createStartDialogWatch();
308
311
  /** Rozjazd `--session-id` znaczy, że ścieżka jsonl byłaby zgadywaniem — to porażka startu. */
309
312
  const assertSameSession = async (probe) => {
310
313
  if (probe.agentSessionId === sessionId)
@@ -374,7 +377,20 @@ export function createHerdrLauncher(deps) {
374
377
  // `agent_session` przy dialogu bywa jeszcze puste — sprawdzamy tylko ROZJAZD.
375
378
  if (probe.agentSessionId !== '')
376
379
  await assertSameSession(probe);
377
- return { status: 'blocked', interactiveReady: false };
380
+ // Without the session id herdr may never push the answer (trust, then a start dialog herdr reads as ready).
381
+ const pending = probe.agentSessionId === '' ? { sessionPending: true } : {};
382
+ return { status: 'blocked', interactiveReady: false, ...pending };
383
+ }
384
+ // A start dialog herdr reads as ready: the same `blocked` as above, so the card and the waiting start prompt
385
+ // take the trust dialog's path. A failed read proves nothing and leaves the poll as it was.
386
+ if (deps.readScreen !== undefined && startDialogSample(probe)) {
387
+ const screen = await deps.readScreen(paneId).catch(() => null);
388
+ const startDialog = startDialogs.observe(screen, now());
389
+ if (startDialog !== null) {
390
+ log(`herdr launcher: pane ${paneId} stands on a start dialog herdr reads as ready `
391
+ + `(${startDialog.id ?? 'unknown'}).`);
392
+ return { status: 'blocked', interactiveReady: false, startDialog, sessionPending: true };
393
+ }
378
394
  }
379
395
  if (now() >= deadline) {
380
396
  // Panel ZOSTAJE (patrz `finish`), więc karta musi mówić, że jest na czym pracować —
@@ -514,10 +530,10 @@ export function createHerdrLauncher(deps) {
514
530
  /*
515
531
  * Krok 6: pochodzenie i tytuł panelu — oba BEST EFFORT, żaden nie przerywa startu.
516
532
  *
517
- * The pane label leads with the tab label set above (`<title> · rarog-claude …`), so
533
+ * The pane label leads with the tab label set above (`<title> · rc:…`), so
518
534
  * herdr's Go-to window names the pane like its tab.
519
535
  *
520
- * Etykieta PANELU `rarog-claude <klucz projektu> <ślad etykiety taba>` jest jedyną rzeczą
536
+ * Etykieta PANELU `rc:<kod klucza projektu><kod śladu etykiety taba>` jest jedyną rzeczą
521
537
  * Raroga, którą herdr trzyma w snapshotcie (przeżywa jego restart) — dowód „ten panel
522
538
  * założył Rarog dla tego projektu". Idzie PO `agent.start`, na panelu, który launcher
523
539
  * sam przed chwilą stworzył; herdr zostawia ją przy wykryciu agenta, przy jego wyjściu
@@ -525,7 +541,8 @@ export function createHerdrLauncher(deps) {
525
541
  * nazwa agenta `rarog-<6 hex>` i klucz zarezerwowany w nadzorcy (`registerLaunch`).
526
542
  */
527
543
  try {
528
- await client.renamePane(paneId, claudePaneLabel(projectKey(realCwd), labelTrace(title), title));
544
+ const label = claudePaneLabelFrom(newClaudeProvenance(realCwd, title), title, 'keep');
545
+ await client.renamePane(paneId, label);
529
546
  }
530
547
  catch (err) {
531
548
  log(`herdr launcher: failed to set the provenance label on pane ${paneId} `
@@ -544,10 +561,18 @@ export function createHerdrLauncher(deps) {
544
561
  // Kroki 7–8. Timeout NIE sprząta: panel może stać na dialogu i za chwilę ruszyć,
545
562
  // a zabicie go byłoby gorsze niż wisząca karta.
546
563
  const settled = await waitReady(paneId, sessionId, startKind);
564
+ const { sessionAppeared, launchHeld } = deps;
565
+ if (settled.sessionPending === true && sessionAppeared !== undefined) {
566
+ void watchStartDialogSession({
567
+ key, paneId, probe: probeAgent, held: (k) => launchHeld?.(k) ?? true,
568
+ appeared: sessionAppeared, sleep, now, log,
569
+ });
570
+ }
547
571
  return {
548
572
  key, paneId, tabId, agentSessionId: sessionId, createdWorkspace, argv,
549
573
  status: settled.status,
550
574
  interactiveReady: settled.interactiveReady,
575
+ ...(settled.startDialog === undefined ? {} : { startDialog: settled.startDialog }),
551
576
  };
552
577
  };
553
578
  // Kroki 6–8 dopiero po oddaniu uchwytu (patrz `defer`): manager ma zdążyć odpowiedzieć
@@ -16,13 +16,15 @@
16
16
  * wykryciu agenta, przy jego wyjściu, przy ręcznym uruchomieniu kolejnego i przy zmianie
17
17
  * silnika; znika wyłącznie po jawnym `pane.rename` z `null`.
18
18
  *
19
- * The provenance suffix is CLOSED (anchored at the end, lowercase hex, single spaces): a human in
20
- * herdr can label a pane too, and anything outside the patterns means "a foreign pane". In front
21
- * of the suffix the label carries a description, ` · ` apart: the pane's tab label, cut to 40
22
- * code points ({@link paneLabelDescription}), so herdr's Go-to window and the pane frame name the
23
- * pane like its tab. The suffix carries hashes, never a path; the description repeats what the
24
- * tab label already shows (the card title, a name given by hand, the directory name of a
25
- * terminal tab), so the label reveals nothing the herdr snapshot did not hold before.
19
+ * The provenance suffix is CLOSED (anchored at the end, `rt:` or `rc:` and a fixed number of
20
+ * base32 characters, `herdr/label-code.ts`): a human in herdr can label a pane too, and anything
21
+ * outside the patterns means "a foreign pane". In front of the suffix the label carries a
22
+ * description, ` · ` apart: the pane's tab label, cut to 40 code points
23
+ * ({@link paneLabelDescription}), so herdr's Go-to window and the pane frame name the pane like
24
+ * its tab. The suffix carries hashes, never a path; the description repeats what the tab label
25
+ * already shows (the card title, a name given by hand, the directory name of a terminal tab), so
26
+ * the label reveals nothing the herdr snapshot did not hold before. Every label is read through
27
+ * `legacyToCurrent` (`herdr/label-migration.ts`), so a label in the old format reads the same.
26
28
  *
27
29
  * Tu mieszka też etykieta TABA: czyszczenie wspólne dla Claude i terminala
28
30
  * ({@link sanitizeTabLabel} — to samo co karta, bez znaków sterujących) i format taba terminala
@@ -34,7 +36,9 @@ import path from 'node:path';
34
36
  import { TERM_ID_RE } from '@rarog/shared';
35
37
  import { DIRECT_DISK } from '../folder-gate/disk.js';
36
38
  import { normalizeSessionLabel } from '../session-label.js';
37
- /** Przedrostek nazw Raroga w herdr: nazwa agenta, etykiety paneli i etykieta taba terminala. */
39
+ import { claudeLabelSuffix, joinLabel, keyCodeOf, readLabelSuffix, termLabelSuffix, } from './label-code.js';
40
+ import { legacyToCurrent } from './label-migration.js';
41
+ /** Prefix of Rarog names in herdr: the agent name and the terminal tab label. */
38
42
  export const HERDR_NAME_PREFIX = 'rarog';
39
43
  /** Nazwa agenta zakładanego przez Raroga. JEDNO źródło dla generatora i dla czytelnika. */
40
44
  export const RAROG_AGENT_NAME_RE = new RegExp(`^${HERDR_NAME_PREFIX}-[0-9a-f]{6}$`);
@@ -44,18 +48,14 @@ export function newRarogAgentName() {
44
48
  }
45
49
  const PROJECT_KEY_RE = /^[0-9a-f]{16}$/;
46
50
  const LABEL_TRACE_RE = /^[0-9a-f]{8}$/;
47
- /*
48
- * Readers accept an optional leading description: `<description> · rarog-term <id>` and
49
- * `<description> · rarog-claude <key> <trace>`. The provenance suffix stays exact and anchored
50
- * at the end. The description is captured and checked in code (at least one non-whitespace
51
- * character), so a label made of a separator alone stays foreign; one greedy group keeps the
52
- * match linear on long labels.
53
- */
54
- const TERM_LABEL_RE = new RegExp(`^(?:(.+) · )?${HERDR_NAME_PREFIX}-term ([0-9a-f]{16})$`);
55
- const CLAUDE_LABEL_RE = new RegExp(`^(?:(.+) · )?${HERDR_NAME_PREFIX}-claude ([0-9a-f]{16}) ([0-9a-f]{8})$`);
56
- /** A captured description is valid when absent (bare format) or not blank. */
57
- function descriptionOk(description) {
58
- return description === undefined || /\S/u.test(description);
51
+ function opaque(raw) {
52
+ return raw;
53
+ }
54
+ function rawOf(provenance) {
55
+ return provenance;
56
+ }
57
+ function claudeRawOf(provenance) {
58
+ return provenance;
59
59
  }
60
60
  function sha256Hex(text) {
61
61
  return createHash('sha256').update(text, 'utf8').digest('hex');
@@ -161,44 +161,84 @@ export function paneLabelDescription(tabLabel) {
161
161
  return Array.from(normalizeSessionLabel(tabLabel))
162
162
  .slice(0, PANE_LABEL_DESCRIPTION_MAX).join('').trim();
163
163
  }
164
- /** `<description> · <origin>`, or the bare origin when the description is empty. */
165
- function describedLabel(origin, tabLabel) {
166
- const description = paneLabelDescription(tabLabel);
167
- return description === '' ? origin : `${description} · ${origin}`;
164
+ /** `<description> · <suffix>`, or the bare suffix when the description is empty. */
165
+ function describedLabel(suffix, tabLabel) {
166
+ return joinLabel(paneLabelDescription(tabLabel), suffix);
167
+ }
168
+ /** Claude pane label from the project key CODE, so a rewrite keeps the key read from the label. */
169
+ function claudeLabelFromCode(keyCode, trace, tabLabel) {
170
+ if (!LABEL_TRACE_RE.test(trace))
171
+ throw new Error('Ślad etykiety taba spoza wzorca 8 hex.');
172
+ return describedLabel(claudeLabelSuffix(keyCode, trace), tabLabel);
168
173
  }
169
174
  /**
170
- * Claude pane label: `<description> · rarog-claude <project key> <tab label trace>`.
171
- * `tabLabel` is the pane's current tab label; omitted or blank = the bare format.
175
+ * Claude pane label: `<description> · rc:<project key code><tab label trace code>` for a 16-hex
176
+ * project key and an 8-hex trace. `tabLabel` is the pane's current tab label; omitted or blank =
177
+ * the bare format.
172
178
  */
173
179
  export function claudePaneLabel(key, trace, tabLabel = '') {
174
180
  if (!PROJECT_KEY_RE.test(key))
175
181
  throw new Error('Klucz projektu spoza wzorca 16 hex.');
176
- if (!LABEL_TRACE_RE.test(trace))
177
- throw new Error('Ślad etykiety taba spoza wzorca 8 hex.');
178
- return describedLabel(`rarog-claude ${key} ${trace}`, tabLabel);
182
+ return claudeLabelFromCode(keyCodeOf(key), trace, tabLabel);
179
183
  }
180
184
  /**
181
- * Terminal pane label: `<description> · rarog-term <terminal id>` (id shaped like `TERM_ID_RE`).
185
+ * Terminal pane label: `<description> · rt:<terminal id code>` (id shaped like `TERM_ID_RE`).
182
186
  * `tabLabel` is the terminal tab label (`terminalTabLabel`); omitted or blank = the bare format.
183
187
  */
184
188
  export function termPaneLabel(id, tabLabel = '') {
185
189
  if (!TERM_ID_RE.test(id))
186
190
  throw new Error('Identyfikator terminala spoza wzorca 16 hex.');
187
- return describedLabel(`rarog-term ${id}`, tabLabel);
191
+ return describedLabel(termLabelSuffix(id), tabLabel);
188
192
  }
189
193
  /**
190
194
  * Pane label from `pane.list` → provenance, or `null` for any label outside the patterns.
191
- * Reads both the bare format and the one with a leading description.
195
+ * Reads both the bare format and the one with a leading description, and an old-format label
196
+ * through `legacyToCurrent`.
192
197
  */
193
198
  export function parsePaneLabel(label) {
194
199
  if (typeof label !== 'string')
195
200
  return null;
196
- const term = TERM_LABEL_RE.exec(label);
197
- if (term?.[2] !== undefined && descriptionOk(term[1]))
198
- return { kind: 'term', value: term[2] };
199
- const claude = CLAUDE_LABEL_RE.exec(label);
200
- if (claude?.[2] !== undefined && claude[3] !== undefined && descriptionOk(claude[1])) {
201
- return { kind: 'claude', value: claude[2], trace: claude[3] };
202
- }
203
- return null;
201
+ const suffix = readLabelSuffix(legacyToCurrent(label));
202
+ return suffix === null ? null : opaque(suffix);
203
+ }
204
+ /** Full terminal id (`TERM_ID_RE` shape) of a terminal provenance; `null` for Claude or none. */
205
+ export function provenanceTermId(provenance) {
206
+ if (provenance === null)
207
+ return null;
208
+ const raw = rawOf(provenance);
209
+ return raw.kind === 'term' ? raw.id : null;
210
+ }
211
+ /** Full terminal id from a pane label, or `null` (no label, a foreign one, a Claude pane). */
212
+ export function paneLabelTermId(label) {
213
+ return provenanceTermId(parsePaneLabel(label));
214
+ }
215
+ /**
216
+ * A Claude provenance whose project key code is the code of the key of `dir`, compared in the
217
+ * spelling given (the caller tries each candidate spelling); always `false` for a terminal
218
+ * provenance. 35 bits against the candidates of one path (about 60): a false match is about 2e-9.
219
+ */
220
+ export function claudeKeyMatches(provenance, dir) {
221
+ const raw = rawOf(provenance);
222
+ return raw.kind === 'claude' && raw.keyCode === keyCodeOf(projectKey(dir));
223
+ }
224
+ /** The trace in a Claude provenance is the trace of `tabLabel` ("Rarog set this tab label"). */
225
+ export function claudeTraceMatches(provenance, tabLabel) {
226
+ return claudeRawOf(provenance).trace === labelTrace(tabLabel);
227
+ }
228
+ /**
229
+ * Provenance for a Claude pane that has none yet: the key of `realCwd` (after
230
+ * {@link realProjectPath}) and the trace of the tab label Rarog has just set.
231
+ */
232
+ export function newClaudeProvenance(realCwd, tabLabel) {
233
+ const raw = { kind: 'claude', keyCode: keyCodeOf(projectKey(realCwd)), trace: labelTrace(tabLabel) };
234
+ return raw;
235
+ }
236
+ /**
237
+ * Claude pane label rebuilt from a provenance: the description from `tabLabel`, the project key
238
+ * from the provenance as it was read (never hashed again from a path), and the trace either kept
239
+ * (`'keep'`) or taken from `tabLabel` (`'fresh'`, the tab label is Rarog's own).
240
+ */
241
+ export function claudePaneLabelFrom(provenance, tabLabel, trace) {
242
+ const raw = claudeRawOf(provenance);
243
+ return claudeLabelFromCode(raw.keyCode, trace === 'keep' ? raw.trace : labelTrace(tabLabel), tabLabel);
204
244
  }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Start dialog wait of the launcher: a Claude Code start dialog herdr reads as ready (`idle`, `interactive_ready`,
3
+ * no session id), for example the dialog about external imports of the project's memory files, ends the readiness
4
+ * wait as `blocked`, like the trust dialog herdr reports itself. After any `blocked` start without a session id (also
5
+ * the trust dialog, which a start dialog herdr reads as ready can follow), a bounded poll notices the session id the
6
+ * answer brings: herdr pushes no status change for it.
7
+ *
8
+ * Two legs end the wait: the signature of a measured dialog on one read, or the same screen without the prompt field
9
+ * for {@link START_DIALOG_STABLE_MS}. The screen rule is `dialogs/screen/start-dialog.ts`; this module only keeps the
10
+ * time and the poll, sends no key and knows neither the supervisor nor the manager (they come in as functions).
11
+ */
12
+ import { startDialogOf } from './dialogs/index.js';
13
+ import { HerdrGoneError } from './types.js';
14
+ /**
15
+ * How long one screen without the prompt field and without a known signature must stand unchanged before it counts
16
+ * as an unknown start dialog. A wrong hit costs one card for a few seconds, because the session id lifts it; a long
17
+ * wait leaves the phone without a word. A screen that changes (a render in progress) restarts the count.
18
+ */
19
+ export const START_DIALOG_STABLE_MS = 8_000;
20
+ /**
21
+ * Poll period of `agent.get` after a start dialog. The pane is `idle` before and after the answer (herdr 0.9.5), so
22
+ * no status change has to be pushed; without this poll the full resync would be the first to notice the session id.
23
+ */
24
+ export const START_DIALOG_SESSION_POLL_MS = 1_000;
25
+ /**
26
+ * Bound of that poll: it limits the `agent.get` calls on a pane nobody answers. An answer after it is still found by
27
+ * the full resync, only later.
28
+ */
29
+ export const START_DIALOG_SESSION_WATCH_MS = 10 * 60_000;
30
+ /**
31
+ * Whether a readiness sample is worth a screen read: herdr says ready, or has no readiness flag because the launch
32
+ * record is gone (`interactive_ready` absent without `launch_pending`), and knows no session id. A sample under
33
+ * `launch_pending` is not read: a cold start keeps the shell line on the screen for seconds, and that is no dialog.
34
+ */
35
+ export function startDialogSample(sample) {
36
+ if (sample.agentSessionId !== '')
37
+ return false;
38
+ if (sample.interactiveReady === true)
39
+ return true;
40
+ return sample.interactiveReady === null && sample.launchPending !== true;
41
+ }
42
+ export function createStartDialogWatch(stableMs = START_DIALOG_STABLE_MS) {
43
+ let first = null;
44
+ return {
45
+ observe(screen, at) {
46
+ if (screen === null)
47
+ return null;
48
+ const dialog = startDialogOf(screen);
49
+ if (dialog === null) {
50
+ first = null;
51
+ return null;
52
+ }
53
+ if (dialog.id !== null)
54
+ return dialog;
55
+ if (first?.screen !== screen) {
56
+ first = { screen, at };
57
+ return null;
58
+ }
59
+ return at - first.at >= stableMs ? dialog : null;
60
+ },
61
+ };
62
+ }
63
+ /**
64
+ * Polls `agent.get` until the session id appears, then asks the supervisor to refresh the pane once. Stops without a
65
+ * refresh when the agent is gone, when the supervisor no longer holds the launch, or after
66
+ * {@link START_DIALOG_SESSION_WATCH_MS}. Another read error keeps the poll. Never rejects.
67
+ */
68
+ export async function watchStartDialogSession(watch) {
69
+ const deadline = watch.now() + START_DIALOG_SESSION_WATCH_MS;
70
+ try {
71
+ while (watch.now() < deadline) {
72
+ await watch.sleep(START_DIALOG_SESSION_POLL_MS);
73
+ if (!watch.held(watch.key))
74
+ return;
75
+ let sessionId;
76
+ try {
77
+ ({ agentSessionId: sessionId } = await watch.probe(watch.paneId));
78
+ }
79
+ catch (err) {
80
+ if (err instanceof HerdrGoneError)
81
+ return;
82
+ continue;
83
+ }
84
+ if (sessionId !== '') {
85
+ watch.log(`herdr launcher: pane ${watch.paneId} reports its session after the start dialog; refreshing.`);
86
+ watch.appeared(watch.paneId);
87
+ return;
88
+ }
89
+ }
90
+ watch.log(`herdr launcher: no session on pane ${watch.paneId} within `
91
+ + `${Math.round(START_DIALOG_SESSION_WATCH_MS / 60_000)} min of its start dialog; the resync takes over.`);
92
+ }
93
+ catch (err) {
94
+ watch.log(`herdr launcher: the session watch of pane ${watch.paneId} failed: ${err.message}`);
95
+ }
96
+ }