@hcflabs/pi-herdr-tools 1.9.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
@@ -68,12 +68,13 @@ Run `/handoff-worktree Fix the flaky login test`. The agent collects missing fac
68
68
 
69
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.
70
70
 
71
- The tool selects the repository in one of two ways:
71
+ The tool selects the repository in one of three ways:
72
72
 
73
73
  - Without `repo`, the current directory and the pane workspace must be in the same Git repository.
74
- - 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.
75
76
 
76
- 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:
77
78
 
78
79
  | Parameter | Requirement |
79
80
  | --- | --- |
@@ -81,7 +82,7 @@ The tool never selects a child repository automatically. All parameters must be
81
82
  | `label` | Workspace label. |
82
83
  | `agentName` | Unique agent name matching `^[a-z][a-z0-9_-]{0,31}$`. |
83
84
  | `prompt` | Self-contained task prompt. |
84
- | `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. |
85
86
 
86
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.
87
88
 
@@ -198,6 +199,7 @@ Clones are separate session files in the Pi-selected session directory. Each con
198
199
  | Agent start requested | An ambiguous launch retains targets and session files. Inspect reported IDs. |
199
200
  | Clone focus failure | Pi already started. Focus its tab manually. |
200
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. |
201
203
  | Handoff cancellation | Before creation, nothing remains. After creation, reported resources remain; later launch or delivery steps stop. |
202
204
  | Handoff start or prompt failure | Resources remain. Errors identify worktree, branch, workspace, tab, pane, and agent. No automatic cleanup occurs. |
203
205
  | `agent_blocked` or `agent_prompt_stalled` | Prompt delivery failed. Inspect the agent before retrying. |
@@ -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.9.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",
@@ -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.