hive-swarm 2.0.0 → 2.1.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.
package/installer.mjs CHANGED
@@ -20,7 +20,7 @@ const standardFiles = ['LICENSE', 'README.md', 'package.json'];
20
20
  export const CORE_PACKAGE_FILES = Object.freeze([
21
21
  '.agents/plugins/marketplace.json', '.codex-plugin/plugin.json', '.mcp.json',
22
22
  'assets/hive-swarm-banner.svg', 'assets/hive-swarm-flow.svg', 'assets/hive-swarm-icon.png', 'assets/hive-swarm-icon.svg',
23
- 'board.css', 'board.html', 'board.js', 'cli.mjs', 'codex.mjs', 'core.mjs', 'engine.mjs', 'hive-bees.js', 'hive-graph.js',
23
+ 'board.css', 'board.html', 'board.js', 'cli.mjs', 'codex.mjs', 'core.mjs', 'engine.mjs', 'hive-bees.js', 'hive-gif.js', 'hive-graph.js',
24
24
  'installer.mjs', 'run-store.mjs', 'server.mjs', 'skills/swarm/SKILL.md', 'skills/swarm/agents/openai.yaml', 'worktrees.mjs',
25
25
  ...standardFiles,
26
26
  ].sort());
@@ -129,13 +129,15 @@ async function publishDirectory(target, populate) {
129
129
  }
130
130
  }
131
131
 
132
- function checkMetadata(bytes, command) {
132
+ function checkMetadata(bytes, command, {allowPriorFiles = false} = {}) {
133
133
  const manifest = json(bytes.get('package.json'));
134
134
  const plugin = json(bytes.get('.codex-plugin/plugin.json'));
135
135
  if (!validIdentity(manifest) || !validIdentity(plugin) || manifest.version !== plugin.version) {
136
136
  throw Error('Hive Swarm package and Codex plugin identities and versions must match.');
137
137
  }
138
- if (!matchesPackageFiles(manifest.files)) throw Error('Unexpected Hive Swarm package allowlist.');
138
+ if (allowPriorFiles ? !priorPackageFiles(manifest.files) : !matchesPackageFiles(manifest.files)) {
139
+ throw Error('Unexpected Hive Swarm package allowlist.');
140
+ }
139
141
  const market = json(bytes.get('.agents/plugins/marketplace.json'));
140
142
  const mcp = json(bytes.get('.mcp.json')).mcpServers;
141
143
  const source = market.plugins?.[0]?.source;
@@ -150,25 +152,41 @@ function checkMetadata(bytes, command) {
150
152
  }
151
153
 
152
154
  const packageDigest = bytes => sha256(JSON.stringify([...bytes].map(([file, contents]) => [file, sha256(contents)])));
155
+ const requiredMetadataFiles = Object.freeze([
156
+ '.agents/plugins/marketplace.json', '.codex-plugin/plugin.json', '.mcp.json',
157
+ 'LICENSE', 'README.md', 'cli.mjs', 'package.json', 'server.mjs', 'skills/swarm/SKILL.md',
158
+ ]);
159
+ const safeRelativeFile = file => typeof file === 'string' && file.length > 0 && file.length <= 260 &&
160
+ !file.startsWith('/') && !file.endsWith('/') && !file.includes('\\') && !file.includes('\0') &&
161
+ !/^[a-zA-Z]:/.test(file) && file.split('/').every(part => part && part !== '.' && part !== '..');
162
+ function priorPackageFiles(files) {
163
+ if (!Array.isArray(files) || !files.every(safeRelativeFile)) return null;
164
+ const all = [...new Set([...files, ...standardFiles])].sort();
165
+ return requiredMetadataFiles.every(file => all.includes(file)) ? all : null;
166
+ }
153
167
 
154
- function readPackage(path, nodePath) {
155
- const bytes = new Map(CORE_PACKAGE_FILES.map(file => [file, readRegularFile(join(path, file))]));
156
- const version = checkMetadata(bytes, nodePath ?? 'node');
157
- return {version, digest: packageDigest(bytes), bytes};
168
+ function readPackage(path, nodePath, {allowPriorFiles = false} = {}) {
169
+ const files = allowPriorFiles
170
+ ? priorPackageFiles(json(readRegularFile(join(path, 'package.json'))).files)
171
+ : CORE_PACKAGE_FILES;
172
+ if (!files) throw Error('Unexpected Hive Swarm package allowlist.');
173
+ const bytes = new Map(files.map(file => [file, readRegularFile(join(path, file))]));
174
+ const version = checkMetadata(bytes, nodePath ?? 'node', {allowPriorFiles});
175
+ return {version, digest: packageDigest(bytes), bytes, files};
158
176
  }
159
177
 
160
- const publicDirectories = new Set(CORE_PACKAGE_FILES.flatMap(file => {
178
+ const directorySet = files => new Set(files.flatMap(file => {
161
179
  const parts = file.split('/');
162
180
  return parts.slice(0, -1).map((_, index) => parts.slice(0, index + 1).join('/'));
163
181
  }));
164
182
 
165
- function verifyTree(path, prefix = '') {
183
+ function verifyTree(path, files = CORE_PACKAGE_FILES, prefix = '', allowedDirs = directorySet(files)) {
166
184
  for (const item of readdirSync(path)) {
167
185
  const file = prefix + item;
168
186
  const next = join(path, item);
169
187
  const stat = entry(next);
170
- if (stat?.isDirectory() && publicDirectories.has(file)) verifyTree(next, file + '/');
171
- else if (!stat?.isFile() || !CORE_PACKAGE_FILES.includes(file)) throw Error('Unexpected entry in a Hive Swarm package copy: ' + next);
188
+ if (stat?.isDirectory() && allowedDirs.has(file)) verifyTree(next, files, file + '/', allowedDirs);
189
+ else if (!stat?.isFile() || !files.includes(file)) throw Error('Unexpected entry in a Hive Swarm package copy: ' + next);
172
190
  }
173
191
  }
174
192
 
@@ -184,12 +202,12 @@ function verifiedRelease(store, version) {
184
202
  throw Error('Invalid Node runtime binding in the Hive Swarm release marker: ' + release);
185
203
  }
186
204
  const path = join(release, 'marketplace');
187
- const actual = readPackage(path, nodePath);
188
- verifyTree(path);
205
+ const actual = readPackage(path, nodePath, {allowPriorFiles: true});
206
+ verifyTree(path, actual.files);
189
207
  if (marker.version !== version || actual.version !== version || marker.digest !== actual.digest) {
190
208
  throw Error('Hive Swarm release differs from its ownership marker: ' + path);
191
209
  }
192
- return {path, version, digest: actual.digest, sourceDigest: bound ? marker.sourceDigest : actual.digest, nodePath};
210
+ return {path, version, digest: actual.digest, sourceDigest: bound ? marker.sourceDigest : actual.digest, nodePath, files: actual.files};
193
211
  }
194
212
 
195
213
  function installedBytes(candidate, nodePath) {
@@ -274,8 +292,10 @@ function cacheVersions(paths, owned) {
274
292
  const path = join(paths.cache, version);
275
293
  if (!owned || !validVersion(version) || !directory(path)) throw Error('Refusing foreign Codex plugin cache: ' + path);
276
294
  const release = verifiedRelease(paths.store, version);
277
- verifyTree(path);
278
- if (readPackage(path, release.nodePath).digest !== release.digest) throw Error('Codex plugin cache differs from the managed release: ' + path);
295
+ verifyTree(path, release.files);
296
+ if (readPackage(path, release.nodePath, {allowPriorFiles: true}).digest !== release.digest) {
297
+ throw Error('Codex plugin cache differs from the managed release: ' + path);
298
+ }
279
299
  return version;
280
300
  });
281
301
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hive-swarm",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "Local multi-agent coordination, dependent tasks, and a shared Swarm board.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -37,6 +37,7 @@
37
37
  "core.mjs",
38
38
  "engine.mjs",
39
39
  "hive-bees.js",
40
+ "hive-gif.js",
40
41
  "hive-graph.js",
41
42
  "installer.mjs",
42
43
  "run-store.mjs",
package/server.mjs CHANGED
@@ -1,21 +1,22 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
3
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
4
4
  import { createServer } from 'node:http';
5
5
  import { homedir } from 'node:os';
6
6
  import { join } from 'node:path';
7
7
  import { createInterface } from 'node:readline';
8
8
  import { setTimeout as delay } from 'node:timers/promises';
9
9
  import { fileURLToPath } from 'node:url';
10
- import { TeamBoard, boardWaitTimeout, childEnvironment, configuredEffort, pendingWaitFor, stallIssues, teamPhase, visibleChannels } from './engine.mjs';
10
+ import { TeamBoard, boardWaitTimeout, childEnvironment, configuredEffort, pendingWaitFor, readSafeScreenshot, stallIssues, teamPhase, visibleChannels } from './engine.mjs';
11
11
  import { openWorktree, removeWorktree, worktreeSource } from './worktrees.mjs';
12
12
 
13
13
  const boardUri = 'ui://hive-swarm/board.html';
14
14
  const asset = name => readFileSync(new URL(name,import.meta.url),'utf8');
15
15
  const {version} = JSON.parse(asset('package.json'));
16
+ const scripts = ['hive-graph.js','hive-bees.js',...(existsSync(new URL('hive-gif.js',import.meta.url))?['hive-gif.js']:[]),'board.js'];
16
17
  const html = asset('board.html').replace('<!-- hive-style -->', () => '<style>'+asset('board.css')+'</style>')
17
18
  .replace('<!-- hive-scripts -->', () => '<script>globalThis.__HIVE_SWARM_VERSION__='+JSON.stringify(version)+';</script>\n' +
18
- ['hive-graph.js','hive-bees.js','board.js'].map(name => '<script>'+asset(name)+'</script>').join('\n'));
19
+ scripts.map(name => '<script>'+asset(name)+'</script>').join('\n'));
19
20
  const root = process.env.HIVE_SWARM_DATA || process.env.TEAM_BOARD_DATA || join(process.env.LOCALAPPDATA || homedir(), 'CodexTeamBoard');
20
21
  const port = Number(process.env.HIVE_SWARM_PORT || process.env.TEAM_BOARD_PORT || 17943);
21
22
  const origin = 'http://127.0.0.1:' + port;
@@ -26,7 +27,7 @@ const strings = {type:'array',items:string};
26
27
  const shape = (properties, required = []) => ({type: 'object', properties, required, additionalProperties: false});
27
28
  const teamId = {teamId: string};
28
29
  const memberForm = shape({
29
- name: string, brief: string, group: string, model: string, effort: string,
30
+ name: string, brief: string, taskLabel: string, group: string, model: string, effort: string,
30
31
  fallbackModel: string, fallbackEffort: {type:['string','null']},
31
32
  fork: string,
32
33
  writable:boolean,worktree:boolean,waitFor:strings,channels:strings,
@@ -34,10 +35,11 @@ const memberForm = shape({
34
35
  tasks:{...strings,minItems:2,maxItems:8,description:'Shard this member into N copies (<name>-1..<name>-N), one per slice; omit for a single worker.'},
35
36
  }, ['name','brief']);
36
37
  const threadForm = shape({id:string,title:string,goal:string,members:strings}, ['id','title','goal']);
38
+ const taskUpdateForm = shape({member:string,label:{type:['string','null']}},['member','label']);
37
39
  const tools = [
38
40
  {
39
- name: 'start_team', title: 'Start a team', description: 'Start a user-requested team in a local workspace. Workers wait for their dependencies and mentions. Set writable only for members authorized to edit. Pass fork: "coordinator" on a member to inherit the current conversation. Optionally pass threads (outcome groups) and fallbackModel (quota failover).',
40
- inputSchema: shape({title: string, cwd: string, task: string, model: string, effort: string,
41
+ name: 'start_team', title: 'Start a team', description: 'Start a user-requested team in a local workspace. Workers wait for their dependencies and mentions. Set writable only for members authorized to edit. Pass fork: "coordinator" on a member to inherit the current conversation. Optionally pass goalLine, member taskLabel, threads (outcome groups), and fallbackModel (quota failover).',
42
+ inputSchema: shape({title: string, goalLine: string, cwd: string, task: string, model: string, effort: string,
41
43
  fallbackModel: string, fallbackEffort: {type:['string','null']},
42
44
  threads: {type:'array',items:threadForm}, coordinator:boolean,
43
45
  concurrency: integer, turnLimit: integer, members: {type: 'array', items: memberForm}},
@@ -80,9 +82,9 @@ const tools = [
80
82
  inputSchema:shape({...teamId,title:string},['teamId','title']),
81
83
  },
82
84
  {
83
- name:'set_team_plan',title:'Update outcome threads',
84
- description:'Set or update outcome-grouped threads displayed in the Swarm Overview.',
85
- inputSchema:shape({...teamId,threads:{type:'array',items:threadForm}},['teamId','threads']),
85
+ name:'set_team_plan',title:'Update team plan and outcome threads',
86
+ description:'Set or update optional team goalLine, member task labels, and outcome-grouped threads displayed in the Swarm Overview.',
87
+ inputSchema:shape({...teamId,goalLine:{type:['string','null']},tasks:{type:'array',items:taskUpdateForm},threads:{type:'array',items:threadForm}},['teamId']),
86
88
  },
87
89
  {
88
90
  name:'resolve_recovery',title:'Resolve an unconfirmed worker run',
@@ -219,16 +221,22 @@ function present(team, origin, activity, actor) {
219
221
  const events=visible?team.events.filter(event=>visible.includes(event.channel??'main')):team.events;
220
222
  return {
221
223
  id,title,cwd,task,model,effort,paused,turns,turnLimit,channels,activity,phase,
224
+ ...(team.goalLine?{goalLine:team.goalLine}:{}),
222
225
  ...(team.parentSessionId?{parentSessionId:team.parentSessionId}:{}),
223
226
  ...(team.fallbackModel?{fallbackModel:team.fallbackModel,...(team.fallbackEffort!==undefined?{fallbackEffort:team.fallbackEffort}:{})}:{}),
224
227
  ...(team.threads?.length?{threads:team.threads}:{}),
228
+ ...(team.screenshots?.length?{screenshots:team.screenshots.map(({id:shotId,seq,index,author,caption,time})=>({
229
+ id:shotId,seq,index,author,caption,time,
230
+ url:'/board/'+id+'/screenshot/'+seq+'/'+index,
231
+ }))}:{}),
225
232
  attention:phase==='stalled'?issues:phase==='budget'?
226
233
  [{kind:'budget',text:'Turn limit reached ('+turns+'/'+turnLimit+'). Add 8 turns to continue.'},...blockers]:blockers,
227
234
  ...panelLink(team, origin),
228
235
  members: team.members.map(member => {
229
- const {name,role,group,brief,threadId,status,writable,waitFor,retireAfterTurn,worktree,workspace,addedBy,channels,lastTurn,fallbackModel,fallbackEffort,subagentName} = member;
236
+ const {name,role,group,brief,taskLabel,threadId,status,writable,waitFor,retireAfterTurn,worktree,workspace,addedBy,channels,lastTurn,fallbackModel,fallbackEffort,subagentName} = member;
230
237
  const executionMode = member.executionMode ?? (threadId ? 'session' : undefined);
231
238
  return {name,role,group,brief,threadId,status,writable,waitFor,retireAfterTurn,worktree,workspace,addedBy,channels,lastTurn,
239
+ ...(taskLabel?{taskLabel}:{}),
232
240
  ...(executionMode?{executionMode}:{}),
233
241
  ...(subagentName?{subagentName}:{}),
234
242
  ...(fallbackModel?{fallbackModel,...(fallbackEffort!==undefined?{fallbackEffort}:{})}:{}),
@@ -337,6 +345,7 @@ export async function service({dataDirectory = root, listenPort = port, runner}
337
345
  try {
338
346
  const {pathname,searchParams} = new URL(req.url, origin);
339
347
  const isBoard = pathname.match(/^\/board\/([a-f0-9-]{36})$/);
348
+ const screenshot = pathname.match(/^\/board\/([a-f0-9-]{36})\/screenshot\/(\d+)\/(\d+)$/);
340
349
  const transcript = pathname.match(/^\/board\/([a-f0-9-]{36})\/member\/([a-z][a-z0-9_-]{0,29})\/transcript$/);
341
350
  const api = pathname.match(/^\/board\/([a-f0-9-]{36})\/(status|history|post|pause|resume|events|member-model|member-retire|worktree-remove|title|resolve-recovery)$/);
342
351
  if ((isBoard || pathname === '/swarm') && req.method === 'GET') {
@@ -345,10 +354,24 @@ export async function service({dataDirectory = root, listenPort = port, runner}
345
354
  'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store',
346
355
  'Referrer-Policy': 'no-referrer', 'X-Content-Type-Options': 'nosniff',
347
356
  'X-Frame-Options': 'DENY',
348
- 'Content-Security-Policy': "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; base-uri 'none'; form-action 'none'",
357
+ 'Content-Security-Policy': "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; base-uri 'none'; form-action 'none'",
349
358
  });
350
359
  return res.end(html);
351
360
  }
361
+ if (screenshot && req.method==='GET') {
362
+ if (req.headers['sec-fetch-site']!=='same-origin') return send(res,403,{error:'Open Swarm to view board screenshots.'});
363
+ const [,id,rawSeq,rawIdx]=screenshot;
364
+ const file=readSafeScreenshot(board,dataDirectory,id,Number(rawSeq),Number(rawIdx));
365
+ if (!file) return send(res,404,{error:'Screenshot not found.'});
366
+ res.writeHead(200,{
367
+ 'Content-Type':file.contentType,
368
+ 'Cache-Control':'no-store',
369
+ 'X-Content-Type-Options':'nosniff',
370
+ 'Cross-Origin-Resource-Policy':'same-origin',
371
+ 'Content-Length':String(file.body.byteLength),
372
+ });
373
+ return res.end(file.body);
374
+ }
352
375
  if (pathname === '/swarm/teams' && req.method === 'GET') {
353
376
  if (req.headers['sec-fetch-site'] !== 'same-origin') return send(res, 403, {error:'Open Swarm to list its teams.'});
354
377
  return send(res,200,recentTeams(board));
@@ -534,7 +557,15 @@ export async function service({dataDirectory = root, listenPort = port, runner}
534
557
  case 'board_status': team = board.get(args.teamId); break;
535
558
  case 'post_message': team = board.post(args.teamId,args.text,args.channel); break;
536
559
  case 'set_team_title': team = board.setTeamTitle(args.teamId,args.title,actor); break;
537
- case 'set_team_plan': team = board.setTeamPlan(args.teamId,args.threads,actor); break;
560
+ case 'set_team_plan': {
561
+ const plan=Array.isArray(args)?args:{
562
+ ...(Object.hasOwn(args,'goalLine')?{goalLine:args.goalLine}:{}),
563
+ ...(Object.hasOwn(args,'tasks')?{tasks:args.tasks}:{}),
564
+ ...(Object.hasOwn(args,'threads')?{threads:args.threads}:{}),
565
+ };
566
+ team = board.setTeamPlan(args.teamId,plan,actor);
567
+ break;
568
+ }
538
569
  case 'resolve_recovery': team = board.resolveRecovery(args.teamId,args.member,{action:args.action}); break;
539
570
  case 'pause_team': team = board.pause(args.teamId); break;
540
571
  case 'resume_team': team = board.resume(args.teamId, args.extraTurns); break;
@@ -14,21 +14,22 @@ As coordinator, delegate technical work — code edits, research, investigations
14
14
  ## Start the team
15
15
 
16
16
  1. **Size lean and design disjoint file ownership**: Count the pieces that can genuinely proceed independently; use one worker for a tightly coupled change. Assign disjoint file ownership before anyone starts — two writers editing the same file is a failure mode to design out, not manage. Name workers for their job (`parser`, `verifier`, `docs`), never `agent-1`. Aim for one read-only verifier per 2–4 writers, with `waitFor` listing the responsible workers and an explicit check to run (a verifier reports and the author fixes). Default to read-only; set `writable: true` only for user-authorized edits. Keep at most 12 active workers; use `n` for identical shards or `tasks` for distinct slices under one `group`.
17
- 2. **Write self-contained public briefs, or fork warm context**: Every brief is posted publicly on the board and is everything a fresh worker receives — state what it owns, what it must not touch, and what "done" looks like. Pass `fork: "coordinator"` on a member in `start_team` (or `add_member`) when a worker needs the files already read, decisions made, and reasoning in this coordinator conversation instead of starting cold; pass `fork: "<teammate>"` in `add_member` to inherit a teammate's saved chat.
17
+ 2. **Write self-contained public briefs, or fork warm context**: Every brief is posted publicly on the board and is everything a fresh worker receives — state what it owns, what it must not touch, and what "done" looks like. Set a crisp `taskLabel` (`<= 96` chars) on each member so the Overview task list is immediately scannable. Pass `fork: "coordinator"` on a member in `start_team` (or `add_member`) when a worker needs the files already read, decisions made, and reasoning in this coordinator conversation instead of starting cold; pass `fork: "<teammate>"` in `add_member` to inherit a teammate's saved chat.
18
18
  3. **Give concurrent writers isolated worktrees**: For writers that edit or build at the same time, set `worktree: true` (each starts from the committed Git revision) while leaving readers and verifiers on the shared checkout. Have each author commit in its worktree and leave integration into the main checkout to the coordinator/user.
19
- 4. **Verify models and routes first**: Use the current local project's absolute `cwd`. Resolve explicitly requested or role-matched models and reasoning efforts via `list_models` before launching — never silently substitute an unconfigured model. Keep the user's requested model or current chat's model (omit `model` for the runtime default unless requested or role-matched). Optionally pass `fallbackModel` / `fallbackEffort` on the team or member when the user wants automatic quota failover.
20
- 5. **Call `start_team` once**: Preserve the user's file scope, deliverables, and turn limit. Include optional outcome `threads` (`[{id, title, goal, members}]`) — or update them later via `set_team_plan` — so the Overview tracks outcomes (`Blocked` -> `Active` -> `Queued` -> `Done`). In a Goal, set `coordinator: false` so the current chat is the sole coordinator; in a regular one-turn chat, set `coordinator: true` only when you want `@coordinator` to summarize completed worker rounds in the background. Under Codex Desktop, worker threads stay attached to the parent conversation instead of cluttering the sidebar.
19
+ 4. **Verify models and routes first (Strict Model Lock)**: Use the current local project's absolute `cwd`. Resolve explicitly requested or role-matched models and reasoning efforts via `list_models` before launching — keep Strict Model Lock by default and never silently substitute an unconfigured model or provider. Keep the user's requested model or current chat's model (omit `model` for the runtime default unless requested or role-matched). Pass `fallbackModel` / `fallbackEffort` on the team or member only when the user opts into automatic quota failover.
20
+ 5. **Follow Overview Plan discipline and call `start_team` once**: Preserve the user's file scope, deliverables, and turn limit. Include a concise `goalLine` (`<= 140` chars), per-member `taskLabel` (`<= 96` chars), and 1–6 outcome `threads` (`[{id, title, goal, members}]`) so Overview tracks outcomes (`Blocked` -> `Active` -> `Queued` -> `Done`). Call `set_team_plan` (`{ goalLine, tasks, threads }`) only when scope, labels, or roster actually change — never churn plans mid-round. In a Goal, set `coordinator: false` so the current chat is the sole coordinator; in a regular one-turn chat, set `coordinator: true` only when you want `@coordinator` to summarize completed worker rounds in the background. Under Codex Desktop, worker threads stay attached to the parent conversation instead of cluttering the sidebar.
21
21
  6. **Open the Swarm UI**: Immediately call the Codex app tool `open_in_codex` with the exact `openInCodex` arguments returned by `start_team` or `open_swarm_panel` (omit `threadId` unless the user asks for another chat). If the host has no panel tool or it reports an error, fall back to `open_board` as the inline MCP App. In either case, give the user a clickable Markdown link labeled `🐝 Open Swarm UI` to the returned `url`, along with the work split and actual team status.
22
22
 
23
23
  ## Coordinate on the board
24
24
 
25
25
  - **`@name` is a wakeup doorbell, never a CC**: Write teammate names without `@` when merely referencing them in prose. Use `@name` (or `@group`, `@#channel`) only for members who must take a turn next. Brief builders and verifiers for direct peer-to-peer handoffs (`@builder` <-> `@verifier`), reserving `@coordinator` for final delivery, blockers, or scope changes. Reserve `@all` for genuine team-wide rules or interface decisions, never for status. A post with no recipient does not wake an idle member.
26
26
  - **Cite `#seq` and finish with `[done]`**: Refer to earlier board posts by sequence number (`#4`, `#12`) instead of copy-pasting or summarizing one worker's report into another worker's message (`@verifier check #4 and #6`). Ask workers to start finished reports with `[done]` and never double-post their final report via `post_to_board` right before returning their turn-end report.
27
+ - **Visual timeline (`Screenshot: <path> | <caption>`)**: For UI/visual tasks, instruct UI authors or verifiers to include `Screenshot: <path> | <caption>` lines (workspace-relative or inside the workspace/data directory, `.png`/`.jpg`/`.jpeg`/`.webp`, `<= 10 MiB`, caption `1–140` chars) in their board post or report so Overview displays a safe visual timeline. Skip screenshots for pure backend, API, or documentation tasks.
27
28
  - **Channels — keep `main` quiet**: For multi-area or larger swarms, split workstreams with `manage_channel` (`create`, `subscribe`, `unsubscribe`, `archive`). Everyone sees `main` plus their subscribed channels, so keep area chatter inside its channel (`channel`, `@#channel`) and reserve `main` for cross-area asks, decisions, and final results. Archive channels when an area finishes.
28
29
  - **Wait without polling**: In a Goal, call `wait_for_board` with the last seen `since` cursor rather than polling `board_status` or `board_history` in a loop. If `hasMore` is true, continue from the last returned post. Act on stopped or stalled phases before issuing the next wait: read `[stall]` and structured `attention` issues (unaddressed `#seq`, unanswered mention, dependency root blocker) from saved facts without starting a diagnostic model turn. Use `board_history` with a cursor to read earlier posts.
29
30
 
30
31
  ## Roster, quota, recovery, and cleanup
31
32
 
32
- - **Roster updates**: Look up the team first. Use `add_member` to invite a worker, `replaces` to transfer an idle worker's unfinished dependencies, and `fork: "coordinator"` or `fork: "<teammate>"` to inherit warm history. Read-only workers can invite only read-only helpers. Use `retire_member` (member or shard group) once nothing depends on it; retirement is permanent — never retire as a pause, because idle waiting workers cost nothing. Use `set_team_title` for a requested rename.
33
- - **Switch model on quota without killing history**: Never retire and re-add a worker that hits quota (`status: "quota"`). Use `set_member_model` (`effort: null` for the model default, `resume: true` to wake an idle member) so the worker keeps its saved conversation history (a history-preserving fork handles provider changes automatically). Verify configured and executed routes via `list_models` and member Journals.
33
+ - **Roster updates**: Look up the team first. Use `add_member` (including `taskLabel`) to invite a worker, `replaces` to transfer an idle worker's unfinished dependencies, and `fork: "coordinator"` or `fork: "<teammate>"` to inherit warm history. Update `set_team_plan` only if the scope or roster changes. Read-only workers can invite only read-only helpers. Use `retire_member` (member or shard group) once nothing depends on it; retirement is permanent — never retire as a pause, because idle waiting workers cost nothing. Use `set_team_title` for a requested rename.
34
+ - **Switch model on quota without killing history**: Never retire and re-add a worker that hits quota (`status: "quota"`). Use `set_member_model` (`effort: null` for the model default, `resume: true` to wake an idle member) so the worker keeps its saved conversation history (a history-preserving fork handles provider changes automatically). Verify configured and executed routes (`Verified route:` / active model) via `list_models` and member Journals.
34
35
  - **Recovery and worktree cleanup**: If a member has an unconfirmed run (`recoveryRequired`), inspect its Journal first and resolve explicitly with `resolve_recovery` (`action: "retry"` or `"dismiss"`). Use `remove_worktree` when the user asks to clean a checkout after its member retires or the team finishes (`force: true` only on explicit user request to discard uncommitted changes). The user can add eight turns from the board when the team reaches its turn limit.
package/worktrees.mjs CHANGED
@@ -1,98 +1,167 @@
1
- import { execFile } from 'node:child_process';
2
- import { lstat, mkdir, realpath } from 'node:fs/promises';
3
- import { isAbsolute, join, relative, sep } from 'node:path';
4
- import { promisify } from 'node:util';
5
-
6
- const execute = promisify(execFile);
7
-
8
- async function git(cwd, args, timeout = 5000) {
9
- try {
10
- const {stdout} = await execute('git', ['-C', cwd, ...args], {windowsHide:true, timeout});
11
- return stdout.trim();
12
- } catch (error) {
13
- const detail = String(error.stderr || error.message).trim().slice(-380);
14
- throw Error('Git ' + args[0] + ' failed: ' + detail);
15
- }
16
- }
17
-
18
- async function repository(cwd) {
19
- const [root, directory] = (await git(cwd, ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir'])).split(/\r?\n/);
20
- return {root:await realpath(root), directory:await realpath(directory)};
21
- }
22
-
23
- function within(root, target) {
24
- const offset = relative(root, target);
25
- return !isAbsolute(offset) && offset !== '..' && !offset.startsWith('..' + sep);
26
- }
27
-
28
- export async function worktreeSource(cwd) {
29
- const workspace = await realpath(cwd);
30
- const repo = await repository(workspace);
31
- if (!within(repo.root, workspace)) throw Error('Workspace is outside its Git repository.');
32
- const commit = await git(repo.root, ['rev-parse', '--verify', 'HEAD^{commit}']);
33
- const offset = relative(repo.root, workspace);
34
- if (offset) {
35
- const objectType = await git(repo.root, ['cat-file', '-t', commit + ':' + offset.split(sep).join('/')]);
36
- if (objectType !== 'tree') throw Error('Workspace must be a directory in the selected commit.');
37
- }
38
- return {...repo, commit, offset};
39
- }
40
-
41
- async function managedPath(storage, teamId, member, create = false) {
42
- if (!/^[a-f0-9-]{36}$/.test(teamId) || !/^[a-z][a-z0-9_-]{0,29}$/.test(member)) {
43
- throw Error('Invalid team or member workspace name.');
44
- }
45
- if (create) await mkdir(storage, {recursive:true});
46
- const root = await realpath(storage);
47
- const directory = join(root, 'worktrees', teamId);
48
- if (create) await mkdir(directory, {recursive:true});
49
- const resolved = await realpath(directory).catch(error => {
50
- if (create || error.code !== 'ENOENT') throw error;
51
- return null;
52
- });
53
- if (resolved && relative(directory,resolved)) throw Error('Unexpected worktree storage location.');
54
- return join(directory, teamId + '-' + member);
55
- }
56
-
57
- async function ownedCheckout(destination, source) {
58
- const previous = await lstat(destination).catch(error => {
59
- if (error.code !== 'ENOENT') throw error;
60
- return null;
61
- });
62
- if (!previous) return false;
63
- if (!previous.isDirectory() || relative(destination, await realpath(destination))) {
64
- throw Error('Existing worktree path is not an owned checkout: ' + destination);
65
- }
66
- const found = await repository(destination);
67
- if (relative(destination, found.root) || relative(source.directory, found.directory)) {
68
- throw Error('Existing worktree belongs to a different repository: ' + destination);
69
- }
70
- return true;
71
- }
72
-
73
- export async function openWorktree(storage, source, teamId, member, {mustExist = false} = {}) {
74
- const destination = await managedPath(storage, teamId, member, true);
75
- if (!(await ownedCheckout(destination, source))) {
76
- if (mustExist) throw Error('Saved worktree is missing: ' + destination);
77
- await git(source.root, ['worktree', 'add', '--detach', destination, source.commit], 120000);
78
- }
79
- const cwd = await realpath(join(destination, source.offset));
80
- if (!within(destination, cwd)) throw Error('Worktree workspace resolved outside its checkout.');
81
- return {path:destination, cwd, base:source.commit};
82
- }
83
-
84
- export async function removeWorktree(storage, source, teamId, member, workspace, {force = false} = {}) {
85
- const destination = await managedPath(storage, teamId, member);
86
- if (!isAbsolute(workspace.path) || relative(destination, workspace.path)) {
87
- throw Error('The saved path is not the owned checkout for this member.');
88
- }
89
- const exists = await ownedCheckout(destination, source);
90
- if (exists) {
91
- if (force !== true && await git(destination, ['status','--porcelain','--untracked-files=all'])) {
92
- throw Error('The worktree has uncommitted changes. Use force only to discard them.');
93
- }
94
- const options = force === true ? ['--force'] : [];
95
- await git(source.root, ['worktree','remove',...options,'--',destination], 120000);
96
- }
97
- await git(source.root, ['worktree','prune',...(exists ? [] : ['--expire','now'])]);
98
- }
1
+ import { execFile } from 'node:child_process';
2
+ import { realpathSync } from 'node:fs';
3
+ import { lstat, mkdir } from 'node:fs/promises';
4
+ import path, { isAbsolute, join, resolve, sep } from 'node:path';
5
+ import { setTimeout as delay } from 'node:timers/promises';
6
+ import { promisify } from 'node:util';
7
+
8
+ const execute = promisify(execFile);
9
+ const repoQueues = new Map();
10
+ const pathOps = (platform = process.platform) => platform === 'win32' ? path.win32 : path.posix;
11
+
12
+ function realPathSync(target) {
13
+ return (realpathSync.native ?? realpathSync)(target);
14
+ }
15
+
16
+ function canonicalCase(target, platform = process.platform) {
17
+ return platform === 'win32' ? target.toLowerCase() : target;
18
+ }
19
+
20
+ export function samePath(left, right, platform = process.platform) {
21
+ return pathOps(platform).relative(canonicalCase(left, platform), canonicalCase(right, platform)) === '';
22
+ }
23
+
24
+ export function within(root, target, platform = process.platform) {
25
+ const ops = pathOps(platform);
26
+ const offset = ops.relative(canonicalCase(root, platform), canonicalCase(target, platform));
27
+ return !ops.isAbsolute(offset) && offset !== '..' && !offset.startsWith('..' + ops.sep);
28
+ }
29
+
30
+ function relativeOffset(root, target, platform = process.platform) {
31
+ const ops = pathOps(platform);
32
+ if (platform !== 'win32') return ops.relative(root, target);
33
+ const rel = ops.relative(root.toLowerCase(), target.toLowerCase());
34
+ if (!rel || ops.isAbsolute(rel) || rel === '..' || rel.startsWith('..' + ops.sep)) return rel;
35
+ const cleanRoot = ops.resolve(root);
36
+ const cleanTarget = ops.resolve(target);
37
+ if (cleanTarget.toLowerCase().startsWith(cleanRoot.toLowerCase())) {
38
+ const rest = cleanTarget.slice(cleanRoot.length).replace(/^[\\/]+/, '');
39
+ if (rest.toLowerCase() === rel.toLowerCase()) return rest;
40
+ }
41
+ return rel;
42
+ }
43
+
44
+ function isTransientLockError(error) {
45
+ if (!error) return false;
46
+ if (['EPERM', 'EBUSY', 'EACCES'].includes(error.code)) return true;
47
+ const text = String(error.stderr || error.message || error);
48
+ return /\.git[\\/]worktrees[\\/]|commondir|index\.lock|\bEPERM\b|\bEBUSY\b|unable to create .*\.lock|cannot lock|permission denied/i.test(text);
49
+ }
50
+
51
+ function lockKey(directory) {
52
+ try { return canonicalCase(realPathSync(directory)); }
53
+ catch { return canonicalCase(resolve(directory)); }
54
+ }
55
+
56
+ async function withRepoLock(directory, task) {
57
+ const key = lockKey(directory);
58
+ const previous = repoQueues.get(key) ?? Promise.resolve();
59
+ const run = previous.catch(() => {}).then(task);
60
+ const tail = run.catch(() => {});
61
+ repoQueues.set(key, tail);
62
+ try {
63
+ return await run;
64
+ } finally {
65
+ if (repoQueues.get(key) === tail) repoQueues.delete(key);
66
+ }
67
+ }
68
+
69
+ async function git(cwd, args, timeout = 5000, {exec = execute, retryDelayMs = 120} = {}) {
70
+ for (let attempt = 0; ; attempt++) {
71
+ try {
72
+ const {stdout} = await exec('git', ['-C', cwd, ...args], {windowsHide:true, timeout});
73
+ return stdout.trim();
74
+ } catch (error) {
75
+ if (attempt === 0 && isTransientLockError(error)) {
76
+ await delay(retryDelayMs);
77
+ continue;
78
+ }
79
+ const detail = String(error.stderr || error.message).trim().slice(-380);
80
+ throw Error('Git ' + args[0] + ' failed: ' + detail);
81
+ }
82
+ }
83
+ }
84
+
85
+ async function repository(cwd, gitOpts) {
86
+ const [root, directory] = (await git(cwd, ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir'], 5000, gitOpts)).split(/\r?\n/);
87
+ return {root: realPathSync(root), directory: realPathSync(directory)};
88
+ }
89
+
90
+ export async function worktreeSource(cwd) {
91
+ const workspace = realPathSync(cwd);
92
+ const repo = await repository(workspace);
93
+ if (!within(repo.root, workspace)) throw Error('Workspace is outside its Git repository.');
94
+ const commit = await git(repo.root, ['rev-parse', '--verify', 'HEAD^{commit}']);
95
+ const offset = relativeOffset(repo.root, workspace);
96
+ if (offset) {
97
+ const objectType = await git(repo.root, ['cat-file', '-t', commit + ':' + offset.split(sep).join('/')]);
98
+ if (objectType !== 'tree') throw Error('Workspace must be a directory in the selected commit.');
99
+ }
100
+ return {...repo, commit, offset};
101
+ }
102
+
103
+ async function managedPath(storage, teamId, member, create = false) {
104
+ if (!/^[a-f0-9-]{36}$/.test(teamId) || !/^[a-z][a-z0-9_-]{0,29}$/.test(member)) {
105
+ throw Error('Invalid team or member workspace name.');
106
+ }
107
+ if (create) await mkdir(storage, {recursive:true});
108
+ const root = realPathSync(storage);
109
+ const directory = join(root, 'worktrees', teamId);
110
+ if (create) await mkdir(directory, {recursive:true});
111
+ let resolved = null;
112
+ try { resolved = realPathSync(directory); }
113
+ catch (error) {
114
+ if (create || error.code !== 'ENOENT') throw error;
115
+ }
116
+ if (resolved && !samePath(directory, resolved)) throw Error('Unexpected worktree storage location.');
117
+ return join(directory, teamId + '-' + member);
118
+ }
119
+
120
+ async function ownedCheckout(destination, source, gitOpts) {
121
+ const previous = await lstat(destination).catch(error => {
122
+ if (error.code !== 'ENOENT') throw error;
123
+ return null;
124
+ });
125
+ if (!previous) return false;
126
+ if (!previous.isDirectory() || !samePath(destination, realPathSync(destination))) {
127
+ throw Error('Existing worktree path is not an owned checkout: ' + destination);
128
+ }
129
+ const found = await repository(destination, gitOpts);
130
+ if (!samePath(destination, found.root) || !samePath(source.directory, found.directory)) {
131
+ throw Error('Existing worktree belongs to a different repository: ' + destination);
132
+ }
133
+ return true;
134
+ }
135
+
136
+ export async function openWorktree(storage, source, teamId, member, {mustExist = false, exec, retryDelayMs = 120} = {}) {
137
+ const gitOpts = {exec, retryDelayMs};
138
+ return withRepoLock(source.directory, async () => {
139
+ const destination = await managedPath(storage, teamId, member, true);
140
+ if (!(await ownedCheckout(destination, source, gitOpts))) {
141
+ if (mustExist) throw Error('Saved worktree is missing: ' + destination);
142
+ await git(source.root, ['worktree', 'add', '--detach', destination, source.commit], 120000, gitOpts);
143
+ }
144
+ const cwd = realPathSync(join(destination, source.offset));
145
+ if (!within(destination, cwd)) throw Error('Worktree workspace resolved outside its checkout.');
146
+ return {path:destination, cwd, base:source.commit};
147
+ });
148
+ }
149
+
150
+ export async function removeWorktree(storage, source, teamId, member, workspace, {force = false, exec, retryDelayMs = 120} = {}) {
151
+ const gitOpts = {exec, retryDelayMs};
152
+ return withRepoLock(source.directory, async () => {
153
+ const destination = await managedPath(storage, teamId, member);
154
+ if (!isAbsolute(workspace.path) || !samePath(destination, workspace.path)) {
155
+ throw Error('The saved path is not the owned checkout for this member.');
156
+ }
157
+ const exists = await ownedCheckout(destination, source, gitOpts);
158
+ if (exists) {
159
+ if (force !== true && await git(destination, ['status','--porcelain','--untracked-files=all'], 5000, gitOpts)) {
160
+ throw Error('The worktree has uncommitted changes. Use force only to discard them.');
161
+ }
162
+ const options = force === true ? ['--force'] : [];
163
+ await git(source.root, ['worktree','remove',...options,'--',destination], 120000, gitOpts);
164
+ }
165
+ await git(source.root, ['worktree','prune',...(exists ? [] : ['--expire','now'])], 5000, gitOpts);
166
+ });
167
+ }