@henryqw/pi-herdr 0.6.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -35,6 +35,7 @@ For a ready-to-use Pi workflow, see [`@henryqw/pi-herdr-tools`](https://pi.henry
35
35
  | `HerdrRequestError` | class | Reports a structured error code and whether dispatch was possible. |
36
36
  | `checkoutAdmission` | function | Shares process-local checkout ownership through Pi's public event bus. |
37
37
  | `checkoutKey` | function | Resolves the canonical checkout for admission. |
38
+ | `checkoutToolCanWrite` | function | Applies the shared Main-tool and direct-request write classification. |
38
39
  | `registerCheckoutAdmission` | function | Registers the existing direct-writer policy and returns its ownership hold function. |
39
40
  | `startPiAgent` | function | Validates and runs the shared `agent start --kind pi --pane ... --` boundary after a shell-readiness probe. |
40
41
 
@@ -52,19 +53,50 @@ Errors expose `code` and `dispatched`. If `dispatched` is true, a mutation can h
52
53
 
53
54
  ### Checkout admission
54
55
 
55
- `checkoutAdmission(pi)` finds one coordinator through Pi's public event bus. Call `install(pi)` to register tool lifecycle guards. `guard(name, refresh)` installs an awaited recovery check before writes. `reserve(owner, checkout)` returns a release function only when no admitted writer or Main write is active. `restore(owner, checkout)` restores durable ownership; `release(owner)` requires caller-proved completion.
56
+ `checkoutAdmission(pi)` finds one coordinator through Pi's public event bus. Call `install(pi)` to register tool lifecycle guards.
57
+
58
+ `checkoutKey(pi, ctx)` uses the canonical working directory for a verified non-Git workspace. A Git timeout or an uncertain repository lookup blocks writes. Failed lookups are not cached; the next call tries again.
59
+
60
+ `guard(name, refresh)` installs an awaited recovery check before writes. The callback receives the exact canonical checkout set after target resolution and before any member is admitted. `reserve` passes its one checkout to the same checks. If recovery fails, no member is admitted. `reserve(owner, checkout)` returns a release function only when no admitted writer or Main write is active.
61
+
62
+ `restore(owner, checkout)` restores durable ownership. Use `complete(owner)` only after verified terminal proof or a durable, explicit human waiver in the owning workflow. It releases ownership and rejects later restoration or reservation of that owner, including from a stale recovery scan. Use `release(owner)` to release a temporary reservation without marking its owner complete. A missing record is not terminal proof.
56
63
 
57
64
  `registerCheckoutAdmission(pi, directCanWrite)` keeps the direct-subagent policy: Main writes can overlap, but direct writers must wait for them and exclude other writes. A returned hold function keeps a direct request admitted beyond its tool result. Consumers must restore durable command ownership before allowing writes after restart. These mechanisms do not intercept external processes or provide a sandbox.
58
65
 
66
+ Coordinators with `supportsDirectJournal: true` provide `admittedCheckouts(toolCallId)` and `restoreSet(owner, checkouts)`. The first returns the exact admitted set, not a new path lookup. The second restores every member under one durable identity. `complete(owner)` clears that set and rejects stale restoration. These calls do not save state.
67
+
68
+ `beginReplacement()` refuses replacement while a direct writer is in admission or preflight. Otherwise it synchronously blocks new direct writes until `session_start`. If a later handler cancels replacement, reload before direct writing. The caller must first check durable holds and the exact fork path.
69
+
70
+ The caller must save admission before allocation and save release before clearing holds. Check the capability and required methods when another installed package can supply an older coordinator.
71
+
59
72
  An optional third argument, `directCheckouts(input, ctx)`, returns additional canonical checkout paths for a direct request. Admission reserves the current checkout and the complete selected set together. A conflict in one member blocks the request without a partial reservation. The caller validates repository selection; the hold function releases the set only after caller-proved worker termination.
60
73
 
61
74
  ### Path locks
62
75
 
63
- `withWorktreeLock(checkout, operation)` locks a path while the operation runs. Acquisition, heartbeat updates, and release use synchronous filesystem calls. Slow storage can block the event loop. The operation can remain asynchronous. A heartbeat cannot remain in flight when the helper releases the lock.
76
+ `withWorktreeLock(checkout, operation)` resolves an existing file or directory to its real path. It holds a native kernel lock on `<real-path>.lock` until the operation finishes. A competing call fails immediately with `ELOCKED`, the lock-contention error code. A paused process keeps its lock; there is no heartbeat or stale takeover. Existing caller lock order is unchanged.
77
+
78
+ ```mermaid
79
+ flowchart LR
80
+ A[Open persistent lock file] --> B[Short native command acquires lock]
81
+ B --> C[Parent keeps open descriptor during operation]
82
+ C --> D[Close descriptor to release lock]
83
+ ```
84
+
85
+ A descriptor is a process handle for an open file. The native command inherits the parent's descriptor, so its exit does not release the parent's lock.
86
+
87
+ The callback receives this descriptor as its argument. Do not close or unlock it. Pass it through a local child's `stdio` array when that child must retain the lock if its parent dies. An inherited child copy can keep the lock held after the callback returns.
88
+
89
+ Each acquisition starts one short process. Acquisition and close use synchronous calls; slow storage or process startup can block the event loop. The native command has a 5-second timeout and an 8192-byte output limit. Callers own any acquisition retries; the helper never repeats the operation.
90
+
91
+ On macOS, `/usr/bin/lockf` must support descriptor-only mode. The command uses `-t`, which sets the wait timeout, with zero to refuse contention. On Linux, install util-linux `flock`; `-n` disables waiting and `-E` sets contention status 75. Other platforms, missing commands, and unsupported command syntax fail without a lease fallback. The oldest supported macOS release is not established; verify descriptor-only mode on each deployment.
92
+
93
+ The regular lock file persists after release and checkout removal. Never delete or replace it during normal use: another process could then lock a different file at the same path. Symbolic links and non-regular lock objects are refused.
94
+
95
+ A legacy lock directory returns `ELOCKED`. Stop all old holders before manual removal of an abandoned directory; age alone is not proof. Old heartbeat clients and directory-lock scripts must migrate together. They cannot share ownership with the new protocol.
64
96
 
65
- If a heartbeat detects lost ownership, the call rejects after the operation finishes and does not release the changed lock. If the operation also fails, an `AggregateError` contains both errors. Acquisition, operation, and release errors remain visible. The helper does not stop or undo the operation.
97
+ Acquisition, operation, and close errors remain visible. If an operation or acquisition fails and close also fails, an `AggregateError` contains both errors. Process death releases the lock after all inherited descriptor copies close. Descriptor inheritance is not automatic: a Git child or a dispatched Herdr request can continue after the parent dies. The helper does not stop or undo that work. Inspect state before a retry.
66
98
 
67
- Heartbeats do not prove continuous ownership or detect all external lock removal or replacement between checks. Do not remove active lock files. Long event-loop pauses can delay heartbeats and permit stale-lock recovery by another process. A lock error does not prove that the operation had no effect. Inspect state before a retry.
99
+ These advisory locks exclude only cooperating processes on supported local filesystems. Network filesystem behavior is not verified. They are not a global checkout write barrier and do not share the separate `pi-pr` lock namespace.
68
100
 
69
101
  ### `startPiAgent`
70
102
 
@@ -26,6 +26,7 @@ interface AdmissionHost {
26
26
  }) => void): unknown;
27
27
  on(event: "session_start" | "session_shutdown", handler: () => void): unknown;
28
28
  }
29
+ export declare function checkoutToolCanWrite(toolName: string, input: unknown, directCanWrite: (input: unknown) => boolean): boolean;
29
30
  export declare function checkoutKey(pi: Pick<AdmissionHost, "exec">, ctx: {
30
31
  cwd: string;
31
32
  }): Promise<string>;
@@ -38,12 +39,17 @@ declare function createAdmission(): {
38
39
  install: (host: AdmissionHost) => void;
39
40
  hold: (toolCallId: string) => () => void;
40
41
  supportsCheckoutSets: true;
42
+ supportsDirectJournal: true;
43
+ beginReplacement: () => boolean;
44
+ admittedCheckouts: (toolCallId: string) => readonly string[];
45
+ restoreSet: (owner: string, keys: readonly string[]) => void;
41
46
  classifyDirect: (classify: (input: unknown) => boolean, select?: ((input: unknown, ctx: {
42
47
  cwd: string;
43
48
  }) => Promise<readonly string[]>) | undefined) => void;
44
- guard: (name: string, refresh: () => Promise<void>) => void;
49
+ guard: (name: string, refresh: (checkouts: readonly string[]) => Promise<void>) => void;
45
50
  restore: (owner: string, checkout: string) => void;
46
51
  release: (owner: string) => void;
52
+ complete: (owner: string) => void;
47
53
  reserve(owner: string, checkout: string): Promise<() => void>;
48
54
  };
49
55
  export type CheckoutAdmission = ReturnType<typeof createAdmission>;
package/dist/admission.js CHANGED
@@ -5,11 +5,26 @@ const CHANNEL = "pi-herdr:checkout-admission";
5
5
  const MAIN_NON_WRITING_TOOLS = new Set([
6
6
  "read", "grep", "find", "ffgrep", "fffind", "ls", "codegraph_explore", "subagent_status", "codemode",
7
7
  ]);
8
+ export function checkoutToolCanWrite(toolName, input, directCanWrite) {
9
+ return toolName === "delegate_task" ? directCanWrite(input) : !MAIN_NON_WRITING_TOOLS.has(toolName);
10
+ }
8
11
  export async function checkoutKey(pi, ctx) {
9
12
  const cwd = await realpath(ctx.cwd);
10
13
  const result = await pi.exec("git", ["rev-parse", "--show-toplevel"], { cwd, timeout: 5_000 });
11
- if (result.code !== 0 || result.killed)
12
- return cwd;
14
+ if (result.killed)
15
+ throw new Error("Git checkout resolution was terminated during delegation admission; writes are blocked.");
16
+ if (result.code !== 0) {
17
+ // Exit 128 also covers unsafe ownership and invalid configuration. Git runs
18
+ // shell aliases at the root, with either .git or an explicit GIT_DIR.
19
+ // Relax discovery restrictions only for this absence check, never for admission.
20
+ if (result.code === 128) {
21
+ const absent = await pi.exec("git", ["-c", "safe.directory=*", "-c", "safe.bareRepository=all",
22
+ "-c", 'alias.pi-admission-non-repository=!test -z "${GIT_DIR+x}" && test ! -e .git && test ! -L .git', "pi-admission-non-repository"], { cwd, timeout: 5_000 });
23
+ if (absent.code === 0 && !absent.killed)
24
+ return cwd;
25
+ }
26
+ throw new Error(`Git checkout resolution failed (exit ${result.code}) during delegation admission; writes are blocked.`);
27
+ }
13
28
  const root = result.stdout.replace(/\r?\n$/, "");
14
29
  if (!root || /[\r\n\0]/.test(root))
15
30
  throw new Error("Git returned a malformed checkout root during delegation admission.");
@@ -25,10 +40,12 @@ function createAdmission() {
25
40
  let directCheckouts;
26
41
  const guards = new Map();
27
42
  const durable = new Map();
43
+ const completed = new Set();
28
44
  const events = new WeakMap();
29
45
  const heldCalls = new Set();
30
46
  const ownerByCheckout = new Map();
31
47
  const calls = new Map();
48
+ let replacing = false;
32
49
  // One Git lookup per working directory per session; a failed lookup is retried.
33
50
  const checkouts = new Map();
34
51
  const lookup = (host, ctx) => {
@@ -50,18 +67,14 @@ function createAdmission() {
50
67
  if (ownerByCheckout.get(key) === toolCallId)
51
68
  ownerByCheckout.delete(key);
52
69
  };
53
- const refresh = async () => { for (const guard of guards.values())
54
- await guard(); };
70
+ const refresh = async (keys) => { for (const guard of guards.values())
71
+ await guard(keys); };
55
72
  const admit = async (event, ctx, host) => {
56
73
  const direct = event.toolName === "delegate_task";
57
- if (event.toolName === "background_command" || (direct ? !directCanWrite(event.input) : MAIN_NON_WRITING_TOOLS.has(event.toolName)))
74
+ if (event.toolName === "background_command" || !checkoutToolCanWrite(event.toolName, event.input, directCanWrite))
58
75
  return;
59
- try {
60
- await refresh();
61
- }
62
- catch {
63
- return { block: true, reason: "Command ownership recovery failed; writes are blocked. Inspect /commands." };
64
- }
76
+ if (direct && replacing)
77
+ return { block: true, reason: "Session replacement is pending; direct writes are blocked. If another extension cancelled replacement, reload before delegation." };
65
78
  const call = { direct };
66
79
  calls.set(event.toolCallId, call);
67
80
  let keys;
@@ -72,10 +85,17 @@ function createAdmission() {
72
85
  release(event.toolCallId);
73
86
  throw error;
74
87
  }
88
+ try {
89
+ await refresh(keys);
90
+ }
91
+ catch {
92
+ release(event.toolCallId);
93
+ return { block: true, reason: "Command ownership recovery failed; writes are blocked. Inspect /commands." };
94
+ }
75
95
  if (calls.get(event.toolCallId) !== call) {
76
96
  return { block: true, reason: `Call ${event.toolCallId} already settled; use mode: isolated to keep Main free.` };
77
97
  }
78
- const owner = keys.map((key) => ownerByCheckout.get(key) ?? [...durable].find(([, checkout]) => checkout === key)?.[0]).find(Boolean);
98
+ const owner = keys.map((key) => ownerByCheckout.get(key) ?? [...durable].find(([, checkouts]) => checkouts.includes(key))?.[0]).find(Boolean);
79
99
  const main = direct ? [...calls].find(([, active]) => !active.direct && active.keys?.some((key) => keys.includes(key)))?.[0] : undefined;
80
100
  if (owner || main) {
81
101
  release(event.toolCallId);
@@ -100,7 +120,7 @@ function createAdmission() {
100
120
  });
101
121
  host.on("tool_result", (event) => release(event.toolCallId));
102
122
  host.on("tool_execution_end", (event) => release(event.toolCallId));
103
- host.on("session_start", () => checkouts.clear());
123
+ host.on("session_start", () => { checkouts.clear(); replacing = false; });
104
124
  host.on("session_shutdown", () => {
105
125
  checkouts.clear();
106
126
  for (const toolCallId of calls.keys())
@@ -116,19 +136,37 @@ function createAdmission() {
116
136
  return () => { heldCalls.delete(toolCallId); release(toolCallId); };
117
137
  };
118
138
  return {
119
- install, hold, supportsCheckoutSets: true,
139
+ install, hold, supportsCheckoutSets: true, supportsDirectJournal: true,
140
+ beginReplacement: () => {
141
+ if ([...calls.values()].some(({ direct }) => direct))
142
+ return false;
143
+ replacing = true;
144
+ return true;
145
+ },
146
+ admittedCheckouts: (toolCallId) => {
147
+ const call = calls.get(toolCallId);
148
+ if (!call?.direct || !call.keys?.length)
149
+ throw new Error(`Direct call ${toolCallId} was not admitted as a checkout writer; delegate again.`);
150
+ return [...call.keys];
151
+ },
152
+ restoreSet: (owner, keys) => { if (!completed.has(owner))
153
+ durable.set(owner, [...keys]); },
120
154
  classifyDirect: (classify, select) => { directCanWrite = classify; directCheckouts = select; },
121
155
  guard: (name, refresh) => { guards.set(name, refresh); },
122
- restore: (owner, checkout) => { durable.set(owner, checkout); },
156
+ restore: (owner, checkout) => { if (!completed.has(owner))
157
+ durable.set(owner, [checkout]); },
123
158
  release: (owner) => { durable.delete(owner); },
159
+ complete: (owner) => { completed.add(owner); durable.delete(owner); },
124
160
  async reserve(owner, checkout) {
125
- await refresh();
126
- const conflict = [...durable].find(([, key]) => key === checkout)?.[0]
161
+ await refresh([checkout]);
162
+ if (completed.has(owner))
163
+ throw new Error("Completed checkout owners cannot reserve again.");
164
+ const conflict = [...durable].find(([, keys]) => keys.includes(checkout))?.[0]
127
165
  ?? ownerByCheckout.get(checkout)
128
166
  ?? [...calls].find(([, call]) => call.keys?.includes(checkout))?.[0];
129
167
  if (conflict)
130
168
  throw new Error(`Checkout ${checkout} has an active writer (${conflict}); wait until it stops.`);
131
- durable.set(owner, checkout);
169
+ durable.set(owner, [checkout]);
132
170
  return () => { durable.delete(owner); };
133
171
  },
134
172
  };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { requestHerdr, HerdrRequestError } from "./socket.js";
2
- export { checkoutAdmission, checkoutKey, registerCheckoutAdmission, type CheckoutAdmission } from "./admission.js";
2
+ export { checkoutAdmission, checkoutKey, checkoutToolCanWrite, registerCheckoutAdmission, type CheckoutAdmission } from "./admission.js";
3
3
  export interface HerdrExecResult {
4
4
  code: number;
5
5
  stdout: string;
@@ -27,5 +27,5 @@ export declare function startPiAgent<Options>(client: Pick<HerdrClient<Options>,
27
27
  export declare function createHerdrClient<Options>(execute: HerdrExecutor<Options>): HerdrClient<Options>;
28
28
  export declare function herdrCommandFailure(args: readonly string[], result: HerdrExecResult): string;
29
29
  export declare function hasHerdrErrorCode(result: Pick<HerdrExecResult, "stdout" | "stderr">, expected: string): boolean;
30
- /** Lock a Herdr worktree checkout path while mutating it via the Herdr CLI. */
31
- export declare function withWorktreeLock<T>(checkout: string, operation: () => Promise<T>): Promise<T>;
30
+ /** Hold a native path lock until the operation settles. */
31
+ export declare function withWorktreeLock<T>(checkout: string, operation: (descriptor: number) => Promise<T>): Promise<T>;
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { lockSync } from "proper-lockfile";
1
+ import { withPathLock } from "./path-lock.js";
2
2
  export { requestHerdr, HerdrRequestError } from "./socket.js";
3
- export { checkoutAdmission, checkoutKey, registerCheckoutAdmission } from "./admission.js";
3
+ export { checkoutAdmission, checkoutKey, checkoutToolCanWrite, registerCheckoutAdmission } from "./admission.js";
4
4
  const delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
5
5
  const MAX_AGENT_START_ATTEMPTS = 5;
6
6
  const AGENT_START_RETRY_DELAY_MS = 250;
@@ -137,27 +137,9 @@ export function hasHerdrErrorCode(result, expected) {
137
137
  }
138
138
  });
139
139
  }
140
- /** Lock a Herdr worktree checkout path while mutating it via the Herdr CLI. */
140
+ /** Hold a native path lock until the operation settles. */
141
141
  export async function withWorktreeLock(checkout, operation) {
142
- let compromised;
143
- // Synchronous heartbeats cannot remain in flight when release removes the lock.
144
- const release = lockSync(checkout, { onCompromised: (error) => { compromised = error; } });
145
- try {
146
- const result = await operation();
147
- if (compromised)
148
- throw compromised;
149
- return result;
150
- }
151
- catch (error) {
152
- if (compromised && error !== compromised)
153
- throw new AggregateError([error, compromised], "Operation failed and lock ownership was lost.");
154
- throw error;
155
- }
156
- finally {
157
- // A compromised lock is no longer ours to release.
158
- if (!compromised)
159
- release();
160
- }
142
+ return await withPathLock(checkout, operation);
161
143
  }
162
144
  function herdrCommandName(args) {
163
145
  return ["herdr", ...args.slice(0, 2)].join(" ");
@@ -0,0 +1,2 @@
1
+ /** Internal descriptor access lets local commands retain the lock if their parent exits. */
2
+ export declare function withPathLock<T>(target: string, operation: (descriptor: number) => Promise<T>): Promise<T>;
@@ -0,0 +1,53 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { closeSync, constants, fstatSync, openSync, realpathSync } from "node:fs";
3
+ /** Internal descriptor access lets local commands retain the lock if their parent exits. */
4
+ export async function withPathLock(target, operation) {
5
+ const command = process.platform === "darwin" ? "/usr/bin/lockf" : process.platform === "linux" ? "flock" : undefined;
6
+ if (!command)
7
+ throw new Error(`Path locks require macOS lockf or Linux util-linux flock; unsupported platform: ${process.platform}`);
8
+ const path = `${realpathSync(target)}.lock`;
9
+ let descriptor;
10
+ try {
11
+ descriptor = openSync(path, constants.O_RDWR | constants.O_CREAT | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);
12
+ }
13
+ catch (error) {
14
+ if (error.code === "EISDIR") {
15
+ throw Object.assign(new Error(`Legacy lock directory blocks ${path}; stop old holders before manual removal.`, { cause: error }), { code: "ELOCKED" });
16
+ }
17
+ throw error;
18
+ }
19
+ let failed = false;
20
+ let failure;
21
+ try {
22
+ if (!fstatSync(descriptor).isFile())
23
+ throw new Error(`Path lock is not a regular file: ${path}`);
24
+ // -t sets the timeout; -n disables waiting; -E selects the contention exit code.
25
+ const args = process.platform === "darwin" ? ["-t", "0", "3"] : ["-n", "-E", "75", "3"];
26
+ const result = spawnSync(command, args, {
27
+ stdio: ["ignore", "ignore", "pipe", descriptor], encoding: "utf8", timeout: 5_000, maxBuffer: 8_192,
28
+ });
29
+ if (result.error)
30
+ throw Object.assign(new Error(`Cannot acquire path lock with ${command}: ${result.error.message}`, { cause: result.error }), { code: result.error.code });
31
+ if (result.status === 75)
32
+ throw Object.assign(new Error(`Lock file is already being held: ${path}`), { code: "ELOCKED" });
33
+ if (result.status !== 0)
34
+ throw new Error(`${command} descriptor lock failed (${result.signal ?? result.status}): ${result.stderr.trim()}`);
35
+ // The short child shares this open-file description. Its exit does not release our lock.
36
+ return await operation(descriptor);
37
+ }
38
+ catch (error) {
39
+ failed = true;
40
+ failure = error;
41
+ throw error;
42
+ }
43
+ finally {
44
+ try {
45
+ closeSync(descriptor);
46
+ }
47
+ catch (error) {
48
+ if (failed)
49
+ throw new AggregateError([failure, error], "Operation or acquisition failed and lock release failed.");
50
+ throw error;
51
+ }
52
+ }
53
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henryqw/pi-herdr",
3
- "version": "0.6.2",
3
+ "version": "0.7.0",
4
4
  "description": "Shared client for interacting with Herdr from Node.js tools and Pi packages.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -32,12 +32,6 @@
32
32
  "prepack": "npm run build",
33
33
  "pack:check": "npm pack --dry-run"
34
34
  },
35
- "devDependencies": {
36
- "@types/proper-lockfile": "^4.1.4"
37
- },
38
- "dependencies": {
39
- "proper-lockfile": "^4.1.2"
40
- },
41
35
  "repository": {
42
36
  "type": "git",
43
37
  "url": "git+https://github.com/HenryQW/pi-harness.git",