@hcflabs/pi-herdr-tools 1.8.0 → 1.9.1

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/README.md CHANGED
@@ -25,6 +25,8 @@ Configure `fast` in `/task-models`.
25
25
 
26
26
  ## Use
27
27
 
28
+ Use `/diagnostics` to read recent config reports and command recovery errors.
29
+
28
30
  Run `/clone-tab`; the original session stays active. Commands and prompts are for humans; tools are for agents.
29
31
 
30
32
  | Surface | Type | Purpose |
@@ -66,12 +68,13 @@ Run `/handoff-worktree Fix the flaky login test`. The agent collects missing fac
66
68
 
67
69
  The tool registers only with `HERDR_ENV=1`. It also requires `HERDR_PANE_ID` and local `main`. A handoff has no checked integration: the new agent works without supervision. Delegated subagents cannot use the tool.
68
70
 
69
- The tool selects the repository in one of two ways:
71
+ The tool selects the repository in one of three ways:
70
72
 
71
73
  - Without `repo`, the current directory and the pane workspace must be in the same Git repository.
72
- - With `repo`, the tool uses that child repository of the Pi working directory. Use it when Pi runs in a parent directory that holds many repositories. The current workspace does not need a Git checkout.
74
+ - Without `repo`, when the pane workspace has no Git checkout, the Pi working directory is the repository. This works only when the working directory is a Git top-level directory. The tool then uses `--cwd <repository>`.
75
+ - With `repo`, the tool uses that repository below the Pi working directory. Use it when Pi runs in a parent directory that holds many repositories. Use `.` for the working directory itself. The current workspace does not need a Git checkout.
73
76
 
74
- The tool never selects a child repository automatically. All parameters must be non-empty strings:
77
+ The tool never selects a child repository automatically. When `repo` is needed, the error names the `repo` parameter. It lists at most 20 repository paths that it found below the Pi working directory. All parameters must be non-empty strings:
75
78
 
76
79
  | Parameter | Requirement |
77
80
  | --- | --- |
@@ -79,7 +82,7 @@ The tool never selects a child repository automatically. All parameters must be
79
82
  | `label` | Workspace label. |
80
83
  | `agentName` | Unique agent name matching `^[a-z][a-z0-9_-]{0,31}$`. |
81
84
  | `prompt` | Self-contained task prompt. |
82
- | `repo` | Optional. A Git top-level directory, relative to the Pi working directory. It must not contain `..` or resolve outside that directory. A subdirectory of a repository fails. |
85
+ | `repo` | Optional. A Git top-level directory, relative to the Pi working directory. `.` names the working directory. It must not contain `..` or resolve outside that directory. A subdirectory of a repository fails. |
83
86
 
84
87
  After validation, the tool runs `herdr worktree create --workspace <parent> --branch <branch> --base main --label <label> --no-focus`. With `repo`, it uses `--cwd <repository>` instead of `--workspace <parent>`. Herdr then opens the primary workspace of the repository, or creates it, and does not close it later. It starts Pi without session arguments. It submits `herdr agent prompt <agentName> <prompt> --wait --until working --timeout 30000`, with the prompt as one argument, not a shell command or file. The result includes workspace ID, tab, pane, branch, checkout path, agent name, and `repo` when set.
85
88
 
@@ -196,6 +199,7 @@ Clones are separate session files in the Pi-selected session directory. Each con
196
199
  | Agent start requested | An ambiguous launch retains targets and session files. Inspect reported IDs. |
197
200
  | Clone focus failure | Pi already started. Focus its tab manually. |
198
201
  | Handoff validation failure | No worktree exists. Correct the reported requirement. |
202
+ | Handoff Git failure, for example a timeout or an old Git version | No worktree exists. The error gives the exit code and the first part of the Git error text. Fix Git, then call the tool again. |
199
203
  | Handoff cancellation | Before creation, nothing remains. After creation, reported resources remain; later launch or delivery steps stop. |
200
204
  | Handoff start or prompt failure | Resources remain. Errors identify worktree, branch, workspace, tab, pane, and agent. No automatic cleanup occurs. |
201
205
  | `agent_blocked` or `agent_prompt_stalled` | Prompt delivery failed. Inspect the agent before retrying. |
@@ -1,4 +1,5 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { registerDiagnosticsCommand } from "@hcflabs/pi-config-store";
2
3
  import registerBtwExtension, { BTW_TASK } from "../internal/btw.ts";
3
4
  import herdrCloneExtension from "../internal/clone-tab.ts";
4
5
  import herdrCommandExtension from "../internal/command.ts";
@@ -9,6 +10,7 @@ import herdrRenameExtension, { RENAME_TASK } from "../internal/rename.ts";
9
10
  import { registerTaskModelsWarning } from "../internal/task-models.ts";
10
11
 
11
12
  export default async function herdrToolsExtension(pi: ExtensionAPI): Promise<void> {
13
+ registerDiagnosticsCommand(pi);
12
14
  registerTaskModelsWarning(pi, [RENAME_TASK, BTW_TASK, RECAP_TASK]);
13
15
  herdrRenameExtension(pi);
14
16
  idleRecapExtension(pi);
@@ -4,7 +4,7 @@ import { isAbsolute, join } from "node:path";
4
4
  import { setTimeout as delay } from "node:timers/promises";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
7
- import { createConfigStore, extensionConfigDir, field, formatConfigIssues, parsers, registerConfigReporting } from "@hcflabs/pi-config-store";
7
+ import { createConfigStore, extensionConfigDir, field, formatConfigIssues, parsers, recordDiagnostic, registerConfigReporting } from "@hcflabs/pi-config-store";
8
8
  import { awaitShellPrompt, createHerdrClient, hasHerdrErrorCode, herdrCommandFailure } from "@hcflabs/pi-herdr";
9
9
  import { scanProcessLease } from "@hcflabs/pi-process";
10
10
  import { isWithin, resolveRepoTarget } from "@hcflabs/pi-repo";
@@ -369,7 +369,7 @@ export default function herdrCommandExtension(pi: ExtensionAPI, options: { agent
369
369
  endActivity(job);
370
370
  throw new Error("herdr_command: the session ended during start. The pane was closed; no command was started.");
371
371
  }
372
- const ready = await awaitShellPrompt(herdr, paneId, { cwd }, undefined, true);
372
+ const ready = await awaitShellPrompt(herdr, paneId, { cwd }, undefined, true, true);
373
373
  if (ready) {
374
374
  await herdr.exec(["pane", "close", paneId], { cwd });
375
375
  jobs.delete(id);
@@ -420,18 +420,18 @@ export default function herdrCommandExtension(pi: ExtensionAPI, options: { agent
420
420
  if (ctx.hasUI) ctx.ui.notify(text, "warning");
421
421
  else process.stderr.write(`${text}\n`);
422
422
  } catch (error) {
423
- console.error(`herdr_command: job ${id} could not be restored: ${error instanceof Error ? error.message : String(error)} Evidence: ${directory}.`);
423
+ recordDiagnostic("pi-herdr-tools", "error", `herdr_command: job ${id} could not be restored: ${error instanceof Error ? error.message : String(error)} Evidence: ${directory}.`, ctx);
424
424
  }
425
425
  }
426
426
  });
427
427
 
428
- pi.on("session_shutdown", async () => {
428
+ pi.on("session_shutdown", async (_event, ctx) => {
429
429
  closed = true;
430
430
  // A job does not outlive its session. Unproved stops keep their evidence in the job directory.
431
431
  for (const job of jobs.values()) {
432
432
  if (job.stopped) continue;
433
433
  try { await stopJob(job); }
434
- catch (error) { console.error(`herdr_command: ${error instanceof Error ? error.message : String(error)} Evidence: ${job.directory}.`); }
434
+ catch (error) { recordDiagnostic("pi-herdr-tools", "error", `herdr_command: ${error instanceof Error ? error.message : String(error)} Evidence: ${job.directory}.`, ctx); }
435
435
  }
436
436
  jobs.clear();
437
437
  });
@@ -1,6 +1,7 @@
1
+ import { realpath } from "node:fs/promises";
1
2
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
3
  import { createHerdrClient, herdrCommandFailure } from "@hcflabs/pi-herdr";
3
- import { resolveRepoTarget } from "@hcflabs/pi-repo";
4
+ import { discoverRepos, gitTopLevel, resolveRepoTarget, type RepoOptions } from "@hcflabs/pi-repo";
4
5
  import { Type } from "typebox";
5
6
  import {
6
7
  createWorktree,
@@ -13,6 +14,12 @@ import {
13
14
  } from "./worktree.ts";
14
15
 
15
16
  const PROMPT_TIMEOUT_MS = 30_000;
17
+ // An error message lists at most this many repo selectors, and searches for them for at most this long.
18
+ const MAX_SELECTORS = 20;
19
+ const SELECTOR_SEARCH_MS = 5_000;
20
+ const TEXT_LIMIT = 300;
21
+
22
+ const bounded = (text: string) => text.length > TEXT_LIMIT ? `${text.slice(0, TEXT_LIMIT)}...` : text;
16
23
 
17
24
  const nonEmpty = (description: string) => Type.String({ description, minLength: 1, pattern: "\\S" });
18
25
 
@@ -26,7 +33,7 @@ const HandoffParams = Type.Object({
26
33
  }),
27
34
  prompt: nonEmpty("Self-contained task prompt for the new agent"),
28
35
  repo: Type.Optional(nonEmpty(
29
- "Child Git repository for the worktree, as a path relative to the Pi working directory. Omit it to use the repository of the current Herdr workspace.",
36
+ "Git repository for the worktree, as a path relative to the Pi working directory. Use . for the working directory itself when it is a Git top-level directory. Omit it to use the repository of the current Herdr workspace, or the working directory when the workspace has no Git checkout and the working directory is a Git top-level directory.",
30
37
  )),
31
38
  });
32
39
 
@@ -42,7 +49,7 @@ export default function herdrHandoffExtension(pi: ExtensionAPI): void {
42
49
  promptSnippet: "Hand off a separate task to a new Pi agent in a new Herdr worktree from local main",
43
50
  promptGuidelines: [
44
51
  "Use herdr_handoff for a separate task that the user authorized, for example through /handoff-worktree. A handoff has no checked integration: the new agent works unsupervised.",
45
- "When the Pi working directory holds several repositories, set repo to the child repository of the task. herdr_handoff never selects a repository automatically.",
52
+ "When the Pi working directory is not a Git repository, or holds several repositories, set repo to the child repository of the task. herdr_handoff never selects a child repository automatically.",
46
53
  ],
47
54
  parameters: HandoffParams,
48
55
  executionMode: "sequential",
@@ -50,32 +57,60 @@ export default function herdrHandoffExtension(pi: ExtensionAPI): void {
50
57
  async execute(_toolCallId, { branch, label, agentName, prompt, repo }, signal, _onUpdate, ctx) {
51
58
  const paneId = requiredString(process.env.HERDR_PANE_ID, "HERDR_PANE_ID");
52
59
  const git = (cwd: string, args: string[]) => pi.exec("git", args, { cwd });
60
+ const repoOptions: RepoOptions = {
61
+ signal,
62
+ runProcess: (command, args, options) => pi.exec(command, args, { cwd: options.cwd, signal: options.signal, timeout: options.timeoutMs ?? undefined }),
63
+ };
64
+ /** List the repo values below the Pi working directory. A failed search adds no text. */
65
+ const selectorHint = async (): Promise<string> => {
66
+ try {
67
+ const found = await discoverRepos(ctx.cwd, { ...repoOptions, limit: MAX_SELECTORS, budgetMs: SELECTOR_SEARCH_MS });
68
+ if (found.repos.length === 0) return `Discovery found no Git repository below ${found.base}.`;
69
+ return `Repositories below ${found.base}: ${found.repos.map((item) => bounded(item.repo)).join(", ")}.${found.truncated ? " The list may be incomplete." : ""}`;
70
+ } catch {
71
+ return "";
72
+ }
73
+ };
74
+ const needRepo = async (reason: string) =>
75
+ new Error(`herdr_handoff: ${reason} Set the repo parameter to a Git repository, as a path relative to ${ctx.cwd}. ${await selectorHint()} Nothing was created.`);
76
+ const repository = async (cwd: string): Promise<string> => {
77
+ const result = await git(cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
78
+ if (result.code === 0 && !result.killed) return result.stdout.trim();
79
+ // Only a second check that finds no Git directory means "not a repository". Any other failure keeps its exit code.
80
+ const top = result.killed ? "failed" : await gitTopLevel(cwd, repoOptions).catch(() => "failed");
81
+ if (top === undefined) {
82
+ if (cwd === ctx.cwd) throw await needRepo(`${cwd} is not in a Git repository.`);
83
+ throw new Error(`herdr_handoff: ${cwd} is not in a Git repository; nothing was created.`);
84
+ }
85
+ const stderr = result.stderr.trim();
86
+ const outcome = result.killed ? `did not finish in ${cwd}` : `failed in ${cwd} with exit ${result.code}`;
87
+ throw new Error(`herdr_handoff: git rev-parse --git-common-dir ${outcome}${stderr ? `: ${bounded(stderr)}` : ""}. Nothing was created.`);
88
+ };
53
89
  let gitCwd: string;
54
90
  let location: string[];
55
91
  if (repo === undefined) {
56
92
  const workspace = await resolveWorkspace(herdr, ctx.cwd, paneId);
57
93
  if (!workspace.checkout) {
58
- throw new Error(
59
- `herdr_handoff: Herdr workspace ${workspace.workspaceId} has no Git checkout. Set repo to a child repository relative to ${ctx.cwd}; nothing was created.`,
60
- );
61
- }
62
- const repository = async (cwd: string) => {
63
- const result = await git(cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
64
- if (result.code !== 0 || result.killed) throw new Error(`herdr_handoff: ${cwd} is not in a Git repository; nothing was created.`);
65
- return result.stdout.trim();
66
- };
67
- // The worktree comes from the pane's workspace, so it must be the repository checked here.
68
- if (await repository(ctx.cwd) !== await repository(workspace.checkout)) {
69
- throw new Error(`herdr_handoff: ${ctx.cwd} and Herdr workspace ${workspace.workspaceId} (${workspace.checkout}) are different Git repositories; nothing was created.`);
94
+ // A plain workspace has no checkout to branch from. A working directory that is a Git top-level directory is the repository.
95
+ const top = await gitTopLevel(ctx.cwd, repoOptions).catch((error: unknown) => {
96
+ throw new Error(`herdr_handoff: ${errorMessage(error)} Nothing was created.`, { cause: error });
97
+ });
98
+ if (top === undefined || top !== await realpath(ctx.cwd)) {
99
+ throw await needRepo(`Herdr workspace ${workspace.workspaceId} has no Git checkout, and ${ctx.cwd} is not a Git top-level directory${top === undefined ? "" : ` (Git reports ${top})`}.`);
100
+ }
101
+ gitCwd = top;
102
+ location = ["--cwd", top];
103
+ } else {
104
+ // The worktree comes from the pane's workspace, so it must be the repository checked here.
105
+ if (await repository(ctx.cwd) !== await repository(workspace.checkout)) {
106
+ throw new Error(`herdr_handoff: ${ctx.cwd} and Herdr workspace ${workspace.workspaceId} (${workspace.checkout}) are different Git repositories; nothing was created.`);
107
+ }
108
+ gitCwd = ctx.cwd;
109
+ location = ["--workspace", await worktreeParentWorkspace(herdr, ctx.cwd, workspace)];
70
110
  }
71
- gitCwd = ctx.cwd;
72
- location = ["--workspace", await worktreeParentWorkspace(herdr, ctx.cwd, workspace)];
73
111
  } else {
74
112
  // Herdr opens or creates the repository's primary workspace when it gets --cwd.
75
- const target = await resolveRepoTarget(ctx.cwd, repo, {
76
- signal,
77
- runProcess: (command, args, options) => pi.exec(command, args, { cwd: options.cwd, signal: options.signal, timeout: options.timeoutMs ?? undefined }),
78
- }).catch((error: unknown) => {
113
+ const target = await resolveRepoTarget(ctx.cwd, repo, repoOptions).catch((error: unknown) => {
79
114
  throw new Error(`herdr_handoff: ${errorMessage(error)} Nothing was created.`, { cause: error });
80
115
  });
81
116
  gitCwd = target.root;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hcflabs/pi-herdr-tools",
3
- "version": "1.8.0",
3
+ "version": "1.9.1",
4
4
  "description": "Clone, hand off, name, and finish Pi conversations in Herdr, with mergeable side questions.",
5
5
  "keywords": ["pi-package", "pi", "herdr", "session", "clone", "side-thread", "title"],
6
6
  "type": "module",
@@ -19,8 +19,8 @@
19
19
  "typebox": "^1.3.15"
20
20
  },
21
21
  "dependencies": {
22
- "@hcflabs/pi-config-store": "^4.0.0",
23
- "@hcflabs/pi-herdr": "^0.6.0",
22
+ "@hcflabs/pi-config-store": "^4.2.0",
23
+ "@hcflabs/pi-herdr": "^0.7.0",
24
24
  "@hcflabs/pi-process": "^0.3.0",
25
25
  "@hcflabs/pi-repo": "^0.1.0",
26
26
  "@hcflabs/pi-task-models": "^9.0.0"
@@ -9,5 +9,5 @@ If the issue is empty, stop and ask the user to run `/handoff-worktree <issue>`.
9
9
 
10
10
  1. Gather only the missing facts from the conversation and the repository. Ask one focused question only if the repository, expected outcome, or a critical constraint is unclear.
11
11
  2. Write one self-contained prompt: problem, evidence, expected outcome, constraints, starting files, validation, and requested delivery. Exclude unrelated context, secrets, and stale runtime IDs.
12
- 3. Choose a concise branch, a short label, and a unique agent name. If the Pi working directory holds several repositories, also choose `repo`: the path of the child repository, relative to the working directory.
12
+ 3. Choose a concise branch, a short label, and a unique agent name. If the Pi working directory is not a Git repository, or holds several repositories, also choose `repo`: the path of the child repository, relative to the working directory. If `herdr_handoff` reports that `repo` is required, choose from the repositories that it lists.
13
13
  4. Call `herdr_handoff` with them. Report its result. Do not wait for the new agent to finish.