sideby 0.28.2 → 0.29.0

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 (47) hide show
  1. package/dist/build.json +1 -1
  2. package/dist/src/cli/commands.d.ts +2 -0
  3. package/dist/src/cli/commands.js +34 -7
  4. package/dist/src/cli/json-schemas.js +15 -0
  5. package/dist/src/cli/main.js +1 -1
  6. package/dist/src/core/handoff-chain.d.ts +2 -0
  7. package/dist/src/core/handoff-chain.js +4 -2
  8. package/dist/src/core/handoff-doctor.d.ts +8 -3
  9. package/dist/src/core/handoff-doctor.js +9 -1
  10. package/dist/src/core/handoff-enable.d.ts +2 -0
  11. package/dist/src/core/handoff-enable.js +7 -1
  12. package/dist/src/core/handoff-status.js +4 -1
  13. package/dist/src/core/live-sessions.d.ts +2 -0
  14. package/dist/src/core/messages.d.ts +2 -0
  15. package/dist/src/core/messages.js +3 -3
  16. package/dist/src/core/run-link.d.ts +6 -1
  17. package/dist/src/core/run-link.js +62 -22
  18. package/dist/src/core/session-handoffs.d.ts +22 -0
  19. package/dist/src/core/session-handoffs.js +110 -0
  20. package/dist/src/core/session-select.d.ts +18 -3
  21. package/dist/src/core/session-select.js +82 -8
  22. package/dist/src/families/claude/handoff.js +10 -1
  23. package/dist/src/families/claude/quota.js +3 -2
  24. package/dist/src/handoff/hook.d.ts +28 -1
  25. package/dist/src/handoff/hook.js +83 -5
  26. package/dist/src/handoff/messages.d.ts +5 -0
  27. package/dist/src/handoff/messages.js +7 -0
  28. package/dist/src/panel/handler.js +3 -1
  29. package/dist/src/panel/i18n.d.ts +3 -0
  30. package/dist/src/panel/i18n.js +6 -0
  31. package/dist/src/panel/page-script.js +10 -5
  32. package/dist/src/quota/claude-statusline.d.ts +5 -0
  33. package/dist/src/quota/claude-statusline.js +61 -7
  34. package/dist/src/runtime.js +2 -2
  35. package/dist/src/types.d.ts +10 -2
  36. package/package.json +4 -3
  37. package/schemas/handoff-setup.json +4 -0
  38. package/schemas/messages.json +4 -0
  39. package/schemas/quota-setup.json +4 -0
  40. package/schemas/send.json +4 -0
  41. package/schemas/sessions-copy.json +4 -0
  42. package/schemas/sessions-open-run.json +4 -0
  43. package/schemas/sessions.json +7 -0
  44. package/skills/sideby/SKILL.md +2 -2
  45. package/skills/sideby/references/handoff.md +1 -1
  46. package/skills/sideby/references/quota.md +2 -0
  47. package/skills/sideby/references/sessions.md +1 -1
package/dist/build.json CHANGED
@@ -1 +1 @@
1
- {"id":"20261028T152431-425962"}
1
+ {"id":"20261029T062926-04866c"}
@@ -130,6 +130,8 @@ export declare function cmdConfig(a: ParsedArgs, io: Io): Promise<number>;
130
130
  * `sideby sessions open-run <account|session-id>` opens the Run Board of one (spec §3.32 step 2b).
131
131
  */
132
132
  export declare function cmdSessions(a: ParsedArgs, io: Io, runtime?: Runtime): Promise<number>;
133
+ /** The line that says a session id was followed along its Handoff chain (ADR-0057). */
134
+ export declare function handedOverLine(from: string, label: string, doing: string): string;
133
135
  export declare function cmdHistory(a: ParsedArgs, io: Io): Promise<number>;
134
136
  export interface SendArgs extends ParsedArgs {
135
137
  /** Every `--image` given, in order (main.ts collects them; parseArgs keeps only the last). */
@@ -636,7 +636,7 @@ export async function cmdNext(a, io) {
636
636
  const runCmd = ['sideby run', plan.pick, ...(a.rest.length ? ['--', ...a.rest.map(shellQuote)] : [])].join(' ');
637
637
  if (!plan.hasQuota) {
638
638
  // Without any Quota the pick is a guess, often the Account that just ran out: recommend nothing, start nothing.
639
- const setup = (await rt.quotaSetups()).some((s) => s.family === family && s.plan.status === 'ready');
639
+ const setup = (await rt.quotaSetups()).some((s) => s.family === family && s.plan.status === 'ready' && !s.plan.upgrade);
640
640
  io.err(c.yellow(`\nno ${family} account has quota data yet, so sideby cannot tell which one has room; ${setup ? `turn it on with \`sideby quota setup ${family}\`, or ` : ''}start one yourself, for example \`${runCmd}\`.`));
641
641
  return 1;
642
642
  }
@@ -1094,7 +1094,8 @@ async function runSetup(a, io, rt, command, sub, familyId, setup) {
1094
1094
  else {
1095
1095
  io.out(plan.message);
1096
1096
  if (plan.status === 'ready') {
1097
- io.out(`\n${setup.summary}\nChange to ${tildify(plan.file, rt.paths.home)}:\n`);
1097
+ // An upgrade's message already says what the one added key does; the summary describes the first setup.
1098
+ io.out(`\n${plan.upgrade ? '' : `${setup.summary}\n`}Change to ${tildify(plan.file, rt.paths.home)}:\n`);
1098
1099
  io.out(plan.diff);
1099
1100
  io.out(c.cyan(`\nApply it with \`sideby ${command} setup ${familyId} --yes\`; undo any time with \`sideby ${command} teardown ${familyId}\`.`));
1100
1101
  }
@@ -2990,8 +2991,11 @@ export async function cmdSessions(a, io, runtime) {
2990
2991
  const rt = runtime ?? (await createRuntime());
2991
2992
  const { listLiveSessions, sessionLabel } = await import('../core/live-sessions.js');
2992
2993
  const { withRuns } = await import('../core/run-link.js');
2994
+ const { readHandoffChains, withHandoffs } = await import('../core/session-handoffs.js');
2993
2995
  const r = await listLiveSessions(rt, first ? { only: first } : {});
2994
- const sessions = await withRuns(rt.env, rt.paths.home, r.sessions);
2996
+ // Where an Auto Handoff chain led to a Session, its earlier ids; the Run Link falls back to them (ADR-0057).
2997
+ const handed = withHandoffs(await readHandoffChains(rt.paths.stateDir), r.sessions);
2998
+ const sessions = await withRuns(rt.env, rt.paths.home, handed);
2995
2999
  if (a.flags.has('json')) {
2996
3000
  json(io, { sessions, problems: r.problems });
2997
3001
  return 0;
@@ -3033,6 +3037,10 @@ export async function cmdSessions(a, io, runtime) {
3033
3037
  io.out(c.dim('Copy one for another AI: sideby sessions copy <account|session-id>'));
3034
3038
  return 0;
3035
3039
  }
3040
+ /** The line that says a session id was followed along its Handoff chain (ADR-0057). */
3041
+ export function handedOverLine(from, label, doing) {
3042
+ return c.dim(`${from.slice(0, 8)} was handed over to ${label}; ${doing}`);
3043
+ }
3036
3044
  /** Prints the listing's problems to stderr unless the output is JSON. */
3037
3045
  const listedProblems = (a, io) => (l) => {
3038
3046
  if (!a.flags.has('json'))
@@ -3046,7 +3054,7 @@ async function sessionsOpenRun(a, args, io, runtime) {
3046
3054
  const rt = runtime ?? (await createRuntime());
3047
3055
  const { selectSession } = await import('../core/session-select.js');
3048
3056
  const { openRunBoard } = await import('../core/run-link.js');
3049
- const { session: s } = await selectSession(rt, target, {
3057
+ const { session: s, handedOverFrom } = await selectSession(rt, target, {
3050
3058
  next: { verb: 'open the run report of', command: (id) => `sideby sessions open-run ${id}` },
3051
3059
  onListed: listedProblems(a, io),
3052
3060
  });
@@ -3054,9 +3062,17 @@ async function sessionsOpenRun(a, args, io, runtime) {
3054
3062
  const r = await openRunBoard(rt, s.sessionId);
3055
3063
  const board = tildify(r.board, rt.paths.home);
3056
3064
  if (a.flags.has('json')) {
3057
- json(io, { opened: true, board, sessionId: s.sessionId, label: s.label });
3065
+ json(io, {
3066
+ opened: true,
3067
+ board,
3068
+ sessionId: s.sessionId,
3069
+ label: s.label,
3070
+ ...(handedOverFrom ? { handedOverFrom } : {}),
3071
+ });
3058
3072
  return 0;
3059
3073
  }
3074
+ if (handedOverFrom)
3075
+ io.out(handedOverLine(handedOverFrom, s.label, 'opening its run report'));
3060
3076
  io.out(`${c.green('✓')} opened the run report of ${c.bold(s.label)}`);
3061
3077
  io.out(c.dim(` ${board}`));
3062
3078
  return 0;
@@ -3073,13 +3089,22 @@ async function sessionsCopy(a, args, io, runtime) {
3073
3089
  const { sessionCopyText } = await import('../core/live-sessions.js');
3074
3090
  const { copyToClipboard } = await import('../core/live-sessions-copy.js');
3075
3091
  const { selectSession } = await import('../core/session-select.js');
3076
- const { session: s } = await selectSession(rt, target, { onListed: listedProblems(a, io) });
3092
+ const { session: s, handedOverFrom } = await selectSession(rt, target, { onListed: listedProblems(a, io) });
3077
3093
  const text = sessionCopyText(s, as, lang);
3078
3094
  const program = await copyToClipboard(text, rt.env);
3079
3095
  if (a.flags.has('json')) {
3080
- json(io, { copied: program !== null, as, text, sessionId: s.sessionId, label: s.label });
3096
+ json(io, {
3097
+ copied: program !== null,
3098
+ as,
3099
+ text,
3100
+ sessionId: s.sessionId,
3101
+ label: s.label,
3102
+ ...(handedOverFrom ? { handedOverFrom } : {}),
3103
+ });
3081
3104
  return 0;
3082
3105
  }
3106
+ if (handedOverFrom)
3107
+ io.out(handedOverLine(handedOverFrom, s.label, 'copying that one'));
3083
3108
  const what = as === 'reference' ? 'a reference to' : as === 'id' ? 'the id of' : 'the resume command of';
3084
3109
  if (program) {
3085
3110
  io.out(`${c.green('✓')} copied ${what} ${c.bold(s.label)}; paste it into the other AI`);
@@ -3442,6 +3467,8 @@ export async function cmdSend(a, io) {
3442
3467
  return 0;
3443
3468
  }
3444
3469
  const home = rt.paths.home;
3470
+ if (r.handedOverFrom)
3471
+ io.out(handedOverLine(r.handedOverFrom, r.to, 'sending there'));
3445
3472
  if (r.status === 'delivered') {
3446
3473
  io.out(`${c.green('✓')} delivered to ${c.bold(r.to)} (message ${r.id})`);
3447
3474
  if (r.note)
@@ -267,6 +267,9 @@ const QuotaSetupPlan = Type.Object({
267
267
  file: Str,
268
268
  diff: Str,
269
269
  message: Str,
270
+ upgrade: Type.Optional(Type.Boolean({
271
+ description: 'With `ready`: the setup is already on and only an addition from a newer sideby is missing (Claude: `statusLine.refreshInterval`).',
272
+ })),
270
273
  });
271
274
  const ShellInitFiles = Type.Array(Type.Object({
272
275
  shell: Type.Union([Type.Literal('zsh'), Type.Literal('bash')]),
@@ -433,6 +436,9 @@ const MessageReceipt = Type.Object({
433
436
  description: 'true while a delivered Message waits for the user to approve it in the target terminal (ADR-0045); dropped once it is read, and after 6 minutes unread the status becomes paste-needed.',
434
437
  })),
435
438
  sentAt: Str,
439
+ handedOverFrom: Type.Optional(Type.String({
440
+ description: 'The session id that was named, when an Auto Handoff chain led from it to this target (ADR-0057).',
441
+ })),
436
442
  });
437
443
  const IndexState = Type.Union(['building', 'ready', 'off', 'unavailable'].map((k) => Type.Literal(k)), {
438
444
  description: '`building`: the History Index is still reading files (what is built answers already); `off`: config `history.index` is false or the index file could not be opened, so only titles and folders are searched; `unavailable`: this Node has no `node:sqlite`.',
@@ -903,6 +909,9 @@ export const OUTPUT_SCHEMAS = {
903
909
  }),
904
910
  family: Str,
905
911
  sessionId: Type.String({ description: "The host's own session id." }),
912
+ handedOverFrom: Type.Optional(Type.Array(Str, {
913
+ description: "When an Auto Handoff chain led to this session: the earlier hops' session ids, oldest first (ADR-0057).",
914
+ })),
906
915
  title: Type.String({
907
916
  description: "The host's own title for the session, or its working directory name when the host gives none; may be empty.",
908
917
  }),
@@ -960,6 +969,9 @@ export const OUTPUT_SCHEMAS = {
960
969
  board: Type.String({ description: 'The Run Board file opened, with the home folder as ~.' }),
961
970
  sessionId: Str,
962
971
  label: Type.String({ description: 'The Session Label of the session whose run report was opened.' }),
972
+ handedOverFrom: Type.Optional(Type.String({
973
+ description: 'The session id that was named, when an Auto Handoff chain led from it to this session (ADR-0057).',
974
+ })),
963
975
  }, { title: 'sideby sessions open-run --json' }),
964
976
  'sessions-copy': Type.Object({
965
977
  schemaVersion: Version,
@@ -970,6 +982,9 @@ export const OUTPUT_SCHEMAS = {
970
982
  text: Type.String({ description: 'The text copied, also when it could not be.' }),
971
983
  sessionId: Str,
972
984
  label: Type.String({ description: 'The Session Label of the session copied.' }),
985
+ handedOverFrom: Type.Optional(Type.String({
986
+ description: 'The session id that was named, when an Auto Handoff chain led from it to this session (ADR-0057).',
987
+ })),
973
988
  }, { title: 'sideby sessions copy --json' }),
974
989
  history: Type.Object({
975
990
  schemaVersion: Version,
@@ -690,7 +690,7 @@ export async function main(argv) {
690
690
  // so a Host never gets a version error from its own hook (spec §3.17).
691
691
  if (first === 'handoff-hook') {
692
692
  const { runHandoffHook } = await import('../handoff/hook.js');
693
- return runHandoffHook(rest, process.env, process.stdin, process.stdout);
693
+ return runHandoffHook(rest, process.env, process.stdin, process.stdout, process.stderr);
694
694
  }
695
695
  // Network Guard's hook runs before every prompt and tool call it guards (spec §3.35); same fast path.
696
696
  if (first === 'network-hook') {
@@ -94,6 +94,8 @@ export declare const FILES: {
94
94
  readonly waiting: 'waiting.json';
95
95
  readonly chain: 'chain.json';
96
96
  readonly run: (runId: string) => string;
97
+ /** `{ id }` of the run's current `IdleWatch` (ADR-0056): a later one replaces it, and the earlier one then ends. */
98
+ readonly watch: (runId: string) => string;
97
99
  };
98
100
  /** A short random id for a chain or a run: safe in file names and environment values. */
99
101
  export declare function newId(): string;
@@ -1,8 +1,8 @@
1
1
  // The files one Handoff chain keeps under `<state>/handoffs/<chain>/` (spec §3.17). The handoff hook runs on every
2
2
  // tool call, so this module imports only Node built-ins and leaf modules (never the Runtime or a Family index).
3
3
  // The parent `sideby run` writes `plan.json`, `chain.json` and, while a session waits for a reset, `waiting.json`; the
4
- // hook writes `run-<id>.json` and `ready.json`; `sideby handoff ready` writes `request.json` (`ready.json` while the
5
- // session waits). Every file is mode 600 in a mode 700 directory.
4
+ // hook writes `run-<id>.json`, `ready.json` and, for Claude's background `IdleWatch`, `watch-<id>.json`; `sideby
5
+ // handoff ready` writes `request.json` (`ready.json` while the session waits). Every file is mode 600 in a mode 700 directory.
6
6
  import { randomBytes } from 'node:crypto';
7
7
  import { chmod, mkdir, readFile } from 'node:fs/promises';
8
8
  import { join } from 'node:path';
@@ -22,6 +22,8 @@ export const FILES = {
22
22
  waiting: 'waiting.json',
23
23
  chain: 'chain.json',
24
24
  run: (runId) => `run-${runId}.json`,
25
+ /** `{ id }` of the run's current `IdleWatch` (ADR-0056): a later one replaces it, and the earlier one then ends. */
26
+ watch: (runId) => `watch-${runId}.json`,
25
27
  };
26
28
  /** A short random id for a chain or a run: safe in file names and environment values. */
27
29
  export function newId() {
@@ -1,5 +1,7 @@
1
- import type { Account, Finding } from '../types.ts';
1
+ import type { Account, Finding, QuotaSetupPlan } from '../types.ts';
2
2
  import type { HandoffSettings } from './config.ts';
3
+ /** What Claude's quota setup plan says about the tap, for `claudeTap`. */
4
+ export declare function tapState(plan: QuotaSetupPlan): 'on' | 'off' | 'stale';
3
5
  export declare function handoffFindings(input: {
4
6
  settings: HandoffSettings;
5
7
  /** Family ids this Doctor run checks. */
@@ -7,7 +9,10 @@ export declare function handoffFindings(input: {
7
9
  /** Every Account on disk, to resolve `order` entries in any Family. */
8
10
  accounts: readonly Account[];
9
11
  aliases: Readonly<Record<string, string>>;
10
- /** Whether Claude's quota tap is on; undefined when Claude is not part of the run. */
11
- claudeTap?: boolean;
12
+ /**
13
+ * Claude's quota tap: on, off, or on without the refresh that keeps it current while a session idles (`stale`,
14
+ * ADR-0056); undefined when Claude is not part of the run.
15
+ */
16
+ claudeTap?: 'on' | 'off' | 'stale';
12
17
  home: string;
13
18
  }): Promise<Finding[]>;
@@ -1,6 +1,12 @@
1
1
  // Doctor warnings for Auto Handoff (spec §3.17): only when `handoff.auto` is on, never a failure, never fixed.
2
2
  import { join } from 'node:path';
3
3
  import { statOrNull } from './fs-safe.js';
4
+ /** What Claude's quota setup plan says about the tap, for `claudeTap`. */
5
+ export function tapState(plan) {
6
+ if (plan.status === 'enabled')
7
+ return 'on';
8
+ return plan.status === 'ready' && plan.upgrade ? 'stale' : 'off';
9
+ }
4
10
  export async function handoffFindings(input) {
5
11
  const { settings: s } = input;
6
12
  if (!s.auto)
@@ -17,8 +23,10 @@ export async function handoffFindings(input) {
17
23
  fixable: false,
18
24
  });
19
25
  const has = (family) => input.families.includes(family) && input.accounts.some((a) => a.family === family);
20
- if (has('claude') && input.claudeTap === false)
26
+ if (has('claude') && input.claudeTap === 'off')
21
27
  out.push(warn('claude:main', 'handoff.no-quota-tap', 'Auto Handoff is on, but Claude Code reports no quota to sideby, so Claude sessions never hand over', 'run `sideby quota setup claude` (it shows the change first)'));
28
+ if (has('claude') && input.claudeTap === 'stale')
29
+ out.push(warn('claude:main', 'handoff.quota-refresh', "Auto Handoff is on, but Claude's quota stops updating while a session waits on background agents, so such a session hands over late", 'run `sideby quota setup claude` (it shows the change first)'));
22
30
  if (has('grok') && !(await statOrNull(join(input.home, '.grok', 'hooks', 'sideby-handoff.json'))))
23
31
  out.push(warn('grok:main', 'handoff.setup-missing', 'Auto Handoff is on, but Grok has no sideby hook file, so a Grok session that hits its limit cannot hand over', 'run `sideby handoff setup grok`, then `sideby doctor grok --fix` to copy it to every Grok account'));
24
32
  const refs = new Set(input.accounts.map((a) => a.ref));
@@ -8,6 +8,8 @@ export interface EnableStep {
8
8
  diff?: string;
9
9
  /** For `copy`: the Accounts that get the file. */
10
10
  accounts?: string[];
11
+ /** For `quota`: the display is on, and the step only adds what keeps it current (Claude's refresh, ADR-0056). */
12
+ upgrade?: true;
11
13
  }
12
14
  export interface EnableManual {
13
15
  /** `codex-trust`: each Codex account trusts the hooks once, in `/hooks`; `setup-blocked`: a setup that cannot be applied. */
@@ -87,7 +87,13 @@ export async function planHandoffEnable(rt, opts = {}) {
87
87
  .plan()
88
88
  .catch(() => null);
89
89
  if (plan?.status === 'ready')
90
- steps.push({ id: 'quota', family: f.family, file: plan.file, diff: plan.diff });
90
+ steps.push({
91
+ id: 'quota',
92
+ family: f.family,
93
+ file: plan.file,
94
+ diff: plan.diff,
95
+ ...(plan.upgrade ? { upgrade: true } : {}),
96
+ });
91
97
  else if (plan?.status === 'blocked')
92
98
  manual.push({ id: 'setup-blocked', family: f.family, message: plan.message });
93
99
  }
@@ -43,7 +43,10 @@ export async function handoffStatus(rt) {
43
43
  .plan()
44
44
  .catch(() => null);
45
45
  if (plan?.status !== 'enabled') {
46
- problems.push(`${f.title} reports no quota to sideby yet`);
46
+ // On, but without the refresh that keeps the reading current while a session idles (ADR-0056).
47
+ problems.push(plan?.status === 'ready' && plan.upgrade
48
+ ? `${f.title}'s quota stops updating while a session waits on background agents, so it hands over late`
49
+ : `${f.title} reports no quota to sideby yet`);
47
50
  steps.push(`sideby quota setup ${f.id}`);
48
51
  }
49
52
  }
@@ -30,6 +30,8 @@ export interface LiveSession {
30
30
  reference: string;
31
31
  /** The Run of a local orchestrator the Session works for (spec §3.32 step 2b); set by `withRuns`, not the readers. */
32
32
  run?: SessionRun;
33
+ /** Earlier hops' session ids, oldest first, when an Auto Handoff chain led to this Session (ADR-0057); set by `withHandoffs`. */
34
+ handedOverFrom?: string[];
33
35
  }
34
36
  export interface LiveSessionsResult {
35
37
  sessions: LiveSession[];
@@ -25,6 +25,8 @@ export interface MessageReceipt {
25
25
  /** Delivered, but the target shows it only once the user approves it in its terminal (ADR-0045). */
26
26
  needsApproval?: boolean;
27
27
  sentAt: string;
28
+ /** The session id the sender named, when an Auto Handoff chain led from it to this target (ADR-0057). */
29
+ handedOverFrom?: string;
28
30
  }
29
31
  export interface SendOptions {
30
32
  text: string;
@@ -199,7 +199,7 @@ export async function sendMessage(rt, target, opts, deps = {}) {
199
199
  async function sendOpened(rt, target, opts, deps) {
200
200
  const { text, lang } = opts;
201
201
  const procDeps = deps.procs ?? systemDeps(rt.env);
202
- const { session: to, listed } = await selectSession(rt, target, {
202
+ const { session: to, listed, handedOverFrom, } = await selectSession(rt, target, {
203
203
  next: { verb: 'send to', command: (id) => `sideby send ${id} "<text>"` },
204
204
  deps: procDeps,
205
205
  });
@@ -254,7 +254,7 @@ async function sendOpened(rt, target, opts, deps) {
254
254
  // Without a receipt sideby could not follow it later, so it does not deliver it; the Message file is kept.
255
255
  receipt.status = 'paste-needed';
256
256
  receipt.note = `sideby saved the message file, but could not save its status (${err.code ?? err.message}). Paste the line into the session's tab`;
257
- return publicReceipt(receipt);
257
+ return { ...publicReceipt(receipt), ...(handedOverFrom ? { handedOverFrom } : {}) };
258
258
  }
259
259
  let result;
260
260
  try {
@@ -279,7 +279,7 @@ async function sendOpened(rt, target, opts, deps) {
279
279
  else
280
280
  receipt.note = `${receipt.note ?? 'paste the line into its tab'} (sideby also could not save the message status: ${why})`;
281
281
  }
282
- return publicReceipt(receipt);
282
+ return { ...publicReceipt(receipt), ...(handedOverFrom ? { handedOverFrom } : {}) };
283
283
  }
284
284
  async function deliver(rt, to, acct, r, text, procDeps, deps) {
285
285
  if (to.guessed)
@@ -59,9 +59,14 @@ export declare function stillTheBoard(board: string, check: BoardCheck, id: Boar
59
59
  export declare function byRole(list: readonly RunEntry[]): RunEntry[];
60
60
  /** The Run each of `sessionIds` works for; an empty map when there is no index, no boards folder or no match. */
61
61
  export declare function runsForSessions(env: Env, home: string, sessionIds: readonly string[], uid?: number): Promise<Map<string, SessionRun>>;
62
- /** The same Sessions, each with `run` where the Session Index ties it to a Run. */
62
+ /**
63
+ * The same Sessions, each with `run` where the Session Index ties it to a Run: by its own id, else by the ids it was
64
+ * handed over from, newest first, so a Run Board stays linked after its coordinator moves to another Account. An id
65
+ * whose boards all fail the checks is passed over, as `openRunBoard` passes it over.
66
+ */
63
67
  export declare function withRuns<T extends {
64
68
  sessionId: string;
69
+ handedOverFrom?: readonly string[];
65
70
  }>(env: Env, home: string, sessions: T[], uid?: number): Promise<(T & {
66
71
  run?: SessionRun;
67
72
  })[]>;
@@ -8,6 +8,7 @@ import { basename, dirname, isAbsolute, join } from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import { openWithDefault } from './edit-settings.js';
10
10
  import { UserError } from './errors.js';
11
+ import { earlierHops, readHandoffChains } from './session-handoffs.js';
11
12
  /** The largest Session Index sideby reads; a bigger one is ignored. */
12
13
  export const INDEX_MAX_BYTES = 256 * 1024;
13
14
  const MAX_TEXT = 120;
@@ -202,26 +203,64 @@ export async function runsForSessions(env, home, sessionIds, uid) {
202
203
  if (!check)
203
204
  return out;
204
205
  for (const id of wanted) {
205
- const [first, ...rest] = await checkedRuns(index.get(id), check);
206
- if (!first)
207
- continue;
208
- const others = rest.map((e) => ({
209
- title: e.title,
210
- ...(e.laneTitle ? { laneTitle: e.laneTitle } : {}),
211
- ...(e.role ? { role: e.role } : {}),
212
- board: e.board,
213
- }));
214
- out.set(id, { ...first, ...(others.length ? { others } : {}) });
206
+ const run = sessionRun(await checkedRuns(index.get(id), check));
207
+ if (run)
208
+ out.set(id, run);
215
209
  }
216
210
  return out;
217
211
  }
218
- /** The same Sessions, each with `run` where the Session Index ties it to a Run. */
212
+ /** The first checked entry as the Session's Run, the rest as its `others`; undefined when none checked out. */
213
+ function sessionRun([first, ...rest]) {
214
+ if (!first)
215
+ return undefined;
216
+ const others = rest.map((e) => ({
217
+ title: e.title,
218
+ ...(e.laneTitle ? { laneTitle: e.laneTitle } : {}),
219
+ ...(e.role ? { role: e.role } : {}),
220
+ board: e.board,
221
+ }));
222
+ return { ...first, ...(others.length ? { others } : {}) };
223
+ }
224
+ /** A Session's own id, then the ids an Auto Handoff chain passed it from, newest first (ADR-0057). */
225
+ const linkIds = (s) => [
226
+ s.sessionId,
227
+ ...[...(s.handedOverFrom ?? [])].reverse(),
228
+ ];
229
+ /**
230
+ * The one rule a Run Link follows, for listing and opening alike: the entries of the first id in `ids` that has an
231
+ * entry whose board checks out, those that check out ordered by role, each with its board's identity at the check.
232
+ */
233
+ async function linkedEntries(index, check, ids) {
234
+ for (const sessionId of ids) {
235
+ const entries = index.get(sessionId);
236
+ if (!entries)
237
+ continue;
238
+ const ok = (await Promise.all(entries.map((e) => inspectEntry(e, check)))).filter((x) => x !== undefined);
239
+ if (!ok.length)
240
+ continue;
241
+ const order = byRole(ok.map((x) => x.entry));
242
+ return order.map((entry) => ok.find((x) => x.entry === entry));
243
+ }
244
+ return [];
245
+ }
246
+ /**
247
+ * The same Sessions, each with `run` where the Session Index ties it to a Run: by its own id, else by the ids it was
248
+ * handed over from, newest first, so a Run Board stays linked after its coordinator moves to another Account. An id
249
+ * whose boards all fail the checks is passed over, as `openRunBoard` passes it over.
250
+ */
219
251
  export async function withRuns(env, home, sessions, uid) {
220
- const runs = await runsForSessions(env, home, sessions.map((s) => s.sessionId), uid);
221
- return sessions.map((s) => {
222
- const run = runs.get(s.sessionId);
252
+ if (!sessions.length)
253
+ return sessions;
254
+ const index = await readSessionIndex(sessionIndexPath(env, home));
255
+ const check = index && sessions.some((s) => linkIds(s).some((id) => index.has(id)))
256
+ ? await boardsCheck(env, home, uid)
257
+ : undefined;
258
+ if (!index || !check)
259
+ return sessions;
260
+ return Promise.all(sessions.map(async (s) => {
261
+ const run = sessionRun((await linkedEntries(index, check, linkIds(s))).map((x) => x.entry));
223
262
  return run ? { ...s, run } : s;
224
- });
263
+ }));
225
264
  }
226
265
  /**
227
266
  * Opens the Run Board of `sessionId` with the system's default program. The path comes only from the Session Index,
@@ -230,15 +269,16 @@ export async function withRuns(env, home, sessions, uid) {
230
269
  */
231
270
  export async function openRunBoard(rt, sessionId) {
232
271
  const gone = () => new UserError('This session is not part of a run any more, or its board file is gone; ask the coordinating AI to show the board again', { code: 'no-run' });
233
- const entries = (await readSessionIndex(sessionIndexPath(rt.env, rt.paths.home)))?.get(sessionId);
234
- const check = entries && (await boardsCheck(rt.env, rt.paths.home));
235
- if (!entries || !check)
272
+ const index = await readSessionIndex(sessionIndexPath(rt.env, rt.paths.home));
273
+ const check = index && (await boardsCheck(rt.env, rt.paths.home));
274
+ if (!index || !check)
236
275
  throw gone();
237
- const ok = (await Promise.all(entries.map((e) => inspectEntry(e, check)))).filter((x) => x !== undefined);
238
- const first = byRole(ok.map((x) => x.entry))[0];
239
- const id = ok.find((x) => x.entry === first)?.id;
240
- if (!first || !id)
276
+ // The same rule as the listing: its own id, then the ids it was handed over from, newest first (ADR-0057).
277
+ const earlier = earlierHops(await readHandoffChains(rt.paths.stateDir), sessionId) ?? [];
278
+ const [picked] = await linkedEntries(index, check, linkIds({ sessionId, handedOverFrom: earlier }));
279
+ if (!picked)
241
280
  throw gone();
281
+ const { entry: first, id } = picked;
242
282
  if (!(await stillTheBoard(first.board, check, id)))
243
283
  throw new UserError('The board file changed while sideby checked it; ask the coordinating AI to show the board again', { code: 'board-changed' });
244
284
  return { board: first.board, command: await openWithDefault(rt, first.board, { text: false }) };
@@ -0,0 +1,22 @@
1
+ /** One hop of a chain: its session, and when the hop started (the time its run id starts with). */
2
+ export interface HandoffHop {
3
+ sessionId: string;
4
+ /** Milliseconds since the epoch, from the run id's base36 time; 0 when it has none. */
5
+ at: number;
6
+ }
7
+ /** The hops of one chain, oldest first. A resumed session handed over again starts a new chain. */
8
+ export type HandoffChain = readonly HandoffHop[];
9
+ /** Every Handoff chain under `<stateDir>/handoffs`, each its hops in run-id order; links are not followed. */
10
+ export declare function readHandoffChains(stateDir: string): Promise<HandoffHop[][]>;
11
+ /** The session ids the task passed through before `sessionId`, oldest first; undefined when no chain led to it. */
12
+ export declare function earlierHops(chains: readonly HandoffChain[], sessionId: string): string[] | undefined;
13
+ /** The same Sessions, each with `handedOverFrom` where a Handoff chain led to it. */
14
+ export declare function withHandoffs<T extends {
15
+ sessionId: string;
16
+ }>(chains: readonly HandoffChain[], sessions: readonly T[]): (T & {
17
+ handedOverFrom?: string[];
18
+ })[];
19
+ /** The full session ids in any chain that `target` names: the id itself, or its first 8 or more characters. */
20
+ export declare function chainIdsMatching(chains: readonly HandoffChain[], target: string): string[];
21
+ /** The sessions the task passed to after `sessionId`, across every chain, the newest hop first. */
22
+ export declare function laterHops(chains: readonly HandoffChain[], sessionId: string): string[];
@@ -0,0 +1,110 @@
1
+ // Which Sessions an Auto Handoff chain passed a task through (spec §3.32 step 2, ADR-0057): each hop of a chain
2
+ // writes `run-<runId>.json` under `<state>/handoffs/<chain>/`, and run ids start with the time, so sorting them sorts
3
+ // the hops. Read-only and best effort: only the `sessionId` of run files is read (never a Brief or another chain
4
+ // file), a file that cannot be read or parsed is skipped, and nothing is written. Imports Node built-ins only.
5
+ import { lstat, readdir, readFile } from 'node:fs/promises';
6
+ import { join } from 'node:path';
7
+ /** A run file bigger than this is not a hop sideby wrote; it is skipped. */
8
+ const RUN_MAX_BYTES = 256 * 1024;
9
+ const RUN_FILE = /^run-.+\.json$/;
10
+ async function names(dir) {
11
+ try {
12
+ return await readdir(dir);
13
+ }
14
+ catch {
15
+ return [];
16
+ }
17
+ }
18
+ async function hopSession(file) {
19
+ try {
20
+ const st = await lstat(file);
21
+ if (!st.isFile() || st.size > RUN_MAX_BYTES)
22
+ return undefined;
23
+ const raw = JSON.parse(await readFile(file, 'utf8'));
24
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
25
+ return undefined;
26
+ const id = raw.sessionId;
27
+ return typeof id === 'string' && id ? id : undefined;
28
+ }
29
+ catch {
30
+ return undefined;
31
+ }
32
+ }
33
+ /** The time a run id starts with (`<base36 ms>-<hex>`, `newId` in handoff-chain.ts); 0 when it has none. */
34
+ function runTime(name) {
35
+ const t = Number.parseInt(name.slice('run-'.length).split('-')[0] ?? '', 36);
36
+ return Number.isFinite(t) ? t : 0;
37
+ }
38
+ /** Every Handoff chain under `<stateDir>/handoffs`, each its hops in run-id order; links are not followed. */
39
+ export async function readHandoffChains(stateDir) {
40
+ const root = join(stateDir, 'handoffs');
41
+ const chains = [];
42
+ for (const name of (await names(root)).sort()) {
43
+ const dir = join(root, name);
44
+ const st = await lstat(dir).catch(() => undefined);
45
+ if (!st?.isDirectory())
46
+ continue;
47
+ const runs = (await names(dir)).filter((n) => RUN_FILE.test(n)).sort();
48
+ const hops = [];
49
+ for (const run of runs) {
50
+ const sessionId = await hopSession(join(dir, run));
51
+ // A session that keeps its hop over two run files (a resumed wait) is one hop.
52
+ if (sessionId && sessionId !== hops[hops.length - 1]?.sessionId)
53
+ hops.push({ sessionId, at: runTime(run) });
54
+ }
55
+ if (hops.length)
56
+ chains.push(hops);
57
+ }
58
+ return chains;
59
+ }
60
+ /**
61
+ * The hops on one side of `sessionId`, following every chain that holds it and, through them, the chains of those
62
+ * hops (a session resumed and handed over again starts a new chain). Each session once, at its latest hop time.
63
+ */
64
+ function reach(chains, sessionId, side) {
65
+ const found = new Map();
66
+ const todo = [sessionId];
67
+ for (let id = todo.pop(); id !== undefined; id = todo.pop())
68
+ for (const chain of chains) {
69
+ const i = chain.map((h) => h.sessionId).lastIndexOf(id);
70
+ if (i === -1)
71
+ continue;
72
+ for (const hop of side === 'before' ? chain.slice(0, i) : chain.slice(i + 1)) {
73
+ if (hop.sessionId === sessionId)
74
+ continue;
75
+ const seen = found.get(hop.sessionId);
76
+ if (seen === undefined)
77
+ todo.push(hop.sessionId);
78
+ if (seen === undefined || hop.at > seen)
79
+ found.set(hop.sessionId, hop.at);
80
+ }
81
+ }
82
+ return [...found].map(([id, at]) => ({ sessionId: id, at }));
83
+ }
84
+ /** The session ids the task passed through before `sessionId`, oldest first; undefined when no chain led to it. */
85
+ export function earlierHops(chains, sessionId) {
86
+ const hops = reach(chains, sessionId, 'before').sort((a, b) => a.at - b.at);
87
+ return hops.length ? hops.map((h) => h.sessionId) : undefined;
88
+ }
89
+ /** The same Sessions, each with `handedOverFrom` where a Handoff chain led to it. */
90
+ export function withHandoffs(chains, sessions) {
91
+ return sessions.map((s) => {
92
+ const from = earlierHops(chains, s.sessionId);
93
+ return from ? { ...s, handedOverFrom: from } : s;
94
+ });
95
+ }
96
+ /** The full session ids in any chain that `target` names: the id itself, or its first 8 or more characters. */
97
+ export function chainIdsMatching(chains, target) {
98
+ const out = new Set();
99
+ for (const chain of chains)
100
+ for (const { sessionId: id } of chain)
101
+ if (id === target || (target.length >= 8 && id.startsWith(target)))
102
+ out.add(id);
103
+ return [...out];
104
+ }
105
+ /** The sessions the task passed to after `sessionId`, across every chain, the newest hop first. */
106
+ export function laterHops(chains, sessionId) {
107
+ return reach(chains, sessionId, 'after')
108
+ .sort((a, b) => b.at - a.at)
109
+ .map((h) => h.sessionId);
110
+ }