@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
@@ -5,7 +5,9 @@
5
5
  * reads no file and keeps no state; the tracker in `inbox.ts` keeps the shown turn between reads.
6
6
  */
7
7
  import { createHash } from 'node:crypto';
8
+ import { inboxCardMergeSchema } from '@rarog/shared';
8
9
  import { DECISION_STATES, WORKING_STATES } from '../sessions/state-sentences.js';
10
+ import { isStateOnlyEngine } from '../herdr/engines.js';
9
11
  const FAILED_STATES = ['error', 'limit-reached', 'interrupted'];
10
12
  /** Card kind of a session state; `null` for a closed session (`done`, `resumable`). */
11
13
  export function cardKindOf(state) {
@@ -43,7 +45,7 @@ export function shownTurnFor(kind, segments) {
43
45
  }
44
46
  /** Whether a session can have a card at all: an open Claude session in scope. */
45
47
  function carded(session) {
46
- if (session.engine === 'codex' || session.outOfScope === true)
48
+ if (isStateOnlyEngine(session.engine) || session.outOfScope === true)
47
49
  return null;
48
50
  return cardKindOf(session.state);
49
51
  }
@@ -51,36 +53,57 @@ function carded(session) {
51
53
  * The card of a session over the turn it shows, or `null` when it has none.
52
54
  *
53
55
  * @param requestOf the card id behind the summary's `waitingFor`; none = the dialog is known by its summary only
56
+ * @param checked the commit the coordinator's checks passed on, from the session's thread file; none = not a thread
57
+ * or not checked
54
58
  */
55
- export function composeCard(session, shown, requestOf = () => undefined) {
59
+ export function composeCard(session, shown, requestOf = () => undefined, checked) {
56
60
  const kind = carded(session);
57
61
  if (kind === null || shown === undefined)
58
62
  return null;
59
63
  const at = kind === 'result' ? shown.at : session.stateSince;
60
64
  const decided = kind === 'decision' ? dialogOf(session, requestOf) : undefined;
61
65
  const dialog = decided?.dialog;
62
- const key = keyOf(shown.turnId, kind, dialog, at);
66
+ const merge = kind === 'result' ? mergeOf(session, checked) : undefined;
67
+ const key = keyOf(shown.turnId, kind, dialog, at, merge);
63
68
  // The revision changes the version only: a removal of the card holds while its buttons change.
64
69
  const revision = decided?.revision === undefined ? [] : [decided.revision];
70
+ // Only a card with a Merge adds its commit, so every other card keeps the version it had.
71
+ const commit = key.checked === undefined ? [] : [key.checked];
65
72
  return {
66
73
  sessionId: session.id,
67
74
  turnId: shown.turnId,
68
- version: digest([shown.version, kind, key.dialog ?? '', key.dialogId ?? '', key.since ?? '', ...revision]),
75
+ version: digest([
76
+ shown.version, kind, key.dialog ?? '', key.dialogId ?? '', key.since ?? '', ...revision, ...commit,
77
+ ]),
69
78
  kind,
70
79
  state: session.state,
71
80
  at,
72
81
  text: shown.text,
73
82
  truncated: shown.truncated,
74
83
  ...(dialog === undefined ? {} : { dialog }),
84
+ ...(merge === undefined ? {} : { merge }),
75
85
  };
76
86
  }
87
+ /**
88
+ * The Merge of a result card: the session is a thread that is `ready` (the state rule of the coordination modules,
89
+ * which this function does not repeat), its coordinator is live and `checked` is a full SHA. Anything less gives a
90
+ * card without Merge, never one the stream would reject.
91
+ */
92
+ function mergeOf(session, checked) {
93
+ const role = session.coordination;
94
+ if (role?.role !== 'thread' || role.merge?.state !== 'ready' || role.coordinatorId === undefined)
95
+ return undefined;
96
+ const merge = inboxCardMergeSchema.safeParse({ name: role.name, coordinatorId: role.coordinatorId, checked });
97
+ return merge.success ? merge.data : undefined;
98
+ }
77
99
  /** The removal key of a card. */
78
100
  export function removalKeyOf(card) {
79
- return keyOf(card.turnId, card.kind, card.dialog, card.at);
101
+ return keyOf(card.turnId, card.kind, card.dialog, card.at, card.merge);
80
102
  }
81
- function keyOf(turnId, kind, dialog, at) {
82
- if (kind === 'result')
83
- return { turnId, card: kind };
103
+ function keyOf(turnId, kind, dialog, at, merge) {
104
+ if (kind === 'result') {
105
+ return merge === undefined ? { turnId, card: kind } : { turnId, card: kind, checked: merge.checked };
106
+ }
84
107
  if (kind === 'failed')
85
108
  return { turnId, card: kind, since: at };
86
109
  if (dialog === undefined)
@@ -3,6 +3,7 @@ export function headOf(card) {
3
3
  return {
4
4
  sessionId: card.sessionId, turnId: card.turnId, version: card.version, kind: card.kind, state: card.state,
5
5
  at: card.at, ...(card.dialog === undefined ? {} : { dialog: card.dialog.kind }),
6
+ ...(card.merge === undefined ? {} : { merge: card.merge }),
6
7
  };
7
8
  }
8
9
  /** Newest first, as the Inbox shows the cards; the session id keeps the order stable for equal times. */
@@ -13,12 +13,16 @@ const CLOSED_STATES = ['done', 'resumable'];
13
13
  function sameMark(a, b) {
14
14
  return a.state === b.state && a.stateSince === b.stateSince && a.transitions === b.transitions;
15
15
  }
16
- /** What a session summary says that its card depends on, besides the conversation file. */
17
- function lookOf(session) {
16
+ /**
17
+ * What a session summary says that its card depends on, besides the conversation file: also the role in its
18
+ * project's coordination and the checked commit of a thread, which change while the session state stays.
19
+ */
20
+ function lookOf(session, checked) {
18
21
  return JSON.stringify([
19
22
  session.state, session.stateSince, session.herdrDialog ?? null, session.herdrDialogReason ?? null,
20
23
  session.waitingFor ?? null,
21
24
  session.engine ?? null, session.outOfScope ?? false,
25
+ session.coordination ?? null, checked ?? null,
22
26
  ]);
23
27
  }
24
28
  export class Inbox {
@@ -27,6 +31,7 @@ export class Inbox {
27
31
  #log;
28
32
  #debounceMs;
29
33
  #timing;
34
+ #checkedOf;
30
35
  #store;
31
36
  #cards = new Map();
32
37
  #turns = new Map();
@@ -52,6 +57,7 @@ export class Inbox {
52
57
  this.#log = config.log;
53
58
  this.#debounceMs = config.debounceMs ?? INBOX_DEBOUNCE_MS;
54
59
  this.#timing = config.timing;
60
+ this.#checkedOf = config.checkedOf ?? (() => undefined);
55
61
  this.#store = new RemovalStore({
56
62
  dataDir: config.dataDir,
57
63
  isOpen: (sessionId) => {
@@ -258,7 +264,7 @@ export class Inbox {
258
264
  }
259
265
  #observe(session) {
260
266
  this.#states.set(session.id, session.state);
261
- const look = lookOf(session);
267
+ const look = lookOf(session, this.#checked(session.id));
262
268
  if (this.#looks.get(session.id) === look)
263
269
  return;
264
270
  this.#looks.set(session.id, look);
@@ -397,7 +403,7 @@ export class Inbox {
397
403
  }
398
404
  this.#turns.set(sessionId, turns);
399
405
  const requestOf = (dialog, waitingFor) => this.#dialogs.request(sessionId, dialog, waitingFor);
400
- const card = composeCard(session, working ? turns.ended : turns.shown, requestOf);
406
+ const card = composeCard(session, working ? turns.ended : turns.shown, requestOf, this.#checked(sessionId));
401
407
  if (card === null) {
402
408
  this.#cards.delete(sessionId);
403
409
  return false;
@@ -417,6 +423,17 @@ export class Inbox {
417
423
  return undefined;
418
424
  }
419
425
  }
426
+ /** {@link InboxConfig.checkedOf}; a failure of it gives a card without Merge, not a lost event or card read. */
427
+ #checked(sessionId) {
428
+ try {
429
+ return this.#checkedOf(sessionId);
430
+ }
431
+ catch (err) {
432
+ const reason = err instanceof Error ? err.message : String(err);
433
+ this.#log(`inbox: checked commit read failed for session ${sessionId} (${reason})`);
434
+ return undefined;
435
+ }
436
+ }
420
437
  /** The session has no card and no shown turn; its removals stay. */
421
438
  #forget(sessionId) {
422
439
  this.#cards.delete(sessionId);
@@ -22,9 +22,13 @@ const FILE_MAX_BYTES = 1024 * 1024;
22
22
  const FILE_MODE = 0o600;
23
23
  const CARD_KINDS = ['result', 'decision', 'failed'];
24
24
  const DIALOG_KINDS = ['permission', 'question', 'panel'];
25
+ /** The checked commit of a removed Merge card: a full lowercase SHA, as the card carries it. */
26
+ const CHECKED_PATTERN = /^[0-9a-f]{40}$/u;
25
27
  /** Map key of a removal key. */
26
28
  function slot(key) {
27
- return JSON.stringify([key.turnId, key.card, key.dialog ?? '', key.dialogId ?? '', key.since ?? '']);
29
+ return JSON.stringify([
30
+ key.turnId, key.card, key.dialog ?? '', key.dialogId ?? '', key.since ?? '', key.checked ?? '',
31
+ ]);
28
32
  }
29
33
  function entryOf(raw) {
30
34
  if (typeof raw !== 'object' || raw === null)
@@ -38,11 +42,16 @@ function entryOf(raw) {
38
42
  if (card === undefined)
39
43
  return null;
40
44
  const dialog = DIALOG_KINDS.find((kind) => kind === e['dialog']);
45
+ const checked = e['checked'];
46
+ // A checked commit that is not a full SHA matches no card; read without it, it would hide the plain result card.
47
+ if (checked !== undefined && (typeof checked !== 'string' || !CHECKED_PATTERN.test(checked)))
48
+ return null;
41
49
  return {
42
50
  sessionId: e['sessionId'], turnId: e['turnId'], card,
43
51
  ...(dialog === undefined ? {} : { dialog }),
44
52
  ...(typeof e['dialogId'] === 'string' && e['dialogId'] !== '' ? { dialogId: e['dialogId'] } : {}),
45
53
  ...(typeof e['since'] === 'string' ? { since: e['since'] } : {}),
54
+ ...(typeof checked === 'string' ? { checked } : {}),
46
55
  ...(e['seen'] === true ? { seen: true } : {}),
47
56
  };
48
57
  }
@@ -17,7 +17,7 @@ import { createAdminHandler, publicUrlOf, redact, startAdminSocket } from './aut
17
17
  import { clearReviewClientLogs } from './client-log.js';
18
18
  import { assembleCompanion } from './companion/index.js';
19
19
  import { ConfigError, HERDR_HISTORY_BYTES, assertLoopbackHost, loadConfig } from './config.js';
20
- import { DIALOG_LAYER2_ENV } from './config-env.js';
20
+ import { DIALOG_LAYER2_ENV, DIALOG_LIVE_ENV } from './config-env.js';
21
21
  import { skippedOriginLine } from './config/listen.js';
22
22
  import { irohAdminStatus } from './iroh/listener.js';
23
23
  import { gitReadEnv, probeGitSandboxAtStart } from './git-status.js';
@@ -33,10 +33,12 @@ import { healthProbes } from './bootstrap/health.js';
33
33
  import { prepareHookFiles } from './bootstrap/hook-files.js';
34
34
  import { loadDemoHerdr } from './bootstrap/herdr.js';
35
35
  import { buildRouter, configureHttpServer } from './bootstrap/http.js';
36
+ import { coordinationFollower, createCoordination, wireCoordination } from './bootstrap/coordination.js';
37
+ import { createCoordinatorStart, openCoordinators, pluginFact } from './bootstrap/coordinator-start.js';
36
38
  import { assembleInbox } from './bootstrap/inbox.js';
37
39
  import { startServerIroh } from './bootstrap/iroh.js';
38
40
  import { loadSdk, managerConfig } from './bootstrap/manager.js';
39
- import { createPush } from './bootstrap/push.js';
41
+ import { createPush, wireReadyToMerge } from './bootstrap/push.js';
40
42
  import { createPrStatus } from './bootstrap/pr-status.js';
41
43
  import { createSseHub } from './bootstrap/sse.js';
42
44
  import { loadTerm } from './bootstrap/term.js';
@@ -111,7 +113,7 @@ async function readTranscriptTail(file) {
111
113
  * modułu, wyjątek przy budowie nadzorcy, nieosiągalne gniazdo — wszystko kończy się tak samo,
112
114
  * czyli logiem, pustą listą i BANEREM w kliencie. Nigdy 500 i nigdy nieudany start.
113
115
  */
114
- async function loadHerdr(config, log, shadow, demoContent, consentMode, consentLink, cliVersionReader, versionWatch, consentProofGate, aliveSessions) {
116
+ async function loadHerdr(config, log, shadow, demoContent, consentMode, consentLink, cliVersionReader, versionWatch, consentProofGate, aliveSessions, follow) {
115
117
  // `main()` ładuje zestaw treści tylko w demo, więc to jest gałąź demo.
116
118
  if (demoContent !== null)
117
119
  return loadDemoHerdr(log, demoContent);
@@ -201,6 +203,8 @@ async function loadHerdr(config, log, shadow, demoContent, consentMode, consentL
201
203
  launchEnabled: config.herdrLaunch,
202
204
  // Bez tej flagi filtr wejściowy odrzuca panele Codexa.
203
205
  codexStatusEnabled: config.codexStatusEnabled,
206
+ // Without this flag the input filter drops agy panes.
207
+ agyStatusEnabled: config.agyStatusEnabled,
204
208
  // `0` = etykiety tabów zostają z zakładania, bez synchronizacji z kartą i bez migracji.
205
209
  tabLabels: config.herdrTabLabels,
206
210
  maxPanes: config.maxPanes,
@@ -274,6 +278,8 @@ async function loadHerdr(config, log, shadow, demoContent, consentMode, consentL
274
278
  // Dialog zaufania katalogu re-eksekuuje `claude`, a nadzorca musi wiedzieć, że
275
279
  // zniknięcie agenta w tym oknie znaczy „wstaje", a nie „zniknął".
276
280
  markTrustDialog: () => { ctx.markTrustDialog(); },
281
+ // A start dialog herdr reads as ready may stand until herdr knows the engine session.
282
+ startPhase: () => ctx.startPhase(),
277
283
  // Zrzuty hooka `PreToolUse` (warstwa 1 uniwersalnej karty): hook pisze, driver czyta
278
284
  // — oba przez ten sam `dataDir`. Bez zainstalowanego hooka plików po prostu nie ma
279
285
  // i karta powstaje z ekranu (warstwa 2).
@@ -327,8 +333,12 @@ async function loadHerdr(config, log, shadow, demoContent, consentMode, consentL
327
333
  readAgentFiles: config.agentFiles,
328
334
  // `RAROG_PROMPT_BLOCK=0` = follower pomija wpis promptu zablokowanego przez hook (`docs/dialogs.md`).
329
335
  promptBlock: config.promptBlock,
336
+ // The transcript follower that asks the coordination overlay about bubbles of other sessions.
337
+ ...(follow === undefined ? {} : { follow }),
330
338
  // `RAROG_DIALOG_LAYER2`: flaga czytana raz przy starcie, do decyzji dociera tym polem (`docs/dialogs.md`).
331
339
  dialogLayer2: config.dialogLayer2,
340
+ // `RAROG_DIALOG_LIVE`: read once at start, the driver's live dialog card level (`docs/dialogs.md`).
341
+ dialogLive: config.dialogLive,
332
342
  }),
333
343
  });
334
344
  // Restored messages of a pane that does not attach after the first resync (and a grace) are not sent.
@@ -361,7 +371,7 @@ async function loadHerdr(config, log, shadow, demoContent, consentMode, consentL
361
371
  void supervisor.hidden.rememberAlias(engineSessionId, sessionId);
362
372
  },
363
373
  assertSendable: herdr.assertSendable,
364
- commandCatalog: (cwd, cliVersion) => commandCatalogs.get(cwd, cliVersion),
374
+ commandCatalog: (cwd, cliVersion, pluginDirs) => commandCatalogs.get(cwd, cliVersion, pluginDirs),
365
375
  /*
366
376
  * Walidacja `resumeFrom` po TREŚCI transkryptu (`docs/security-model.md`, „`resumeFrom` is validated…”), nie po samym regeksie uuida.
367
377
  *
@@ -526,7 +536,15 @@ async function main() {
526
536
  });
527
537
  // The supervisor's agent set signal for `alive.json`; the writer joins it below (`bootstrap/alive-sessions.ts`).
528
538
  const aliveSessions = createAliveSessionsSignal();
529
- const herdr = await loadHerdr(config, log, shadowChannel, demoContent, consentMode, consentLink, cliVersionReader, versionWatch, consentProofGate, aliveSessions);
539
+ // Coordinators and their threads in the summaries (`bootstrap/coordination.ts`); `null` in the demo. Before the
540
+ // supervisor, because the transcript follower of every pane asks it. One registry for the overlay and the starts
541
+ // (`bootstrap/coordinator-start.ts`); the plugin fact reads the manager, created below.
542
+ const coordinators = openCoordinators(config, (line) => { log.info(line); });
543
+ const coordination = createCoordination(config, {
544
+ log: (line) => { log.info(line); },
545
+ options: { pluginOf: pluginFact(() => managerRef), ...(coordinators === null ? {} : { registry: coordinators }) },
546
+ });
547
+ const herdr = await loadHerdr(config, log, shadowChannel, demoContent, consentMode, consentLink, cliVersionReader, versionWatch, consentProofGate, aliveSessions, coordination === null ? undefined : coordinationFollower(coordination));
530
548
  if (config.demo) {
531
549
  log.info('herdr: demo mode, a supervisor mock instead of the socket (zero panes, zero processes)');
532
550
  }
@@ -562,6 +580,8 @@ async function main() {
562
580
  log.info(`shadow: hook consent channel ${config.consentChannel}`);
563
581
  if (!config.demo)
564
582
  log.info(`dialogs: layer 2 ${DIALOG_LAYER2_ENV}=${config.dialogLayer2 ? '1' : '0'}`);
583
+ if (!config.demo)
584
+ log.info(`dialogs: live card ${DIALOG_LIVE_ENV}=${String(config.dialogLive)}`);
565
585
  /*
566
586
  * Manager powstaje niżej, a cykl woła go od pierwszej karty (`onCard`), także w `recover` przed managerem: wtedy
567
587
  * referencja jest pusta i karta trafia do urządzeń przez snapshot sesji. Rejestracja przed managerem nie szturcha
@@ -588,7 +608,8 @@ async function main() {
588
608
  const macStats = config.demo ? (await import('./demo/mac.js')).demoMacStats() : createMacStats();
589
609
  // Powiadomienia: obecność, kanał APNs i harmonogram banerów (`bootstrap/push.ts`). Manager powstaje niżej,
590
610
  // więc push czyta go przez `managerRef`; sygnał nowej wersji dostaje sink kanału APNs.
591
- const { presence, apns, notifier } = createPush(config, { managerRef: () => managerRef, devices, macStats, log });
611
+ const push = createPush(config, { managerRef: () => managerRef, devices, macStats, log });
612
+ const { presence, apns, notifier, stalledWait } = push;
592
613
  setVersionSink(apns?.sink);
593
614
  // SDK Claude listy „Ostatnie sesje” raz, przed `listen()`; demo go nie dotyka (`bootstrap/manager.ts`).
594
615
  const sdk = await loadSdk(config, log);
@@ -606,8 +627,21 @@ async function main() {
606
627
  ...(consentCycle === null ? {} : { consent: consentManagerPort(consentCycle, consentMode, log) }),
607
628
  ...(consentCycle === null ? {} : { consentForgotten: consentForgottenPort(consentCycle, log) }),
608
629
  ...(prStatus === null ? {} : { prStatus: prStatus.port }),
630
+ ...(stalledWait === undefined ? {} : { stalledWait }),
631
+ ...(coordination === null ? {} : { coordination }),
632
+ ...(coordination === null || coordinators === null ? {} : {
633
+ coordinatorStart: createCoordinatorStart(config, {
634
+ registry: coordinators, coordination, log: (line) => { log.info(line); },
635
+ }),
636
+ }),
609
637
  });
610
638
  managerRef = manager;
639
+ // Roles and merge states follow the session events; the ready-to-merge push follows the thread summaries.
640
+ if (coordination !== null)
641
+ wireCoordination(coordination, manager);
642
+ if (coordination !== null && push.readyToMerge !== undefined) {
643
+ wireReadyToMerge(push.readyToMerge, manager, (id) => coordination.checkedOf(id));
644
+ }
611
645
  /*
612
646
  * Live Activity słucha strumienia GLOBALNEGO — tego samego, z którego lista klienta zna stan
613
647
  * każdej sesji. Każdy event to tylko „przelicz" (składane w 250 ms); czy coś wyjdzie do APNs,
@@ -624,6 +658,7 @@ async function main() {
624
658
  */
625
659
  const inboxParts = await assembleInbox({
626
660
  config, manager, ready: manager.ready, log: (line) => { log.info(line); },
661
+ ...(coordination === null ? {} : { checkedOf: (id) => coordination.checkedOf(id) }),
627
662
  });
628
663
  const inbox = inboxParts?.inbox ?? null;
629
664
  // Nadzorca podpięty, seedy demo założone — dopiero wtedy wpuszczamy ruch HTTP.
@@ -773,12 +808,14 @@ async function main() {
773
808
  demoControl?.dispose();
774
809
  hub.closeAll();
775
810
  prStatus?.tracker.close();
811
+ coordination?.close();
776
812
  // `server.close()` NIE dotyka gniazd po upgrade — bez tego proces wisiałby na żywym
777
813
  // WebSockecie terminala. Powłoki w panelach herdr zostają: giną wyłącznie kontrolery.
778
814
  term?.dispose();
779
815
  // Timery Live Activity i połączenia HTTP/2 do APNs — bez nich proces i tak wyjdzie (`unref`),
780
- // ale grzecznie. The channel closes in its own order (poller, the weekly-limit send in flight, passes, sender).
781
- const apnsClosed = apns?.close() ?? Promise.resolve();
816
+ // ale grzecznie. The stalled wait alarm stops its timers first; the channel closes in its own order (poller, the
817
+ // weekly-limit send in flight, passes, sender).
818
+ const apnsClosed = push.close();
782
819
  versionWatch?.dispose();
783
820
  macStats.close();
784
821
  clearInterval(deviceSweep);
@@ -1,5 +1,5 @@
1
1
  import { RELAY_ALERT_PLACEHOLDER } from '@rarog/shared/relay';
2
- import { isSessionless } from './content.js';
2
+ import { isSessionless, topicFor } from './content.js';
3
3
  import { PUSH_PLAINTEXT_MAX_BYTES } from './push-crypto.js';
4
4
  /** Sufit ładunku powiadomienia APNs (bajty UTF-8 całego JSON-a). */
5
5
  export const APNS_PAYLOAD_MAX_BYTES = 4096;
@@ -130,6 +130,7 @@ export function apnsAlertRequestE2e(content, options) {
130
130
  const exp = expirationOf(content, options.nowMs);
131
131
  const plaintext = fitTexts(content, PUSH_PLAINTEXT_MAX_BYTES, (texts) => plaintextJson(content, exp, texts));
132
132
  const envelope = options.sealer.seal(options.key, plaintext);
133
+ const sessionId = sessionIdOf(content);
133
134
  const aps = badgeOnly(content)
134
135
  ? badgeAps(content)
135
136
  : {
@@ -137,8 +138,9 @@ export function apnsAlertRequestE2e(content, options) {
137
138
  'mutable-content': 1,
138
139
  sound: 'default',
139
140
  ...badgeAps(content),
140
- // Klucz koalescencji (skrót id sesji), ta sama wartość co jawny `apns-collapse-id` — nie surowe id.
141
- ...(sessionIdOf(content) === undefined ? {} : { 'thread-id': content.topic }),
141
+ // Hash of the session id, never the raw id: one group per session in the Notification Center. Equal to
142
+ // `apns-collapse-id` for every session kind except the stalled wait alarm, which has its own collapse key.
143
+ ...(sessionId === undefined ? {} : { 'thread-id': topicFor(sessionId) }),
142
144
  };
143
145
  const body = JSON.stringify({ aps, [APNS_RAROG_BLOCK]: { v: APNS_RAROG_BLOCK_VERSION, ...envelope } });
144
146
  if (bytes(body) > APNS_PAYLOAD_MAX_BYTES)
@@ -19,6 +19,7 @@ import { createHash } from 'node:crypto';
19
19
  import { NOTIFY_KIND_TITLE } from '@rarog/shared/notify-copy';
20
20
  import { isForeignText, isServerSentence, say } from '@rarog/shared/sentences';
21
21
  import { serverSystem } from '../version.js';
22
+ import { READY_TO_MERGE_CLASS } from './policy.js';
22
23
  /** Ile znaków treści mieści się na banerze, zanim iOS i tak ją utnie w środku słowa. */
23
24
  export const MESSAGE_MAX_CHARS = 120;
24
25
  /**
@@ -38,6 +39,8 @@ const FALLBACK_BODY = {
38
39
  done: 'push.body.fallback.done',
39
40
  error: 'push.body.fallback.error',
40
41
  limit: 'push.body.fallback.limit',
42
+ stalled: 'push.body.fallback.stalled',
43
+ 'ready-to-merge': 'push.body.fallback.ready-to-merge',
41
44
  };
42
45
  /**
43
46
  * Jak długo APNs trzyma wiadomość dla telefonu, który akurat jest poza siecią (`apns-expiration`
@@ -51,6 +54,8 @@ const TTL_SECONDS = {
51
54
  blocking: 600,
52
55
  failure: 600,
53
56
  done: 3600,
57
+ // A subagent stuck on its own command stays stuck: an alarm delivered an hour late still tells the truth.
58
+ stalled: 3600,
54
59
  };
55
60
  /**
56
61
  * `high` = dostarcz natychmiast (`apns-priority: 10`), `normal` = system może poczekać na lepszy
@@ -60,6 +65,7 @@ const URGENCY = {
60
65
  blocking: 'high',
61
66
  failure: 'high',
62
67
  done: 'normal',
68
+ stalled: 'high',
63
69
  };
64
70
  /** Czy push nie dotyczy sesji ({@link SessionlessPushKind}). */
65
71
  export function isSessionless(content) {
@@ -107,6 +113,14 @@ export function flatten(text) {
107
113
  export function topicFor(sessionId) {
108
114
  return createHash('sha256').update(sessionId).digest('base64url').slice(0, TOPIC_MAX_CHARS);
109
115
  }
116
+ /**
117
+ * Collapse key of the stalled wait alarm of one session ({@link buildStalledContent}): a hash like {@link topicFor},
118
+ * stable per session, but never the session topic, so the alarm does not replace a pending decision banner of the
119
+ * same session and a later decision banner does not replace the alarm.
120
+ */
121
+ export function stalledTopicFor(sessionId) {
122
+ return topicFor(`rarog:stalled:${sessionId}`);
123
+ }
110
124
  const sentence = (said) => ({ text: said.text, ref: said.ref });
111
125
  /** `text` i `*Ref` pola treści, bez pola `*Ref`, gdy zdanie go nie ma. */
112
126
  const titleFields = (title) => (title.ref === undefined ? { title: title.text } : { title: title.text, titleRef: title.ref });
@@ -203,6 +217,56 @@ export function buildContent(input) {
203
217
  ...(input.badge === undefined ? {} : { badge: input.badge }),
204
218
  };
205
219
  }
220
+ /**
221
+ * Push `stalled`: a subagent of the session has waited over an hour on a background command it started itself. The
222
+ * title has the project (`push.title.stalled`), the body names the subagent by its description
223
+ * (`push.detail.stalled`, flattened and clipped before `say()`, so the body keeps its code), without a description the
224
+ * session label or `push.body.fallback.stalled`. Never the command: the lock screen is readable by bystanders
225
+ * (`docs/security-model.md`, "Push notifications"). Urgent, one hour in APNs, with its own collapse key
226
+ * ({@link stalledTopicFor}); the tap opens the session like any session banner.
227
+ */
228
+ export function buildStalledContent(input) {
229
+ const agent = input.agent === undefined ? '' : oneLine(input.agent);
230
+ const body = agent === ''
231
+ ? bodyFor('stalled', undefined, input.label)
232
+ : fitBody((a) => say('push.detail.stalled', { agent: a }), agent);
233
+ return {
234
+ kind: 'stalled',
235
+ sessionId: input.sessionId,
236
+ ...(input.termId === undefined ? {} : { termId: input.termId }),
237
+ ...titleFields(sentence(say(NOTIFY_KIND_TITLE.stalled, { project: input.project }))),
238
+ ...bodyFields(body),
239
+ topic: stalledTopicFor(input.sessionId),
240
+ urgency: URGENCY.stalled,
241
+ ttl: TTL_SECONDS.stalled,
242
+ ...(input.badge === undefined ? {} : { badge: input.badge }),
243
+ };
244
+ }
245
+ /**
246
+ * Push `ready-to-merge`: a coordinator's thread passed its checks and waits for the owner's Merge. The title has the
247
+ * project (`push.title.ready-to-merge`); the body is `push.body.detail-and-label` with the commit count
248
+ * (`push.detail.merge-ready`, singular or plural) as the detail and the thread name as the label. Urgent and
249
+ * short-lived like a decision banner (`READY_TO_MERGE_CLASS`). The collapse key is the session topic ({@link topicFor}), so
250
+ * the banner takes the place of an older banner of the same thread, and a later banner of the thread takes its place.
251
+ */
252
+ export function buildReadyToMergeContent(input) {
253
+ const label = oneLine(input.name);
254
+ const detail = say('push.detail.merge-ready', { commits: input.commits }).text;
255
+ const body = label === ''
256
+ ? sentence(say(FALLBACK_BODY['ready-to-merge']))
257
+ : fitBody((d) => say('push.body.detail-and-label', { detail: d, label }), detail);
258
+ return {
259
+ kind: 'ready-to-merge',
260
+ sessionId: input.sessionId,
261
+ ...(input.termId === undefined ? {} : { termId: input.termId }),
262
+ ...titleFields(sentence(say(NOTIFY_KIND_TITLE['ready-to-merge'], { project: input.project }))),
263
+ ...bodyFields(body),
264
+ topic: topicFor(input.sessionId),
265
+ urgency: URGENCY[READY_TO_MERGE_CLASS],
266
+ ttl: TTL_SECONDS[READY_TO_MERGE_CLASS],
267
+ ...(input.badge === undefined ? {} : { badge: input.badge }),
268
+ };
269
+ }
206
270
  /**
207
271
  * Push PRÓBNY po włączeniu powiadomień: tap otwiera listę sesji. Krótki TTL — próba, która
208
272
  * dojdzie po godzinie, niczego już nie potwierdza. Bez plakietki: nie wiemy tu, ile sesji czeka.
@@ -48,6 +48,10 @@ function sendLogLine(kind, project, report) {
48
48
  * standby alone keep a fixed wording, because people and documents read them.
49
49
  */
50
50
  function noResultCause(turn) {
51
+ // No input at all: a subagent woken from standby worked in the pane.
52
+ if (turn.standbyNotices === 0 && turn.artifactWatch === 0 && turn.compactions === 0) {
53
+ return { turn: 'turn after subagent work alone', owed: 'with subagent work alone' };
54
+ }
51
55
  // A context compaction, alone or joined with the other causes of the turn.
52
56
  if (turn.compactions > 0) {
53
57
  const cause = [
@@ -161,6 +165,7 @@ export class Notifier {
161
165
  backgroundTasks: input.backgroundTasks,
162
166
  ...(input.afterHerdrRestore === true ? { afterHerdrRestore: true } : {}),
163
167
  ...(input.afterStart === true ? { afterStart: true } : {}),
168
+ ...(input.testSession === true ? { testSession: true } : {}),
164
169
  ...(input.turnInput === undefined ? {} : { turnInput: input.turnInput }),
165
170
  ...(input.waitingOnOwnCommand === true ? { waitingOnOwnCommand: true } : {}),
166
171
  };
@@ -193,12 +198,15 @@ export class Notifier {
193
198
  else if (input.afterStart === true && kind === 'done') {
194
199
  this.#log?.(`${PUSH_QUIET_LOG} ${input.project} (done, session start)`);
195
200
  }
201
+ else if (input.testSession === true && kind === 'done') {
202
+ this.#log?.(`${PUSH_QUIET_LOG} ${input.project} (done, test session in a temporary directory)`);
203
+ }
196
204
  else if (kind === 'done' && input.backgroundTasks === 0 && input.turnInput !== undefined
197
205
  && noResultTurn(input.turnInput)) {
198
206
  // A reason visible neither in the session state nor in the task list: the turn was triggered
199
- // by a CLI report alone, after which nothing finished. With background work running the
200
- // silence keeps its usual reason and no line. An owed "done" waiting for a subagent with its
201
- // own command gets its own wording in the log.
207
+ // by a CLI report alone (or by a woken subagent's work alone), after which nothing finished.
208
+ // With background work running the silence keeps its usual reason and no line. An owed "done"
209
+ // waiting for a subagent with its own command gets its own wording in the log.
202
210
  const held = this.#owed.has(input.sessionId) && input.waitingOnOwnCommand === true
203
211
  ? ', owed waits: the subagent waits for its own command' : '';
204
212
  this.#log?.(`${PUSH_QUIET_LOG} ${input.project} (done, ${noResultCause(input.turnInput).turn}${held})`);
@@ -1,7 +1,7 @@
1
1
  import { TERM_ID_RE } from '@rarog/shared';
2
2
  import { phaseCounts } from '@rarog/shared/workflow-phases';
3
3
  import { LIVE_ACTIVITY_SEGMENTS_MAX, LIVE_ACTIVITY_TEXT_MAX, LIVE_ACTIVITY_WORKFLOWS_MAX, } from '@rarog/shared/rest';
4
- import { hasBackgroundWork, hasOpenWorkflow, workflowsWithRun } from '../herdr/background/work.js';
4
+ import { hasBackgroundWork, hasOpenWorkflow, stuckWait, workflowsWithRun } from '../herdr/background/work.js';
5
5
  import { currentPhase } from './workflow-phase.js';
6
6
  const WAITING = ['waiting-permission', 'waiting-question'];
7
7
  const WORKING = ['starting', 'running'];
@@ -122,14 +122,27 @@ function workflowOf({ session, task, run }) {
122
122
  states: counts.map(stateOf),
123
123
  };
124
124
  }
125
+ /** The merge state of a coordinator's thread (`coordination.merge`); absent for any other session. */
126
+ function threadMerge(session) {
127
+ return session.coordination?.role === 'thread' ? session.coordination.merge?.state : undefined;
128
+ }
125
129
  /** Lista sesji → stan treści aktywności (kolejność kluczy = kolejność w kontrakcie). */
126
130
  export function aggregateState(sessions, nowMs, extras = {}) {
127
131
  const nowSec = Math.floor(nowMs / 1000);
128
132
  const waiting = sessions.filter((s) => WAITING.includes(s.state));
129
133
  const working = sessions.filter((s) => WORKING.includes(s.state));
130
- const background = sessions.filter((s) => QUIET.includes(s.state) && hasBackgroundWork(s.backgroundTasks));
131
- const finished = sessions.filter((s) => s.state === 'waiting-input' && s.seen !== true && !hasBackgroundWork(s.backgroundTasks)).length;
132
- // Wiodąca bez zmian: sesja „w tle" nie jest celem tapnięcia — jej tura już się skończyła.
134
+ // A thread with a merge state counts by it alone, once: `ready` waits for the owner's Merge, `merging` is the
135
+ // coordinator's work, `merged` counts nowhere. The tap target and the tile lifetime stay with the session state.
136
+ const ready = sessions.filter((s) => threadMerge(s) === 'ready').length;
137
+ const merging = sessions.filter((s) => threadMerge(s) === 'merging').length;
138
+ const plain = sessions.filter((s) => threadMerge(s) === undefined);
139
+ // A session after a turn whose subagent is stuck on its own command waits for the owner: it counts once, as waiting.
140
+ const stuck = plain.filter((s) => stuckWait(s.state, s.backgroundTasks));
141
+ const background = plain.filter((s) => QUIET.includes(s.state) && !stuck.includes(s)
142
+ && hasBackgroundWork(s.backgroundTasks));
143
+ const finished = plain.filter((s) => s.state === 'waiting-input' && s.seen !== true && !stuck.includes(s) && !hasBackgroundWork(s.backgroundTasks)).length;
144
+ // Wiodąca bez zmian: sesja „w tle" nie jest celem tapnięcia — jej tura już się skończyła. The same holds for a
145
+ // stuck session, so it is not a lead candidate.
133
146
  const lead = longest(waiting) ?? longest(working);
134
147
  const runs = openRuns(sessions);
135
148
  const workflows = runs.slice(0, LIVE_ACTIVITY_WORKFLOWS_MAX).map(workflowOf);
@@ -137,8 +150,8 @@ export function aggregateState(sessions, nowMs, extras = {}) {
137
150
  const limits = extras.limits !== undefined && Object.keys(extras.limits).length > 0 ? extras.limits : undefined;
138
151
  const mac = extras.mac !== undefined && Object.keys(extras.mac).length > 0 ? extras.mac : undefined;
139
152
  return {
140
- waiting: waiting.length,
141
- working: working.length + background.length,
153
+ waiting: plain.filter((s) => WAITING.includes(s.state)).length + stuck.length + ready,
154
+ working: plain.filter((s) => WORKING.includes(s.state)).length + background.length + merging,
142
155
  finished,
143
156
  ...(lead === undefined ? {} : { top: topOf(lead) }),
144
157
  ...(workflows.length === 0 ? {} : { workflows }),
@@ -295,8 +295,11 @@ export function createLiveActivity(options) {
295
295
  if (result.kind === 'ok')
296
296
  track.lastCounts = sentCounts.key;
297
297
  }
298
- if (chime !== undefined)
299
- safeLog(`live-activity: done chime → ${countsOutcomeOf(result)}`);
298
+ // `updatedEpoch` of the sent content: the app traces every content it receives with the same number, so the two
299
+ // logs join on it (did the chime land while the app was already in the foreground).
300
+ if (chime !== undefined) {
301
+ safeLog(`live-activity: done chime → ${countsOutcomeOf(result)}, updatedEpoch ${String(timestamp)}`);
302
+ }
300
303
  noteCounters();
301
304
  evaluate();
302
305
  };