@chankov/agent-fleet 0.0.2 → 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 (47) 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/peers.yaml +4 -0
  6. package/.pi/agents/teams.yaml +2 -2
  7. package/.pi/harnesses/agent-hub/README.md +57 -4
  8. package/.pi/harnesses/agent-hub/index.ts +236 -80
  9. package/.pi/harnesses/agent-hub/research-retention.js +34 -0
  10. package/.pi/harnesses/ask-user-remote/README.md +2 -0
  11. package/.pi/harnesses/coms/README.md +11 -0
  12. package/.pi/prompts/doctor-agent-fleet.md +1 -1
  13. package/.pi/prompts/setup-agent-fleet.md +4 -4
  14. package/README.md +102 -540
  15. package/agents/architect.md +1 -1
  16. package/agents/planner.md +1 -1
  17. package/agents/security-auditor.md +1 -1
  18. package/bin/snapshot-version.js +17 -1
  19. package/codex/CONDUCTOR.md +148 -0
  20. package/docs/ARCHITECTURE.md +165 -0
  21. package/docs/agent-fleet-setup.md +1 -0
  22. package/docs/claude-code-coms-bridge.md +10 -0
  23. package/docs/codex-remote-conductor.md +170 -0
  24. package/docs/coms-hermes-bridge.md +121 -0
  25. package/docs/getting-started.md +14 -0
  26. package/docs/npm-install.md +2 -0
  27. package/docs/pi-setup.md +2 -0
  28. package/hermes/README.md +48 -0
  29. package/hermes/skills/hub-conductor/SKILL.md +84 -0
  30. package/hermes/skills/hub-liaison/SKILL.md +84 -0
  31. package/justfile +100 -13
  32. package/package.json +10 -3
  33. package/scripts/codex-conductor.ts +41 -0
  34. package/scripts/codex-remote-control.ts +167 -0
  35. package/scripts/coms-cli.ts +311 -199
  36. package/scripts/coms-hermes-bridge.ts +2 -2
  37. package/scripts/lib/codex-conductor.ts +88 -0
  38. package/scripts/lib/codex-remote-control.ts +480 -0
  39. package/scripts/lib/coms-envelope.ts +51 -6
  40. package/scripts/lib/herdr-layout.ts +18 -3
  41. package/scripts/lib/hermes-bridge-core.ts +4 -4
  42. package/scripts/lib/team-project.ts +85 -1
  43. package/scripts/team-up.ts +77 -18
  44. package/skills/guided-workspace-setup/SKILL.md +123 -97
  45. package/skills/guided-workspace-setup/companion-manifest.json +33 -0
  46. package/skills/peer-coms/SKILL.md +9 -0
  47. package/systemd/user/agent-fleet-codex-remote-control.service.in +23 -0
@@ -24,14 +24,20 @@
24
24
  * /models [profile] — apply a named model profile (.pi/agents/model-profiles.yaml)
25
25
  * /agent-models-substitute <source> <target> — swap one model across all personas
26
26
  * /dispatch-policy — show which members route to coms peers (.pi/agents/dispatch-policy.yaml)
27
- * /agents-kill <name> — SIGTERM a frozen specialist (and its delegation tree)
28
- * /agents-restart <name>— kill + re-run its last task fresh
27
+ * /agents-kill <name|rN|all> — SIGTERM a frozen specialist (and its delegation
28
+ * tree); on a research helper it kills AND removes the
29
+ * card + session ("all" clears every research helper)
30
+ * (aliases: /research-rm rN, /research-clear)
31
+ * /agents-restart <name|rN> — kill + re-run its last task fresh (research: must
32
+ * be finished; runs on a fresh session)
29
33
  * /zoom <name|rN|child> — scrollable read-only view of an agent's stream
30
34
  * (team member, research helper rN, or delegate child id)
31
35
  * /research <task> — spawn a read-only research helper (@persona, --model)
32
- * /research-cont rN ... — resume a finished research helper
33
- * /research-rm rN — remove a research helper (kill if running)
34
- * /research-clear — remove all research helpers
36
+ * /agents-cont rN ... — resume a finished research helper (alias: /research-cont)
37
+ *
38
+ * Finished research helpers are auto-pruned: auto-research pipe helpers as soon
39
+ * as they finish (findings persist as files under findings/), manual/persona
40
+ * helpers beyond the `research-keep` most recent (default 4, overrides file).
35
41
  * /persona — select/reset the dispatcher persona
36
42
  * /handoff <peer> — hand the session off to a coms peer (summarized brief)
37
43
  * /coms — refresh the coms peer pool (--all / --project <name>)
@@ -76,6 +82,7 @@ import { crossCheck, extractAssertionIds, parseStructuredReturn } from "./return
76
82
  import { checkScope, diffAgainst, snapshotWorktree } from "./scope-gate.js";
77
83
  import { validateEvidence } from "./evidence-rules.js";
78
84
  import { comsRequiredRefusal, parseDispatchPolicy, resolveDispatchBackend } from "./backend-policy.js";
85
+ import { DEFAULT_RESEARCH_KEEP, parseResearchKeep, selectResearchPrunable } from "./research-retention.js";
79
86
  import { readdirSync, readFileSync, existsSync, mkdirSync, unlinkSync, writeFileSync, rmSync } from "fs";
80
87
  import {
81
88
  formatPeerStatus,
@@ -217,12 +224,16 @@ interface AgentState {
217
224
  // team with reconnaissance/search/doc-reading — it never writes and never runs bash.
218
225
  // Keyed by a numeric id surfaced to the operator as the handle `rN`. Ephemeral by
219
226
  // construction: session files live under the same dir as team sessions and are wiped
220
- // on session_start; `/research-clear` removes them mid-session. Resumable via
221
- // `/research-cont` (subcont-style, bumping turnCount).
227
+ // on session_start; finished helpers are auto-pruned per the retention policy
228
+ // (research-retention.js — auto-pipe helpers immediately, older manual ones beyond
229
+ // the `research-keep` cap); `/agents-kill rN` (alias `/research-rm`) kills AND
230
+ // removes one by hand. Resumable via `/agents-cont` (alias `/research-cont`,
231
+ // subcont-style, bumping turnCount) while retained.
222
232
  interface ResearchState {
223
233
  id: number;
224
234
  def: AgentDef; // a `kind: research` persona, or a synthesized def for anon helpers
225
235
  persona: boolean; // true → spawned from a persona; false → ad-hoc anonymous
236
+ ephemeral: boolean; // true → auto-research pipe spawn: pruned as soon as it finishes
226
237
  model: string; // resolved pi model spec (shown on the card)
227
238
  status: "idle" | "running" | "done" | "error";
228
239
  task: string;
@@ -232,6 +243,7 @@ interface ResearchState {
232
243
  contextPct: number;
233
244
  sessionFile: string | null; // set after a successful run → enables `-c` resume
234
245
  turnCount: number;
246
+ finishedAt?: number; // last time a run ended (any status) — LRU key for retention
235
247
  timer?: ReturnType<typeof setInterval>;
236
248
  proc?: ChildProcess;
237
249
  killedByOperator?: boolean;
@@ -369,6 +381,10 @@ function extractNeedsResearch(output: string): string[] {
369
381
  // orientation): canonical files (e.g. Docs/AGENTS.md) or
370
382
  // doc folders. Specialists and research helpers read the
371
383
  // ones relevant to their task; context, not compliance.
384
+ // research-keep: <n>|all — how many finished manual/persona research helpers
385
+ // to retain for /agents-cont resume (LRU, default 4);
386
+ // "all" disables pruning. Auto-research pipe helpers
387
+ // are always pruned as soon as they finish.
372
388
 
373
389
  interface AgentTeamOverrides {
374
390
  language: string;
@@ -380,6 +396,7 @@ interface AgentTeamOverrides {
380
396
  personaDelegateDepth: Record<string, number>;
381
397
  rulesDirs: string[];
382
398
  docsPaths: string[];
399
+ researchKeep: number;
383
400
  warnings: string[];
384
401
  }
385
402
 
@@ -393,6 +410,7 @@ const DEFAULT_OVERRIDES: AgentTeamOverrides = {
393
410
  personaDelegateDepth: {},
394
411
  rulesDirs: [],
395
412
  docsPaths: [],
413
+ researchKeep: DEFAULT_RESEARCH_KEEP,
396
414
  warnings: [],
397
415
  };
398
416
 
@@ -444,6 +462,14 @@ function parseAgentTeamOverrides(cwd: string): AgentTeamOverrides {
444
462
  if (key === "docs" && value) {
445
463
  result.docsPaths = value.split(",").map(s => s.trim()).filter(Boolean);
446
464
  }
465
+ if (key === "research-keep" && value) {
466
+ const keep = parseResearchKeep(value);
467
+ if (keep != null) {
468
+ result.researchKeep = keep;
469
+ } else {
470
+ result.warnings.push(`research-keep "${value}" is not a non-negative integer or "all" — using the default (${DEFAULT_RESEARCH_KEEP})`);
471
+ }
472
+ }
447
473
  const slug = "[a-z0-9]+(?:-[a-z0-9]+)*";
448
474
  const modelKey = key.match(new RegExp(`^model\\.(${slug})$`));
449
475
  if (modelKey && value) result.personaModels[modelKey[1]] = value;
@@ -1723,6 +1749,10 @@ export default function (pi: ExtensionAPI) {
1723
1749
  // alongside the standing team but renders in its own widget row.
1724
1750
  const researchStates: Map<number, ResearchState> = new Map();
1725
1751
  let nextResearchId = 1;
1752
+ // Retention cap for finished durable (manual/persona) helpers — set from the
1753
+ // overrides file's `research-keep:` key at session start (default 4, Infinity
1754
+ // for "all"). Ephemeral auto-pipe helpers ignore the cap: pruned on finish.
1755
+ let researchKeep = DEFAULT_RESEARCH_KEEP;
1726
1756
 
1727
1757
  // ── Execution history (/agents-history) ──────────
1728
1758
  // A tree of every dispatch: orchestrator (dispatcher) turns, the specialists they
@@ -3358,12 +3388,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3358
3388
  return ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : "openrouter/google/gemini-3-flash-preview";
3359
3389
  }
3360
3390
 
3361
- function createResearchState(def: AgentDef, persona: boolean, model: string): ResearchState {
3391
+ function createResearchState(def: AgentDef, persona: boolean, model: string, ephemeral = false): ResearchState {
3362
3392
  const id = nextResearchId++;
3363
3393
  const state: ResearchState = {
3364
3394
  id,
3365
3395
  def,
3366
3396
  persona,
3397
+ ephemeral,
3367
3398
  model,
3368
3399
  status: "running",
3369
3400
  task: "",
@@ -3379,6 +3410,22 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3379
3410
  return state;
3380
3411
  }
3381
3412
 
3413
+ // Retention pass, run whenever a helper finishes: drop finished auto-pipe
3414
+ // helpers immediately (their findings persist as files under findings/, their
3415
+ // handles are never resumed) and finished durable helpers beyond the
3416
+ // `research-keep` most recent — so the research row doesn't grow without
3417
+ // bound. Running helpers are untouched; ids stay monotonic (no handle reuse).
3418
+ // /agents-history is unaffected: the timeline holds its own entries.
3419
+ function pruneResearch() {
3420
+ const ids = selectResearchPrunable(Array.from(researchStates.values()), researchKeep);
3421
+ if (ids.length === 0) return;
3422
+ for (const id of ids) {
3423
+ try { unlinkSync(researchSessionPath(id)); } catch {}
3424
+ researchStates.delete(id);
3425
+ }
3426
+ updateResearchWidget();
3427
+ }
3428
+
3382
3429
  // Env plumbing for spawned children: the shared exemptions file (both
3383
3430
  // damage-control variants honor pre-granted exemptions from it) and, when
3384
3431
  // coms is up, the endpoint damage-control-continue escalates blocked path
@@ -3480,11 +3527,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3480
3527
  // The process could not be spawned at all (proc `error` event).
3481
3528
  if (res.spawnError) {
3482
3529
  state.status = "error";
3530
+ state.finishedAt = Date.now();
3483
3531
  state.lastWork = `Error: ${res.spawnError}`;
3484
3532
  state.killedByOperator = false;
3485
3533
  updateResearchWidget();
3486
3534
  state.zoomRender?.(true);
3487
3535
  historyEnd(histEntry, "error");
3536
+ pruneResearch();
3488
3537
  return {
3489
3538
  output: `Error spawning research helper: ${res.spawnError}`,
3490
3539
  exitCode: 1,
@@ -3495,15 +3544,18 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3495
3544
  const full = res.output;
3496
3545
  const code = res.exitCode;
3497
3546
 
3498
- // Operator kill (via /research-rm or /research-clear). Resolve gracefully so
3499
- // a spawn_research tool call awaiting this helper doesn't hang.
3547
+ // Operator kill (via /agents-kill rN|all or its research-* aliases).
3548
+ // Resolve gracefully so a spawn_research tool call awaiting this helper
3549
+ // doesn't hang.
3500
3550
  if (state.killedByOperator) {
3501
3551
  state.killedByOperator = false;
3502
3552
  state.status = "idle";
3553
+ state.finishedAt = Date.now();
3503
3554
  state.lastWork = "(killed by operator)";
3504
3555
  updateResearchWidget();
3505
3556
  state.zoomRender?.(true);
3506
3557
  historyEnd(histEntry, "idle");
3558
+ pruneResearch();
3507
3559
  return {
3508
3560
  output: `Research helper r${state.id} was killed by the operator before it finished.`,
3509
3561
  exitCode: code ?? 143,
@@ -3512,11 +3564,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3512
3564
  }
3513
3565
 
3514
3566
  state.status = code === 0 ? "done" : "error";
3567
+ state.finishedAt = Date.now();
3515
3568
  if (code === 0) state.sessionFile = sessionPath;
3516
3569
  state.lastWork = full.split("\n").filter((l: string) => l.trim()).pop() || "";
3517
3570
  updateResearchWidget();
3518
3571
  state.zoomRender?.(true);
3519
3572
  historyEnd(histEntry, state.status);
3573
+ pruneResearch();
3520
3574
 
3521
3575
  ctx.ui.notify(
3522
3576
  `Research r${state.id} ${state.status} in ${Math.round(state.elapsed / 1000)}s`,
@@ -4240,7 +4294,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4240
4294
 
4241
4295
  const answered = await Promise.all(researchQs.map(async (q) => {
4242
4296
  const rDef = anonResearchDef();
4243
- const rState = createResearchState(rDef, false, resolveResearchModel(rDef, undefined, ctx));
4297
+ // Ephemeral: auto-pipe helpers are pruned as soon as they finish —
4298
+ // their findings persist as files, their rN handles are never resumed.
4299
+ const rState = createResearchState(rDef, false, resolveResearchModel(rDef, undefined, ctx), true);
4244
4300
  updateResearchWidget();
4245
4301
  const rRes = await spawnResearch(rState, q, ctx);
4246
4302
  const file = safePathWithin(findingsDir, `${agentKey}-r${rState.id}.md`);
@@ -5942,43 +5998,93 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5942
5998
  return filtered.length > 0 ? filtered : items;
5943
5999
  };
5944
6000
 
5945
- // /research-cont rN <prompt> — resume a finished helper on its existing session.
6001
+ // ── Unified subagent commands ────────────────
6002
+ // Team specialists are addressed by persona name, research helpers by their rN
6003
+ // handle — one command family covers both (mirroring /zoom's target resolution).
6004
+ // The research-* commands remain as aliases of their agents-* counterparts.
6005
+
6006
+ // Resume a finished helper on its existing session. Shared by /agents-cont and
6007
+ // its /research-cont alias.
6008
+ const researchContHandler = async (args: string | undefined, ctx: any) => {
6009
+ widgetCtx = ctx;
6010
+ const trimmed = (args ?? "").trim();
6011
+ const sp = trimmed.indexOf(" ");
6012
+ if (sp === -1) {
6013
+ ctx.ui.notify("Usage: /agents-cont rN <prompt>", "error");
6014
+ return;
6015
+ }
6016
+ const rid = parseResearchHandle(trimmed.slice(0, sp));
6017
+ const prompt = trimmed.slice(sp + 1).trim();
6018
+ const state = rid != null ? researchStates.get(rid) : undefined;
6019
+ if (!state) {
6020
+ ctx.ui.notify(`No research helper "${trimmed.slice(0, sp)}". Use /research to start one.`, "error");
6021
+ return;
6022
+ }
6023
+ if (!prompt) {
6024
+ ctx.ui.notify("Usage: /agents-cont rN <prompt>", "error");
6025
+ return;
6026
+ }
6027
+ if (state.status === "running") {
6028
+ ctx.ui.notify(`Research r${state.id} is still running — wait for it to finish.`, "warning");
6029
+ return;
6030
+ }
6031
+ state.turnCount++;
6032
+ updateResearchWidget();
6033
+ ctx.ui.notify(`Continuing research r${state.id} (Turn ${state.turnCount})…`, "info");
6034
+ spawnResearch(state, prompt, ctx).then(result => deliverResearchFollowUp(state, result));
6035
+ };
6036
+
6037
+ pi.registerCommand("agents-cont", {
6038
+ description: "Continue a finished research helper: /agents-cont rN <prompt>",
6039
+ getArgumentCompletions: researchHandleCompletions,
6040
+ handler: researchContHandler,
6041
+ });
6042
+
5946
6043
  pi.registerCommand("research-cont", {
5947
- description: "Continue a finished research helper: /research-cont rN <prompt>",
6044
+ description: "Continue a finished research helper (alias of /agents-cont): /research-cont rN <prompt>",
5948
6045
  getArgumentCompletions: researchHandleCompletions,
5949
- handler: async (args, ctx) => {
5950
- widgetCtx = ctx;
5951
- const trimmed = (args ?? "").trim();
5952
- const sp = trimmed.indexOf(" ");
5953
- if (sp === -1) {
5954
- ctx.ui.notify("Usage: /research-cont rN <prompt>", "error");
5955
- return;
5956
- }
5957
- const rid = parseResearchHandle(trimmed.slice(0, sp));
5958
- const prompt = trimmed.slice(sp + 1).trim();
5959
- const state = rid != null ? researchStates.get(rid) : undefined;
5960
- if (!state) {
5961
- ctx.ui.notify(`No research helper "${trimmed.slice(0, sp)}". Use /research to start one.`, "error");
5962
- return;
5963
- }
5964
- if (!prompt) {
5965
- ctx.ui.notify("Usage: /research-cont rN <prompt>", "error");
5966
- return;
5967
- }
5968
- if (state.status === "running") {
5969
- ctx.ui.notify(`Research r${state.id} is still running — wait for it to finish.`, "warning");
5970
- return;
5971
- }
5972
- state.turnCount++;
5973
- updateResearchWidget();
5974
- ctx.ui.notify(`Continuing research r${state.id} (Turn ${state.turnCount})…`, "info");
5975
- spawnResearch(state, prompt, ctx).then(result => deliverResearchFollowUp(state, result));
5976
- },
6046
+ handler: researchContHandler,
5977
6047
  });
5978
6048
 
5979
- // /research-rm rN — remove one helper (SIGTERM if running).
6049
+ // Remove one research helper (SIGTERM if running) — the state, its card, and
6050
+ // its session file. Team specialists are standing and cannot be removed.
6051
+ function removeResearchHelper(state: ResearchState, ctx: any) {
6052
+ if (state.proc && state.status === "running") {
6053
+ state.killedByOperator = true;
6054
+ state.proc.kill("SIGTERM");
6055
+ ctx.ui.notify(`Research r${state.id} killed and removed.`, "warning");
6056
+ } else {
6057
+ ctx.ui.notify(`Research r${state.id} removed.`, "info");
6058
+ }
6059
+ try { unlinkSync(researchSessionPath(state.id)); } catch {}
6060
+ researchStates.delete(state.id);
6061
+ updateResearchWidget();
6062
+ }
6063
+
6064
+ // Remove all helpers (SIGTERM any running). Shared by /agents-kill all and /research-clear.
6065
+ function clearResearchHelpers(ctx: any) {
6066
+ let killed = 0;
6067
+ const total = researchStates.size;
6068
+ for (const [, state] of Array.from(researchStates.entries())) {
6069
+ if (state.proc && state.status === "running") {
6070
+ state.killedByOperator = true;
6071
+ state.proc.kill("SIGTERM");
6072
+ killed++;
6073
+ }
6074
+ try { unlinkSync(researchSessionPath(state.id)); } catch {}
6075
+ }
6076
+ researchStates.clear();
6077
+ nextResearchId = 1;
6078
+ updateResearchWidget();
6079
+ const msg = total === 0
6080
+ ? "No research helpers to clear."
6081
+ : `Cleared ${total} research helper${total !== 1 ? "s" : ""}${killed > 0 ? ` (${killed} killed)` : ""}.`;
6082
+ ctx.ui.notify(msg, total === 0 ? "info" : "success");
6083
+ }
6084
+
6085
+ // /research-rm — alias of /agents-kill rN (kill on a research handle removes).
5980
6086
  pi.registerCommand("research-rm", {
5981
- description: "Remove a research helper (kill if running): /research-rm rN",
6087
+ description: "Remove a research helper (alias of /agents-kill rN): /research-rm rN",
5982
6088
  getArgumentCompletions: researchHandleCompletions,
5983
6089
  handler: async (args, ctx) => {
5984
6090
  widgetCtx = ctx;
@@ -5988,41 +6094,16 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5988
6094
  ctx.ui.notify(`Usage: /research-rm rN. Known: ${Array.from(researchStates.values()).map(s => `r${s.id}`).join(", ") || "none"}`, "error");
5989
6095
  return;
5990
6096
  }
5991
- if (state.proc && state.status === "running") {
5992
- state.killedByOperator = true;
5993
- state.proc.kill("SIGTERM");
5994
- ctx.ui.notify(`Research r${state.id} killed and removed.`, "warning");
5995
- } else {
5996
- ctx.ui.notify(`Research r${state.id} removed.`, "info");
5997
- }
5998
- try { unlinkSync(researchSessionPath(state.id)); } catch {}
5999
- researchStates.delete(state.id);
6000
- updateResearchWidget();
6097
+ removeResearchHelper(state, ctx);
6001
6098
  },
6002
6099
  });
6003
6100
 
6004
- // /research-clear — remove all helpers (SIGTERM any running).
6101
+ // /research-clear — alias of /agents-kill all.
6005
6102
  pi.registerCommand("research-clear", {
6006
- description: "Remove all research helpers",
6103
+ description: "Remove all research helpers (alias of /agents-kill all)",
6007
6104
  handler: async (_args, ctx) => {
6008
6105
  widgetCtx = ctx;
6009
- let killed = 0;
6010
- const total = researchStates.size;
6011
- for (const [, state] of Array.from(researchStates.entries())) {
6012
- if (state.proc && state.status === "running") {
6013
- state.killedByOperator = true;
6014
- state.proc.kill("SIGTERM");
6015
- killed++;
6016
- }
6017
- try { unlinkSync(researchSessionPath(state.id)); } catch {}
6018
- }
6019
- researchStates.clear();
6020
- nextResearchId = 1;
6021
- updateResearchWidget();
6022
- const msg = total === 0
6023
- ? "No research helpers to clear."
6024
- : `Cleared ${total} research helper${total !== 1 ? "s" : ""}${killed > 0 ? ` (${killed} killed)` : ""}.`;
6025
- ctx.ui.notify(msg, total === 0 ? "info" : "success");
6106
+ clearResearchHelpers(ctx);
6026
6107
  },
6027
6108
  });
6028
6109
 
@@ -6049,16 +6130,60 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6049
6130
  },
6050
6131
  });
6051
6132
 
6133
+ // Completions over both target kinds: team persona names + research handles
6134
+ // (rN), each annotated with status — for the unified /agents-kill and
6135
+ // /agents-restart.
6136
+ const subagentTargetCompletions = (prefix: string): AutocompleteItem[] | null => {
6137
+ const items = [...(agentNameCompletions("") ?? []), ...(researchHandleCompletions("") ?? [])];
6138
+ if (items.length === 0) return null;
6139
+ const filtered = items.filter(i => i.value.toLowerCase().startsWith(prefix.toLowerCase()));
6140
+ return filtered.length > 0 ? filtered : items;
6141
+ };
6142
+
6143
+ // /agents-kill completions additionally offer "all" (research helpers only).
6144
+ const agentsKillCompletions = (prefix: string): AutocompleteItem[] | null => {
6145
+ const targets = subagentTargetCompletions("") ?? [];
6146
+ const items = researchStates.size > 0
6147
+ ? [...targets, { value: "all", label: "all — kill & remove every research helper" }]
6148
+ : targets;
6149
+ if (items.length === 0) return null;
6150
+ const filtered = items.filter(i => i.value.toLowerCase().startsWith(prefix.toLowerCase()));
6151
+ return filtered.length > 0 ? filtered : items;
6152
+ };
6153
+
6052
6154
  pi.registerCommand("agents-kill", {
6053
- description: "Kill a running specialist: /agents-kill <name>",
6054
- getArgumentCompletions: agentNameCompletions,
6155
+ description: "Kill a running specialist, or kill & remove research helper(s): /agents-kill <name|rN|all>",
6156
+ getArgumentCompletions: agentsKillCompletions,
6055
6157
  handler: async (args, ctx) => {
6056
6158
  widgetCtx = ctx;
6057
6159
  const name = args?.trim();
6160
+ // "all" clears every research helper (kill any running). Team specialists
6161
+ // are standing — never touched by "all".
6162
+ if (name?.toLowerCase() === "all") {
6163
+ clearResearchHelpers(ctx);
6164
+ return;
6165
+ }
6166
+ // An rN handle targets a research helper. Research helpers are disposable
6167
+ // by design, so kill also REMOVES — the card, the state, and the session
6168
+ // file go with the process (a finished helper is simply removed).
6169
+ const rid = name ? parseResearchHandle(name) : null;
6170
+ if (rid != null) {
6171
+ const rState = researchStates.get(rid);
6172
+ if (!rState) {
6173
+ const known = Array.from(researchStates.values()).map(s => `r${s.id}`).join(", ");
6174
+ ctx.ui.notify(`No research helper "${name}". Known: ${known || "none"}`, "error");
6175
+ return;
6176
+ }
6177
+ removeResearchHelper(rState, ctx);
6178
+ return;
6179
+ }
6058
6180
  const state = name ? agentStates.get(name.toLowerCase()) : undefined;
6059
6181
  if (!state) {
6060
- const known = Array.from(agentStates.values()).map(s => displayName(s.def.name)).join(", ");
6061
- ctx.ui.notify(`Usage: /agents-kill <name>. Known: ${known || "none"}`, "error");
6182
+ const known = [
6183
+ ...Array.from(agentStates.values()).map(s => displayName(s.def.name)),
6184
+ ...Array.from(researchStates.values()).map(s => `r${s.id}`),
6185
+ ].join(", ");
6186
+ ctx.ui.notify(`Usage: /agents-kill <name|rN|all>. Known: ${known || "none"}`, "error");
6062
6187
  return;
6063
6188
  }
6064
6189
  if (state.status !== "running" || (!state.proc && !state.comsAbort)) {
@@ -6082,15 +6207,45 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6082
6207
  });
6083
6208
 
6084
6209
  pi.registerCommand("agents-restart", {
6085
- description: "Kill and re-run a specialist's last task fresh: /agents-restart <name>",
6086
- getArgumentCompletions: agentNameCompletions,
6210
+ description: "Kill and re-run a specialist's (or re-run a finished research helper's) last task fresh: /agents-restart <name|rN>",
6211
+ getArgumentCompletions: subagentTargetCompletions,
6087
6212
  handler: async (args, ctx) => {
6088
6213
  widgetCtx = ctx;
6089
6214
  const name = args?.trim();
6215
+ // An rN handle re-runs a finished helper's last task on a fresh session
6216
+ // (unlike /agents-cont, which resumes the existing one). A running helper
6217
+ // can't be restarted mid-flight — spawnResearch's promise is held by its
6218
+ // original caller, and /agents-kill removes the helper outright.
6219
+ const rid = name ? parseResearchHandle(name) : null;
6220
+ if (rid != null) {
6221
+ const rState = researchStates.get(rid);
6222
+ if (!rState) {
6223
+ const known = Array.from(researchStates.values()).map(s => `r${s.id}`).join(", ");
6224
+ ctx.ui.notify(`No research helper "${name}". Known: ${known || "none"}`, "error");
6225
+ return;
6226
+ }
6227
+ if (rState.status === "running") {
6228
+ ctx.ui.notify(`Research r${rState.id} is still running — wait for it to finish (or /agents-kill r${rState.id} to discard it and /research the task again).`, "warning");
6229
+ return;
6230
+ }
6231
+ if (!rState.task) {
6232
+ ctx.ui.notify(`Research r${rState.id} has no previous task to restart.`, "warning");
6233
+ return;
6234
+ }
6235
+ rState.sessionFile = null;
6236
+ rState.turnCount = 1;
6237
+ updateResearchWidget();
6238
+ ctx.ui.notify(`Restarting research r${rState.id} (fresh)...`, "info");
6239
+ spawnResearch(rState, rState.task, ctx).then(result => deliverResearchFollowUp(rState, result));
6240
+ return;
6241
+ }
6090
6242
  const state = name ? agentStates.get(name.toLowerCase()) : undefined;
6091
6243
  if (!state) {
6092
- const known = Array.from(agentStates.values()).map(s => displayName(s.def.name)).join(", ");
6093
- ctx.ui.notify(`Usage: /agents-restart <name>. Known: ${known || "none"}`, "error");
6244
+ const known = [
6245
+ ...Array.from(agentStates.values()).map(s => displayName(s.def.name)),
6246
+ ...Array.from(researchStates.values()).map(s => `r${s.id}`),
6247
+ ].join(", ");
6248
+ ctx.ui.notify(`Usage: /agents-restart <name|rN>. Known: ${known || "none"}`, "error");
6094
6249
  return;
6095
6250
  }
6096
6251
  const task = state.task;
@@ -6745,6 +6900,7 @@ ${researchCatalog}`;
6745
6900
  // Load per-project overrides (user-facing language, persona gate, models).
6746
6901
  const overrides = parseAgentTeamOverrides(_ctx.cwd);
6747
6902
  userLanguage = overrides.language;
6903
+ researchKeep = overrides.researchKeep;
6748
6904
  if (overrides.warnings.length > 0) {
6749
6905
  _ctx.ui.notify(`agent-fleet-overrides warnings:\n${overrides.warnings.join("\n")}`, "warning");
6750
6906
  }
@@ -0,0 +1,34 @@
1
+ // Retention policy for finished research helpers. The hub keeps every helper's
2
+ // card (and resumable session) in memory until something removes it; this module
3
+ // decides which finished helpers to drop so the research row doesn't grow without
4
+ // bound over a long session. Pure — the hub owns the actual state map, session
5
+ // files, and widget refresh.
6
+
7
+ export const DEFAULT_RESEARCH_KEEP = 4;
8
+
9
+ // Parse the `research-keep` override value: "all" disables pruning of durable
10
+ // helpers, a non-negative integer keeps that many most-recently-finished ones.
11
+ // Returns null for anything else (caller warns and keeps the default).
12
+ export function parseResearchKeep(value) {
13
+ const v = String(value ?? "").trim().toLowerCase();
14
+ if (v === "all") return Infinity;
15
+ if (/^\d+$/.test(v)) return Number(v);
16
+ return null;
17
+ }
18
+
19
+ // Decide which helper ids to drop. `states`: [{ id, status, finishedAt, ephemeral }].
20
+ // Running helpers are never dropped. Finished ephemeral helpers (auto-research
21
+ // pipe spawns — their findings persist as files under findings/ and their handles
22
+ // are never resumed) are always dropped. Finished durable helpers beyond the
23
+ // `keep` most recently finished are dropped, oldest first.
24
+ export function selectResearchPrunable(states, keep) {
25
+ const capped = keep >= 0 ? keep : DEFAULT_RESEARCH_KEEP;
26
+ const finished = (states || []).filter((s) => s.status !== "running");
27
+ const ephemeral = finished.filter((s) => s.ephemeral).map((s) => s.id);
28
+ const durable = finished
29
+ .filter((s) => !s.ephemeral)
30
+ .sort((a, b) => (b.finishedAt ?? 0) - (a.finishedAt ?? 0));
31
+ // slice(Infinity) → [] — "all" keeps every durable helper.
32
+ const overflow = durable.slice(capped).map((s) => s.id);
33
+ return [...ephemeral, ...overflow];
34
+ }
@@ -2,6 +2,8 @@
2
2
 
3
3
  Harness wrapper for `pi-ask-user` that preserves the stock `ask_user` UI and result shape while optionally racing it against the Hermes `user-remote` coms peer.
4
4
 
5
+ The experimental Codex Remote-Control conductor is **not** an inbound `ask_user` route. It initiates approval-gated outbound delegation from Android; Hermes remains the only phone answer participant in this race. See the [Codex conductor runbook](../../../docs/codex-remote-conductor.md).
6
+
5
7
  - The stock `pi-ask-user` extension is loaded through a capture proxy; its `ask_user` tool is not registered directly.
6
8
  - If no live `user-remote` peer is present at call time, the wrapper calls stock `execute` with the original arguments and signal unchanged.
7
9
  - If `user-remote` is present, the wrapper races local stock UI against the remote coms request using `race-core.js`; first answer wins and local-first emits one best-effort cancel.
@@ -41,6 +41,17 @@ when you are on the herdr backend.
41
41
  - `coms_list` / `coms_send` / `coms_get` / `coms_await` tools — discover peers and
42
42
  exchange messages
43
43
 
44
+ ## External conductors
45
+
46
+ Two optional phone-facing conductors use this same pool without becoming pane owners:
47
+
48
+ - **Hermes/Telegram** is the inbound `ask_user` route and can also perform bounded coms delegation.
49
+ - **Codex Remote Control** is an experimental outbound-only Android route. Its user-systemd service loads a managed contract from an external user-state workspace, and `scripts/codex-conductor.ts` permits only scoped `list` plus one serialized `send --await`. See the [operator runbook](../../../docs/codex-remote-conductor.md).
50
+
51
+ Both must use the same validated project as the peers they target. Neither conductor may drive Herdr lifecycle.
52
+
53
+ Standalone `coms-cli` queues are project-scoped under `~/.pi/coms/cli/projects/<project>/<name>/`. Legacy name-only queues fail closed until an operator assigns and moves the complete queue; `projects` is a reserved identity name.
54
+
44
55
  ## Pool scope is the reach boundary
45
56
 
46
57
  The pool widget defines who you can reach: `coms_list` and `coms_send` resolve targets through one
@@ -10,6 +10,6 @@ Also flag and offer to rewrite any remaining YAML configs (`teams.yaml`, `peers.
10
10
 
11
11
  Also validate `.ai/agent-fleet-overrides.md` when it exists, against the schema in `docs/agent-fleet-setup.md`: unknown sections, unknown keys in known sections, invalid values for the mechanically parsed `agent-hub` keys, missing `rules:` folders, and `## env` `required:` names that are neither set nor declared in the root `.env`. These findings are advisory only — report them with fix "edit by hand", never edit the overrides file.
12
12
 
13
- Present findings as a `# | Path | Issue | Suggested fix` table and ask the user to pick which fixes to apply.
13
+ Present the findings per the skill's Step 1 interaction contract: print a short text summary (counts per kind, advisory findings as report-only text), then ask one `ask_user` multi-select — *"Which fixes should I apply now?"* — each option titled `<path> — <issue>` with the proposed fix as its description, chunked at ≤ 9 options; empty selection or cancel applies nothing. Without the widget, print a `# | Path | Issue | Suggested fix` table instead and take the picks as text.
14
14
 
15
15
  Never overwrite a regular file — only act on symlinks whose target is missing. Report `repaired`, `deleted`, and `skipped` counts, and append a `## doctor-runs` line to `.ai/agent-fleet-setup.md` with the date, agent, phase (`standalone`), and counts.
@@ -12,9 +12,9 @@ Analyse the workspace. If prior install state is found (`.ai/agent-fleet-setup.m
12
12
 
13
13
  The Skills group draws from **two roots**: fleet-native `skills/` and the vendored upstream import `vendor/agent-skills-upstream/skills/` (see `docs/UPSTREAM-SKILLS.md`). On a name collision the native copy wins — never offer the vendored duplicate as a separate row.
14
14
 
15
- Then present the install menu as **one multi-select per group** — **7 groups** (4 shared: Skills, Agent personas, Commands/prompts, References & Hooks; 3 pi-only: pi extensions & runtime skills, pi harnesses, External pi packages) with `★` marking recommendations. Multi-type groups carry a leading `Group` column labelling the sub-category (lifecycle phase for Skills, `rw`/`ro`/`pi-only` for personas, harness category, etc.). Each group renders as a compact `Pick | Item | Group | St | Purpose` table (omit `Group` for single-type groups); append `★` to the item name for recommended rows instead of using a separate recommendation column. Print the compact status legend once: `St: ok=up to date · upd=update available · mod=modified locally · cflt=conflicting upgrade · gone=removed upstream · new=new this version · pkg=project package · — =not installed · brk=broken`. Installed items are **pre-checked `[x]`** so unchecking = remove; not-installed items start `[ ]`. Per-group reply shortcuts: `all`, `recommended` (adds `★` items on top of the pre-selection — never unticks installed ones), `none`, `keep` (accept the pre-selection unchanged), or a list of picks. The External pi packages group lists `pi-ask-user` and the optional suggested `pi-codex-image-gen` package. After Step 5b, `pi-ask-user` normally has `St=pkg` and is pre-checked to keep; state the scope (`project`, `bundled by @chankov/agent-fleet`, or `global`) in the after-table restate line and do not duplicate bundled/project/global entries. `pi-codex-image-gen` is not bundled or bootstrapped; offer `pi install -l npm:pi-codex-image-gen` only when the user selects that external package. Never offer `setup`, `doctor`, or `guided-workspace-setup` — those are installer-only and live in the source agent-fleet repo.
15
+ Then present the install menu per the skill's Step 1 interaction contract — drive every decision through the `ask_user` widget, never a printed table awaiting a free-text reply (the table format is reserved for the no-widget fallback when the user declined the bootstrap). Open with the **Express question** (fresh workspace: `Recommended ★` / `Everything` / `Custom — group by group` / `Nothing`; existing: `Keep as-is` / `Apply updates` / `Keep + add recommended ★` / `Custom`) — any answer but `Custom` skips all group screens. On `Custom`, run the **7 groups** (4 shared: Skills, Agent personas, Commands/prompts, References & Hooks; 3 pi-only: pi extensions & runtime skills, pi harnesses, External pi packages): each opens as a single-select quick screen (`Recommended ★ (n)` / `Everything (m)` / `Customise` / `Skip group`, or the installed-state variants with `Remove some…`), and multi-select drill-ins appear only behind `Customise`, chunked by sub-category (lifecycle phase for Skills, `rw`/`ro`/`pi-only` for personas, harness category, …) at ≤ 9 options per call, ≤ 8 `context` lines. Option titles carry `name ★ [st]` (`ok`/`upd`/`mod`/`cflt`/`gone`/`new`/`pkg`/`—`/`brk`); descriptions carry the purpose plus the state in plain words (`mod` → warn that refreshing overwrites local edits). There is **no pre-checking** (`ask_user` has no preselect) — installed state shows as counts on quick screens and words in descriptions; leaving an installed item unselected in a drill-in keeps it as-is. Freeform stays on so `all` / `recommended` (adds `★` on top — never removes) / `none` / `keep` still work; cancel = keep-as-is/skip. `cflt` rows are resolved only by printing the three-way diff and asking per row with `displayMode: "inline"` — never by Express or `Apply updates`. The External pi packages group lists `pi-ask-user` and the optional suggested `pi-codex-image-gen`. After Step 5b, `pi-ask-user` normally counts toward `Keep as-is` (`pkg`, scope `project` / `bundled by @chankov/agent-fleet` / `global` — state it in the restate line, no duplicate entries). `pi-codex-image-gen` is not bundled or bootstrapped; offer `pi install -l npm:pi-codex-image-gen` only when the user selects it. Never offer `setup`, `doctor`, or `guided-workspace-setup` — those are installer-only and live in the source agent-fleet repo.
16
16
 
17
- Unchecking an installed item means *remove it*, but **removal is scoped**: only act on items whose name is in the agent-fleet inventory **and** that are recorded in `## install-status` (or are symlinks resolving into the source repo). User-authored skills, custom commands, third-party plugins, external pi packages not recorded by this setup, and unrelated settings/env keys are left untouched and logged as "Skipped — not owned by agent-fleet".
17
+ Removal happens **only** on an explicit `Remove some…` multi-select (empty selection = remove nothing), and it is scoped: the screen lists only items whose name is in the agent-fleet inventory **and** that are recorded in `## install-status` (or are symlinks resolving into the source repo). User-authored skills, custom commands, third-party plugins, external pi packages not recorded by this setup, and unrelated settings/env keys are left untouched and logged as "Skipped — not owned by agent-fleet".
18
18
 
19
19
  **No cross-tool substitution.** Each row is offered only when the source file the chosen agent needs already exists — for `pi`, that means `.pi/prompts/<name>.md`, `.pi/extensions/<name>/`, etc. Never fall back to `.claude/commands/` (or another agent's tree) to satisfy a pi prompt request; items missing their per-agent source are filtered out of the menu entirely.
20
20
 
@@ -22,6 +22,6 @@ Unchecking an installed item means *remove it*, but **removal is scoped**: only
22
22
 
23
23
  **pi harness companions.** Installing, refreshing, or removing any pi harness also refreshes its companions in the same pass — the `justfile` launch recipes, `scripts/team-up.ts`, the peer/team YAML and personas, `.pi/damage-control-rules.yaml`, and `.pi/harnesses/package.json`. When `agent-hub` is installed or kept, keep its required launch companions together: `damage-control`, `damage-control-continue`, and `ask-user-remote`; the managed `just hub` / `hub-solo` recipes load `damage-control-continue`, then `ask-user-remote`, then `agent-hub` so the dispatcher probe sees `ask_user`. Refresh the `justfile` from the **current** source so retired-harness recipes are pruned and new ones added, rewriting only the managed region between the `agent-fleet:harnesses` sentinels so any user recipes survive. Leaving a stale `justfile` (recipes pointing at deleted harness dirs, or no recipe for a new harness) is the regression this prevents.
24
24
 
25
- **No mid-apply overwrite prompts.** The Step 6 `mod` status already warns that locally modified rows will have local edits overwritten if kept ticked. The user's tick is the consent; the Step 9 confirmation is the single gate. During apply, refresh ticked items unconditionally — never pause to ask "should I overwrite this file?". Genuine errors (permission denied, missing source) still stop and report.
25
+ **No mid-apply overwrite prompts.** The `mod` description already warns that refreshing overwrites local edits. The user's selection is the consent; the Step 9 confirmation is the single gate. During apply, refresh selected items unconditionally — never pause to ask "should I overwrite this file?". Genuine errors (permission denied, missing source) still stop and report.
26
26
 
27
- Offer override sections for the workspace's `.ai/agent-fleet-overrides.md` based on the analysis, and record what was installed in `.ai/agent-fleet-setup.md`. Summarise the full plan and wait for explicit confirmation before writing anything, then perform the setup, re-scan for any new breakage, and report what changed.
27
+ Offer override sections for the workspace's `.ai/agent-fleet-overrides.md` based on the analysis (print each draft, then `Accept` / `Edit` / `Skip` per section via `ask_user`), and record what was installed in `.ai/agent-fleet-setup.md`. Print the plan as compact action-grouped lines (Add / Refresh / Remove / Keep-count / Records / Method), then confirm with one `ask_user` single-select asked with `displayMode: "inline"` — `Apply — and remove the installer commands` (default) / `Apply — keep the installer commands` / `Adjust picks` / `Cancel` — and write nothing until an Apply is chosen. Then perform the setup, re-scan for any new breakage, and report what changed.