@chankov/agent-fleet 0.0.1 → 0.0.3

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 (65) hide show
  1. package/.claude/commands/doctor-agent-fleet.md +1 -1
  2. package/.claude/commands/setup-agent-fleet.md +4 -4
  3. package/.opencode/commands/af-doctor-agent-fleet.md +2 -0
  4. package/.opencode/commands/af-setup-agent-fleet.md +1 -1
  5. package/.pi/agents/model-profiles.yaml +12 -12
  6. package/.pi/agents/peers.yaml +26 -22
  7. package/.pi/agents/teams.yaml +2 -2
  8. package/.pi/harnesses/agent-hub/README.md +57 -4
  9. package/.pi/harnesses/agent-hub/index.ts +236 -80
  10. package/.pi/harnesses/agent-hub/research-retention.js +34 -0
  11. package/.pi/harnesses/ask-user-remote/README.md +8 -0
  12. package/.pi/harnesses/ask-user-remote/index.ts +41 -1
  13. package/.pi/harnesses/coms/README.md +11 -0
  14. package/.pi/prompts/doctor-agent-fleet.md +1 -1
  15. package/.pi/prompts/setup-agent-fleet.md +4 -4
  16. package/README.md +133 -354
  17. package/agents/architect.md +4 -2
  18. package/agents/bowser.md +2 -1
  19. package/agents/builder.md +3 -2
  20. package/agents/code-reviewer.md +7 -7
  21. package/agents/deep-researcher.md +3 -3
  22. package/agents/documenter.md +3 -1
  23. package/agents/orchestrator.md +5 -3
  24. package/agents/plan-reviewer.md +5 -5
  25. package/agents/planner.md +7 -7
  26. package/agents/releaser.md +3 -1
  27. package/agents/researcher.md +3 -3
  28. package/agents/security-auditor.md +7 -7
  29. package/agents/test-engineer.md +5 -5
  30. package/agents/web-debugger.md +3 -3
  31. package/agents/web-performance-auditor.md +3 -3
  32. package/bin/snapshot-version.js +17 -1
  33. package/codex/CONDUCTOR.md +148 -0
  34. package/docs/ARCHITECTURE.md +165 -0
  35. package/docs/agent-fleet-setup.md +1 -0
  36. package/docs/claude-code-coms-bridge.md +10 -0
  37. package/docs/codex-remote-conductor.md +170 -0
  38. package/docs/coms-hermes-bridge.md +121 -0
  39. package/docs/getting-started.md +14 -0
  40. package/docs/npm-install.md +2 -0
  41. package/docs/pi-extensions.md +16 -0
  42. package/docs/pi-setup.md +2 -0
  43. package/hermes/README.md +48 -0
  44. package/hermes/skills/hub-conductor/SKILL.md +84 -0
  45. package/hermes/skills/hub-liaison/SKILL.md +84 -0
  46. package/justfile +132 -15
  47. package/package.json +10 -3
  48. package/scripts/codex-conductor.ts +41 -0
  49. package/scripts/codex-remote-control.ts +167 -0
  50. package/scripts/coms-cli.ts +311 -199
  51. package/scripts/coms-hermes-bridge.ts +8 -4
  52. package/scripts/lib/codex-conductor.ts +88 -0
  53. package/scripts/lib/codex-remote-control.ts +480 -0
  54. package/scripts/lib/coms-envelope.ts +51 -6
  55. package/scripts/lib/herdr-layout.ts +35 -7
  56. package/scripts/lib/hermes-bridge-core.ts +4 -4
  57. package/scripts/lib/spawn-stagger.ts +101 -0
  58. package/scripts/lib/team-project.ts +112 -3
  59. package/scripts/lib/team-snapshot.ts +3 -2
  60. package/scripts/team-snapshot.ts +23 -6
  61. package/scripts/team-up.ts +106 -18
  62. package/skills/guided-workspace-setup/SKILL.md +123 -97
  63. package/skills/guided-workspace-setup/companion-manifest.json +33 -0
  64. package/skills/peer-coms/SKILL.md +9 -0
  65. package/systemd/user/agent-fleet-codex-remote-control.service.in +23 -0
@@ -19,6 +19,35 @@ export const COMS_DIR = process.env.PI_COMS_DIR || path.join(os.homedir(), ".pi"
19
19
  export const MAX_HOPS = Number(process.env.PI_COMS_MAX_HOPS) || 5;
20
20
  export const DEFAULT_TIMEOUT_MS = Number(process.env.PI_COMS_TIMEOUT_MS) || 1_800_000;
21
21
  const LINE_CAP_BYTES = 64 * 1024;
22
+ // Pi peers refresh heartbeat_at every 30 seconds. A fresh heartbeat is the
23
+ // portable liveness signal for callers inside a sandbox/PID namespace, where
24
+ // process.kill(pid, 0) can incorrectly report a live host peer as ESRCH.
25
+ const REGISTRY_HEARTBEAT_FRESH_MS = 90_000;
26
+
27
+ // Registry paths are shared by every coms participant. Keep their components
28
+ // conservative so callers cannot escape the project/name directory structure.
29
+ export const COMS_PROJECT_SAFE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
30
+ export const COMS_NAME_SAFE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
31
+
32
+ export function validateComsProject(project: string): string {
33
+ if (
34
+ project.length === 0 ||
35
+ project === "." ||
36
+ project.includes("..") ||
37
+ project.includes("/") ||
38
+ project.includes("\\") ||
39
+ !COMS_PROJECT_SAFE.test(project)
40
+ ) {
41
+ throw new Error(`Invalid project name: ${JSON.stringify(project)}`);
42
+ }
43
+ return project;
44
+ }
45
+
46
+ export function validateComsName(name: string): string {
47
+ if (!COMS_NAME_SAFE.test(name)) throw new Error(`Invalid coms name: ${JSON.stringify(name)}`);
48
+ if (name === "projects") throw new Error(`Invalid reserved coms name: ${JSON.stringify(name)}`);
49
+ return name;
50
+ }
22
51
 
23
52
  // ━━ Envelope shapes (mirror coms/index.ts) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
24
53
 
@@ -221,11 +250,11 @@ export function isCancelEnvelope(obj: unknown): obj is CancelEnvelope {
221
250
  // ━━ Registry I/O (mirrors coms/index.ts semantics) ━━━━━━━━━━━━━━━━━━━━━━━━
222
251
 
223
252
  export function projectAgentsDir(project: string): string {
224
- return path.join(COMS_DIR, "projects", project, "agents");
253
+ return path.join(COMS_DIR, "projects", validateComsProject(project), "agents");
225
254
  }
226
255
 
227
256
  export function registryFilePath(project: string, name: string): string {
228
- return path.join(projectAgentsDir(project), `${name}.json`);
257
+ return path.join(projectAgentsDir(project), `${validateComsName(name)}.json`);
229
258
  }
230
259
 
231
260
  export function ensureComsDirs(project: string): void {
@@ -241,6 +270,7 @@ export function ensureComsDirs(project: string): void {
241
270
  }
242
271
 
243
272
  export function writeRegistryAtomic(entry: RegistryEntry, project: string): string {
273
+ validateComsName(entry.name);
244
274
  const file = registryFilePath(project, entry.name);
245
275
  const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
246
276
  fs.writeFileSync(tmp, JSON.stringify(entry, null, 2));
@@ -261,8 +291,9 @@ export function readAllRegistryEntries(project: string): RegistryEntry[] {
261
291
  let files: string[];
262
292
  try {
263
293
  files = fs.readdirSync(dir).filter((f) => f.endsWith(".json"));
264
- } catch {
265
- return [];
294
+ } catch (error) {
295
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
296
+ throw new Error(`Unable to read coms registry ${dir}: ${(error as NodeJS.ErrnoException).code ?? "unknown error"}`);
266
297
  }
267
298
  const out: RegistryEntry[] = [];
268
299
  for (const f of files) {
@@ -276,11 +307,24 @@ export function readAllRegistryEntries(project: string): RegistryEntry[] {
276
307
  return out;
277
308
  }
278
309
 
279
- // Same liveness rule as the coms harness: ESRCH removes the entry, EPERM
280
- // counts as live.
310
+ export function registryHeartbeatIsFresh(entry: RegistryEntry, now = Date.now()): boolean {
311
+ if (!entry.heartbeat_at) return false;
312
+ const heartbeat = Date.parse(entry.heartbeat_at);
313
+ if (!Number.isFinite(heartbeat)) return false;
314
+ const age = now - heartbeat;
315
+ return age >= -5_000 && age <= REGISTRY_HEARTBEAT_FRESH_MS;
316
+ }
317
+
318
+ // A fresh heartbeat wins before the PID probe because Codex remote commands
319
+ // can execute in a distinct PID namespace. For entries without a fresh
320
+ // heartbeat, preserve the harness rule: ESRCH removes; EPERM counts as live.
281
321
  export function pruneDeadEntries(project: string): RegistryEntry[] {
282
322
  const live: RegistryEntry[] = [];
283
323
  for (const entry of readAllRegistryEntries(project)) {
324
+ if (registryHeartbeatIsFresh(entry)) {
325
+ live.push(entry);
326
+ continue;
327
+ }
284
328
  try {
285
329
  process.kill(entry.pid, 0);
286
330
  live.push(entry);
@@ -296,6 +340,7 @@ export function pruneDeadEntries(project: string): RegistryEntry[] {
296
340
  }
297
341
 
298
342
  export function resolveUniqueName(project: string, desiredName: string): string {
343
+ validateComsName(desiredName);
299
344
  const liveNames = new Set(pruneDeadEntries(project).map((e) => e.name));
300
345
  if (!liveNames.has(desiredName)) return desiredName;
301
346
  let n = 2;
@@ -10,6 +10,7 @@
10
10
  import { resolve as resolvePath } from "node:path";
11
11
 
12
12
  import type { LayoutNode } from "../../.pi/harnesses/lib/herdr-client.ts";
13
+ import { STAGGER_ENV_VAR } from "./spawn-stagger.ts";
13
14
  import { DEFAULT_PROJECT, validateProject } from "./team-project.ts";
14
15
 
15
16
  export type { LayoutNode };
@@ -175,13 +176,17 @@ export interface TeamLayoutOptions {
175
176
  // B5 hook: resume ref (pi session path) for a peer being restored from a
176
177
  // team snapshot. Returning undefined starts the peer fresh.
177
178
  resumeForPeer?: (peer: Peer) => string | undefined;
179
+ // Pre-warm/stagger hook (see spawn-stagger.ts): seconds this pane should
180
+ // sleep before launching pi, injected as AGENT_FLEET_SPAWN_DELAY in the
181
+ // pane env. undefined or 0 launches immediately.
182
+ delayForPeer?: (peer: Peer) => number | undefined;
178
183
  // B2 hook: when set, the hub occupies a larger root pane (ratio of the
179
184
  // horizontal split) and the team tiles in the remaining space.
180
185
  // Coms project scope shared by all panes in this layout. The default keeps
181
186
  // existing argv shapes; non-default projects are appended to hidden recipe
182
187
  // positional args after model/session.
183
188
  project?: string;
184
- hub?: { command: string[]; label: string; ratio?: number };
189
+ hub?: { command: string[]; label: string; ratio?: number; cwd?: string; env?: Record<string, string> };
185
190
  }
186
191
 
187
192
  function paneNode(
@@ -191,15 +196,23 @@ function paneNode(
191
196
  envForPeer?: TeamLayoutOptions["envForPeer"],
192
197
  resumeForPeer?: TeamLayoutOptions["resumeForPeer"],
193
198
  project = DEFAULT_PROJECT,
199
+ delayForPeer?: TeamLayoutOptions["delayForPeer"],
194
200
  ): LayoutNode {
195
201
  validateProject(project);
196
- const env = envForPeer?.(peer);
202
+ const env = { ...envForPeer?.(peer) };
203
+ const delay = delayForPeer?.(peer);
204
+ if (delay !== undefined) {
205
+ if (!Number.isFinite(delay) || delay < 0) {
206
+ throw new Error(`Invalid spawn delay for peer "${peer.name}": ${delay}`);
207
+ }
208
+ if (delay > 0) env[STAGGER_ENV_VAR] = String(Math.round(delay));
209
+ }
197
210
  return {
198
211
  type: "pane",
199
212
  command: peerCommand(peer, team, resumeForPeer?.(peer), project),
200
213
  cwd: repoRoot,
201
214
  label: peer.name as string,
202
- ...(env && Object.keys(env).length > 0 ? { env } : {}),
215
+ ...(Object.keys(env).length > 0 ? { env } : {}),
203
216
  };
204
217
  }
205
218
 
@@ -219,17 +232,32 @@ function bsp(nodes: LayoutNode[], depth: number): LayoutNode {
219
232
 
220
233
  // peers.yaml team → herdr layout tree for layout.apply.
221
234
  export function buildTeamLayout(opts: TeamLayoutOptions): LayoutNode {
222
- const { team, peers, repoRoot, envForPeer, resumeForPeer, hub, project = DEFAULT_PROJECT } = opts;
235
+ const { team, peers, repoRoot, envForPeer, resumeForPeer, delayForPeer, hub, project = DEFAULT_PROJECT } = opts;
223
236
  validateProject(project);
224
- if (peers.length === 0) throw new Error(`Team "${team}" has no peers.`);
225
- const panes = peers.map((p) => paneNode(p, team, repoRoot, envForPeer, resumeForPeer, project));
237
+ if (peers.length === 0) {
238
+ if (!hub) throw new Error(`Team "${team}" has no peers.`);
239
+ return {
240
+ type: "pane",
241
+ command: hub.command,
242
+ cwd: hub.cwd ?? repoRoot,
243
+ label: hub.label,
244
+ ...(hub.env && Object.keys(hub.env).length > 0 ? { env: hub.env } : {}),
245
+ };
246
+ }
247
+ const panes = peers.map((p) => paneNode(p, team, repoRoot, envForPeer, resumeForPeer, project, delayForPeer));
226
248
  const grid = bsp(panes, hub ? 1 : 0);
227
249
  if (!hub) return grid;
228
250
  return {
229
251
  type: "split",
230
252
  direction: "right",
231
253
  ratio: hub.ratio ?? 0.4,
232
- first: { type: "pane", command: hub.command, cwd: repoRoot, label: hub.label },
254
+ first: {
255
+ type: "pane",
256
+ command: hub.command,
257
+ cwd: hub.cwd ?? repoRoot,
258
+ label: hub.label,
259
+ ...(hub.env && Object.keys(hub.env).length > 0 ? { env: hub.env } : {}),
260
+ },
233
261
  second: grid,
234
262
  };
235
263
  }
@@ -117,9 +117,9 @@ export function formatTelegramQuestion(input: HermesBridgeQuestion, limit = TELE
117
117
  if (!isValidQid(input.qid)) throw new Error("qid must be a 26-character Crockford ULID");
118
118
  const options = input.options ?? [];
119
119
  const header = `❓ [${HUB_Q_PREFIX}:${input.qid}] ${input.question}`;
120
- const optionsBlock = options.length > 0 ? `\n\nОпции:\n${formatOptions(options)}` : "";
121
- const instruction = `\n\n↩ Отговори с reply на това съобщение, или напиши: ${HUB_Q_PREFIX}:${input.qid}: <отговор>`;
122
- const contextPrefix = input.context ? "\n\nКонтекст: " : "";
120
+ const optionsBlock = options.length > 0 ? `\n\nOptions:\n${formatOptions(options)}` : "";
121
+ const instruction = `\n\n↩ Reply to this message, or type: ${HUB_Q_PREFIX}:${input.qid}: <answer>`;
122
+ const contextPrefix = input.context ? "\n\nContext: " : "";
123
123
  const fixedLength = header.length + contextPrefix.length + optionsBlock.length + instruction.length;
124
124
  const contextBudget = Math.max(0, limit - fixedLength);
125
125
  const context = input.context ? truncateUtf16(input.context, contextBudget) : "";
@@ -199,7 +199,7 @@ export function timeoutErrorMessage(timeoutMs: number): string {
199
199
  }
200
200
 
201
201
  export function timeoutTelegramNote(qid: string, timeoutMs: number): string {
202
- return `⌛ [${HUB_Q_PREFIX}:${qid}] Въпросът изтече след ${timeoutMs}ms.`;
202
+ return `⌛ [${HUB_Q_PREFIX}:${qid}] The question timed out after ${timeoutMs}ms.`;
203
203
  }
204
204
 
205
205
  export function timeoutOutcome(qid: string, timeoutMs = timeoutMsFromEnv()): {
@@ -0,0 +1,101 @@
1
+ // scripts/lib/spawn-stagger.ts
2
+ //
3
+ // Pre-warm/stagger for simultaneous pi pane spawns (team-up, hub-team,
4
+ // team-resume). pi's credential store (~/.pi/agent/auth.json) is loaded once
5
+ // at boot under a short-retry file lock; when a stale OAuth token forces one
6
+ // pane to refresh it over the network WHILE holding that lock, sibling panes
7
+ // booting in the same instant lose the lock race and come up with an empty
8
+ // credential store — every provider shows "unconfigured". The fix is local:
9
+ // when a stale OAuth credential is detected, one pi pane starts immediately
10
+ // (the warmer — it refreshes the token) and every other pi pane sleeps a few
11
+ // seconds before launching. Fresh tokens mean zero delay everywhere.
12
+ //
13
+ // Pure logic only — no fs, no sockets, no process.exit. Callers read
14
+ // auth.json themselves (lock-free, same as pi's readStoredCredential) and
15
+ // inject delays into pane env; the `_peer`/`_peer-plus` recipes honor
16
+ // AGENT_FLEET_SPAWN_DELAY with a plain `sleep`.
17
+
18
+ /** Env var the justfile peer recipes read: seconds to sleep before launching pi. */
19
+ export const STAGGER_ENV_VAR = "AGENT_FLEET_SPAWN_DELAY";
20
+
21
+ /** Delay for the first staggered pane — long enough for the warmer's token refresh round-trip. */
22
+ export const WARMUP_SECONDS = 4;
23
+
24
+ /** Extra spacing between subsequent staggered panes. */
25
+ export const STEP_SECONDS = 1;
26
+
27
+ /** Treat tokens expiring within this window as stale — pane boot takes seconds. */
28
+ export const EXPIRY_MARGIN_MS = 60_000;
29
+
30
+ /**
31
+ * Does auth.json hold an OAuth credential that a booting pi would refresh?
32
+ * `raw` is the file's contents (undefined when unreadable/absent). Missing or
33
+ * malformed files never stagger: with no stored credential there is nothing
34
+ * to refresh, so there is no long lock hold to dodge.
35
+ */
36
+ export function oauthNeedsWarmup(raw: string | undefined, now = Date.now()): boolean {
37
+ if (!raw) return false;
38
+ let data: unknown;
39
+ try {
40
+ data = JSON.parse(raw);
41
+ } catch {
42
+ return false;
43
+ }
44
+ if (typeof data !== "object" || data === null) return false;
45
+ for (const credential of Object.values(data)) {
46
+ if (typeof credential !== "object" || credential === null) continue;
47
+ const { type, expires } = credential as { type?: unknown; expires?: unknown };
48
+ if (type !== "oauth" || typeof expires !== "number") continue;
49
+ if (expires <= now + EXPIRY_MARGIN_MS) return true;
50
+ }
51
+ return false;
52
+ }
53
+
54
+ export interface StaggerOptions {
55
+ /** Per-peer flag, in spawn order: does this pane boot a pi process? */
56
+ peerIsPi: boolean[];
57
+ /** Does the root pane (hub) boot a pi process? The hub warms when present. */
58
+ rootIsPi: boolean;
59
+ /** Result of oauthNeedsWarmup — false short-circuits to all-zero delays. */
60
+ needed: boolean;
61
+ warmupSeconds?: number;
62
+ stepSeconds?: number;
63
+ }
64
+
65
+ /**
66
+ * Per-peer delay seconds (spawn order). Exactly one pi process — the hub when
67
+ * present, otherwise the first pi peer — starts at 0 and refreshes the stale
68
+ * token; every other pi peer starts after the warm-up window. Non-pi panes
69
+ * (runner: claude-code) never wait: they do not touch pi's credential store.
70
+ */
71
+ export function staggerDelays(opts: StaggerOptions): number[] {
72
+ const { peerIsPi, rootIsPi, needed, warmupSeconds = WARMUP_SECONDS, stepSeconds = STEP_SECONDS } = opts;
73
+ if (!needed) return peerIsPi.map(() => 0);
74
+ let staggered = 0;
75
+ let warmerAssigned = rootIsPi;
76
+ return peerIsPi.map((isPi) => {
77
+ if (!isPi) return 0;
78
+ if (!warmerAssigned) {
79
+ warmerAssigned = true;
80
+ return 0;
81
+ }
82
+ return warmupSeconds + staggered++ * stepSeconds;
83
+ });
84
+ }
85
+
86
+ /**
87
+ * Convenience for the team entrypoints: auth.json contents + peers → a
88
+ * `delayForPeer` hook for buildTeamLayout. Structural peer type avoids a
89
+ * circular import with herdr-layout.ts.
90
+ */
91
+ export function planSpawnDelays<P extends { runner?: string }>(
92
+ peers: P[],
93
+ rootIsPi: boolean,
94
+ authJsonRaw: string | undefined,
95
+ now = Date.now(),
96
+ ): { needed: boolean; delayForPeer: (peer: P) => number | undefined } {
97
+ const needed = oauthNeedsWarmup(authJsonRaw, now);
98
+ const delays = staggerDelays({ peerIsPi: peers.map((p) => p.runner !== "claude-code"), rootIsPi, needed });
99
+ const byPeer = new Map<P, number>(peers.map((p, i) => [p, delays[i]]));
100
+ return { needed, delayForPeer: (peer) => byPeer.get(peer) };
101
+ }
@@ -4,6 +4,7 @@
4
4
  // already isolates peers by --project; this file only keeps team workspace
5
5
  // labels, snapshot files, and generated launch argv in sync with that scope.
6
6
 
7
+ import * as os from "node:os";
7
8
  import * as path from "node:path";
8
9
 
9
10
  export const DEFAULT_PROJECT = "default";
@@ -13,6 +14,32 @@ export const DEFAULT_PROJECT = "default";
13
14
  // like "acme.prod", but ".." is not allowed anywhere.
14
15
  export const PROJECT_SAFE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
15
16
  export const TEAM_SAFE = /^[A-Za-z0-9_-]+$/;
17
+ export const CODEX_CONTRACT_IDENTITY = "agent-fleet-codex-conductor-pilot-v1";
18
+ export const DEFAULT_CODEX_TIMEOUT_MS = 300_000;
19
+
20
+ export type ConductorBackend = "hermes" | "codex";
21
+ export type WorkspaceMode = "peers" | "hub" | "conductor-hermes" | "conductor-codex";
22
+
23
+ export interface ConductorSpec {
24
+ backend: ConductorBackend;
25
+ workspaceMode: Extract<WorkspaceMode, `conductor-${string}`>;
26
+ paneLabel: string;
27
+ command: string[];
28
+ cwd: string;
29
+ env: Record<string, string>;
30
+ ratio: number;
31
+ displayText: string;
32
+ expectedServiceScope: "none" | "agent-fleet-codex-remote-control.service";
33
+ conductorName: string;
34
+ team: string;
35
+ }
36
+
37
+ function validateAbsoluteRepoRoot(repoRoot: string): string {
38
+ if (!path.isAbsolute(repoRoot) || path.resolve(repoRoot) !== repoRoot || repoRoot.includes("..")) {
39
+ throw new Error(`Invalid absolute repository root: ${JSON.stringify(repoRoot)}`);
40
+ }
41
+ return repoRoot;
42
+ }
16
43
 
17
44
  export function validateProject(project: string): string {
18
45
  if (
@@ -35,6 +62,20 @@ export function validateTeamName(team: string): string {
35
62
  return team;
36
63
  }
37
64
 
65
+ // The worktree/repo identity that scopes a workspace label so the same team
66
+ // launched from different checkouts never collides. It is the LAST dot-segment
67
+ // of the checkout directory's basename — the convention the fleet uses for
68
+ // git worktrees: `main.wt2` → `wt2`, `ringithub.end2` → `end2`, a plain
69
+ // `agent-fleet` checkout → `agent-fleet`. Sanitized to the label-safe charset;
70
+ // falls back to "repo" when nothing usable remains.
71
+ export function worktreeTag(repoRoot: string): string {
72
+ const base = path.basename(repoRoot);
73
+ const dot = base.lastIndexOf(".");
74
+ const seg = dot > 0 ? base.slice(dot + 1) : base;
75
+ const safe = seg.replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
76
+ return safe || "repo";
77
+ }
78
+
38
79
  export function parseProjectFlag(argv: string[]): string {
39
80
  let project = DEFAULT_PROJECT;
40
81
  let seen = false;
@@ -50,11 +91,22 @@ export function parseProjectFlag(argv: string[]): string {
50
91
  return validateProject(project);
51
92
  }
52
93
 
53
- export function teamWorkspaceLabel(kind: "peers" | "hub" | "conductor", team: string, project = DEFAULT_PROJECT): string {
94
+ // Workspace label = <worktree-tag>-<mode>-<team>, with a `--project.<name>`
95
+ // suffix when the coms project is non-default. The worktree tag keys the label
96
+ // to the checkout, so `just hub-team <team>` from two repos/worktrees yields
97
+ // distinct labels (e.g. `wt2-hub-plan` vs `end2-hub-plan`) instead of colliding
98
+ // on a shared `pi-hub-<team>`. Pass `tag` from worktreeTag(REPO_ROOT); it
99
+ // defaults to "repo" only for callers that have no checkout in hand.
100
+ export function teamWorkspaceLabel(
101
+ kind: WorkspaceMode,
102
+ team: string,
103
+ project = DEFAULT_PROJECT,
104
+ tag = "repo",
105
+ ): string {
54
106
  validateTeamName(team);
55
107
  validateProject(project);
56
- const prefix = kind === "hub" ? "pi-hub" : kind === "conductor" ? "pi-conductor" : "pi-peers";
57
- return project === DEFAULT_PROJECT ? `${prefix}-${team}` : `${prefix}-${team}--project.${project}`;
108
+ const base = `${tag}-${kind}-${team}`;
109
+ return project === DEFAULT_PROJECT ? base : `${base}--project.${project}`;
58
110
  }
59
111
 
60
112
  export function hubCommand(project = DEFAULT_PROJECT): string[] {
@@ -66,6 +118,63 @@ export function conductorCommand(): string[] {
66
118
  return ["hermes", "-p", "dev"];
67
119
  }
68
120
 
121
+ export function conductorSpec(
122
+ backend: ConductorBackend,
123
+ input: { repoRoot: string; runtimeDir?: string; team: string; project?: string; nodeBin?: string },
124
+ ): ConductorSpec {
125
+ const repoRoot = validateAbsoluteRepoRoot(input.repoRoot);
126
+ const team = validateTeamName(input.team);
127
+ const project = validateProject(input.project ?? DEFAULT_PROJECT);
128
+ const conductorName = `${backend}-${team}-conductor`;
129
+ if (backend === "hermes") {
130
+ return {
131
+ backend,
132
+ workspaceMode: "conductor-hermes",
133
+ paneLabel: "conductor-hermes",
134
+ command: conductorCommand(),
135
+ cwd: repoRoot,
136
+ env: {},
137
+ ratio: 0.35,
138
+ displayText: "Hermes conductor; no herdr control",
139
+ expectedServiceScope: "none",
140
+ conductorName,
141
+ team,
142
+ };
143
+ }
144
+ const runtimeDir = input.runtimeDir ?? path.join(os.homedir(), ".local", "state", "agent-fleet", "codex-conductor");
145
+ if (!path.isAbsolute(runtimeDir) || path.resolve(runtimeDir) !== runtimeDir) {
146
+ throw new Error(`Codex conductor requires an absolute runtime directory: ${JSON.stringify(runtimeDir)}`);
147
+ }
148
+ const relativeRuntime = path.relative(repoRoot, runtimeDir);
149
+ if (relativeRuntime === "" || (!relativeRuntime.startsWith("..") && !path.isAbsolute(relativeRuntime))) {
150
+ throw new Error("Codex conductor requires a runtime directory outside repoRoot");
151
+ }
152
+ const workspaceDir = path.join(runtimeDir, "workspace");
153
+ const nodeBin = input.nodeBin ?? process.execPath;
154
+ if (!path.isAbsolute(nodeBin)) throw new Error(`Codex conductor requires an absolute Node binary path: ${JSON.stringify(nodeBin)}`);
155
+ return {
156
+ backend,
157
+ workspaceMode: "conductor-codex",
158
+ paneLabel: "conductor-codex-control",
159
+ command: [nodeBin, "--experimental-strip-types", path.join(repoRoot, "scripts", "codex-remote-control.ts"), "control-pane"],
160
+ cwd: workspaceDir,
161
+ env: {
162
+ AGENT_FLEET_REPO_ROOT: repoRoot,
163
+ COMS_CLI_PROJECT: project,
164
+ COMS_CLI_NAME: conductorName,
165
+ COMS_CLI_TIMEOUT_MS: String(DEFAULT_CODEX_TIMEOUT_MS),
166
+ AGENT_FLEET_CODEX_CONTRACT_PATH: path.join(workspaceDir, "AGENTS.md"),
167
+ AGENT_FLEET_CODEX_CONTRACT_IDENTITY: CODEX_CONTRACT_IDENTITY,
168
+ AGENT_FLEET_CONDUCTOR_BACKEND: "codex",
169
+ },
170
+ ratio: 0.35,
171
+ displayText: "Codex control pane; requested systemd state only",
172
+ expectedServiceScope: "agent-fleet-codex-remote-control.service",
173
+ conductorName,
174
+ team,
175
+ };
176
+ }
177
+
69
178
  export function teamSnapshotPath(snapshotDir: string, team: string, project = DEFAULT_PROJECT): string {
70
179
  validateTeamName(team);
71
180
  validateProject(project);
@@ -58,8 +58,9 @@ export function buildSnapshot(opts: {
58
58
  agents: AgentLite[];
59
59
  now?: Date;
60
60
  project?: string;
61
+ tag?: string;
61
62
  }): TeamSnapshot {
62
- const { team, hub, peers, panes, agents, project = DEFAULT_PROJECT } = opts;
63
+ const { team, hub, peers, panes, agents, project = DEFAULT_PROJECT, tag } = opts;
63
64
  validateTeamName(team);
64
65
  validateProject(project);
65
66
  const paneByLabel = new Map<string, string>();
@@ -78,7 +79,7 @@ export function buildSnapshot(opts: {
78
79
  team,
79
80
  project,
80
81
  hub,
81
- workspace_label: teamWorkspaceLabel(hub ? "hub" : "peers", team, project),
82
+ workspace_label: teamWorkspaceLabel(hub ? "hub" : "peers", team, project, tag),
82
83
  taken_at: (opts.now ?? new Date()).toISOString(),
83
84
  peers: peers.map((peer) => {
84
85
  const paneId = peer.name ? paneByLabel.get(peer.name) : undefined;
@@ -23,7 +23,8 @@ import * as path from "node:path";
23
23
  import { fileURLToPath } from "node:url";
24
24
 
25
25
  import { buildTeamLayout, parsePeersYaml, type Peer } from "./lib/herdr-layout.ts";
26
- import { DEFAULT_PROJECT, hubCommand, parseProjectFlag, teamSnapshotPath, teamWorkspaceLabel, validateTeamName } from "./lib/team-project.ts";
26
+ import { planSpawnDelays } from "./lib/spawn-stagger.ts";
27
+ import { DEFAULT_PROJECT, hubCommand, parseProjectFlag, teamSnapshotPath, teamWorkspaceLabel, validateTeamName, worktreeTag } from "./lib/team-project.ts";
27
28
  import {
28
29
  assertSnapshotProject,
29
30
  buildSnapshot,
@@ -35,6 +36,8 @@ import {
35
36
 
36
37
  const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));
37
38
  const REPO_ROOT = path.resolve(SCRIPT_DIR, "..");
39
+ // Must match team-up's tag so down/resume target the workspace it created.
40
+ const WORKTREE_TAG = worktreeTag(REPO_ROOT);
38
41
  const PEERS_YAML = path.join(REPO_ROOT, ".pi", "agents", "peers.yaml");
39
42
  const SNAPSHOT_DIR = path.join(os.homedir(), ".pi", "team-snapshots");
40
43
 
@@ -68,8 +71,8 @@ async function findTeamWorkspace(client: Client, team: string, project = DEFAULT
68
71
  let peersLabel: string;
69
72
  let hubLabel: string;
70
73
  try {
71
- peersLabel = teamWorkspaceLabel("peers", team, project);
72
- hubLabel = teamWorkspaceLabel("hub", team, project);
74
+ peersLabel = teamWorkspaceLabel("peers", team, project, WORKTREE_TAG);
75
+ hubLabel = teamWorkspaceLabel("hub", team, project, WORKTREE_TAG);
73
76
  } catch (err) {
74
77
  die(err instanceof Error ? err.message : String(err));
75
78
  }
@@ -78,8 +81,8 @@ async function findTeamWorkspace(client: Client, team: string, project = DEFAULT
78
81
  }
79
82
 
80
83
  async function captureSnapshot(client: Client, team: string, project = DEFAULT_PROJECT): Promise<TeamSnapshot> {
81
- const peersLabel = teamWorkspaceLabel("peers", team, project);
82
- const hubLabel = teamWorkspaceLabel("hub", team, project);
84
+ const peersLabel = teamWorkspaceLabel("peers", team, project, WORKTREE_TAG);
85
+ const hubLabel = teamWorkspaceLabel("hub", team, project, WORKTREE_TAG);
83
86
  const ws = await findTeamWorkspace(client, team, project);
84
87
  if (!ws) {
85
88
  const projectArgs = project === DEFAULT_PROJECT ? "" : ` --project ${project}`;
@@ -104,6 +107,7 @@ async function captureSnapshot(client: Client, team: string, project = DEFAULT_P
104
107
  peers,
105
108
  panes,
106
109
  agents: inWorkspace as Parameters<typeof buildSnapshot>[0]["agents"],
110
+ tag: WORKTREE_TAG,
107
111
  });
108
112
  const file = snapshotPath(team, project);
109
113
  fs.mkdirSync(path.dirname(file), { recursive: true });
@@ -165,12 +169,25 @@ async function cmdResume(team: string, project = DEFAULT_PROJECT): Promise<void>
165
169
  if (ref && peer.name) resumedNames.add(peer.name);
166
170
  return ref;
167
171
  };
168
- const workspaceLabel = teamWorkspaceLabel(snap.hub ? "hub" : "peers", snap.team, project);
172
+ const workspaceLabel = teamWorkspaceLabel(snap.hub ? "hub" : "peers", snap.team, project, WORKTREE_TAG);
173
+ // Resume relaunches every pane simultaneously, so it needs the same
174
+ // pre-warm/stagger as team-up (see scripts/lib/spawn-stagger.ts).
175
+ let authRaw: string | undefined;
176
+ try {
177
+ authRaw = fs.readFileSync(path.join(os.homedir(), ".pi", "agent", "auth.json"), "utf-8");
178
+ } catch {
179
+ authRaw = undefined;
180
+ }
181
+ const { needed: staggerNeeded, delayForPeer } = planSpawnDelays(snap.peers, snap.hub, authRaw);
182
+ if (staggerNeeded) {
183
+ console.log("Stale pi OAuth token detected — staggering pane starts so one pane can refresh it first.");
184
+ }
169
185
  const layout = buildTeamLayout({
170
186
  team: snap.team,
171
187
  peers: snap.peers,
172
188
  repoRoot: REPO_ROOT,
173
189
  resumeForPeer: resumeFor,
190
+ delayForPeer,
174
191
  project,
175
192
  ...(snap.hub ? { hub: { command: hubCommand(project), label: "hub", ratio: 0.4 } } : {}),
176
193
  });