@ethlete/agent-rules 0.1.0-next.4 → 0.1.0-next.41

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 (229) hide show
  1. package/AGENTS.md +28 -0
  2. package/CHANGELOG.md +627 -0
  3. package/CLAUDE.md +1 -0
  4. package/README.md +406 -29
  5. package/THIRD-PARTY-LICENSES.md +35 -0
  6. package/content/defaults.json +1 -1
  7. package/content/git-hooks/post-checkout.sh +10 -0
  8. package/content/git-hooks/pre-push.sh +5 -0
  9. package/content/hooks/away-mode.py +287 -0
  10. package/content/hooks/background-design-commands.py +215 -0
  11. package/content/hooks/builder-chat-words.py +269 -0
  12. package/content/hooks/context-warning.py +836 -142
  13. package/content/hooks/git-safety.py +213 -0
  14. package/content/hooks/subagent-model-policy.py +261 -0
  15. package/content/mods/.claude-plugin/marketplace.json +16 -0
  16. package/content/mods/plugins/e2e-progress/.claude-plugin/plugin.json +6 -0
  17. package/content/mods/plugins/e2e-progress/hooks/hooks.json +1 -0
  18. package/content/mods/plugins/e2e-progress/hooks/register.tsx +442 -0
  19. package/content/mods/plugins/e2e-progress/tsconfig.json +3 -0
  20. package/content/mods/plugins/e2e-progress/types/index.d.ts +23 -0
  21. package/content/mods/plugins/status-line/.claude-plugin/plugin.json +6 -0
  22. package/content/mods/plugins/status-line/hooks/hooks.json +1 -0
  23. package/content/mods/plugins/status-line/hooks/line.ts +73 -0
  24. package/content/mods/plugins/status-line/hooks/register.tsx +141 -0
  25. package/content/mods/plugins/status-line/types/index.d.ts +5 -0
  26. package/content/output-styles/ste-clarity.md +131 -0
  27. package/content/rules/agent-sessions-wake-up.md +11 -0
  28. package/content/rules/app-styling.md +66 -0
  29. package/content/rules/comments.md +4 -1
  30. package/content/rules/lint-and-format.md +7 -5
  31. package/content/rules/nx-layout.md +53 -0
  32. package/content/rules/reactive-state.md +1 -1
  33. package/content/rules/styling.md +19 -10
  34. package/content/rules/subagent-models.md +42 -0
  35. package/content/skills/agent-sessions/SKILL.md +94 -0
  36. package/content/skills/agent-sessions/agent-sessions.mjs +1125 -0
  37. package/content/skills/angular-patterns/SKILL.md +31 -7
  38. package/content/skills/api-source/SKILL.md +156 -0
  39. package/content/skills/app-testing/SKILL.md +141 -0
  40. package/content/skills/codex-subagent/SKILL.md +90 -0
  41. package/content/skills/codex-subagent/codex-agent.mjs +229 -0
  42. package/content/skills/design-exploration/SKILL.md +190 -0
  43. package/content/skills/design-exploration/check-story.mjs +139 -0
  44. package/content/skills/design-exploration/reference-check-and-notes.md +92 -0
  45. package/content/skills/design-exploration/reference-flows-and-wireframes.md +78 -0
  46. package/content/skills/design-exploration/reference-inbox-and-mcp.md +54 -0
  47. package/content/skills/design-exploration/reference-order-and-design-system.md +124 -0
  48. package/content/skills/design-exploration/reference-products-and-sketches.md +211 -0
  49. package/content/skills/design-exploration/reference-shots.md +25 -0
  50. package/content/skills/design-exploration/shoot-template.mjs +61 -0
  51. package/content/skills/domain-modeling/ADR-FORMAT.md +47 -0
  52. package/content/skills/domain-modeling/CONTEXT-FORMAT.md +60 -0
  53. package/content/skills/domain-modeling/SKILL.md +80 -0
  54. package/content/skills/e2e-triage/SKILL.md +80 -0
  55. package/content/skills/figma-export/SKILL.md +191 -0
  56. package/content/skills/figma-export/dump-figma-layers.py +83 -0
  57. package/content/skills/figma-export/dump-figma-svg.py +235 -0
  58. package/content/skills/figma-export/measure-template.mjs +87 -0
  59. package/content/skills/git-commit/SKILL.md +21 -7
  60. package/content/skills/git-flow/SKILL.md +87 -0
  61. package/content/skills/grill-with-docs/SKILL.md +13 -0
  62. package/content/skills/grilling/SKILL.md +52 -0
  63. package/content/skills/handoff/SKILL.md +29 -69
  64. package/content/skills/handoff/save.md +187 -0
  65. package/content/skills/query/SKILL.md +165 -64
  66. package/content/skills/report/SKILL.md +26 -0
  67. package/content/skills/rxjs-signals/SKILL.md +33 -4
  68. package/content/skills/sdk-docs/SKILL.md +50 -14
  69. package/content/skills/sdk-local-build/SKILL.md +26 -8
  70. package/content/skills/sdk-local-build/sdk-local-baseline.mjs +64 -0
  71. package/content/skills/sdk-source/SKILL.md +37 -34
  72. package/content/skills/sdk-update/SKILL.md +103 -0
  73. package/content/skills/story-styling/SKILL.md +10 -8
  74. package/content/skills/styleguide/SKILL.md +13 -8
  75. package/content/skills/styleguide/assets.md +54 -0
  76. package/content/skills/styleguide/changesets.md +17 -0
  77. package/content/skills/styleguide/file-structure.md +73 -0
  78. package/content/skills/styleguide/lint-rule-lookup.md +52 -0
  79. package/content/skills/styleguide/storybook-structure.md +25 -0
  80. package/content/skills/theming/SKILL.md +56 -28
  81. package/content/skills/timetrack/SKILL.md +324 -0
  82. package/content/skills/verify-in-app/SKILL.md +107 -0
  83. package/content/skills/verify-in-storybook/SKILL.md +1 -1
  84. package/migrations/list-state-query-form.md +20 -0
  85. package/migrations/nx-layout.md +29 -0
  86. package/migrations/sdk-components-over-hand-built-ui.md +27 -0
  87. package/migrations/search-query-field.md +52 -0
  88. package/migrations.json +39 -0
  89. package/package.json +19 -3
  90. package/src/index.js +99 -32
  91. package/src/index.js.map +1 -1
  92. package/src/lib/cli-args.d.ts +9 -0
  93. package/src/lib/cli-args.js +48 -0
  94. package/src/lib/cli-args.js.map +1 -0
  95. package/src/lib/commitlint.d.ts +10 -0
  96. package/src/lib/commitlint.js +51 -0
  97. package/src/lib/commitlint.js.map +1 -0
  98. package/src/lib/config.d.ts +51 -6
  99. package/src/lib/config.js +127 -10
  100. package/src/lib/config.js.map +1 -1
  101. package/src/lib/filter.d.ts +2 -0
  102. package/src/lib/filter.js +4 -4
  103. package/src/lib/filter.js.map +1 -1
  104. package/src/lib/frontmatter.d.ts +2 -0
  105. package/src/lib/frontmatter.js +33 -5
  106. package/src/lib/frontmatter.js.map +1 -1
  107. package/src/lib/git-flow/build.d.ts +35 -0
  108. package/src/lib/git-flow/build.js +24 -0
  109. package/src/lib/git-flow/build.js.map +1 -0
  110. package/src/lib/git-flow/config.d.ts +59 -0
  111. package/src/lib/git-flow/config.js +50 -0
  112. package/src/lib/git-flow/config.js.map +1 -0
  113. package/src/lib/git-flow/index.d.ts +6 -0
  114. package/src/lib/git-flow/index.js +23 -0
  115. package/src/lib/git-flow/index.js.map +1 -0
  116. package/src/lib/git-flow/parse.d.ts +49 -0
  117. package/src/lib/git-flow/parse.js +300 -0
  118. package/src/lib/git-flow/parse.js.map +1 -0
  119. package/src/lib/git-flow/rename.d.ts +24 -0
  120. package/src/lib/git-flow/rename.js +70 -0
  121. package/src/lib/git-flow/rename.js.map +1 -0
  122. package/src/lib/git-flow/start.d.ts +49 -0
  123. package/src/lib/git-flow/start.js +57 -0
  124. package/src/lib/git-flow/start.js.map +1 -0
  125. package/src/lib/git-flow/validate.d.ts +34 -0
  126. package/src/lib/git-flow/validate.js +72 -0
  127. package/src/lib/git-flow/validate.js.map +1 -0
  128. package/src/lib/git-flow-command.d.ts +4 -0
  129. package/src/lib/git-flow-command.js +165 -0
  130. package/src/lib/git-flow-command.js.map +1 -0
  131. package/src/lib/git-flow-repair.d.ts +17 -0
  132. package/src/lib/git-flow-repair.js +165 -0
  133. package/src/lib/git-flow-repair.js.map +1 -0
  134. package/src/lib/git-flow-start.d.ts +20 -0
  135. package/src/lib/git-flow-start.js +140 -0
  136. package/src/lib/git-flow-start.js.map +1 -0
  137. package/src/lib/git-test-env.fixtures.d.ts +11 -0
  138. package/src/lib/git-test-env.fixtures.js +31 -0
  139. package/src/lib/git-test-env.fixtures.js.map +1 -0
  140. package/src/lib/git.d.ts +64 -0
  141. package/src/lib/git.js +131 -0
  142. package/src/lib/git.js.map +1 -0
  143. package/src/lib/gitlab.d.ts +35 -0
  144. package/src/lib/gitlab.js +116 -0
  145. package/src/lib/gitlab.js.map +1 -0
  146. package/src/lib/index.d.ts +2 -0
  147. package/src/lib/index.js +26 -11
  148. package/src/lib/index.js.map +1 -1
  149. package/src/lib/migrate.js +8 -2
  150. package/src/lib/migrate.js.map +1 -1
  151. package/src/lib/output-style-command.d.ts +3 -0
  152. package/src/lib/output-style-command.js +69 -0
  153. package/src/lib/output-style-command.js.map +1 -0
  154. package/src/lib/output-style.d.ts +38 -0
  155. package/src/lib/output-style.js +134 -0
  156. package/src/lib/output-style.js.map +1 -0
  157. package/src/lib/owned-paths.js +27 -3
  158. package/src/lib/owned-paths.js.map +1 -1
  159. package/src/lib/package-runner.d.ts +4 -0
  160. package/src/lib/package-runner.js +86 -0
  161. package/src/lib/package-runner.js.map +1 -0
  162. package/src/lib/peer-path.d.ts +12 -0
  163. package/src/lib/peer-path.js +39 -0
  164. package/src/lib/peer-path.js.map +1 -0
  165. package/src/lib/plain-text.d.ts +9 -0
  166. package/src/lib/plain-text.js +22 -0
  167. package/src/lib/plain-text.js.map +1 -0
  168. package/src/lib/plan.d.ts +6 -6
  169. package/src/lib/plan.js +168 -40
  170. package/src/lib/plan.js.map +1 -1
  171. package/src/lib/prettier.d.ts +21 -0
  172. package/src/lib/prettier.js +51 -0
  173. package/src/lib/prettier.js.map +1 -0
  174. package/src/lib/prompt.d.ts +8 -0
  175. package/src/lib/prompt.js +35 -0
  176. package/src/lib/prompt.js.map +1 -0
  177. package/src/lib/render.d.ts +26 -2
  178. package/src/lib/render.js +45 -10
  179. package/src/lib/render.js.map +1 -1
  180. package/src/lib/report-command.d.ts +33 -0
  181. package/src/lib/report-command.js +312 -0
  182. package/src/lib/report-command.js.map +1 -0
  183. package/src/lib/sessions-command.d.ts +4 -0
  184. package/src/lib/sessions-command.js +16 -0
  185. package/src/lib/sessions-command.js.map +1 -0
  186. package/src/lib/sync.d.ts +1 -2
  187. package/src/lib/sync.js +37 -17
  188. package/src/lib/sync.js.map +1 -1
  189. package/src/lib/targets/agents-skills.js +1 -1
  190. package/src/lib/targets/agents-skills.js.map +1 -1
  191. package/src/lib/targets/claude-hooks.d.ts +3 -23
  192. package/src/lib/targets/claude-hooks.js +22 -86
  193. package/src/lib/targets/claude-hooks.js.map +1 -1
  194. package/src/lib/targets/claude-mods.d.ts +20 -0
  195. package/src/lib/targets/claude-mods.js +47 -0
  196. package/src/lib/targets/claude-mods.js.map +1 -0
  197. package/src/lib/targets/claude.js +2 -3
  198. package/src/lib/targets/claude.js.map +1 -1
  199. package/src/lib/targets/codex-hooks.d.ts +12 -0
  200. package/src/lib/targets/codex-hooks.js +35 -0
  201. package/src/lib/targets/codex-hooks.js.map +1 -0
  202. package/src/lib/targets/codex.js +4 -4
  203. package/src/lib/targets/codex.js.map +1 -1
  204. package/src/lib/targets/copilot.js +4 -4
  205. package/src/lib/targets/copilot.js.map +1 -1
  206. package/src/lib/targets/cursor.js +3 -3
  207. package/src/lib/targets/cursor.js.map +1 -1
  208. package/src/lib/targets/git-hooks.d.ts +25 -0
  209. package/src/lib/targets/git-hooks.js +71 -0
  210. package/src/lib/targets/git-hooks.js.map +1 -0
  211. package/src/lib/targets/hooks-shared.d.ts +60 -0
  212. package/src/lib/targets/hooks-shared.js +174 -0
  213. package/src/lib/targets/hooks-shared.js.map +1 -0
  214. package/src/lib/targets/mcp.d.ts +16 -0
  215. package/src/lib/targets/mcp.js +72 -0
  216. package/src/lib/targets/mcp.js.map +1 -0
  217. package/src/lib/targets/shared.d.ts +1 -9
  218. package/src/lib/targets/shared.js +4 -8
  219. package/src/lib/targets/shared.js.map +1 -1
  220. package/src/lib/timetrack-command.d.ts +11 -0
  221. package/src/lib/timetrack-command.js +1262 -0
  222. package/src/lib/timetrack-command.js.map +1 -0
  223. package/src/lib/timetrack-snapshot.d.ts +66 -0
  224. package/src/lib/timetrack-snapshot.js +146 -0
  225. package/src/lib/timetrack-snapshot.js.map +1 -0
  226. package/src/lib/timetrack.d.ts +607 -0
  227. package/src/lib/timetrack.js +285 -0
  228. package/src/lib/timetrack.js.map +1 -0
  229. package/content/skills/styleguide/STYLEGUIDE.md +0 -520
@@ -0,0 +1,1125 @@
1
+ import { execFileSync, spawn, spawnSync } from 'node:child_process';
2
+ import {
3
+ appendFileSync,
4
+ existsSync,
5
+ mkdirSync,
6
+ readdirSync,
7
+ readFileSync,
8
+ rmSync,
9
+ watchFile,
10
+ writeFileSync,
11
+ } from 'node:fs';
12
+ import { basename, dirname, join, relative, resolve } from 'node:path';
13
+ import { homedir } from 'node:os';
14
+ import { fileURLToPath } from 'node:url';
15
+
16
+ const root = (() => {
17
+ try {
18
+ return execFileSync('git', ['rev-parse', '--show-toplevel'], {
19
+ encoding: 'utf8',
20
+ stdio: ['ignore', 'pipe', 'ignore'],
21
+ }).trim();
22
+ } catch {
23
+ return process.cwd();
24
+ }
25
+ })();
26
+ const mailbox = process.env.AGENT_MAILBOX ?? join(root, '.ethlete/mailbox.jsonl');
27
+ const script = fileURLToPath(import.meta.url);
28
+ const DEFAULT_TTL_HOURS = 4;
29
+ const DEFAULT_LAST = 20;
30
+ const ENTER_DELAY_MS = 400;
31
+ const WAKE_GRACE_MS = 1500;
32
+ const DRAFT_RETRY_MS = 2000;
33
+ const RESTART_AFTER_SECONDS = 5;
34
+ const RESTART_MARKER = ' [typed by agent-sessions]';
35
+ const restartPrompt = (words) => `${words.join(' ')}${RESTART_MARKER}`;
36
+ const RESTART_CLEAR_MS = 2500;
37
+ const RESTART_POLL_MS = 2000;
38
+ const RESTART_WAIT_MS = Number(process.env.AGENT_RESTART_WAIT_MS ?? 30 * 60 * 1000);
39
+ const RESTART_DRAFT_NOTICE_MS = Number(process.env.AGENT_RESTART_DRAFT_NOTICE_MS ?? 2 * 60 * 1000);
40
+ const RESTART_CLEAR_WAIT_MS = Number(process.env.AGENT_RESTART_CLEAR_WAIT_MS ?? 60 * 1000);
41
+ const RESTART_EXIT_WAIT_MS = Number(process.env.AGENT_RESTART_EXIT_WAIT_MS ?? 30 * 1000);
42
+ const RESTART_RESUME_WAIT_MS = Number(process.env.AGENT_RESTART_RESUME_WAIT_MS ?? 60 * 1000);
43
+ const RUN_EXIT_CHECK_MS = Number(process.env.AGENT_RUN_EXIT_CHECK_MS ?? 400);
44
+ const RESTART_LOCK_MS = Number(process.env.AGENT_RESTART_LOCK_MS ?? RESTART_WAIT_MS + 10 * 60 * 1000);
45
+ const repoSlug = basename(root).replace(/[.:]/g, '-');
46
+ const sessionFor = (agent) => `${agent}@${repoSlug}`;
47
+ const DISPATCH_SESSION = process.env.AGENT_MAILBOX_DISPATCH_SESSION ?? `mailbox-dispatch@${repoSlug}`;
48
+
49
+ const takeFlag = (args, name, hasValue) => {
50
+ const index = args.indexOf(name);
51
+ if (index === -1) return undefined;
52
+ const [flag, value] = args.splice(index, hasValue ? 2 : 1);
53
+ return hasValue ? value : flag;
54
+ };
55
+
56
+ const args = process.argv.slice(2);
57
+ const last = takeFlag(args, '--last', true);
58
+ const ttl = takeFlag(args, '--ttl', true);
59
+ const all = takeFlag(args, '--all', false);
60
+ const force = takeFlag(args, '--force', false);
61
+ const waitSeconds = takeFlag(args, '--wait', true);
62
+ const recipient = takeFlag(args, '--to', true);
63
+ const rcFile = takeFlag(args, '--file', true);
64
+ const remove = takeFlag(args, '--remove', false);
65
+ const afterSeconds = takeFlag(args, '--after', true);
66
+ const now = takeFlag(args, '--now', false);
67
+ const dryRun = takeFlag(args, '--dry-run', false);
68
+ const role = takeFlag(args, '--role', true);
69
+ const notify = takeFlag(args, '--notify', true);
70
+ const newProcess = takeFlag(args, '--process', false);
71
+ const [command, sender, ...words] = args;
72
+
73
+ const help = `Shared agent mailbox: ${mailbox}
74
+
75
+ Send: node ${script} send <name> [--to <agent>] '<message>' (no message: read it from stdin)
76
+ Inbox: node ${script} inbox <name> [--wait <seconds>] (only the messages you have not seen yet;
77
+ --wait blocks until one arrives or the time ends)
78
+ Read: node ${script} read [--last <n>] [--all] (default: the last ${DEFAULT_LAST} messages)
79
+ Watch: node ${script} watch <name>
80
+ Claim: node ${script} claim <name> <path...> [--ttl <hours>] [--force]
81
+ Release: node ${script} release <name> [path...] (no path: release every claim of <name>)
82
+ Claims: node ${script} claims
83
+ Up: node ${script} up <name>[=<command>]... (start a tmux session per agent, plus one that runs dispatch)
84
+ Run: node ${script} run <name> <command...> [--role builder] [--dry-run]
85
+ (start or attach the agent in its tmux session; starts dispatch;
86
+ the builder role sets ETHLETE_AGENT_ROLE and gives claude a terse system prompt)
87
+ Install: node ${script} shell-install [<agent>...] [--file <path>] [--remove] [--dry-run]
88
+ (write the shell functions into ~/.zshrc or ~/.bashrc)
89
+ Shell: node ${script} shell-init [<agent>...] (print shell functions that wrap each agent with run; default: claude codex)
90
+ Restart: node ${script} restart <name> [--after <seconds>] [--notify <agent,...>] [--process] [--role builder|none] <prompt...>
91
+ (type the clear command and then the prompt into the tmux session of <name>;
92
+ a long wait on a draft and a give-up go to <name> and each --notify agent;
93
+ --process ends the agent and starts it again in the same pane with the prompt;
94
+ it keeps the role, else takes it from a builder-* handoff name, and refuses
95
+ a session with no role while another agent session runs in the repo;
96
+ refuses while a ❓ question of a claude session has no later human message
97
+ and the resumed handoff does not name it under "Open for the human")
98
+ Down: node ${script} down [<name>...] (stop dispatch; stop the named sessions too)
99
+ Dispatch: node ${script} dispatch (wake the session <agent>@<repo> for each message sent --to <agent>)
100
+
101
+ Protocol: append one JSON object per line; never rewrite or truncate.
102
+ Fields: timestamp (UTC), sender, message. A claim also has paths and expires.
103
+ Pick a sender name no other agent uses. Claim the paths you edit before you edit them.
104
+ A claim is advisory, not a lock: it expires after ${DEFAULT_TTL_HOURS} hours unless --ttl says otherwise.
105
+ Silence is not approval. Acknowledge handoffs explicitly.
106
+ Watch prints existing messages and then new messages from other senders every second.
107
+ Keep credentials and personal data out of the mailbox. No agent is started automatically.
108
+ `;
109
+
110
+ const tmux = (...tmuxArgs) => spawnSync('tmux', tmuxArgs, { encoding: 'utf8' });
111
+ const quote = (text) => `'${text.replaceAll("'", "'\\''")}'`;
112
+ const BUILDER_PROMPT =
113
+ 'The user does not read this chat. Write no text between tool calls; end each turn with at most one line. Reports go to the grill session via SendMessage.';
114
+ const BUILDER_DENIED_TOOLS =
115
+ 'Artifact Workflow ScheduleWakeup SendFeedback ShareOnboardingGuide ReportFindings AskUserQuestion';
116
+ const builderFlags = () => [
117
+ '--append-system-prompt',
118
+ BUILDER_PROMPT,
119
+ '--strict-mcp-config',
120
+ `--mcp-config=${join(root, '.mcp.json')}`,
121
+ `--disallowedTools=${BUILDER_DENIED_TOOLS}`,
122
+ ];
123
+ const claudeTmpDir = join(homedir(), '.cache', 'claude-tmp');
124
+ const ensuredClaudeTmpDir = () => {
125
+ mkdirSync(claudeTmpDir, { recursive: true });
126
+ return claudeTmpDir;
127
+ };
128
+ const tempDirEnv = () => `CLAUDE_CODE_TMPDIR=${quote(ensuredClaudeTmpDir())} `;
129
+ const withTempDir = (command) => (/(^|\s)CLAUDE_CODE_TMPDIR=/.test(command) ? command : `${tempDirEnv()}${command}`);
130
+ const programOf = (words) => words.find((word) => word !== 'env' && !ENV_WORD.test(word) && !word.startsWith('-'));
131
+ const withRole = (words) =>
132
+ role === 'builder' && basename(programOf(words) ?? '') === 'claude' ? [...words, ...builderFlags()] : words;
133
+ const roleEnvOf = (agentRole) =>
134
+ agentRole
135
+ ? { ETHLETE_AGENT_ROLE: agentRole, ...(agentRole === 'builder' ? { CLAUDE_CODE_SILENT_TURN_REMINDER: '0' } : {}) }
136
+ : {};
137
+ const roleEnvWords = (agentRole) => Object.entries(roleEnvOf(agentRole)).map(([key, value]) => `${key}=${value}`);
138
+ const sessionExists = (name) => tmux('has-session', '-t', `=${name}`).status === 0;
139
+ const ROLE_OPTION = '@ethlete_role';
140
+ const COMMAND_OPTION = '@ethlete_command';
141
+ const agentCommandOf = (session) =>
142
+ tmux('show-options', '-v', '-t', `=${session}:`, COMMAND_OPTION).stdout.trim() ||
143
+ tmux('display-message', '-p', '-t', `=${session}:`, '#{pane_start_command}')
144
+ .stdout.trim()
145
+ .replace(/^"(.*)"$/, '$1');
146
+ const roleOf = (session) => tmux('show-options', '-v', '-t', `=${session}:`, ROLE_OPTION).stdout.trim() || null;
147
+ const arePaired = (a, b) => (roleOf(a) === 'builder') !== (roleOf(b) === 'builder');
148
+ const checkoutOfSession = (session) => {
149
+ const path = tmux('display-message', '-p', '-t', `=${session}:`, '#{pane_current_path}').stdout.trim();
150
+ if (!path) return null;
151
+ const top = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd: path, encoding: 'utf8' });
152
+ return top.status === 0 ? top.stdout.trim() : path;
153
+ };
154
+ const localSessionFor = (agent) =>
155
+ [sessionFor(agent), agent].find(
156
+ (name) => sessionExists(name) && (name === sessionFor(agent) || checkoutOfSession(name) === root),
157
+ ) ?? null;
158
+ const foreignCheckoutsOf = (agent) => [
159
+ ...new Set(
160
+ tmux('list-sessions', '-F', '#{session_name}')
161
+ .stdout.split('\n')
162
+ .filter((name) => name === agent || name.startsWith(`${agent}@`))
163
+ .map((name) => (name === agent ? basename(checkoutOfSession(name) ?? '') : name.slice(agent.length + 1)))
164
+ .filter(Boolean),
165
+ ),
166
+ ];
167
+ const createRunSession = (session, shellCommand, baseCommand) => {
168
+ const result = tmux('new-session', '-d', '-s', session, '-c', process.cwd(), shellCommand);
169
+ if (result.status !== 0) {
170
+ process.stderr.write(`No agent was started: tmux could not create ${session}: ${result.stderr.trim()}\n`);
171
+ process.exitCode = 1;
172
+ return;
173
+ }
174
+ tmux('set-option', '-t', `=${session}:`, COMMAND_OPTION, baseCommand);
175
+ if (role) tmux('set-option', '-t', `=${session}:`, ROLE_OPTION, role);
176
+ sleep(RUN_EXIT_CHECK_MS);
177
+ if (!sessionExists(session)) {
178
+ process.stderr.write(`No agent stayed up: ${session} ended right after the start of ${baseCommand}\n`);
179
+ process.exitCode = 1;
180
+ }
181
+ };
182
+ const ownSession = () =>
183
+ process.env.TMUX_PANE
184
+ ? tmux('display-message', '-p', '-t', process.env.TMUX_PANE, '#{session_name}').stdout.trim() || null
185
+ : null;
186
+ const ONE_SHOT_FLAGS = new Set(['-p', '--print', '-v', '--version', '-h', '--help']);
187
+ const hasTerminal = Boolean(process.stdin.isTTY && process.stdout.isTTY);
188
+ const runsInSession = (agentArgs) => !agentArgs.some((arg) => ONE_SHOT_FLAGS.has(arg));
189
+ const TEXT_VALUE_FLAGS = new Set(['--append-system-prompt', '--system-prompt']);
190
+ const withoutPrompt = (words) => {
191
+ const separator = words.indexOf('--');
192
+ if (separator > 0) return words.slice(0, separator);
193
+ const [previous, last] = words.slice(-2);
194
+ let binary = 0;
195
+ while (
196
+ binary < words.length - 1 &&
197
+ (ENV_WORD.test(words[binary]) ||
198
+ words[binary] === 'env' ||
199
+ (binary > 0 && words[0] === 'env' && words[binary].startsWith('-')))
200
+ )
201
+ binary++;
202
+ const isPrompt =
203
+ words.length - 1 > binary &&
204
+ !last.startsWith('-') &&
205
+ (!previous.startsWith('-') || (/\s/.test(last) && !TEXT_VALUE_FLAGS.has(previous)));
206
+ return isPrompt ? words.slice(0, -1) : words;
207
+ };
208
+ const SHELL_WORD = /(?:'[^']*'|\\.|[^\s'\\])+/g;
209
+ const ENV_WORD = /^[A-Za-z_][A-Za-z0-9_]*=/;
210
+ const CONFIG_WORD = 'CLAUDE_CONFIG_DIR=';
211
+ const callerConfigDir = () => resolve(process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'));
212
+ const configDirOf = (words) => words.find((word) => word.startsWith(CONFIG_WORD))?.slice(CONFIG_WORD.length);
213
+ const configMismatch = (words) => {
214
+ const given = configDirOf(words);
215
+ return given !== undefined && resolve(given) !== callerConfigDir();
216
+ };
217
+ const callerConfigWords = (words) =>
218
+ process.env.CLAUDE_CONFIG_DIR && configDirOf(words) === undefined
219
+ ? [`${CONFIG_WORD}${quote(process.env.CLAUDE_CONFIG_DIR)}`]
220
+ : [];
221
+ const unquoteWord = (word) => word.replace(/'([^']*)'|\\(.)/g, (_, quoted, escaped) => quoted ?? escaped);
222
+ const hasAgentBinary = (words) => {
223
+ let index = 0;
224
+ while (
225
+ index < words.length &&
226
+ (ENV_WORD.test(words[index]) ||
227
+ words[index] === 'env' ||
228
+ (index > 0 && words.includes('env') && words[index].startsWith('-')))
229
+ )
230
+ index++;
231
+ return index < words.length;
232
+ };
233
+ const quoteShellWord = (word) =>
234
+ ENV_WORD.test(word) ? word.replace(/^([^=]+=)(.*)$/s, (_, key, value) => `${key}${quote(value)}`) : quote(word);
235
+ const unwrappedRun = (command) => {
236
+ const tokens = [...command.matchAll(SHELL_WORD)].map(([word]) => word);
237
+ const words = tokens.map(unquoteWord);
238
+ const at = words.findIndex((word, index) => basename(word) === 'agent-sessions.mjs' && words[index + 1] === 'run');
239
+ if (at < 0) return null;
240
+ let rest = words.slice(at + 3);
241
+ let runRole = null;
242
+ while (rest[0]?.startsWith('--')) {
243
+ if (rest[0] === '--role') runRole = rest[1];
244
+ rest = rest.slice(rest[0] === '--role' ? 2 : 1);
245
+ }
246
+ const end = rest.findIndex((word) => /[;&|]$/.test(word));
247
+ const inner = end < 0 ? rest : [...rest.slice(0, end), rest[end].replace(/[;&|]+$/, '')];
248
+ const program = inner.findIndex((word) => !ENV_WORD.test(word));
249
+ if (program < 0 || !hasAgentBinary(inner)) return null;
250
+ const kept = [...inner.slice(0, program), ...withoutPrompt(inner.slice(program))];
251
+ const env = tokens.slice(0, at).filter((word) => ENV_WORD.test(word));
252
+ const unwrapped = [...env, ...kept.map(quoteShellWord)].join(' ');
253
+ return runRole ? commandWithRole(unwrapped, runRole) : unwrapped;
254
+ };
255
+ const healedCommand = (command, agent) => {
256
+ const unwrapped = unwrappedRun(command);
257
+ if (unwrapped) return unwrapped;
258
+ const words = [...command.matchAll(SHELL_WORD)].map(([word]) => unquoteWord(word));
259
+ if (hasAgentBinary(words)) return command;
260
+ const binary = agent.match(/^(claude|codex)/)?.[1];
261
+ return binary ? `${command} ${quote(binary)}` : null;
262
+ };
263
+ const commandWithoutPrompt = (command) => {
264
+ const tokens = [...command.matchAll(SHELL_WORD)];
265
+ const program = tokens.findIndex(([word]) => !ENV_WORD.test(word));
266
+ if (program < 0) return command;
267
+ const words = tokens.slice(program).map(([word]) => unquoteWord(word));
268
+ const kept = withoutPrompt(words).length;
269
+ return kept === words.length ? command : command.slice(0, tokens[program + kept].index).trimEnd();
270
+ };
271
+ const HANDOFF_ROLE = /^\/handoff\s+resume\s+(builder|doc-agent)-/;
272
+ const handoffRoleOf = (prompt) => prompt.match(HANDOFF_ROLE)?.[1] ?? null;
273
+ const restartRoleOf = (session, prompt) => {
274
+ if (role === 'none') return null;
275
+ const found = role ?? roleOf(session) ?? handoffRoleOf(prompt);
276
+ return found === 'doc-agent' ? null : found;
277
+ };
278
+ const claudeDir = process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude');
279
+ const isAlive = (pid) => {
280
+ try {
281
+ process.kill(pid, 0);
282
+ return true;
283
+ } catch (error) {
284
+ return error.code === 'EPERM';
285
+ }
286
+ };
287
+ const readJson = (path) => {
288
+ try {
289
+ return JSON.parse(readFileSync(path, 'utf8'));
290
+ } catch {
291
+ return null;
292
+ }
293
+ };
294
+ const claudeSessionIdOf = (session, own) => {
295
+ const sessionsDir = join(claudeDir, 'sessions');
296
+ const live = existsSync(sessionsDir)
297
+ ? readdirSync(sessionsDir)
298
+ .filter((name) => name.endsWith('.json'))
299
+ .map((name) => readJson(join(sessionsDir, name)))
300
+ .filter((entry) => entry?.sessionId && entry.tmux?.startsWith(`${session}:`) && isAlive(entry.pid))
301
+ .sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0))
302
+ : [];
303
+ if (live.length) return live[0].sessionId;
304
+ return own === session ? process.env.CLAUDE_CODE_SESSION_ID || null : null;
305
+ };
306
+ const transcriptOf = (sessionId) => {
307
+ const projects = join(claudeDir, 'projects');
308
+ if (!existsSync(projects)) return null;
309
+ return (
310
+ readdirSync(projects)
311
+ .map((project) => join(projects, project, `${sessionId}.jsonl`))
312
+ .find((path) => existsSync(path)) ?? null
313
+ );
314
+ };
315
+ const textOf = (content) =>
316
+ typeof content === 'string'
317
+ ? content
318
+ : (content ?? [])
319
+ .filter((block) => block?.type === 'text')
320
+ .map((block) => block.text)
321
+ .join('\n');
322
+ const isHumanTurn = (entry) =>
323
+ entry.type === 'user' &&
324
+ entry.origin?.kind === 'human' &&
325
+ !/^\s*<command-(name|message)>/.test(textOf(entry.message?.content));
326
+ const QUESTION_LINE = /^\s*(?:[-*]\s+)?❓\s*(.+)$/;
327
+ const normalize = (text) => text.replace(/\s+/g, ' ').trim();
328
+ const unansweredQuestions = (transcript) => {
329
+ let questions = [];
330
+ for (const line of readFileSync(transcript, 'utf8').split('\n')) {
331
+ let entry;
332
+ try {
333
+ entry = JSON.parse(line);
334
+ } catch {
335
+ continue;
336
+ }
337
+ if (isHumanTurn(entry)) questions = [];
338
+ else if (entry.type === 'assistant')
339
+ textOf(entry.message?.content)
340
+ .split('\n')
341
+ .map((text) => text.match(QUESTION_LINE)?.[1])
342
+ .filter(Boolean)
343
+ .forEach((question) => questions.push(normalize(question)));
344
+ }
345
+ return [...new Set(questions)];
346
+ };
347
+ const HANDOFF_NAME = /^\/handoff\s+resume\s+(\S+)/;
348
+ const openForHumanOf = (prompt) => {
349
+ const name = prompt.match(HANDOFF_NAME)?.[1];
350
+ const path = name && join(root, '.claude/handoffs', name.endsWith('.md') ? name : `${name}.md`);
351
+ if (!path || !existsSync(path)) return null;
352
+ const lines = readFileSync(path, 'utf8').split('\n');
353
+ const start = lines.findIndex((line) => /open for the human/i.test(line));
354
+ if (start < 0) return '';
355
+ const end = lines.findIndex((line, index) => index > start && /^#/.test(line));
356
+ return normalize(lines.slice(start, end < 0 ? undefined : end).join('\n'));
357
+ };
358
+ const droppedQuestions = (session, own, prompt) => {
359
+ if (session.startsWith('codex')) return [];
360
+ const sessionId = claudeSessionIdOf(session, own);
361
+ const transcript = sessionId && transcriptOf(sessionId);
362
+ if (!transcript) return [];
363
+ const open = openForHumanOf(prompt) ?? '';
364
+ return unansweredQuestions(transcript).filter((question) => !open.includes(question));
365
+ };
366
+ const hasUnknownRole = (session, prompt) => {
367
+ if (role !== undefined || roleOf(session) || handoffRoleOf(prompt)) return false;
368
+ const peers = tmux('list-sessions', '-F', '#{session_name}')
369
+ .stdout.split('\n')
370
+ .filter((name) => name.endsWith(`@${repoSlug}`) && name !== session && name !== DISPATCH_SESSION);
371
+ return peers.length > 0 && !peers.some((name) => roleOf(name) === 'builder');
372
+ };
373
+ const commandWithRole = (command, agentRole) => {
374
+ const tokens = [...command.matchAll(SHELL_WORD)].map(([word]) => word);
375
+ const program = tokens.findIndex((word) => !ENV_WORD.test(word));
376
+ const env = program < 0 ? tokens : tokens.slice(0, program);
377
+ const words = tokens.slice(env.length).map(unquoteWord);
378
+ const kept = words.filter(
379
+ (word, index) =>
380
+ !(word === '--append-system-prompt' && words[index + 1] === BUILDER_PROMPT) &&
381
+ !(word === BUILDER_PROMPT && words[index - 1] === '--append-system-prompt') &&
382
+ !/^(--strict-mcp-config|--mcp-config=.*|--disallowedTools=.*)$/.test(word),
383
+ );
384
+ const rule = agentRole === 'builder' && basename(programOf(kept) ?? '') === 'claude' ? builderFlags() : [];
385
+ return [
386
+ ...env.filter((word) => !/^(ETHLETE_AGENT_ROLE|CLAUDE_CODE_SILENT_TURN_REMINDER)=/.test(word)),
387
+ ...roleEnvWords(agentRole),
388
+ ...[...kept, ...rule].map(quote),
389
+ ].join(' ');
390
+ };
391
+ const bypassingShellFunction = (base) => base.replace(/^((?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*)/, '$1command ');
392
+ const EXIT_DIALOG_JOBS = /will stop when you exit/i;
393
+ const EXIT_AND_STOP = /exit and stop/i;
394
+ const BACKGROUND_FOOTER = /\b\d+ (?:shells?|agents?)\b|↓ to manage/i;
395
+
396
+ /**
397
+ * Reads the last prompt line (`❯` for Claude Code, `›` for Codex) of the pane. Dim text is the empty
398
+ * prompt's placeholder, so it does not count. A menu cursor (`❯ 1. Yes`) also counts, which keeps a
399
+ * wake-up line from answering a permission dialog.
400
+ */
401
+ const SGR = `${String.fromCharCode(27)}\\[([0-9;]*)m`;
402
+ const BUSY_TEXT = /esc to interrupt|Waiting for/i;
403
+ const isTranscript = (line) => /^\s*[●⎿]/.test(line);
404
+ /**
405
+ * The line that shows a running turn: the spinner line right above the input box, or a footer line below it.
406
+ * A transcript line (`●`, `⎿`) never counts, since an agent can end its turn with its own "Waiting for ..." text.
407
+ */
408
+ const busyLineOf = (lines) => {
409
+ const bottom = lastRuleIndex(lines);
410
+ const top = lines.slice(0, bottom).findLastIndex(isRule);
411
+ if (bottom === -1 || top === -1) return lines.find((line) => BUSY_TEXT.test(line) && !isTranscript(line)) ?? null;
412
+ const spinner = lines.slice(0, top).findLast((line) => line.trim() !== '') ?? '';
413
+ return [spinner, ...lines.slice(bottom + 1)].find((line) => BUSY_TEXT.test(line) && !isTranscript(line)) ?? null;
414
+ };
415
+ const busyLine = (session) => busyLineOf((tmux('capture-pane', '-p', '-t', `=${session}:`).stdout ?? '').split('\n'));
416
+ const restartLog = (message) => {
417
+ mkdirSync(dirname(mailbox), { recursive: true });
418
+ appendFileSync(join(dirname(mailbox), 'restart.log'), `${new Date().toISOString()} ${message}\n`);
419
+ };
420
+ const restartNotice = (message) => {
421
+ restartLog(message);
422
+ [sender, ...(notify ?? '').split(',')]
423
+ .map((agent) => agent.trim())
424
+ .filter(Boolean)
425
+ .forEach((to) => append({ sender: 'restart', to, message }));
426
+ };
427
+
428
+ const restartLockOf = (session) => join(dirname(mailbox), `restart.lock.${session}`);
429
+ const pendingRestartOf = (session) => {
430
+ const lock = readJson(restartLockOf(session));
431
+ return lock && isAlive(lock.pid) && Date.now() - lock.since < RESTART_LOCK_MS ? lock : null;
432
+ };
433
+ const lockRestart = (session, pid) => {
434
+ mkdirSync(dirname(mailbox), { recursive: true });
435
+ writeFileSync(restartLockOf(session), JSON.stringify({ pid, since: Date.now() }));
436
+ };
437
+ const unlockRestart = (session) => {
438
+ if (readJson(restartLockOf(session))?.pid === process.pid) rmSync(restartLockOf(session), { force: true });
439
+ };
440
+ const waitForFirstTurn = (session) => {
441
+ const end = Date.now() + RESTART_RESUME_WAIT_MS;
442
+ while (Date.now() < end && sessionExists(session) && busyLine(session) === null) sleep(RESTART_POLL_MS / 4);
443
+ };
444
+
445
+ /**
446
+ * Waits until the agent ended its turn and nobody types in its prompt, twice in a row; `false` after the time limit.
447
+ * With `allowBusy`, a running turn does not block, since Claude Code queues input typed during a turn.
448
+ * Each change of the reason it waits is logged to `restart.log` next to the mailbox.
449
+ */
450
+ const waitForQuiet = (session, limitMs = RESTART_WAIT_MS, allowBusy = false) => {
451
+ const end = Date.now() + limitMs;
452
+ let quiet = 0;
453
+ let reason = '';
454
+ let draftSince = null;
455
+ let told = false;
456
+ while (Date.now() < end) {
457
+ const busy = allowBusy ? null : busyLine(session);
458
+ const draft = busy === null ? draftLine(session) : null;
459
+ const next = busy !== null ? `busy: ${busy.trim()}` : draft !== null ? `draft: ${draft}` : '';
460
+ if (next !== reason) restartLog(`${session} ${next ? `waits, ${next}` : 'is quiet'}`);
461
+ reason = next;
462
+ draftSince = draft === null ? null : (draftSince ?? Date.now());
463
+ if (!told && draftSince !== null && Date.now() - draftSince >= RESTART_DRAFT_NOTICE_MS) {
464
+ told = true;
465
+ restartNotice(`restart of ${session} waits ${Math.round((Date.now() - draftSince) / 1000)}s, draft: ${draft}`);
466
+ }
467
+ quiet = next ? 0 : quiet + 1;
468
+ if (quiet === 2) return true;
469
+ sleep(RESTART_POLL_MS);
470
+ }
471
+ return false;
472
+ };
473
+
474
+ const backgroundWorkOf = (lines) => {
475
+ const footer = lines.slice(lastRuleIndex(lines) + 1).map(plain);
476
+ return footer.find((line) => BACKGROUND_FOOTER.test(line) || isPanelRow(line))?.trim() ?? null;
477
+ };
478
+
479
+ /** The IDE context chip (`[⧉ In file.ts]`, `[⧉ 3 lines selected]`) shares the prompt line and survives `/clear`. */
480
+ const IDE_CHIP = /\[⧉ [^\]]*\]/g;
481
+ const plain = (line) => line.replace(new RegExp(SGR, 'g'), '');
482
+ const isRule = (line) => /^─{10,}$/.test(plain(line).trim());
483
+ const isPromptMark = (line) => /^\s*[❯›]/.test(plain(line));
484
+ /** A row of the background-agent panel below the footer (`❯ ⏺ main`, ` ● main`, ` ◯ general-purpose …`). */
485
+ const isPanelRow = (line) => /^\s*❯?\s*[⏺●◯]/.test(plain(line));
486
+ const paneLines = (session) => (tmux('capture-pane', '-p', '-e', '-t', `=${session}:`).stdout ?? '').split('\n');
487
+ const lastRuleIndex = (lines) => lines.findLastIndex(isRule);
488
+ /**
489
+ * The prompt is the text between the last two rules of the input box. A `❯` line below the last rule that is not a
490
+ * panel row is a menu (`❯ 1. Yes`) and wins, which keeps a wake-up line from answering a permission dialog.
491
+ */
492
+ const promptLines = (lines) => {
493
+ const below = lastRuleIndex(lines);
494
+ const menu = lines.slice(below + 1).findLast((line) => isPromptMark(line) && !isPanelRow(line));
495
+ if (menu) return [menu];
496
+ const above = lines.slice(0, below).findLastIndex(isRule);
497
+ if (below !== -1 && above !== -1) return lines.slice(above + 1, below);
498
+ const prompt = lines.findLast((line) => isPromptMark(line) && !isPanelRow(line));
499
+ return prompt ? [prompt] : [];
500
+ };
501
+ const withoutDim = (line) => {
502
+ let dim = false;
503
+ return line
504
+ .split(new RegExp(`(${SGR.replace('(', '(?:')})`))
505
+ .map((part) => {
506
+ const codes = part.match(new RegExp(`^${SGR}$`))?.[1].split(';');
507
+ if (!codes) return dim ? '' : part;
508
+ codes.forEach((code) => {
509
+ if (code === '2') dim = true;
510
+ if (code === '' || code === '0' || code === '22') dim = false;
511
+ });
512
+ return '';
513
+ })
514
+ .join('');
515
+ };
516
+ const draftLine = (session) => {
517
+ const text = promptLines(paneLines(session))
518
+ .map(withoutDim)
519
+ .join('\n')
520
+ .replace(/^\s*[❯›]/, '')
521
+ .replace(IDE_CHIP, '')
522
+ .trim();
523
+ return text.length > 0 ? text : null;
524
+ };
525
+ const isInverse = (codes) => {
526
+ for (let index = 0; index < codes.length; index++) {
527
+ if (codes[index] === '38' || codes[index] === '48') index += codes[index + 1] === '2' ? 4 : 2;
528
+ else if (codes[index] === '7') return true;
529
+ }
530
+ return false;
531
+ };
532
+ /** A focused footer pill or panel row is drawn inverse (`ESC[7m`); older builds mark a focused row with `❯`. */
533
+ const panelFocused = (lines) =>
534
+ lines
535
+ .slice(lastRuleIndex(lines) + 1)
536
+ .some(
537
+ (line) =>
538
+ [...line.matchAll(new RegExp(SGR, 'g'))].some((match) => isInverse(match[1].split(';'))) ||
539
+ /^\s*❯\s*[⏺●◯]/.test(plain(line)),
540
+ );
541
+ const PANEL_UP_LIMIT = 10;
542
+ /**
543
+ * Keys typed while the focus sits in the background-agent panel go into the panel. Up moves the focus back to the
544
+ * prompt, and an Up too many recalls history, so C-u clears the line after. `false` if the focus did not leave.
545
+ */
546
+ const leavePanel = (session) => {
547
+ if (!panelFocused(paneLines(session))) return true;
548
+ for (let press = 0; press < PANEL_UP_LIMIT; press++) {
549
+ tmux('send-keys', '-t', `=${session}:`, 'Up');
550
+ sleep(ENTER_DELAY_MS);
551
+ if (!panelFocused(paneLines(session))) {
552
+ tmux('send-keys', '-t', `=${session}:`, 'C-u');
553
+ sleep(ENTER_DELAY_MS);
554
+ return true;
555
+ }
556
+ }
557
+ return false;
558
+ };
559
+ const hasDraft = (session) => draftLine(session) !== null;
560
+ const isAttached = (name) => tmux('list-clients', '-t', `=${name}`).stdout.trim() !== '';
561
+ const freeSessionFor = (agent) => {
562
+ for (let number = 1; ; number++) {
563
+ const session = sessionFor(number === 1 ? agent : `${agent}-${number}`);
564
+ if (!sessionExists(session) || !isAttached(session)) return session;
565
+ }
566
+ };
567
+ const startSession = (name, shellCommand, quiet = false) => {
568
+ if (sessionExists(name)) return quiet ? undefined : process.stdout.write(`Session ${name} already runs.\n`);
569
+ const result = tmux('new-session', '-d', '-s', name, '-c', root, ...(shellCommand ? [shellCommand] : []));
570
+ if (result.status !== 0) return process.stderr.write(`Could not start ${name}: ${result.stderr.trim()}\n`);
571
+ if (!quiet) process.stdout.write(`Started ${name}. Attach with: tmux attach -t ${name}\n`);
572
+ };
573
+
574
+ const ensureDispatch = (quiet = true) =>
575
+ startSession(
576
+ DISPATCH_SESSION,
577
+ `${process.env.AGENT_MAILBOX ? `AGENT_MAILBOX=${quote(process.env.AGENT_MAILBOX)} ` : ''}node ${quote(script)} dispatch`,
578
+ quiet,
579
+ );
580
+
581
+ const IGNORED = ['mailbox.jsonl', 'mailbox.cursor.*', 'restart.log', 'restart.prompt.*', 'restart.lock.*'];
582
+
583
+ const prepare = () => {
584
+ mkdirSync(dirname(mailbox), { recursive: true });
585
+ if (process.env.AGENT_MAILBOX) return;
586
+ const ignore = join(dirname(mailbox), '.gitignore');
587
+ const present = existsSync(ignore) ? readFileSync(ignore, 'utf8') : '';
588
+ const missing = IGNORED.filter((line) => !present.split('\n').includes(line));
589
+ if (missing.length)
590
+ writeFileSync(ignore, `${present && !present.endsWith('\n') ? `${present}\n` : present}${missing.join('\n')}\n`);
591
+ };
592
+
593
+ const append = (entry) => {
594
+ prepare();
595
+ appendFileSync(mailbox, `${JSON.stringify({ timestamp: new Date().toISOString(), ...entry })}\n`, 'utf8');
596
+ };
597
+
598
+ const parse = (line) => {
599
+ if (!line.trim()) return undefined;
600
+ try {
601
+ return JSON.parse(line);
602
+ } catch {
603
+ process.stderr.write('Ignoring malformed mailbox line.\n');
604
+ return undefined;
605
+ }
606
+ };
607
+
608
+ const entries = () => (existsSync(mailbox) ? readFileSync(mailbox, 'utf8').split('\n').map(parse).filter(Boolean) : []);
609
+
610
+ const show = (entry) => process.stdout.write(`[${entry.timestamp}] ${entry.sender}: ${entry.message}\n`);
611
+
612
+ const inboxCursor = (reader) => join(dirname(mailbox), `mailbox.cursor.${reader}`);
613
+
614
+ const unreadFor = (reader) => {
615
+ const cursor = inboxCursor(reader);
616
+ const history = entries();
617
+ const seen = existsSync(cursor) ? Number(readFileSync(cursor, 'utf8')) : history.length - DEFAULT_LAST;
618
+ return { count: history.length, unread: history.slice(Math.max(0, seen)).filter((entry) => entry.sender !== reader) };
619
+ };
620
+
621
+ const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
622
+
623
+ const showInbox = (reader, waitFor = 0) => {
624
+ const deadline = Date.now() + waitFor * 1000;
625
+ let { count, unread } = unreadFor(reader);
626
+ while (!unread.length && Date.now() < deadline) {
627
+ sleep(1000);
628
+ ({ count, unread } = unreadFor(reader));
629
+ }
630
+ if (!unread.length) process.stdout.write('No new messages.\n');
631
+ unread.forEach(show);
632
+ prepare();
633
+ writeFileSync(inboxCursor(reader), String(count));
634
+ };
635
+
636
+ const toRepoPath = (path) => relative(root, resolve(path)).split('\\').join('/');
637
+
638
+ const overlaps = (a, b) => a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
639
+
640
+ const activeClaims = () => {
641
+ const now = Date.now();
642
+ const claims = [];
643
+ for (const entry of entries()) {
644
+ if (entry.type === 'claim') {
645
+ for (const path of entry.paths) claims.push({ sender: entry.sender, path, expires: entry.expires });
646
+ } else if (entry.type === 'release') {
647
+ for (let index = claims.length - 1; index >= 0; index--) {
648
+ const claim = claims[index];
649
+ const released = !entry.paths?.length || entry.paths.some((path) => overlaps(path, claim.path));
650
+ if (claim.sender === entry.sender && released) claims.splice(index, 1);
651
+ }
652
+ }
653
+ }
654
+ return claims.filter((claim) => Date.parse(claim.expires) > now);
655
+ };
656
+
657
+ if (command === 'send' && sender) {
658
+ const message = words.length ? words.join(' ') : process.stdin.isTTY ? '' : readFileSync(0, 'utf8').trim();
659
+ if (!message) {
660
+ process.stderr.write('No message given.\n');
661
+ process.exitCode = 1;
662
+ } else if (recipient && !localSessionFor(recipient)) {
663
+ const checkouts = foreignCheckoutsOf(recipient);
664
+ process.stderr.write(
665
+ `Refused: ${recipient} is not a session of ${repoSlug}${checkouts.length ? `; it belongs to ${checkouts.join(', ')}` : ''}. Nothing was sent. Pass the name of a session ${sessionFor('<agent>')} of this checkout.\n`,
666
+ );
667
+ process.exitCode = 1;
668
+ } else {
669
+ append({ sender, message, ...(recipient ? { to: recipient } : {}) });
670
+ process.stdout.write(`Sent as ${sender}.\n`);
671
+ }
672
+ } else if (command === 'up') {
673
+ ensureDispatch(false);
674
+ [sender, ...words].filter(Boolean).forEach((spec) => {
675
+ const [name, ...rest] = spec.split('=');
676
+ startSession(sessionFor(name), rest.join('=') || undefined);
677
+ });
678
+ } else if (command === 'run' && sender && words.length && role !== undefined && role !== 'builder') {
679
+ process.stderr.write(`Unknown role ${role}. Only builder exists.\n`);
680
+ process.exitCode = 1;
681
+ } else if (command === 'run' && sender && words.length && !hasAgentBinary(words)) {
682
+ process.stderr.write(`Refused: no agent was started, ${words.join(' ')} has no program to run.\n`);
683
+ process.exitCode = 1;
684
+ } else if (command === 'run' && sender && words.length && configMismatch(words)) {
685
+ process.stderr.write(
686
+ `Refused: no agent was started, the command sets CLAUDE_CONFIG_DIR=${configDirOf(words)} but the caller runs under ${callerConfigDir()}. One checkout keeps one config.\n`,
687
+ );
688
+ process.exitCode = 1;
689
+ } else if (command === 'run' && sender && words.length && dryRun) {
690
+ process.stdout.write(
691
+ `${withTempDir([...callerConfigWords(words), ...roleEnvWords(role), ...withRole(words).map(quote)].join(' '))}\n`,
692
+ );
693
+ } else if (
694
+ command === 'run' &&
695
+ sender &&
696
+ words.length &&
697
+ (!runsInSession(words.slice(1)) || (process.env.TMUX && [sessionFor(sender), sender].includes(ownSession())))
698
+ ) {
699
+ if (runsInSession(words.slice(1))) {
700
+ const own = `=${ownSession()}:`;
701
+ tmux(
702
+ 'set-option',
703
+ '-t',
704
+ own,
705
+ COMMAND_OPTION,
706
+ withTempDir(
707
+ [...callerConfigWords(words), ...roleEnvWords(role), ...withRole(withoutPrompt(words)).map(quote)].join(' '),
708
+ ),
709
+ );
710
+ if (role) tmux('set-option', '-t', own, ROLE_OPTION, role);
711
+ }
712
+ const [program, ...programArgs] = withRole(words);
713
+ process.exitCode =
714
+ spawnSync(program, programArgs, {
715
+ stdio: 'inherit',
716
+ env: {
717
+ ...process.env,
718
+ CLAUDE_CODE_TMPDIR: ensuredClaudeTmpDir(),
719
+ ...roleEnvOf(role),
720
+ },
721
+ }).status ?? 1;
722
+ } else if (command === 'run' && sender && words.length) {
723
+ ensureDispatch();
724
+ const session = freeSessionFor(sender);
725
+ const roleEnv = [...callerConfigWords(words), ...roleEnvWords(role)].map((word) => `${word} `).join('');
726
+ const shellCommand = withTempDir(`${roleEnv}${withRole(words).map(quote).join(' ')}`);
727
+ const baseCommand = withTempDir(`${roleEnv}${withRole(withoutPrompt(words)).map(quote).join(' ')}`);
728
+ if (process.env.TMUX) {
729
+ if (sessionExists(session)) {
730
+ process.stderr.write(
731
+ `Refused: ${session} already exists, no second agent was started. Switch to it with: tmux switch-client -t ${session}\n`,
732
+ );
733
+ process.exitCode = 1;
734
+ } else createRunSession(session, shellCommand, baseCommand);
735
+ const callerSession = tmux(
736
+ 'display-message',
737
+ '-p',
738
+ '-t',
739
+ process.env.TMUX_PANE ?? '',
740
+ '#{session_id}',
741
+ ).stdout.trim();
742
+ const [callerClient] = callerSession
743
+ ? tmux('list-clients', '-t', callerSession, '-F', '#{client_tty}').stdout.split('\n').filter(Boolean)
744
+ : [];
745
+ if (!process.exitCode && !callerClient)
746
+ process.stdout.write(`Started ${session}. Attach with: tmux attach -t ${session}\n`);
747
+ process.exitCode ||= callerClient
748
+ ? (spawnSync('tmux', ['switch-client', '-c', callerClient, '-t', `=${session}`], { stdio: 'inherit' }).status ??
749
+ 1)
750
+ : 0;
751
+ } else if (!hasTerminal) {
752
+ if (!sessionExists(session)) createRunSession(session, shellCommand, baseCommand);
753
+ if (!process.exitCode) process.stdout.write(`Started ${session}. Attach with: tmux attach -t ${session}\n`);
754
+ } else {
755
+ if (!sessionExists(session)) createRunSession(session, shellCommand, baseCommand);
756
+ process.exitCode ||= !sessionExists(session)
757
+ ? 1
758
+ : (spawnSync('tmux', ['attach-session', '-t', `=${session}`], { stdio: 'inherit' }).status ?? 1);
759
+ }
760
+ } else if (command === 'shell-init' || command === 'shell-install') {
761
+ const agents = [sender, ...words].filter(Boolean);
762
+ const locate = `_ethlete_agent_sessions_script() {
763
+ local root dir
764
+ root=$(git rev-parse --show-toplevel 2>/dev/null) || return 1
765
+ for dir in .agents/skills .claude/skills; do
766
+ if [ -f "$root/$dir/ethlete-agent-sessions/agent-sessions.mjs" ]; then
767
+ printf '%s\\n' "$root/$dir/ethlete-agent-sessions/agent-sessions.mjs"
768
+ return 0
769
+ fi
770
+ done
771
+ return 1
772
+ }
773
+ `;
774
+ const functions = (agents.length ? agents : ['claude', 'codex'])
775
+ .map(
776
+ (agent) => `${agent}() {
777
+ local script
778
+ script=$(_ethlete_agent_sessions_script)
779
+ if [ -n "$script" ] && command -v tmux >/dev/null; then
780
+ node "$script" run ${agent} ${agent} "$@"
781
+ else
782
+ command ${agent} "$@"
783
+ fi
784
+ }
785
+ `,
786
+ )
787
+ .reduce((text, fn) => text + fn, locate);
788
+ if (command === 'shell-init') {
789
+ process.stdout.write(functions);
790
+ } else {
791
+ const shell = basename(process.env.SHELL ?? '');
792
+ const file = rcFile ?? (shell === 'zsh' ? '.zshrc' : shell === 'bash' ? '.bashrc' : undefined);
793
+ if (!file) {
794
+ process.stderr.write('Unknown shell. Pass --file <path> to the startup file.\n');
795
+ process.exitCode = 1;
796
+ } else {
797
+ const path = rcFile ? resolve(rcFile) : join(homedir(), file);
798
+ const present = existsSync(path) ? readFileSync(path, 'utf8') : '';
799
+ const start = '# >>> ethlete agent-sessions >>>';
800
+ const end = '# <<< ethlete agent-sessions <<<';
801
+ const without = ['agent-mailbox', 'agent-sessions']
802
+ .reduce(
803
+ (text, name) =>
804
+ text.replace(new RegExp(`\\n?# >>> ethlete ${name} >>>[\\s\\S]*?# <<< ethlete ${name} <<<\\n?`), '\n'),
805
+ present,
806
+ )
807
+ .replace(/\n+$/, '\n');
808
+ const block = `${start}\n${functions}${end}\n`;
809
+ const next = remove ? without : `${without}\n${block}`;
810
+ if (dryRun) {
811
+ process.stdout.write(`Would write ${path}:\n${remove ? '(block removed)\n' : block}`);
812
+ } else {
813
+ writeFileSync(path, next);
814
+ process.stdout.write(
815
+ `${remove ? 'Removed the block from' : 'Wrote the block to'} ${path}. Open a new terminal.\n`,
816
+ );
817
+ }
818
+ }
819
+ }
820
+ } else if (command === 'restart' && sender && words.length) {
821
+ const own = process.env.TMUX_PANE
822
+ ? tmux('display-message', '-p', '-t', process.env.TMUX_PANE, '#{session_name}').stdout.trim()
823
+ : null;
824
+ const session = localSessionFor(sender) ?? (own === sender ? own : undefined);
825
+ const dropped = session && !now ? droppedQuestions(session, own, words.join(' ')) : [];
826
+ const pending = session ? pendingRestartOf(session) : null;
827
+ if (session) ensureDispatch();
828
+ if (!session) {
829
+ process.stderr.write(`No tmux session for ${sender}.\n`);
830
+ process.exitCode = 1;
831
+ } else if (pending && pending.pid !== process.pid) {
832
+ process.stderr.write(
833
+ `Refused: a restart of ${session} is already pending (pid ${pending.pid} since ${new Date(pending.since).toISOString()}). Let it finish, or end that process first.\n`,
834
+ );
835
+ restartLog(`${session} refused a second restart, pid ${pending.pid} still pending`);
836
+ process.exitCode = 1;
837
+ } else if (own && own !== session && !arePaired(own, session)) {
838
+ process.stderr.write(
839
+ `Refused: ${session} is not your session. You run in ${own}, so pass ${own.replace(`@${repoSlug}`, '')}.\n`,
840
+ );
841
+ process.exitCode = 1;
842
+ } else if (role !== undefined && role !== 'builder' && role !== 'none') {
843
+ process.stderr.write(`Unknown role ${role}. Pass --role builder or --role none.\n`);
844
+ process.exitCode = 1;
845
+ } else if (newProcess && hasUnknownRole(session, words.join(' '))) {
846
+ process.stderr.write(
847
+ `Refused: ${session} has no role and another agent session runs in this repo, so the new process could lose the builder rule. Resume a builder-* or doc-agent-* handoff, or pass --role builder or --role none.\n`,
848
+ );
849
+ process.exitCode = 1;
850
+ } else if (
851
+ (newProcess || (now && backgroundWorkOf(paneLines(session)) !== null)) &&
852
+ healedCommand(commandWithoutPrompt(agentCommandOf(session)), sender) === null
853
+ ) {
854
+ process.stderr.write(
855
+ `Refused: the stored command of ${session} has no agent program (${agentCommandOf(session)}), restarting would end the session. Nothing was stopped.\n`,
856
+ );
857
+ restartLog(`${session} refused, stored command has no agent program: ${agentCommandOf(session)}`);
858
+ process.exitCode = 1;
859
+ } else if (dropped.length) {
860
+ process.stderr.write(
861
+ `Refused: ${session} asked the human a ❓ question that no later human message answers, and the handoff does not name it. Put each question verbatim under "Open for the human" in the handoff the prompt resumes (/handoff resume <name>), then restart again:\n${dropped.map((question) => `❓ ${question}`).join('\n')}\n`,
862
+ );
863
+ process.exitCode = 1;
864
+ } else if (now) {
865
+ lockRestart(session, process.pid);
866
+ process.on('exit', () => unlockRestart(session));
867
+ const type = (...keys) => tmux('send-keys', '-t', `=${session}:`, ...keys);
868
+ sleep(Number(afterSeconds ?? RESTART_AFTER_SECONDS) * 1000);
869
+ if (!waitForQuiet(session)) {
870
+ restartNotice(`restart of ${session} gave up after ${RESTART_WAIT_MS / 1000}s, reason in restart.log`);
871
+ process.exitCode = 1;
872
+ } else if (!leavePanel(session)) {
873
+ restartNotice(
874
+ `restart of ${session} gave up, the focus did not leave the agent panel after ${PANEL_UP_LIMIT} Up`,
875
+ );
876
+ process.exitCode = 1;
877
+ } else if (newProcess || backgroundWorkOf(paneLines(session)) !== null) {
878
+ const background = newProcess ? null : backgroundWorkOf(paneLines(session));
879
+ if (background !== null)
880
+ restartLog(`${session} shows background work (${background}), restart goes through --process`);
881
+ const pane = `=${session}:`;
882
+ const restartRole = restartRoleOf(session, words.join(' '));
883
+ const recorded = commandWithoutPrompt(agentCommandOf(session));
884
+ const stored = healedCommand(recorded, sender);
885
+ if (configMismatch(stored.split(' ').map((word) => word.replaceAll("'", '')))) {
886
+ restartNotice(
887
+ `restart of ${session} refused, its command sets another CLAUDE_CONFIG_DIR than the caller (${callerConfigDir()})`,
888
+ );
889
+ process.exit(1);
890
+ }
891
+ if (stored !== recorded) {
892
+ tmux('set-option', '-t', pane, COMMAND_OPTION, stored);
893
+ restartLog(`${session} stored command could not restart, healed to: ${stored}`);
894
+ }
895
+ const base = withTempDir(restartRole ? commandWithRole(stored, restartRole) : stored);
896
+ if (restartRole) tmux('set-option', '-t', pane, ROLE_OPTION, restartRole);
897
+ tmux('set-option', '-p', '-t', pane, 'remain-on-exit', 'on');
898
+ type('-l', sender.startsWith('codex') ? '/quit' : '/exit');
899
+ sleep(ENTER_DELAY_MS);
900
+ type('Enter');
901
+ const end = Date.now() + RESTART_EXIT_WAIT_MS;
902
+ const dead = () => tmux('display-message', '-p', '-t', pane, '#{pane_dead}').stdout.trim() === '1';
903
+ const answerExitDialog = () => {
904
+ const lines = (tmux('capture-pane', '-p', '-t', pane).stdout ?? '').split('\n');
905
+ const start = lines.findIndex((line) => EXIT_DIALOG_JOBS.test(line));
906
+ const stop = lines.findIndex((line, index) => index > start && EXIT_AND_STOP.test(line));
907
+ if (start < 0 || stop < 0) return false;
908
+ const selected = lines.findIndex((line, index) => index > start && line.trim().startsWith('❯'));
909
+ const jobs = lines
910
+ .slice(start + 1, stop)
911
+ .map((line) => line.trim())
912
+ .filter(Boolean);
913
+ restartNotice(
914
+ `restart of ${session} stopped its background work, start it again: ${jobs.join('; ') || '(none listed)'}`,
915
+ );
916
+ const between = (from, to) => lines.slice(from, to).filter((line) => line.trim()).length;
917
+ const [key, steps] = selected > stop ? ['Up', between(stop, selected)] : ['Down', between(selected, stop)];
918
+ for (let step = 0; selected >= 0 && step < steps; step++) type(key);
919
+ type('Enter');
920
+ return true;
921
+ };
922
+ let answered = false;
923
+ while (!dead() && Date.now() < end) {
924
+ if (!answered) answered = answerExitDialog();
925
+ sleep(RESTART_POLL_MS / 4);
926
+ }
927
+ if (!dead()) restartLog(`${session} did not exit ${RESTART_EXIT_WAIT_MS / 1000}s after the exit command, killed`);
928
+ const shell = process.env.SHELL || 'sh';
929
+ tmux(
930
+ 'respawn-pane',
931
+ '-k',
932
+ '-t',
933
+ pane,
934
+ '-c',
935
+ root,
936
+ shell,
937
+ '-lic',
938
+ `${bypassingShellFunction(base)} ${quote(restartPrompt(words))}`,
939
+ );
940
+ tmux('set-option', '-p', '-t', pane, 'remain-on-exit', 'off');
941
+ tmux('set-option', '-t', pane, COMMAND_OPTION, base);
942
+ restartLog(`${session} started a new process: ${base}`);
943
+ waitForFirstTurn(session);
944
+ } else {
945
+ type('-l', sender.startsWith('codex') ? '/new' : '/clear');
946
+ sleep(ENTER_DELAY_MS);
947
+ type('Enter');
948
+ sleep(RESTART_CLEAR_MS);
949
+ if (waitForQuiet(session, RESTART_CLEAR_WAIT_MS, true) && leavePanel(session)) {
950
+ type('-l', restartPrompt(words));
951
+ sleep(ENTER_DELAY_MS);
952
+ type('Enter');
953
+ waitForFirstTurn(session);
954
+ } else {
955
+ const saved = join(dirname(mailbox), `restart.prompt.${session}.txt`);
956
+ writeFileSync(saved, `${restartPrompt(words)}\n`);
957
+ restartNotice(
958
+ `restart of ${session} gave up: prompt not empty ${RESTART_CLEAR_WAIT_MS / 1000}s after the clear, prompt not typed, saved to ${saved}`,
959
+ );
960
+ tmux(
961
+ 'display-message',
962
+ '-t',
963
+ `=${session}:`,
964
+ `restart: prompt not empty after the clear, prompt not typed. Saved to ${saved}`,
965
+ );
966
+ process.exitCode = 1;
967
+ }
968
+ }
969
+ } else {
970
+ if (own && own !== session) restartLog(`peer restart: ${own} restarted ${session}`);
971
+ const delay = Number(afterSeconds ?? RESTART_AFTER_SECONDS);
972
+ const forward = notify ? ['--notify', notify] : [];
973
+ const mode = [...(newProcess ? ['--process'] : []), ...(role ? ['--role', role] : [])];
974
+ const child = spawn(
975
+ process.execPath,
976
+ [script, 'restart', sender, '--now', '--after', String(delay), ...forward, ...mode, ...words],
977
+ {
978
+ detached: true,
979
+ stdio: 'ignore',
980
+ },
981
+ );
982
+ lockRestart(session, child.pid);
983
+ child.unref();
984
+ process.stdout.write(
985
+ `${newProcess ? 'Starting a new process in' : 'Restarting'} ${session} once its turn ended and its prompt is empty, ${delay} seconds at the earliest. End your turn now.\n`,
986
+ );
987
+ }
988
+ } else if (command === 'down') {
989
+ [DISPATCH_SESSION, ...[sender, ...words].filter(Boolean).map(sessionFor)].forEach((name) => {
990
+ const result = tmux('kill-session', '-t', `=${name}`);
991
+ process.stdout.write(result.status === 0 ? `Stopped ${name}.\n` : `No session ${name}.\n`);
992
+ });
993
+ } else if (command === 'dispatch') {
994
+ prepare();
995
+ appendFileSync(mailbox, '');
996
+ const started = entries().length;
997
+ let seen = started;
998
+ const woken = {};
999
+ const due = {};
1000
+ const waiting = new Set();
1001
+ const addressedTo = (agent) => {
1002
+ const history = entries();
1003
+ const cursor = inboxCursor(agent);
1004
+ const read = existsSync(cursor) ? Number(readFileSync(cursor, 'utf8')) : 0;
1005
+ return {
1006
+ count: history.length,
1007
+ unread: history
1008
+ .slice(Math.max(read, woken[agent] ?? started))
1009
+ .filter((entry) => entry.to === agent && entry.sender !== agent),
1010
+ };
1011
+ };
1012
+ const wake = (agent) => {
1013
+ if (!addressedTo(agent).unread.length) return;
1014
+ const session = localSessionFor(agent);
1015
+ if (!session) return process.stderr.write(`No tmux session ${sessionFor(agent)} in this checkout.\n`);
1016
+ if (pendingRestartOf(session)) {
1017
+ if (!waiting.has(agent)) process.stdout.write(`Waiting for the restart of ${session}.\n`);
1018
+ waiting.add(agent);
1019
+ due[agent] = Date.now() + DRAFT_RETRY_MS;
1020
+ return;
1021
+ }
1022
+ if (hasDraft(session)) {
1023
+ if (!waiting.has(agent)) process.stdout.write(`Waiting for the typed text in ${session}.\n`);
1024
+ waiting.add(agent);
1025
+ due[agent] = Date.now() + DRAFT_RETRY_MS;
1026
+ return;
1027
+ }
1028
+ waiting.delete(agent);
1029
+ if (!leavePanel(session)) return process.stderr.write(`The focus of ${session} stays in the agent panel.\n`);
1030
+ const { count, unread } = addressedTo(agent);
1031
+ unread.forEach((entry) => {
1032
+ spawnSync('tmux', [
1033
+ 'send-keys',
1034
+ '-t',
1035
+ `=${session}:`,
1036
+ '-l',
1037
+ `Mailbox message from ${entry.sender}: ${normalize(String(entry.message ?? ''))}`,
1038
+ ]);
1039
+ sleep(ENTER_DELAY_MS);
1040
+ spawnSync('tmux', ['send-keys', '-t', `=${session}:`, 'Enter']);
1041
+ });
1042
+ woken[agent] = count;
1043
+ if (existsSync(inboxCursor(agent))) writeFileSync(inboxCursor(agent), String(count));
1044
+ process.stdout.write(`Woke ${session}.\n`);
1045
+ };
1046
+ const poll = () => {
1047
+ const history = entries();
1048
+ const fresh = history.slice(seen);
1049
+ seen = history.length;
1050
+ fresh
1051
+ .filter((entry) => entry.to && entry.to !== entry.sender)
1052
+ .forEach((entry) => (due[entry.to] ??= Date.now() + WAKE_GRACE_MS));
1053
+ Object.keys(due)
1054
+ .filter((agent) => due[agent] <= Date.now())
1055
+ .forEach((agent) => {
1056
+ delete due[agent];
1057
+ wake(agent);
1058
+ });
1059
+ };
1060
+ process.stdout.write(`Dispatching for ${resolve(mailbox)}\n`);
1061
+ setInterval(poll, 1000);
1062
+ } else if (command === 'inbox' && sender) {
1063
+ showInbox(sender, Number(waitSeconds ?? 0));
1064
+ } else if (command === 'read') {
1065
+ const history = entries();
1066
+ (all ? history : history.slice(-Number(last ?? DEFAULT_LAST))).forEach(show);
1067
+ } else if (command === 'claims') {
1068
+ const claims = activeClaims();
1069
+ if (!claims.length) process.stdout.write('No active claims.\n');
1070
+ claims.forEach((claim) => process.stdout.write(`${claim.path} ${claim.sender} until ${claim.expires}\n`));
1071
+ } else if (command === 'claim' && sender && words.length) {
1072
+ showInbox(sender);
1073
+ const paths = words.map(toRepoPath);
1074
+ const conflicts = activeClaims().filter(
1075
+ (claim) => claim.sender !== sender && paths.some((path) => overlaps(path, claim.path)),
1076
+ );
1077
+ if (conflicts.length && !force) {
1078
+ conflicts.forEach((claim) =>
1079
+ process.stderr.write(`Claimed by ${claim.sender}: ${claim.path} until ${claim.expires}\n`),
1080
+ );
1081
+ process.stderr.write('Ask for a handoff, or pass --force to claim anyway.\n');
1082
+ process.exitCode = 2;
1083
+ } else {
1084
+ const hours = ttl === undefined ? DEFAULT_TTL_HOURS : Number(ttl);
1085
+ const expires = new Date(Date.now() + hours * 3_600_000).toISOString();
1086
+ append({ sender, type: 'claim', paths, expires, message: `claims ${paths.join(', ')}` });
1087
+ process.stdout.write(`Claimed ${paths.join(', ')} as ${sender} until ${expires}.\n`);
1088
+ }
1089
+ } else if (command === 'release' && sender) {
1090
+ const paths = words.map(toRepoPath);
1091
+ append({
1092
+ sender,
1093
+ type: 'release',
1094
+ paths,
1095
+ message: paths.length ? `releases ${paths.join(', ')}` : 'releases all claims',
1096
+ });
1097
+ process.stdout.write(`Released as ${sender}.\n`);
1098
+ } else if (command === 'watch' && sender) {
1099
+ prepare();
1100
+ appendFileSync(mailbox, '');
1101
+ let consumed = 0;
1102
+ let pending = '';
1103
+ const update = () => {
1104
+ const contents = readFileSync(mailbox, 'utf8');
1105
+ if (contents.length < consumed) {
1106
+ process.stderr.write('Mailbox was truncated; restarting read.\n');
1107
+ consumed = 0;
1108
+ pending = '';
1109
+ }
1110
+ pending += contents.slice(consumed);
1111
+ consumed = contents.length;
1112
+ const lines = pending.split('\n');
1113
+ pending = lines.pop() ?? '';
1114
+ lines
1115
+ .map(parse)
1116
+ .filter((entry) => entry && entry.sender !== sender)
1117
+ .forEach(show);
1118
+ };
1119
+ process.stdout.write(`Watching ${resolve(mailbox)} as ${sender}\n`);
1120
+ update();
1121
+ watchFile(mailbox, { interval: 1000 }, update);
1122
+ } else {
1123
+ process.stdout.write(help);
1124
+ if (command && command !== '--help') process.exitCode = 1;
1125
+ }