@andorra-labs/code 0.1.16 → 0.1.17

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 (188) hide show
  1. package/dist/src/acp-agent.d.ts +6 -0
  2. package/dist/src/acp-agent.js +15 -4
  3. package/dist/src/agent-execution.js +11 -8
  4. package/dist/src/agent-mcp-catalog.js +1 -0
  5. package/dist/src/agent-mcp.d.ts +3 -0
  6. package/dist/src/agent-mcp.js +33 -1
  7. package/dist/src/andorra/entry.d.ts +10 -0
  8. package/dist/src/andorra/entry.js +18 -4
  9. package/dist/src/andorra/hosted.d.ts +2 -1
  10. package/dist/src/andorra/hosted.js +2 -1
  11. package/dist/src/andorra/notices.d.ts +5 -0
  12. package/dist/src/andorra/notices.js +7 -0
  13. package/dist/src/andorra/state.d.ts +3 -2
  14. package/dist/src/andorra/state.js +4 -4
  15. package/dist/src/andorra/terminal.js +7 -2
  16. package/dist/src/anthropic-credentials.js +2 -0
  17. package/dist/src/app-server/error.d.ts +5 -0
  18. package/dist/src/app-server/error.js +7 -0
  19. package/dist/src/app-server/protocol.d.ts +19 -44
  20. package/dist/src/app-server/protocol.js +5 -1
  21. package/dist/src/app-server/workspace.d.ts +89 -0
  22. package/dist/src/app-server/workspace.js +457 -11
  23. package/dist/src/app-server.d.ts +358 -32
  24. package/dist/src/app-server.js +2429 -509
  25. package/dist/src/bridge/cloud.d.ts +27 -0
  26. package/dist/src/bridge/cloud.js +187 -0
  27. package/dist/src/bridge/command.d.ts +30 -0
  28. package/dist/src/bridge/command.js +347 -0
  29. package/dist/src/bridge/control.d.ts +68 -0
  30. package/dist/src/bridge/control.js +233 -0
  31. package/dist/src/bridge/engines.d.ts +90 -0
  32. package/dist/src/bridge/engines.js +601 -0
  33. package/dist/src/bridge/host-ops.d.ts +9 -0
  34. package/dist/src/bridge/host-ops.js +129 -0
  35. package/dist/src/bridge/host.d.ts +47 -0
  36. package/dist/src/bridge/host.js +540 -0
  37. package/dist/src/bridge/link.d.ts +38 -0
  38. package/dist/src/bridge/link.js +508 -0
  39. package/dist/src/bridge/login-link.d.ts +29 -0
  40. package/dist/src/bridge/login-link.js +54 -0
  41. package/dist/src/bridge/protocol.d.ts +136 -0
  42. package/dist/src/bridge/protocol.js +11 -0
  43. package/dist/src/bridge/store.d.ts +12 -0
  44. package/dist/src/bridge/store.js +61 -0
  45. package/dist/src/bridge/wording.d.ts +6 -0
  46. package/dist/src/bridge/wording.js +10 -0
  47. package/dist/src/browser-server.js +7 -1
  48. package/dist/src/browser-ui/tokens.css +1 -1
  49. package/dist/src/change-authors.d.ts +41 -0
  50. package/dist/src/change-authors.js +146 -0
  51. package/dist/src/cli.js +182 -32
  52. package/dist/src/coding-tools.js +15 -15
  53. package/dist/src/command-screens.d.ts +6 -0
  54. package/dist/src/command-screens.js +14 -11
  55. package/dist/src/commands.d.ts +14 -2
  56. package/dist/src/compaction-phrases.js +1 -1
  57. package/dist/src/completion.js +82 -5
  58. package/dist/src/config.d.ts +71 -3
  59. package/dist/src/config.js +202 -77
  60. package/dist/src/deadline.js +13 -1
  61. package/dist/src/decision/checks.js +1 -1
  62. package/dist/src/decision/requestPhrases.js +0 -1
  63. package/dist/src/default-graph.js +1 -1
  64. package/dist/src/file-diff.d.ts +4 -0
  65. package/dist/src/file-diff.js +2 -1
  66. package/dist/src/github-app/agent-writes.d.ts +102 -0
  67. package/dist/src/github-app/agent-writes.js +320 -0
  68. package/dist/src/github-app/client.d.ts +349 -0
  69. package/dist/src/github-app/client.js +810 -0
  70. package/dist/src/github-app/event-source.d.ts +208 -0
  71. package/dist/src/github-app/event-source.js +684 -0
  72. package/dist/src/github-app/metrics.d.ts +32 -0
  73. package/dist/src/github-app/metrics.js +49 -0
  74. package/dist/src/github-app/review-loop.d.ts +274 -0
  75. package/dist/src/github-app/review-loop.js +1177 -0
  76. package/dist/src/github-app/review-node.d.ts +81 -0
  77. package/dist/src/github-app/review-node.js +205 -0
  78. package/dist/src/github-app/review-post.d.ts +73 -0
  79. package/dist/src/github-app/review-post.js +139 -0
  80. package/dist/src/github-app/review-text.d.ts +107 -0
  81. package/dist/src/github-app/review-text.js +1133 -0
  82. package/dist/src/github-app/review-threads.d.ts +47 -0
  83. package/dist/src/github-app/review-threads.js +107 -0
  84. package/dist/src/github-app/reviewer.d.ts +121 -0
  85. package/dist/src/github-app/reviewer.js +598 -0
  86. package/dist/src/github-app/store.d.ts +59 -0
  87. package/dist/src/github-app/store.js +148 -0
  88. package/dist/src/github-app/triggers.d.ts +141 -0
  89. package/dist/src/github-app/triggers.js +441 -0
  90. package/dist/src/github-names.d.ts +8 -0
  91. package/dist/src/github-names.js +8 -0
  92. package/dist/src/glob-search.d.ts +61 -0
  93. package/dist/src/glob-search.js +180 -0
  94. package/dist/src/graph-health.js +6 -1
  95. package/dist/src/graph-manager-chat.js +1 -1
  96. package/dist/src/graph-preview.d.ts +46 -0
  97. package/dist/src/graph-preview.js +55 -0
  98. package/dist/src/graph-provider-portability.js +2 -1
  99. package/dist/src/graph-runner.js +64 -3
  100. package/dist/src/graph-server.js +3 -3
  101. package/dist/src/graph-sync.js +3 -3
  102. package/dist/src/graph-ui/app.js +91 -7
  103. package/dist/src/graph-ui/icons.js +2 -1
  104. package/dist/src/graph-ui/studio.js +15 -1
  105. package/dist/src/graph-ui/tokens.css +1 -1
  106. package/dist/src/graphs.d.ts +34 -1
  107. package/dist/src/graphs.js +158 -14
  108. package/dist/src/image-input.d.ts +16 -0
  109. package/dist/src/image-input.js +41 -0
  110. package/dist/src/membership.d.ts +10 -0
  111. package/dist/src/membership.js +19 -4
  112. package/dist/src/model-health-cache.js +1 -1
  113. package/dist/src/model-metadata.d.ts +6 -0
  114. package/dist/src/model-metadata.js +35 -15
  115. package/dist/src/model-relay/local.d.ts +116 -0
  116. package/dist/src/model-relay/local.js +468 -0
  117. package/dist/src/model-relay/remote.d.ts +129 -0
  118. package/dist/src/model-relay/remote.js +252 -0
  119. package/dist/src/model-relay/runs.d.ts +34 -0
  120. package/dist/src/model-relay/runs.js +146 -0
  121. package/dist/src/model-relay/wire.d.ts +5 -0
  122. package/dist/src/model-relay/wire.js +5 -0
  123. package/dist/src/project-registry.d.ts +21 -0
  124. package/dist/src/project-registry.js +74 -0
  125. package/dist/src/provider-import.d.ts +0 -12
  126. package/dist/src/provider-import.js +7 -195
  127. package/dist/src/providers.d.ts +23 -2
  128. package/dist/src/providers.js +25 -4
  129. package/dist/src/pull-request-logs.d.ts +12 -1
  130. package/dist/src/pull-request-logs.js +14 -3
  131. package/dist/src/pull-requests.d.ts +327 -7
  132. package/dist/src/pull-requests.js +429 -51
  133. package/dist/src/react-runtime.js +1 -1
  134. package/dist/src/remote/engine-pool.d.ts +88 -4
  135. package/dist/src/remote/engine-pool.js +366 -89
  136. package/dist/src/remote/roots.d.ts +19 -0
  137. package/dist/src/remote/roots.js +45 -7
  138. package/dist/src/remote/types.d.ts +0 -44
  139. package/dist/src/run-control.d.ts +7 -0
  140. package/dist/src/run-control.js +23 -0
  141. package/dist/src/run-records.d.ts +7 -2
  142. package/dist/src/run-records.js +71 -6
  143. package/dist/src/runtime.d.ts +5 -1
  144. package/dist/src/runtime.js +10 -2
  145. package/dist/src/session-changes.d.ts +35 -0
  146. package/dist/src/session-changes.js +194 -6
  147. package/dist/src/session-monitor.js +2 -1
  148. package/dist/src/session-reaper.d.ts +1 -1
  149. package/dist/src/session-reaper.js +6 -1
  150. package/dist/src/session-summary.d.ts +2 -1
  151. package/dist/src/session-summary.js +2 -1
  152. package/dist/src/sessions.d.ts +11 -1
  153. package/dist/src/sessions.js +17 -4
  154. package/dist/src/skills/bundled/diagram/SKILL.md +5 -3
  155. package/dist/src/skills/bundled/graph-manager/SKILL.md +7 -4
  156. package/dist/src/skills/bundled/provenance.json +2 -2
  157. package/dist/src/skills/runtime-skills.js +1 -1
  158. package/dist/src/telemetry/emitter.d.ts +15 -0
  159. package/dist/src/telemetry/emitter.js +35 -1
  160. package/dist/src/telemetry/schema.d.ts +25 -2
  161. package/dist/src/telemetry/schema.js +52 -4
  162. package/dist/src/telemetry/surface.d.ts +2 -1
  163. package/dist/src/telemetry/surface.js +4 -1
  164. package/dist/src/terminal-ui.d.ts +1 -0
  165. package/dist/src/terminal-ui.js +10 -3
  166. package/dist/src/test-edit-guard.d.ts +7 -0
  167. package/dist/src/test-edit-guard.js +49 -1
  168. package/dist/src/timers.d.ts +2 -0
  169. package/dist/src/tools.js +59 -9
  170. package/package.json +6 -1
  171. package/dist/src/remote/cert.d.ts +0 -11
  172. package/dist/src/remote/cert.js +0 -87
  173. package/dist/src/remote/client.d.ts +0 -119
  174. package/dist/src/remote/client.js +0 -544
  175. package/dist/src/remote/command.d.ts +0 -4
  176. package/dist/src/remote/command.js +0 -194
  177. package/dist/src/remote/errors.d.ts +0 -11
  178. package/dist/src/remote/errors.js +0 -14
  179. package/dist/src/remote/network.d.ts +0 -22
  180. package/dist/src/remote/network.js +0 -102
  181. package/dist/src/remote/pairing.d.ts +0 -63
  182. package/dist/src/remote/pairing.js +0 -299
  183. package/dist/src/remote/pem.d.ts +0 -2
  184. package/dist/src/remote/pem.js +0 -7
  185. package/dist/src/remote/serve.d.ts +0 -68
  186. package/dist/src/remote/serve.js +0 -244
  187. package/dist/src/remote/server.d.ts +0 -21
  188. package/dist/src/remote/server.js +0 -406
@@ -2,7 +2,8 @@ import { createHash, randomUUID } from 'node:crypto';
2
2
  import { chmod, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, rmdir, unlink, writeFile } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { acquireSaveLock, SaveLockBusyError } from './save-lock.js';
5
- import { fileDiff } from './file-diff.js';
5
+ import { decodeText, fileDiff } from './file-diff.js';
6
+ import { carriedUserLines, lineMap, linesWords, markAuthors, rangesOf, userLines, userRemovedLines } from './change-authors.js';
6
7
  export const BASELINE_BYTE_LIMIT = 16 * 1024 * 1024;
7
8
  export const LIST_DIFF_LINES = 200;
8
9
  export const MAX_DIFF_LINES = 20_000;
@@ -124,7 +125,7 @@ async function readBlob(home, sessionId, hash) {
124
125
  return bytes;
125
126
  }
126
127
  async function collectBlobs(home, sessionId, state) {
127
- const referenced = new Set(state.changes.flatMap(change => change.baseline.kind === 'file' ? [change.baseline.hash] : []));
128
+ const referenced = new Set(state.changes.flatMap(change => [...(change.baseline.kind === 'file' ? [change.baseline.hash] : []), ...(change.agentSide ? [change.agentSide.hash] : [])]));
128
129
  let names;
129
130
  try {
130
131
  names = await readdir(blobFolder(home, sessionId));
@@ -280,6 +281,7 @@ function summary(change) {
280
281
  path: change.path, status: change.status, linesAdded: change.linesAdded, linesRemoved: change.linesRemoved,
281
282
  ...(change.binary ? { binary: true } : {}), ...(change.tooLarge ? { tooLarge: true } : {}),
282
283
  ...(change.modeChange ? { modeChange: change.modeChange } : {}), ...(change.lineEndings ? { lineEndings: change.lineEndings } : {}),
284
+ ...(change.editedByUser ? { editedByUser: change.editedByUser } : {}),
283
285
  undoable: change.baseline.kind !== 'unavailable', version: change.version,
284
286
  firstChangedAt: change.firstChangedAt, updatedAt: change.updatedAt,
285
287
  };
@@ -432,7 +434,7 @@ export class SessionChangeStore {
432
434
  await collectBlobs(this.home, sessionId, state);
433
435
  return snapshot(sessionId, state);
434
436
  }
435
- async recordWrite(sessionId, state, root, relative, before, created, review = true) {
437
+ async recordWrite(sessionId, state, root, relative, before, created, review = true, by = 'agent') {
436
438
  const target = path.join(root, ...relative.split('/'));
437
439
  if (before.kind === 'other')
438
440
  return false;
@@ -472,8 +474,15 @@ export class SessionChangeStore {
472
474
  const { binary: _binary, tooLarge: _tooLarge, modeChange: _modeChange, lineEndings: _lineEndings, diffLines: _diffLines, ...rest } = entry;
473
475
  const modeChange = modeChangeOf(entry.baseline, after);
474
476
  const lineEndings = lineEndingsOf(result, baselineBytes, after.kind === 'file' ? after.bytes : null);
475
- entry = { ...rest, ...measured(result), ...(modeChange ? { modeChange } : {}), ...(lineEndings ? { lineEndings } : {}),
476
- ...(result.kind === 'text' ? { diffLines: result.diff.hiddenLines } : {}),
477
+ // Who changed the file: a save from the Files tab marks it the person's, and an agent write to a file only they had
478
+ // changed makes it both of theirs. The record of what was last written follows either, so neither is "changed on disk".
479
+ const editedByUser = by === 'user' ? (index < 0 || entry.editedByUser === 'only' ? 'only' : 'also')
480
+ : entry.editedByUser === 'only' ? 'also' : entry.editedByUser;
481
+ const { editedByUser: _editedByUser, agentSide: _agentSide, ...unattributed } = rest;
482
+ const agentSide = await this.nextAgentSide(sessionId, entry, index < 0, by, before, after, baselineBytes);
483
+ entry = { ...unattributed, ...measured(result), ...(modeChange ? { modeChange } : {}), ...(lineEndings ? { lineEndings } : {}),
484
+ ...(result.kind === 'text' ? { diffLines: result.diff.hiddenLines } : {}), ...(editedByUser ? { editedByUser } : {}),
485
+ ...(agentSide ? { agentSide } : {}),
477
486
  written, status: statusOf(entry.baseline, after), version: state.revision + 1, updatedAt: now };
478
487
  if (index < 0)
479
488
  state.changes.push(entry);
@@ -481,6 +490,80 @@ export class SessionChangeStore {
481
490
  state.changes[index] = entry;
482
491
  return true;
483
492
  }
493
+ /**
494
+ * The agent's side of a file after a write (see `agentSide`). The person's first save over the agent's work keeps the
495
+ * file as the save found it; their later saves change nothing. An agent write to a file the person edited keeps what
496
+ * it wrote, and which of the person's lines it carried over. A file only the person changed has none.
497
+ */
498
+ async nextAgentSide(sessionId, entry, fresh, by, before, after, baselineBytes) {
499
+ try {
500
+ if (by === 'user') {
501
+ if (fresh || entry.agentSide || entry.editedByUser === 'only')
502
+ return entry.agentSide;
503
+ // A file already both of theirs without an agent side (a record from before the split, or one whose agent side
504
+ // was dropped) cannot be told apart: what the save found holds the person's earlier lines too.
505
+ if (entry.editedByUser === 'also')
506
+ return undefined;
507
+ const bytes = before.kind === 'file' ? before.bytes : before.kind === 'stored' ? await readBlob(this.home, sessionId, before.hash) : undefined;
508
+ if (!bytes || decodeText(bytes) === undefined)
509
+ return undefined;
510
+ const hash = hashOf(bytes);
511
+ await writeBlob(this.home, sessionId, hash, bytes);
512
+ return { hash, size: bytes.length };
513
+ }
514
+ if (!entry.agentSide && entry.editedByUser !== 'only')
515
+ return undefined;
516
+ if (after.kind !== 'file')
517
+ return undefined;
518
+ // What this write replaced must be what was last recorded: lines written some other way (the shell, another
519
+ // editor) are no one's we know, so the split is dropped rather than giving them to the person.
520
+ const beforeHash = before.kind === 'file' ? hashOf(before.bytes) : before.kind === 'stored' ? before.hash : undefined;
521
+ if (entry.written.kind !== 'file' || beforeHash !== entry.written.hash)
522
+ return undefined;
523
+ const afterText = decodeText(after.bytes);
524
+ const previous = entry.agentSide ? await readBlob(this.home, sessionId, entry.agentSide.hash) : baselineBytes;
525
+ const previousText = previous === null ? '' : decodeText(previous);
526
+ const beforeBytes = before.kind === 'file' ? before.bytes : before.kind === 'stored' ? await readBlob(this.home, sessionId, before.hash) : before.kind === 'absent' ? Buffer.alloc(0) : undefined;
527
+ const beforeText = beforeBytes === undefined ? undefined : decodeText(beforeBytes);
528
+ if (typeof afterText !== 'string' || typeof previousText !== 'string' || typeof beforeText !== 'string')
529
+ return undefined;
530
+ const baselineText = baselineBytes === null ? '' : decodeText(baselineBytes);
531
+ if (typeof baselineText !== 'string')
532
+ return undefined;
533
+ const carried = carriedUserLines(previousText, entry.agentSide?.userLines ?? [], beforeText, afterText);
534
+ const removedBefore = userRemovedLines(baselineText, previousText, beforeText, entry.agentSide?.userRemoved ?? []);
535
+ if (carried === undefined || removedBefore === undefined)
536
+ return undefined;
537
+ // Of the lines the person removed, those the agent's text still lacks stay theirs.
538
+ const gone = lineMap(baselineText, afterText)?.removed;
539
+ const removed = gone ? rangesOf([...removedBefore].filter(line => gone.has(line))) : [];
540
+ const hash = hashOf(after.bytes);
541
+ await writeBlob(this.home, sessionId, hash, after.bytes);
542
+ return { hash, size: after.bytes.length, ...(carried.length ? { userLines: carried } : {}), ...(removed.length ? { userRemoved: removed } : {}) };
543
+ }
544
+ catch {
545
+ return undefined;
546
+ }
547
+ }
548
+ /** The texts that tell the person's lines from the agent's, or undefined when the file's record cannot. */
549
+ async authorTexts(sessionId, stored, baselineBytes, current) {
550
+ if (!stored.editedByUser || current.kind !== 'file')
551
+ return undefined;
552
+ if (stored.editedByUser === 'also' && !stored.agentSide)
553
+ return undefined;
554
+ try {
555
+ const baseline = baselineBytes === null ? '' : decodeText(baselineBytes);
556
+ const agentBytes = stored.agentSide ? await readBlob(this.home, sessionId, stored.agentSide.hash) : baselineBytes;
557
+ const agent = agentBytes === null ? '' : decodeText(agentBytes);
558
+ const now = decodeText(current.bytes);
559
+ if (typeof baseline !== 'string' || typeof agent !== 'string' || typeof now !== 'string')
560
+ return undefined;
561
+ return { baseline, agent, current: now, carried: stored.agentSide?.userLines ?? [], carriedRemoved: stored.agentSide?.userRemoved ?? [] };
562
+ }
563
+ catch {
564
+ return undefined;
565
+ }
566
+ }
484
567
  async pending(sessionId) {
485
568
  return snapshot(sessionId, await readState(this.home, sessionId));
486
569
  }
@@ -536,6 +619,12 @@ export class SessionChangeStore {
536
619
  }
537
620
  result = fileDiff(baselineBytes, current.kind === 'file' ? current.bytes : null, { maxLines: Math.max(0, maxLines), maxChars: Math.max(0, maxChars), lineChars: LINE_CHARS });
538
621
  }
622
+ // Lines changed outside the recorded writes are no one's we know, so a file changed on disk is not split.
623
+ if (result.kind === 'text' && result.diff.hunks.length && sameAsWritten(stored.written, current)) {
624
+ const texts = await this.authorTexts(sessionId, stored, baselineBytes, current);
625
+ if (texts)
626
+ markAuthors(result.diff.hunks, texts.baseline, texts.agent, texts.current, texts.carried, texts.carriedRemoved);
627
+ }
539
628
  const { binary: _binary, tooLarge: _tooLarge, modeChange: _modeChange, lineEndings: _lineEndings, ...base } = summary(stored);
540
629
  const modeChange = modeChangeOf(stored.baseline, current);
541
630
  const lineEndings = lineEndingsOf(result, baselineBytes, current.kind === 'file' ? current.bytes : null);
@@ -608,6 +697,14 @@ export class SessionChangeStore {
608
697
  failed.push({ path: change.path, message: errorText(error) });
609
698
  continue;
610
699
  }
700
+ if (!force && change.editedByUser && sameAsWritten(change.written, current)) {
701
+ const lines = await this.userLinesNow(sessionId, change, current);
702
+ const yours = lines?.length ? ` ${linesWords(lines)}` : '';
703
+ conflicts.push({ path: change.path, reason: 'user-edited', ...(lines?.length ? { userLines: lines } : {}), message: change.editedByUser === 'only'
704
+ ? `You edited this file${yours ? ` (${yours.trim()})` : ''} in the Files tab. Undo puts back the file from before your edits.`
705
+ : `You also edited${yours || ' this file'} in the Files tab. Undo puts back the file from before the agent, which discards ${yours ? 'those lines' : 'your edits'} too.` });
706
+ continue;
707
+ }
611
708
  if (!force && !sameAsWritten(change.written, current)) {
612
709
  conflicts.push({ path: change.path, reason: 'changed-on-disk', message: current.kind === 'absent'
613
710
  ? 'The file was deleted after the agent last wrote it.'
@@ -617,7 +714,7 @@ export class SessionChangeStore {
617
714
  }
618
715
  ready.push({ change, current });
619
716
  }
620
- const blocked = !force && conflicts.some(conflict => conflict.reason === 'changed-on-disk');
717
+ const blocked = !force && conflicts.some(conflict => conflict.reason === 'changed-on-disk' || conflict.reason === 'user-edited');
621
718
  const reverted = [];
622
719
  if (!blocked) {
623
720
  if (ready.length)
@@ -641,6 +738,22 @@ export class SessionChangeStore {
641
738
  }
642
739
  return { ...snapshot(sessionId, state), reverted, conflicts, failed };
643
740
  }
741
+ /** The person's lines in the file now, as ranges, or undefined when they cannot be told apart. */
742
+ async userLinesNow(sessionId, change, current) {
743
+ let baselineBytes = null;
744
+ try {
745
+ if (change.baseline.kind === 'file')
746
+ baselineBytes = await readBlob(this.home, sessionId, change.baseline.hash);
747
+ }
748
+ catch {
749
+ return undefined;
750
+ }
751
+ const texts = await this.authorTexts(sessionId, change, baselineBytes, current);
752
+ if (!texts)
753
+ return undefined;
754
+ const lines = userLines(texts.agent, texts.current, texts.carried);
755
+ return lines ? rangesOf(lines) : undefined;
756
+ }
644
757
  async restore(sessionId, change, current) {
645
758
  const root = await realpath(change.root);
646
759
  const target = path.join(root, ...change.path.split('/'));
@@ -677,12 +790,87 @@ export class SessionChangeStore {
677
790
  throw error;
678
791
  }
679
792
  }
793
+ /**
794
+ * Saves a file from the Files tab, only if it still holds what the person loaded (`expectedHash`, the SHA-256 of its
795
+ * bytes), so a save never replaces a newer copy the agent wrote. The file is written in place (its mode, owner and
796
+ * links stay), under the same per-file lock the agent's writes take. With a session, the save is recorded as the
797
+ * person's in that session's changes: the record of the written content moves with it, so the file is not reported
798
+ * "changed on disk", and a file the agent never touched becomes a change of theirs.
799
+ */
800
+ async userWrite(input) {
801
+ const { sessionId, root, relative, bytes, expectedHash, onError } = input;
802
+ if (sessionId !== undefined)
803
+ sessionChangesId(sessionId);
804
+ const target = path.join(root, ...relative.split('/'));
805
+ if (!within(root, target) || target === root)
806
+ throw new Error('The path is outside the project');
807
+ const releaseFiles = await holdFiles(this.home, [fileLockKey(root, relative)]);
808
+ try {
809
+ const write = async () => {
810
+ const before = await observe(target, this.baselineLimit);
811
+ if (before.kind === 'absent')
812
+ return { written: false, reason: 'deleted' };
813
+ if (before.kind !== 'file')
814
+ return { written: false, reason: 'changed' };
815
+ const current = hashOf(before.bytes);
816
+ if (current !== expectedHash)
817
+ return { written: false, reason: 'changed', hash: current };
818
+ const hash = hashOf(bytes);
819
+ // The same bytes: nothing to write, and nothing the person changed.
820
+ if (hash === current)
821
+ return { written: true, hash, size: bytes.length };
822
+ await writeInPlace(target, bytes, before.bytes);
823
+ if (sessionId === undefined)
824
+ return { written: true, hash, size: bytes.length };
825
+ let changes;
826
+ try {
827
+ const state = await readState(this.home, sessionId);
828
+ if (await this.recordWrite(sessionId, state, root, relative, before, [], true, 'user')) {
829
+ state.revision += 1;
830
+ await writeState(this.home, sessionId, state);
831
+ await collectBlobs(this.home, sessionId, state);
832
+ changes = snapshot(sessionId, state);
833
+ }
834
+ }
835
+ catch (error) {
836
+ // The file is saved; only its place in the review could not be recorded.
837
+ onError?.(error);
838
+ await readState(this.home, sessionId).then(state => collectBlobs(this.home, sessionId, state)).catch(() => { });
839
+ }
840
+ return { written: true, hash, size: bytes.length, ...(changes ? { changes } : {}) };
841
+ };
842
+ return sessionId === undefined ? await write() : await withSession(this.home, sessionId, write);
843
+ }
844
+ finally {
845
+ await releaseFiles();
846
+ }
847
+ }
680
848
  async remove(sessionId) {
681
849
  await withSession(this.home, sessionId, async () => {
682
850
  await rm(sessionFolder(this.home, sessionId), { recursive: true, force: true });
683
851
  });
684
852
  }
685
853
  }
854
+ /**
855
+ * Writes a file in place (its mode, owner and links stay), never creating it: a file removed since it was checked is
856
+ * an error, not a new file. A write that fails part way puts the old bytes back.
857
+ */
858
+ async function writeInPlace(target, bytes, previous) {
859
+ const handle = await open(target, 'r+');
860
+ try {
861
+ try {
862
+ await handle.write(bytes, 0, bytes.length, 0);
863
+ await handle.truncate(bytes.length);
864
+ }
865
+ catch (error) {
866
+ await handle.write(previous, 0, previous.length, 0).then(() => handle.truncate(previous.length)).catch(() => { });
867
+ throw error;
868
+ }
869
+ }
870
+ finally {
871
+ await handle.close();
872
+ }
873
+ }
686
874
  async function nearestExisting(folder, root) {
687
875
  for (let current = folder;; current = path.dirname(current)) {
688
876
  try {
@@ -262,7 +262,8 @@ export async function getAgentSession(directory, sessionId, historyLimit = 0, hi
262
262
  throw new SessionQueryError('INVALID_SESSION_ID', 'sessionId must be a valid UUID.');
263
263
  nonnegativeInt(historyLimit, 'historyLimit', 20);
264
264
  nonnegativeInt(historyOffset, 'historyOffset', 100_000);
265
- const state = await loadSessionQueryState(directory, () => store.list());
265
+ // Asked for by id, a hidden session (a review run's) is found too; only the lists leave it out.
266
+ const state = await loadSessionQueryState(directory, () => store.list(undefined, { includeHidden: true }));
266
267
  const session = state.all.find(item => item.id === sessionId);
267
268
  if (!session)
268
269
  throw new SessionQueryError('SESSION_NOT_FOUND', 'Session ' + sessionId + ' was not found.');
@@ -5,4 +5,4 @@ export interface AutoArchivePlan {
5
5
  restore: string[];
6
6
  }
7
7
  export declare function idleFor(session: Pick<SavedSession, 'updatedAt'>, days: number, now: number): boolean;
8
- export declare function planAutoArchive(sessions: readonly Pick<SavedSession, 'id' | 'updatedAt' | 'archived' | 'autoArchived'>[], days: number | undefined, now: number, busy?: (id: string) => boolean): AutoArchivePlan;
8
+ export declare function planAutoArchive(sessions: readonly Pick<SavedSession, 'id' | 'updatedAt' | 'archived' | 'autoArchived' | 'pinned' | 'parentId' | 'ancestors'>[], days: number | undefined, now: number, busy?: (id: string) => boolean): AutoArchivePlan;
@@ -5,6 +5,11 @@ export function idleFor(session, days, now) {
5
5
  }
6
6
  export function planAutoArchive(sessions, days, now, busy = () => false) {
7
7
  const plan = { archive: [], restore: [] };
8
+ // A pin holds its whole family on the rail: the continuation of a pinned task is often the live conversation.
9
+ const pinned = new Set(sessions.filter(session => session.pinned === true && session.archived !== true).map(session => session.id));
10
+ const held = (session) => session.pinned === true
11
+ || (session.parentId !== undefined && pinned.has(session.parentId))
12
+ || (session.ancestors ?? []).some(id => pinned.has(id));
8
13
  for (const session of sessions) {
9
14
  if (busy(session.id))
10
15
  continue;
@@ -12,7 +17,7 @@ export function planAutoArchive(sessions, days, now, busy = () => false) {
12
17
  if (session.autoArchived === true && (days === undefined || !idleFor(session, days, now)))
13
18
  plan.restore.push(session.id);
14
19
  }
15
- else if (days !== undefined && idleFor(session, days, now))
20
+ else if (!held(session) && days !== undefined && idleFor(session, days, now))
16
21
  plan.archive.push(session.id);
17
22
  }
18
23
  return plan;
@@ -1,6 +1,7 @@
1
1
  import type { ProviderConfig } from './providers.js';
2
2
  import type { ModelAdapter } from './types.js';
3
- export declare const titleRequestSupported: (_provider: Pick<ProviderConfig, "type">) => boolean;
3
+ /** A relayed provider's model is on the desktop; a title is not worth a request there. */
4
+ export declare const titleRequestSupported: (provider: Pick<ProviderConfig, "type">) => boolean;
4
5
  export declare const SESSION_SUMMARY_TIMEOUT_MS = 120000;
5
6
  export declare const MAX_SESSION_TITLE_CHARS = 80;
6
7
  export declare function summarizeSessionPrompt(prompt: string, adapter: ModelAdapter, model: string, signal?: AbortSignal): Promise<string>;
@@ -1,6 +1,7 @@
1
1
  import { stripVTControlCharacters } from 'node:util';
2
2
  import { redactSecrets } from './secret-redaction.js';
3
- export const titleRequestSupported = (_provider) => true;
3
+ /** A relayed provider's model is on the desktop; a title is not worth a request there. */
4
+ export const titleRequestSupported = (provider) => provider.type !== 'relayed';
4
5
  export const SESSION_SUMMARY_TIMEOUT_MS = 120_000;
5
6
  export const MAX_SESSION_TITLE_CHARS = 80;
6
7
  const MAX_PROMPT_CHARS = 4_000;
@@ -36,10 +36,17 @@ export interface SavedSession {
36
36
  context?: SavedContextReading;
37
37
  archived?: boolean;
38
38
  autoArchived?: boolean;
39
+ /** Pinned by the user to the top of its project in the rail. Archiving clears it, and auto-archive leaves a pinned session alone. */
40
+ pinned?: boolean;
39
41
  renamed?: boolean;
40
42
  goal?: SessionGoal;
41
43
  jevEnabled?: boolean;
44
+ /** Set on a session another part of Andorra started for itself, such as a review run; such a session is kept out of every list. */
45
+ origin?: SessionOrigin;
42
46
  }
47
+ export type SessionOrigin = 'andorra-review';
48
+ /** A session the review loop's reviewer saved: it stays on disk and opens by id, but no task list, search or stats shows it. */
49
+ export declare const hiddenSession: (session: Pick<SavedSession, "origin">) => boolean;
43
50
  export declare const MAX_LINEAGE_ENTRIES = 64;
44
51
  export declare function canExtendLineage(ancestors: string[] | undefined): boolean;
45
52
  export declare function lineageThrough(ancestors: string[] | undefined, id: string): string[];
@@ -88,7 +95,10 @@ export declare class SessionStore {
88
95
  private readonly directory;
89
96
  constructor(directory: string);
90
97
  save(session: SavedSession, assertCanWrite?: () => void): Promise<void>;
91
- list(workspace?: string): Promise<SavedSession[]>;
98
+ /** The saved sessions, newest first. A hidden session (a review run's) is left out unless includeHidden is set. */
99
+ list(workspace?: string, options?: {
100
+ includeHidden?: boolean;
101
+ }): Promise<SavedSession[]>;
92
102
  stats(): Promise<SessionStats>;
93
103
  }
94
104
  export {};
@@ -20,6 +20,8 @@ export const sessionName = (prompt) => {
20
20
  const useful = words.filter(word => !/^(please|can|could|you|would|the|a|an|my|me|to|i|want|need|inside)$/i.test(word));
21
21
  return [...(useful.length ? useful : words).slice(0, 5), 'coding', 'task', 'session'].slice(0, Math.max(3, Math.min(5, useful.length || words.length))).map(word => word.slice(0, 32)).join(' ');
22
22
  };
23
+ /** A session the review loop's reviewer saved: it stays on disk and opens by id, but no task list, search or stats shows it. */
24
+ export const hiddenSession = (session) => session.origin !== undefined;
23
25
  export const MAX_LINEAGE_ENTRIES = 64;
24
26
  export function canExtendLineage(ancestors) {
25
27
  return (ancestors?.length ?? 0) < MAX_LINEAGE_ENTRIES;
@@ -31,7 +33,7 @@ export function lineagePoints(parent, parentUsage, parentTurns) {
31
33
  return [...(parent.lineage ?? []), { usage: parentUsage, turns: parentTurns }].slice(-MAX_LINEAGE_ENTRIES);
32
34
  }
33
35
  export function savedSessionFields(session) {
34
- const { version, id, name, workspace, updatedAt, history, usage, contextHistory, parentId, inheritedUsage, inheritedTurns, ancestors, lineage, projectId, trajectoryId, widgets, context, archived, autoArchived, renamed, goal, jevEnabled } = session;
36
+ const { version, id, name, workspace, updatedAt, history, usage, contextHistory, parentId, inheritedUsage, inheritedTurns, ancestors, lineage, projectId, trajectoryId, widgets, context, archived, autoArchived, pinned, renamed, goal, jevEnabled, origin } = session;
35
37
  return { version, id, name, workspace, updatedAt, history, usage, contextHistory, parentId, projectId, widgets,
36
38
  ...(context === undefined ? {} : { context }),
37
39
  ...(inheritedUsage === undefined ? {} : { inheritedUsage }),
@@ -40,9 +42,11 @@ export function savedSessionFields(session) {
40
42
  ...(lineage === undefined ? {} : { lineage }),
41
43
  ...(trajectoryId === undefined ? {} : { trajectoryId }),
42
44
  ...(archived === undefined ? {} : { archived }), ...(autoArchived === undefined ? {} : { autoArchived }),
45
+ ...(pinned === undefined ? {} : { pinned }),
43
46
  ...(renamed === undefined ? {} : { renamed }),
44
47
  ...(goal === undefined ? {} : { goal }),
45
- ...(jevEnabled === undefined ? {} : { jevEnabled }) };
48
+ ...(jevEnabled === undefined ? {} : { jevEnabled }),
49
+ ...(origin === undefined ? {} : { origin }) };
46
50
  }
47
51
  export const primaryDigest = (session) => createHash('sha256').update(JSON.stringify(savedSessionFields(session))).digest('hex');
48
52
  async function readRunUsage(path) {
@@ -77,6 +81,10 @@ export function carryRailOwnedFields(record, stored) {
77
81
  record.autoArchived = stored.autoArchived;
78
82
  else
79
83
  delete record.autoArchived;
84
+ if (stored.pinned !== undefined)
85
+ record.pinned = stored.pinned;
86
+ else
87
+ delete record.pinned;
80
88
  }
81
89
  export function displayHistory(history) {
82
90
  return history.map(turn => {
@@ -166,9 +174,11 @@ export function validSavedSession(value) {
166
174
  && (session.context.cacheRead === undefined || (Number.isSafeInteger(session.context.cacheRead) && session.context.cacheRead >= 0)))) &&
167
175
  (session.archived === undefined || typeof session.archived === 'boolean') &&
168
176
  (session.autoArchived === undefined || typeof session.autoArchived === 'boolean') &&
177
+ (session.pinned === undefined || typeof session.pinned === 'boolean') &&
169
178
  (session.renamed === undefined || typeof session.renamed === 'boolean') &&
170
179
  (session.goal === undefined || validSessionGoal(session.goal)) &&
171
180
  (session.jevEnabled === undefined || typeof session.jevEnabled === 'boolean') &&
181
+ (session.origin === undefined || session.origin === 'andorra-review') &&
172
182
  validUsage(session.usage) &&
173
183
  (session.inheritedUsage === undefined || (validUsage(session.inheritedUsage)
174
184
  && (!session.usage || (session.inheritedUsage.inputTokens <= session.usage.inputTokens
@@ -242,7 +252,8 @@ export class SessionStore {
242
252
  await mkdir(directory, { recursive: true, mode: 0o700 });
243
253
  await writeSessionSnapshot(join(directory, `${session.id}.json`), JSON.stringify(session) + '\n', assertCanWrite);
244
254
  }
245
- async list(workspace) {
255
+ /** The saved sessions, newest first. A hidden session (a review run's) is left out unless includeHidden is set. */
256
+ async list(workspace, options = {}) {
246
257
  const directory = join(this.directory, 'sessions');
247
258
  let names;
248
259
  try {
@@ -261,6 +272,8 @@ export class SessionStore {
261
272
  const value = JSON.parse(await readFile(join(directory, name), 'utf8'));
262
273
  if (!validSavedSession(value) || name !== `${value.id}.json` || workspace !== undefined && resolve(value.workspace) !== resolve(workspace))
263
274
  continue;
275
+ if (hiddenSession(value) && options.includeHidden !== true)
276
+ continue;
264
277
  sessions.push(value);
265
278
  }
266
279
  catch { }
@@ -287,7 +300,7 @@ export class SessionStore {
287
300
  continue;
288
301
  try {
289
302
  const value = JSON.parse(await readFile(join(directory, name), 'utf8'));
290
- if (!validSavedSession(value) || name !== `${value.id}.json`)
303
+ if (!validSavedSession(value) || name !== `${value.id}.json` || hiddenSession(value))
291
304
  continue;
292
305
  stats.total += 1;
293
306
  if (value.archived === true)
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: diagram
3
- description: "Draw a UML-style diagram in a reply instead of hand-typed arrows. Use when about to describe or explain a graph, process, routing, state machine, call sequence, data model or code structure to the user, including when reviewing an Andorra graph."
3
+ description: "Draw a UML-style diagram in a reply instead of hand-typed arrows. Use when about to describe or explain a graph, process, routing, state machine, call sequence, data model or code structure to the user. An Andorra graph is shown with the graphs tool's andorra_graph_show action instead."
4
4
  ---
5
5
 
6
6
  # Explain with a diagram
@@ -67,8 +67,10 @@ and the rest) do not.
67
67
  ### A workflow graph (state machine)
68
68
 
69
69
  Nodes are states, outcome routes are transitions, `[*]` is where a run starts and ends. Declare a readable
70
- name once with `state "..." as id`. This is the form for describing an Andorra graph: read it with the graph
71
- tools first (see the `graph-manager` skill), then draw each node and each route once.
70
+ name once with `state "..." as id`. An Andorra graph saved in the account is not drawn this way: the `graphs`
71
+ tool's `andorra_graph_show` action draws it as the Graph Editor does (see the `graph-manager` skill). Use a
72
+ state diagram for any other workflow, or for an Andorra graph only where that tool is not available, drawing
73
+ each node and each route once.
72
74
 
73
75
  ```mermaid
74
76
  stateDiagram-v2
@@ -58,9 +58,12 @@ What you need to know:
58
58
  Build it with the "Pull request with review fixes" pattern in `patterns.md`: that agent switches Auto-fix on
59
59
  itself and loops on the reviews, and the graph's entry stays where it is.
60
60
 
61
- Then sketch the nodes and routes. When the `diagram` skill is in your catalog, load it and draw the sketch
62
- as a state diagram instead; do the same whenever you describe or review an existing graph for the user.
63
- The plain-text form, for a host that has no such skill:
61
+ Then sketch the nodes and routes. To show the user a graph, call the `andorra_graph_show` action: with
62
+ `draftId` for a draft you are building, or with `id` (and `revision`, if not the latest) for a published graph.
63
+ The Andorra desktop app draws it in the chat the way the Graph Editor does, so do not also draw it as a
64
+ diagram or retype it as arrows. Do the same whenever you describe or review an existing graph for the user.
65
+ The reply's `note` says whether the host draws it. Where nothing does (a terminal, another MCP client), put
66
+ the reply's plain-text `sketch` in your message; it reads like this:
64
67
 
65
68
  ```
66
69
  plan (agent) --completed--> build (agent) --completed--> review (agent)
@@ -135,7 +138,7 @@ and the upsert reply's `placed` says where it went.
135
138
  - each route added or removed, and any change to the entry or the limits;
136
139
  - what a run of the graph will now do that it did not before, including anything the user did not ask for
137
140
  that the change brings with it;
138
- - the updated diagram, when the `diagram` skill is available.
141
+ - the updated graph, shown with `andorra_graph_show` and the draft's `draftId` (see section 3).
139
142
  3. `andorra_graph_publish`. A `REVISION_CONFLICT` means someone saved a newer revision: begin a new edit draft
140
143
  from the latest, reapply your changes, validate and publish again.
141
144
  4. If the user stops partway, `andorra_graph_discard` the draft.
@@ -714,7 +714,7 @@
714
714
  {
715
715
  "source": "src/skills/bundled/graph-manager/SKILL.md",
716
716
  "asset": "graph-manager/SKILL.md",
717
- "sha256": "fcb0b27d6db360f402b2f6cb4a4bbecbfe7f670eec6b91ccb74aedaf21bfcb91"
717
+ "sha256": "cedffd79e4e632d62426758d8b50b6f0e8b2f5e30cc764efd1ff20fa40f3d6db"
718
718
  },
719
719
  {
720
720
  "source": "src/skills/bundled/graph-manager/errors.md",
@@ -734,7 +734,7 @@
734
734
  {
735
735
  "source": "src/skills/bundled/diagram/SKILL.md",
736
736
  "asset": "diagram/SKILL.md",
737
- "sha256": "2840d736a0001ca82dc002056648ac2b73bdc3f6ce3f710a3d1832a548bbd4dc"
737
+ "sha256": "17fbc15678e4163538adb5c4e4f234bfe9a90f3f6ce35b6c87b8a7773c4fd731"
738
738
  }
739
739
  ],
740
740
  "additionalCopyright": [
@@ -22,7 +22,7 @@ const bundled = [
22
22
  { id: 'andorra:bug-report', path: 'bug-report/SKILL.md', description: "Report a bug in Andorra Code to the Andorra team: ask the user what went wrong, write it up, and send it once they approve. Use when the user types /bug-report or says something in Andorra Code itself is broken and wants it reported.", source: 'bundled' },
23
23
  { id: 'andorra:write-instructions', path: 'write-instructions/SKILL.md', description: "Create or improve a repository's agent instructions (ANDORRA.md or AGENTS.md): build and test commands, conventions, and rules agents must follow. Use when the user wants agents to work the way their team does, or asks to set up or tighten project instructions.", source: 'bundled' },
24
24
  { id: 'andorra:graph-manager', path: 'graph-manager/SKILL.md', description: "Design, create, edit, delete or restore Andorra Code graphs (multi-agent pipelines) from the user's requirements, through Andorra's graph tools. Use when the user wants a new graph, wants to change how an existing graph routes work, or wants a graph removed or brought back.", source: 'bundled' },
25
- { id: 'andorra:diagram', path: 'diagram/SKILL.md', description: "Draw a UML-style diagram in a reply instead of hand-typed arrows. Use when about to describe or explain a graph, process, routing, state machine, call sequence, data model or code structure to the user, including when reviewing an Andorra graph.", source: 'bundled', loadWhen: 'before describing or explaining a graph, workflow, state machine, call sequence or code structure to the user' },
25
+ { id: 'andorra:diagram', path: 'diagram/SKILL.md', description: "Draw a UML-style diagram in a reply instead of hand-typed arrows. Use when about to describe or explain a graph, process, routing, state machine, call sequence, data model or code structure to the user. An Andorra graph is shown with the graphs tool's andorra_graph_show action instead.", source: 'bundled', loadWhen: 'before describing or explaining a graph, workflow, state machine, call sequence or code structure to the user' },
26
26
  ];
27
27
  export function bundledSkillCatalog() {
28
28
  return bundled.map(({ id, description, path, requiredTools }) => ({ id, description, path, ...(requiredTools ? { requiredTools: [...requiredTools] } : {}) }));
@@ -45,5 +45,20 @@ export declare function emitRunStarted(context: TelemetryContext, input: RunDime
45
45
  }): Promise<number | undefined>;
46
46
  export declare function emitRunFinished(context: TelemetryContext, input: RunFinishInput): Promise<boolean>;
47
47
  export declare function emitInterruptedRun(context: TelemetryContext, record: Record<string, unknown>): Promise<boolean>;
48
+ export interface GitHubWatchInput {
49
+ minutes: number;
50
+ coverage: {
51
+ state: string;
52
+ prs: number;
53
+ calls: number;
54
+ }[];
55
+ wakeLatencies: number[];
56
+ }
57
+ /**
58
+ * One window of the GitHub App watcher's counts (ADR 0021, `github.watch`): per coverage state, how many PRs
59
+ * were watched and how many gh calls the watcher made for them, and the Auto-fix wake latencies in whole
60
+ * seconds. Built field by field: no PR, repository, account or session reaches the record.
61
+ */
62
+ export declare function emitGitHubWatch(context: TelemetryContext, input: GitHubWatchInput): Promise<boolean>;
48
63
  export declare function engineSpoolId(prefix: string): string;
49
64
  export declare function telemetryHome(home?: string): string;
@@ -5,7 +5,7 @@ import { classifyOutcome, classifyTaskCounts, stopReasonFor } from './classify.j
5
5
  import { createRunTelemetry, hasRunTelemetry, recordRunError, savingsFrom } from './capture.js';
6
6
  import { aggregateModelTuples } from './aggregate.js';
7
7
  import { ensureInstallId, telemetryDirectory } from './identity.js';
8
- import { TELEMETRY_PERMISSION_MODES, TELEMETRY_ROUTING, TELEMETRY_BOUNDS, bucketAppVersion, bucketArchitecture, bucketErrorCode, bucketGraph, bucketOperatingSystem, isMetadataTool, telemetryEventId, telemetryTimestamp, validateTelemetryEvent, } from './schema.js';
8
+ import { TELEMETRY_PERMISSION_MODES, TELEMETRY_ROUTING, TELEMETRY_BOUNDS, bucketAppVersion, bucketArchitecture, bucketErrorCode, bucketGraph, bucketOperatingSystem, isMetadataTool, TELEMETRY_GITHUB_COVERAGE, telemetryEventId, telemetrySchemaFor, telemetryTimestamp, validateTelemetryEvent, } from './schema.js';
9
9
  import { telemetryGate } from './gate.js';
10
10
  import { queueEvent } from './uploader.js';
11
11
  import { appVersion } from './version.js';
@@ -247,6 +247,40 @@ export async function emitInterruptedRun(context, record) {
247
247
  decisionRouting: typeof telemetry.decisionRouting === 'string' ? telemetry.decisionRouting : undefined,
248
248
  });
249
249
  }
250
+ /**
251
+ * One window of the GitHub App watcher's counts (ADR 0021, `github.watch`): per coverage state, how many PRs
252
+ * were watched and how many gh calls the watcher made for them, and the Auto-fix wake latencies in whole
253
+ * seconds. Built field by field: no PR, repository, account or session reaches the record.
254
+ */
255
+ export async function emitGitHubWatch(context, input) {
256
+ let queued = false;
257
+ await safely(async () => {
258
+ const watched = TELEMETRY_GITHUB_COVERAGE.flatMap(coverage => {
259
+ const record = input.coverage.find(entry => entry.state === coverage);
260
+ if (!record || record.prs < 1)
261
+ return [];
262
+ return [{ coverage: coverage, prs: Math.min(record.prs, TELEMETRY_BOUNDS.watchedPrs), ghCalls: Math.max(0, Math.min(record.calls, TELEMETRY_BOUNDS.counter)) }];
263
+ });
264
+ if (!watched.length)
265
+ return;
266
+ const resolved = await identityFor(context);
267
+ if (!resolved)
268
+ return;
269
+ const latencies = input.wakeLatencies.slice(0, TELEMETRY_BOUNDS.wakeLatencies)
270
+ .map(seconds => Math.max(0, Math.min(TELEMETRY_BOUNDS.wakeLatencySeconds, Math.round(seconds))));
271
+ const event = {
272
+ ...resolved.identity,
273
+ schema: telemetrySchemaFor('github.watch'),
274
+ event: 'github.watch',
275
+ minutes: Math.max(1, Math.min(TELEMETRY_BOUNDS.watchMinutes, Math.round(input.minutes))),
276
+ watched,
277
+ ...(latencies.length ? { wakeLatencies: latencies } : {}),
278
+ };
279
+ await queue(context, resolved.generation, event);
280
+ queued = true;
281
+ });
282
+ return queued;
283
+ }
250
284
  export function engineSpoolId(prefix) {
251
285
  return `${prefix}-${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
252
286
  }