@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,57 @@
1
+ /**
2
+ * The branch diff routes of a coordinator's thread (`GET /api/sessions/:id/branch-diff/files` and
3
+ * `…/branch-diff/file?path=…`): the scope gate of the session diff, the main checkout of the session read fresh, then
4
+ * the collectors of `git-branch-diff.ts`. A session that is no thread of a project, or whose branch has no base, gets a
5
+ * refusal with a sentence (400 `bad-request`); git failures and bad paths throw `DiffError` with the codes of the
6
+ * session diff routes. The demo answers from its fixed data. It runs no git itself and does not import `manager.ts`.
7
+ */
8
+ import { DIFF_BAD_PATH_ERROR, DIFF_FILE_NOT_FOUND_ERROR } from '@rarog/shared';
9
+ import { say } from '@rarog/shared/sentences';
10
+ import { collectBranchDiffFile, collectBranchDiffList } from '../git-branch-diff.js';
11
+ import { DiffError, validateDiffPath } from '../git-diff.js';
12
+ import { ProjectRoots } from '../project-root.js';
13
+ import { BadRequestError } from './errors.js';
14
+ import { diffSession } from './session-scope.js';
15
+ const REFUSALS = {
16
+ 'no-project-root': () => new BadRequestError(say('rest.branch-diff-no-project')),
17
+ 'no-base': () => new BadRequestError(say('rest.branch-diff-no-base')),
18
+ };
19
+ /**
20
+ * The main checkout of the session directory, read now: the rule of the summaries' `projectRoot` (a main checkout
21
+ * inside the work area, read through the work-area disk), without their memory, so a worktree removed or moved since
22
+ * the last summary is seen at once.
23
+ */
24
+ function projectRootOf(cwd, port) {
25
+ return new ProjectRoots({
26
+ roots: port.roots, home: port.home, ...(port.disk === undefined ? {} : { disk: port.disk }), changed: () => { },
27
+ }).read(cwd);
28
+ }
29
+ /** `GET …/branch-diff/files`: the files and commits of the thread's branch past its base. */
30
+ export async function branchDiffFiles(id, port) {
31
+ const session = diffSession(id, port);
32
+ if (session === null)
33
+ return port.demoList();
34
+ const projectRoot = await projectRootOf(session.cwd, port);
35
+ const answer = await collectBranchDiffList({ cwd: session.cwd, projectRoot }, { run: port.run, runNumstat: port.runNumstat });
36
+ if (!answer.ok)
37
+ throw REFUSALS[answer.refusal]();
38
+ return answer.value;
39
+ }
40
+ /** `GET …/branch-diff/file?path=…`: the patch of one file of that list. */
41
+ export async function branchDiffFile(id, path, port) {
42
+ const session = diffSession(id, port);
43
+ // The shape check stands before the demo branch: `?path=../x` is 400 there too, as in production.
44
+ if (validateDiffPath(path) === null)
45
+ throw new DiffError(DIFF_BAD_PATH_ERROR);
46
+ if (session === null) {
47
+ const patch = port.demoFile(path);
48
+ if (patch === null)
49
+ throw new DiffError(DIFF_FILE_NOT_FOUND_ERROR);
50
+ return patch;
51
+ }
52
+ const projectRoot = await projectRootOf(session.cwd, port);
53
+ const answer = await collectBranchDiffFile({ cwd: session.cwd, projectRoot }, path, { run: port.run });
54
+ if (!answer.ok)
55
+ throw REFUSALS[answer.refusal]();
56
+ return answer.value;
57
+ }
@@ -1,6 +1,7 @@
1
1
  import { cliProcessStartOf, cliUpdateFor, cliWaitingOf, runningCliVersion } from '../cli-version.js';
2
2
  import { cliAcceptsNotes } from './question-card.js';
3
3
  import { CLI_VERSION_POLL_MS, CLI_WAITING_POLL_MS, HERDR_MODE_UNKNOWN_MESSAGE, herdrDialogStandsMessage, } from './state-sentences.js';
4
+ import { isStateOnlyEngine } from '../herdr/engines.js';
4
5
  /** Readings of the CLI registry and the two ticks that refresh them; one instance per manager. */
5
6
  export class CliRegistryState {
6
7
  #config;
@@ -23,6 +24,8 @@ export class CliRegistryState {
23
24
  * prawa ruszać mimochodem.
24
25
  */
25
26
  #cliRegistry = null;
27
+ /** Whether the fast tick has given an accepted reading; from then on {@link cliPidsOf} trusts only it. */
28
+ #cliRegistryAccepted = false;
26
29
  /**
27
30
  * Czego ostatnio przyjęty odczyt rejestru NIE widział: żywe pidy z plikiem bez wpisu
28
31
  * i rozmowy żywych procesów bez pliku. Przy którymkolwiek rejestr nie dowodzi, że rozmowę pisze
@@ -54,7 +57,7 @@ export class CliRegistryState {
54
57
  * od Raroga żadnej władzy — pigułka nad nim byłaby obietnicą bez pokrycia.
55
58
  */
56
59
  cliUpdateOf(session) {
57
- if (session.engine === 'codex' || session.outOfScope === true)
60
+ if (isStateOnlyEngine(session.engine) || session.outOfScope === true)
58
61
  return undefined;
59
62
  if (session.driver === null || session.herdrKey === undefined)
60
63
  return undefined;
@@ -167,6 +170,7 @@ export class CliRegistryState {
167
170
  this.#cliRegistryGen = generation;
168
171
  }
169
172
  this.#cliRegistry = snapshot.registry;
173
+ this.#cliRegistryAccepted = true;
170
174
  this.#cliRegistryDoubt = {
171
175
  ...(snapshot.unreadablePids === undefined ? {} : { unreadablePids: snapshot.unreadablePids }),
172
176
  ...(snapshot.unlistedSessions === undefined ? {} : { unlistedSessions: snapshot.unlistedSessions }),
@@ -194,7 +198,7 @@ export class CliRegistryState {
194
198
  * już zrestartowanym CLI nie potrzebuje osobnej ścieżki).
195
199
  */
196
200
  #noteCliProcessStart(session) {
197
- if (session.engine === 'codex' || session.outOfScope === true || session.herdrKey === undefined)
201
+ if (isStateOnlyEngine(session.engine) || session.outOfScope === true || session.herdrKey === undefined)
198
202
  return;
199
203
  const sessionId = session.engineSessionId;
200
204
  const startedAt = cliProcessStartOf({ registry: this.#cliRegistry, ...this.#cliRegistryDoubt }, sessionId);
@@ -208,7 +212,7 @@ export class CliRegistryState {
208
212
  * ani odczytu ekranu — sygnał byłby tam obietnicą bez pokrycia.
209
213
  */
210
214
  cliWaitingOf(session) {
211
- if (this.#config.cliWaiting !== true || session.engine === 'codex'
215
+ if (this.#config.cliWaiting !== true || isStateOnlyEngine(session.engine)
212
216
  || session.outOfScope === true || session.driver === null || session.herdrKey === undefined) {
213
217
  return { kind: 'unknown' };
214
218
  }
@@ -223,6 +227,16 @@ export class CliRegistryState {
223
227
  const registry = this.#cliRegistry ?? this.#cliVersion.registry;
224
228
  return cliAcceptsNotes(runningCliVersion(registry, session.engineSessionId));
225
229
  }
230
+ /**
231
+ * The live process ids writing the conversation: the fast tick's last accepted reading once there is one (a failed
232
+ * reading is unknown, never the older slow snapshot), else the slow one. `null` = unknown: no reading, a failed
233
+ * one, or no live process of the conversation.
234
+ */
235
+ cliPidsOf(conversation) {
236
+ const registry = this.#cliRegistryAccepted ? this.#cliRegistry : this.#cliVersion.registry;
237
+ const entries = registry?.get(conversation);
238
+ return entries === undefined || entries.length === 0 ? null : entries.map((entry) => entry.pid);
239
+ }
226
240
  /** 400 bramki „nie znam trybu" — z nazwaną przyczyną, gdy rejestr mówi o dialogu. */
227
241
  modeUnknownMessage(session) {
228
242
  const signal = this.cliWaitingOf(session);
@@ -8,6 +8,7 @@ import { homedir } from 'node:os';
8
8
  import { say } from '@rarog/shared/sentences';
9
9
  import { inWorkAreaOnDisk } from '../config/work-area.js';
10
10
  import { BadStateError } from './errors.js';
11
+ import { isStateOnlyEngine } from '../herdr/engines.js';
11
12
  /**
12
13
  * Scope of the commands list (`GET /api/sessions/:id/commands`) and of the voice agent, the same as for sending and
13
14
  * for reading the session catalog. Out of scope: a pane outside `RAROG_HERDR_ROOTS` (every Codex pane among them)
@@ -16,7 +17,7 @@ import { BadStateError } from './errors.js';
16
17
  * directory. A card without a pane is in scope with its directory; demo mode reads the registry only.
17
18
  */
18
19
  export function inCommandScope(session, config, options = {}) {
19
- if (session.engine === 'codex' || session.outOfScope === true)
20
+ if (isStateOnlyEngine(session.engine) || session.outOfScope === true)
20
21
  return false;
21
22
  return config.demo || sessionCwdInArea(session, config, options);
22
23
  }
@@ -4,6 +4,7 @@ import { classifyRisk } from '../risk.js';
4
4
  import { consentStep } from '../herdr/consent-step.js';
5
5
  import { CONSENT_FINAL_STATES, CONSENT_HOLDING_STATES } from '../herdr/dialogs/layer1/contract.js';
6
6
  import { consentPermissionRequest, consentResolvedEvent, consentSettledEvent, } from '../herdr/dialogs/layer1/frames.js';
7
+ import { isStateOnlyEngine } from '../herdr/engines.js';
7
8
  /** Consent channel cards of the manager's sessions; one instance per manager. */
8
9
  export class ConsentCards {
9
10
  #config;
@@ -18,6 +19,11 @@ export class ConsentCards {
18
19
  * pole rekordu (`retired` w widoku portu). Błąd zapisu zostawia wpis do końca procesu.
19
20
  */
20
21
  #consentRetired = new Set();
22
+ /**
23
+ * The stay in `waiting-permission` (its `stateSince`) whose hold by a subagent card is already in the log
24
+ * ({@link subagentCardHold}): one line per stay, however many herdr statuses repeat during it.
25
+ */
26
+ #subagentHeldSince = new WeakMap();
21
27
  constructor(config, port) {
22
28
  this.#config = config;
23
29
  this.#port = port;
@@ -183,7 +189,12 @@ export class ConsentCards {
183
189
  this.#port.emitSession(session, { type: 'permission-pending', request: this.#consentRequest(session, view) });
184
190
  this.#port.timingCard(session, 'hook');
185
191
  if (view.state !== 'pending' || !this.#port.applyTransition(session, { type: 'permission-requested' })) {
186
- this.#port.emitSessionChanged(session);
192
+ // A subagent's card is the decision that stands, also after the turn ended (`waiting-input`): herdr never
193
+ // reports `blocked` for it. Its silent transition goes first; the banner comes from the note below.
194
+ const reconciled = view.state === 'pending' && view.agentId !== null
195
+ && this.#port.applyTransition(session, { type: 'subagent-consent-pending' });
196
+ if (!reconciled)
197
+ this.#port.emitSessionChanged(session);
187
198
  if (view.state === 'pending')
188
199
  this.#port.note(session, { type: 'permission-requested' });
189
200
  }
@@ -377,7 +388,7 @@ export class ConsentCards {
377
388
  const engines = new Set();
378
389
  if (session.engineSessionId !== undefined && session.engineSessionId !== '')
379
390
  engines.add(session.engineSessionId);
380
- if (agent.engine !== 'codex' && agent.agentSessionId !== '')
391
+ if (!isStateOnlyEngine(agent.engine) && agent.agentSessionId !== '')
381
392
  engines.add(agent.agentSessionId);
382
393
  if (engines.size === 0)
383
394
  return;
@@ -462,6 +473,42 @@ export class ConsentCards {
462
473
  return this.#port.hasPending(session.id)
463
474
  || this.consentRequests(session).some((request) => request.state === 'pending');
464
475
  }
476
+ /**
477
+ * What herdr `working` or `idle` does to the session state while a subagent's channel card of the conversation this
478
+ * session handles stands in `pending`. A background subagent's request has no dialog on screen while the hook waits
479
+ * ("When the hook gets a request" in `docs/dialogs.md`), so herdr never reports `blocked` for it, and the session
480
+ * belongs in `waiting-permission` until the card leaves `pending` ({@link applyConsentCard} moves it then):
481
+ * `hold` in `waiting-permission` (the first hold of each stay goes to the log), `reconcile` from `running` and
482
+ * `waiting-input` (a turn end or an early herdr status left the state), `null` without such a card and in every other
483
+ * state. A main-thread card does not count: its dialog stands on the pane and herdr reports it. A cycle error = `null`.
484
+ */
485
+ subagentCardHold(session, herdr) {
486
+ const state = session.state;
487
+ if (state !== 'waiting-permission' && state !== 'running' && state !== 'waiting-input')
488
+ return null;
489
+ if (!this.#subagentCardPending(session))
490
+ return null;
491
+ if (state !== 'waiting-permission')
492
+ return 'reconcile';
493
+ if (this.#subagentHeldSince.get(session) !== session.stateSince) {
494
+ this.#subagentHeldSince.set(session, session.stateSince);
495
+ this.#config.logger?.(`consent: session ${session.id} stays waiting-permission: subagent card pending (herdr: ${herdr})`);
496
+ }
497
+ return 'hold';
498
+ }
499
+ #subagentCardPending(session) {
500
+ const consent = this.#config.consent;
501
+ const engine = session.engineSessionId;
502
+ if (consent === undefined || engine === undefined || engine === '' || !this.#ownsConsent(session))
503
+ return false;
504
+ try {
505
+ return consent.cards(engine).some((card) => card.state === 'pending' && card.agentId !== null
506
+ && !this.#consentCardRetired(engine, card));
507
+ }
508
+ catch {
509
+ return false;
510
+ }
511
+ }
465
512
  }
466
513
  /** Kto zdjął kartę kanału zgód w `permission-resolved`: hook (skutek albo koniec cyklu), nie urządzenie. */
467
514
  const CONSENT_RESOLVED_BY = 'hook';
@@ -1,4 +1,5 @@
1
- import { holdsOwedDone } from '../herdr/background/work.js';
1
+ import { agentsWoken, holdsOwedDone, stuckWaits } from '../herdr/background/work.js';
2
+ import { noteSubagentWakes } from './state-sentences.js';
2
3
  export function applyConversationList(session, event, port) {
3
4
  switch (event.type) {
4
5
  /*
@@ -15,8 +16,16 @@ export function applyConversationList(session, event, port) {
15
16
  if (tasks === undefined && session.backgroundTasks === undefined)
16
17
  return;
17
18
  const held = holdsOwedDone(session.backgroundTasks);
19
+ const waits = stuckWaits(session.state, session.backgroundTasks, tasks);
20
+ // A subagent woken from standby works in the main pane: a turn herdr reports for it alone has no result.
21
+ noteSubagentWakes(session, agentsWoken(session.backgroundTasks, tasks));
18
22
  session.backgroundTasks = tasks;
19
23
  port.emitSessionChanged(session);
24
+ /*
25
+ * The stalled wait alarm on every swap, also without an edge: the alarm drops its tries and its memory of waits
26
+ * that left the list. Before `quiet`, on the same swap; the alarm never touches the owed "done".
27
+ */
28
+ port.stuckWaits(session, waits);
20
29
  /*
21
30
  * Cisza w tle bez końca tury: lista przestała wstrzymywać
22
31
  * zaległe „gotowe" — skończyła się praca albo komenda subagenta w postoju. Raz na przejście,
@@ -43,7 +52,7 @@ export function applyConversationList(session, event, port) {
43
52
  }
44
53
  // Pull requesty sesji: reguła artefaktów, lista i jej stan na GitHubie w `pr-status-link.ts`.
45
54
  case 'pull-requests':
46
- port.prStatus.applyList(session, event.pullRequests);
55
+ port.prStatus.applyList(session, event.pullRequests, event.windowStart);
47
56
  return;
48
57
  /*
49
58
  * Scheduled tasks: the artifacts rule. An empty list clears the field; an empty one over an absent field sends
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Start of a project coordinator, decided before anything exists in herdr. A Launch with the coordinator switch
3
+ * reserves its project's role in the coordinator registry; a resume of the conversation the registry keeps for the
4
+ * project reserves it again; a fork and any other resume stay ordinary. A reserved start gets the plugin copy for
5
+ * `--plugin-dir` and `/rarog:coordinator` as its first prompt, and its ticket settles the reservation exactly once.
6
+ * The module starts no process and writes no session state; the plugin path comes from the copy it made, never from
7
+ * the client.
8
+ */
9
+ import path from 'node:path';
10
+ import { say } from '@rarog/shared/sentences';
11
+ import { projectOfSession } from '../coordination/summary.js';
12
+ import { DIRECT_DISK } from '../folder-gate/disk.js';
13
+ import { DISK_LAYOUT } from '../herdr/commands/registry.js';
14
+ import { BadRequestError, BadStateError } from './errors.js';
15
+ /** The coordinator skill of the plugin; every coordinator start and resume sends it first, so its rules are fresh. */
16
+ export const COORDINATOR_SKILL_COMMAND = '/rarog:coordinator';
17
+ /** A process whose state is one of these is gone, so it runs from no plugin copy. */
18
+ const GONE = new Set(['done', 'resumable']);
19
+ /**
20
+ * First prompt of a coordinator start: the skill command with the user's prompt as its arguments. A prompt that
21
+ * already starts with the command (the start prompt sent again after a hook blocked it) stays as it is.
22
+ */
23
+ export function coordinatorPrompt(prompt) {
24
+ const own = prompt ?? '';
25
+ if (own.trim() === '')
26
+ return COORDINATOR_SKILL_COMMAND;
27
+ const first = /^\S+/.exec(own.trimStart())?.[0] ?? '';
28
+ return first.toLowerCase() === COORDINATOR_SKILL_COMMAND ? own : `${COORDINATOR_SKILL_COMMAND} ${own}`;
29
+ }
30
+ /** The user's words of a coordinator's start prompt (the text after the skill command) for the card label. */
31
+ export function coordinatorLabel(text) {
32
+ const trimmed = text.trim();
33
+ const own = trimmed.toLowerCase().startsWith(COORDINATOR_SKILL_COMMAND)
34
+ ? trimmed.slice(COORDINATOR_SKILL_COMMAND.length).trim()
35
+ : trimmed;
36
+ return own === '' ? null : own;
37
+ }
38
+ /** The plugin directories of a session's command catalog: its coordinator plugin copy, if any. */
39
+ export function pluginDirsOf(session) {
40
+ return typeof session.pluginDir === 'string' ? [session.pluginDir] : undefined;
41
+ }
42
+ /**
43
+ * The `--plugin-dir` values of the live sessions, which the copy keeps; `null` while a live session's arguments are
44
+ * not known (a pane found after a server restart may run a coordinator from an older copy), and then nothing goes.
45
+ */
46
+ export function pluginCopiesInUse(sessions) {
47
+ const dirs = new Set();
48
+ for (const session of sessions) {
49
+ if (GONE.has(session.state))
50
+ continue;
51
+ if (session.pluginDir === undefined)
52
+ return null;
53
+ if (session.pluginDir !== null)
54
+ dirs.add(session.pluginDir);
55
+ }
56
+ return dirs;
57
+ }
58
+ class Ticket {
59
+ pluginDir;
60
+ #registry;
61
+ #reservation;
62
+ #roleChanged;
63
+ #settled = false;
64
+ constructor(registry, reservation, pluginDir, roleChanged) {
65
+ this.#registry = registry;
66
+ this.#reservation = reservation;
67
+ this.pluginDir = pluginDir;
68
+ this.#roleChanged = roleChanged;
69
+ }
70
+ release() {
71
+ if (this.#settled)
72
+ return;
73
+ this.#settled = true;
74
+ this.#registry.release(this.#reservation);
75
+ }
76
+ started(card) {
77
+ if (this.#settled)
78
+ return;
79
+ card.ready.then(() => {
80
+ if (this.#settled)
81
+ return;
82
+ if (!card.current()) {
83
+ this.release();
84
+ return;
85
+ }
86
+ this.#settled = true;
87
+ this.#registry.confirm(this.#reservation, card.id, card.conversation);
88
+ this.#roleChanged(card.id);
89
+ }, () => { this.release(); });
90
+ }
91
+ }
92
+ /** The coordinator decision of every start; one instance per server, shared by every manager start. */
93
+ export class CoordinatorStart {
94
+ #registry;
95
+ #pluginCopy;
96
+ #roleChanged;
97
+ #log;
98
+ #disk;
99
+ constructor(opts) {
100
+ this.#registry = opts.registry;
101
+ this.#pluginCopy = opts.pluginCopy;
102
+ this.#roleChanged = opts.roleChanged;
103
+ this.#log = opts.log;
104
+ this.#disk = opts.disk ?? DIRECT_DISK;
105
+ }
106
+ /**
107
+ * The ticket of a coordinator start, or `null` for an ordinary one. Synchronous from the reservation to the copy,
108
+ * so two starts cannot both pass. `coordinator` counts only for a new conversation: with `resumeFrom` the registry
109
+ * alone decides, so the switch never makes a resumed conversation the coordinator.
110
+ *
111
+ * @throws {BadRequestError} the Launch is not in the top folder of a project's main git checkout
112
+ * @throws {BadStateError} the project's coordinator lives or starts, or the plugin copy failed
113
+ */
114
+ admit(opts, port) {
115
+ if (opts.fork === true)
116
+ return null;
117
+ let reservation;
118
+ if (opts.resumeFrom !== undefined) {
119
+ const project = projectOfSession({ peek: () => undefined }, opts.cwd, this.#disk);
120
+ const id = opts.sessionId ?? port.aliasFor(opts.resumeFrom);
121
+ const reserved = this.#registry.reserveResume(project, opts.resumeFrom, id);
122
+ if (reserved === null)
123
+ return null;
124
+ reservation = reserved;
125
+ }
126
+ else if (opts.coordinator === true) {
127
+ reservation = this.#reserveLaunch(opts.cwd, port);
128
+ }
129
+ else {
130
+ return null;
131
+ }
132
+ const copy = this.#pluginCopy(pluginCopiesInUse(port.sessions()));
133
+ if (!copy.ok) {
134
+ this.#registry.release(reservation);
135
+ this.#log(`coordinator: plugin copy failed (${copy.code}): ${copy.reason}`);
136
+ throw new BadStateError(copy.code === 'path'
137
+ ? say('session.coordinator-plugin-path')
138
+ : say('session.coordinator-plugin-missing', { reason: copy.code }));
139
+ }
140
+ return new Ticket(this.#registry, reservation, copy.dir, this.#roleChanged);
141
+ }
142
+ /**
143
+ * A Launch reserves the project of its directory, which must be the top folder of a main checkout: `.git` right
144
+ * under it is a directory. The registry keys a project by the main checkout the summary overlay reads
145
+ * (`projectOfSession`), and in a subdirectory or a linked worktree the Launch directory is another string.
146
+ * A live process of the project's stored conversation refuses the Launch like a live coordinator: after a server
147
+ * restart nothing in memory knows it ran with the plugin, and the plugin of a second coordinator would refuse its
148
+ * claim while the first lives. An unknown process reading admits.
149
+ */
150
+ #reserveLaunch(cwd, port) {
151
+ const refused = new BadRequestError(say('session.coordinator-not-project', { cwd }));
152
+ let project;
153
+ try {
154
+ const real = this.#disk.sync('realpath', { path: cwd });
155
+ if (!this.#disk.sync('lstat', { path: path.join(real, DISK_LAYOUT.gitDir) }).isDirectory())
156
+ throw refused;
157
+ project = projectOfSession({ peek: () => undefined }, cwd, this.#disk);
158
+ }
159
+ catch {
160
+ // A missing `.git`, a closed guarded folder or any other read error: no proof of a main checkout.
161
+ throw refused;
162
+ }
163
+ const reserved = this.#registry.reserveLaunch(project, (conversation) => port.cliPids(conversation) !== null);
164
+ if (reserved.ok)
165
+ return reserved.reservation;
166
+ if (reserved.reason === 'live')
167
+ throw new BadStateError(say('session.coordinator-live'));
168
+ if (reserved.reason === 'starting')
169
+ throw new BadStateError(say('session.coordinator-starting'));
170
+ throw refused;
171
+ }
172
+ }
@@ -10,6 +10,7 @@ export async function loadDemoModules(content) {
10
10
  demoDiff: () => seeds.demoDiff(content),
11
11
  demoDiffFiles: seeds.demoDiffFiles,
12
12
  demoDiffFile: (path) => seeds.demoDiffFile(content, path),
13
+ demoBranchDiffFiles: seeds.demoBranchDiffFiles,
13
14
  demoFileEntries: files.demoFileEntries,
14
15
  demoFileBytes: files.demoFileBytes,
15
16
  };
@@ -0,0 +1,100 @@
1
+ import { classifyRisk } from '../risk.js';
2
+ import { STALE } from '../drivers/types.js';
3
+ import { permissionSemantics } from '../drivers/tool-text.js';
4
+ import { Session } from './session.js';
5
+ import { seedDetailField } from './state-sentences.js';
6
+ /**
7
+ * Sesje demo — jedyne miejsce, w którym karta powstaje bez udziału herdr.
8
+ *
9
+ * Ziarna niosą historię, wiersz gita i czekającą zgodę, czyli rzeczy, których `HerdrAgent`
10
+ * nie ma i mieć nie może. Driver dla nich daje MOCK NADZORCY (`demo/mock-herdr.ts`) przez
11
+ * `attach(key)` — dzięki temu demo chodzi tą samą ścieżką co produkcja i żaden scenariusz
12
+ * (zgoda, pytanie, limit, błąd, git) nie ginie.
13
+ */
14
+ export function applyDemoSeeds(port) {
15
+ const supervisor = port.supervisor;
16
+ const now = port.now;
17
+ const demo = port.demo;
18
+ for (const seed of demo.demoSeeds(now)) {
19
+ const session = new Session({
20
+ id: seed.id,
21
+ cwd: seed.cwd,
22
+ title: seed.title,
23
+ // Panel „Raroga" także w demo: dzięki temu da się przeklikać ścieżkę „Zamknij panel"
24
+ // (i jej potwierdzenie), a nie tylko „Ukryj".
25
+ herdrKey: seed.id,
26
+ paneId: `w0:${seed.id}`,
27
+ launchedByRarog: true,
28
+ // Seed niesie gotową etykietę; gdyby jej nie miał, liczymy ją z pierwszego promptu
29
+ // dokładnie tak, jak przy prawdziwym `create()`.
30
+ label: seed.label ?? port.labelFor(seed.cwd, seedPrompt(seed)),
31
+ state: seed.state,
32
+ ...seedDetailField(seed),
33
+ stateSince: port.iso(now - seed.stateSinceAgoMs),
34
+ createdAt: port.iso(now - seed.createdAtAgoMs),
35
+ lastActivityAt: port.iso(now - seed.lastActivityAgoMs),
36
+ branch: seed.branch,
37
+ dirtyCount: seed.dirtyCount,
38
+ ahead: seed.ahead,
39
+ behind: seed.behind,
40
+ lastSummary: seed.lastSummary,
41
+ model: seed.model,
42
+ effort: seed.effort,
43
+ ultracode: seed.ultracode,
44
+ engineSessionId: seed.engineSessionId,
45
+ ...(seed.projectRoot === undefined ? {} : { projectRoot: seed.projectRoot }),
46
+ ...(seed.coordination === undefined ? {} : { coordination: seed.coordination }),
47
+ });
48
+ for (const message of seed.messages) {
49
+ session.appendMessage(message.role, demo.demoBlocks(message.blocks), port.iso(now - message.agoMs), message.attachments, message.notice === undefined ? {} : { notice: message.notice });
50
+ }
51
+ // `appendMessage` przesuwa `lastActivityAt` — seed decyduje o nim sam.
52
+ session.lastActivityAt = port.iso(now - seed.lastActivityAgoMs);
53
+ port.sessions.set(session.id, session);
54
+ port.herdrByKey.set(seed.id, session.id);
55
+ port.indexEngineSession(session);
56
+ if (seed.live !== undefined && supervisor !== undefined) {
57
+ // Mock nadzorcy zna scenariusz każdego ziarna po jego kluczu — model i effort też
58
+ // stamtąd, żeby pigułka w composerze pokazywała w demo realne warianty.
59
+ port.attachDriver(session, supervisor.attach(seed.id));
60
+ }
61
+ const permission = seed.permission;
62
+ if (permission !== undefined) {
63
+ const request = {
64
+ permId: permission.permId,
65
+ sessionId: session.id,
66
+ toolName: permission.toolName,
67
+ displayText: permission.displayText,
68
+ risk: classifyRisk(permission.displayText, permission.toolName),
69
+ cwd: session.cwd,
70
+ createdAt: port.iso(now - permission.agoMs),
71
+ subject: port.permissionSubject(permission.toolName),
72
+ // Ta sama reguła co na żywo — seed z komendą powłoki niesie jej input.
73
+ ...permissionSemantics(permission.input, permission.displayText),
74
+ };
75
+ port.pending.addPermission(request, async (decision, message) => {
76
+ // Sesja seeda bez drivera nie ma czym wysłać decyzji — `stale` jest tu prawdą
77
+ // (karta nie reprezentuje niczego żywego), a nie odmową do pokazania na ekranie.
78
+ const driver = session.driver;
79
+ if (driver === null)
80
+ return STALE;
81
+ return driver.respondPermission(permission.permId, decision, message);
82
+ });
83
+ // Do bufora (żeby replay transkryptu był spójny), bez broadcastu — nikt jeszcze nie słucha.
84
+ session.pushEvent({ type: 'permission-pending', request });
85
+ }
86
+ }
87
+ }
88
+ /** Pierwszy prompt użytkownika z seeda demo (do etykiety) albo `null`, gdy seed go nie ma. */
89
+ function seedPrompt(seed) {
90
+ for (const message of seed.messages) {
91
+ // Notka harnessu nie jest promptem człowieka — rola efektywna, nie `role`.
92
+ if (message.role !== 'user' || message.notice !== undefined)
93
+ continue;
94
+ for (const block of message.blocks) {
95
+ if (block.type === 'text' && block.text.trim() !== '')
96
+ return block.text;
97
+ }
98
+ }
99
+ return null;
100
+ }