pi-better-harness 0.51.2 → 0.52.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.
Files changed (53) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +41 -0
  3. package/extensions/harness-instructions/AGENTS.md +4 -0
  4. package/extensions/settings/index.ts +39 -2
  5. package/extensions/settings/page.ts +2 -1
  6. package/extensions/shared-harness-settings.ts +2 -5
  7. package/extensions/task-context/work-ledger.ts +1 -4
  8. package/lib/cli.mjs +21 -0
  9. package/lib/install-settings.mjs +2 -2
  10. package/lib/instructions.d.mts +7 -0
  11. package/lib/instructions.mjs +121 -0
  12. package/node_modules/pi-better-background-tasks/package.json +1 -1
  13. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.gz +0 -0
  14. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.json +1 -1
  15. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.gz +0 -0
  16. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.json +1 -1
  17. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.gz +0 -0
  18. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.json +1 -1
  19. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.gz +0 -0
  20. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.json +1 -1
  21. package/node_modules/pi-better-background-tasks/src/shared-harness-settings.ts +2 -5
  22. package/node_modules/pi-better-background-tasks/src/shared-sandbox-diagnostics.ts +12 -16
  23. package/node_modules/pi-better-background-tasks/src/shared-ssh-core/index.ts +1 -1
  24. package/node_modules/pi-better-goal/package.json +1 -1
  25. package/node_modules/pi-better-goal/src/shared-harness-settings.ts +2 -5
  26. package/node_modules/pi-better-goal/src/workflow-gates.ts +43 -6
  27. package/node_modules/pi-better-sandbox/package.json +1 -1
  28. package/node_modules/pi-better-sandbox/shared-harness-settings.ts +2 -5
  29. package/node_modules/pi-better-sandbox/shared-sandbox-diagnostics.ts +12 -16
  30. package/node_modules/pi-better-ssh/README.md +1 -1
  31. package/node_modules/pi-better-ssh/package.json +1 -1
  32. package/node_modules/pi-better-ssh/src/shared-ssh-core/index.ts +1 -1
  33. package/node_modules/pi-better-subagents/catalog-preferences.ts +1 -5
  34. package/node_modules/pi-better-subagents/config.ts +1 -1
  35. package/node_modules/pi-better-subagents/extensions.mjs +1 -0
  36. package/node_modules/pi-better-subagents/finalization.ts +30 -28
  37. package/node_modules/pi-better-subagents/git-workspace.ts +48 -6
  38. package/node_modules/pi-better-subagents/index.ts +61 -26
  39. package/node_modules/pi-better-subagents/isolated-workspace.ts +6 -12
  40. package/node_modules/pi-better-subagents/package.json +1 -1
  41. package/node_modules/pi-better-subagents/registry.ts +8 -8
  42. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.gz +0 -0
  43. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.json +1 -1
  44. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.gz +0 -0
  45. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.json +1 -1
  46. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.gz +0 -0
  47. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.json +1 -1
  48. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.gz +0 -0
  49. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.json +1 -1
  50. package/node_modules/pi-better-subagents/shared-harness-settings.ts +2 -5
  51. package/node_modules/pi-better-subagents/shared-sandbox-diagnostics.ts +12 -16
  52. package/node_modules/pi-better-subagents/workspace-prepare-worker.mjs +11 -0
  53. package/package.json +9 -7
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.52.0] - 2026-11-23
4
+
5
+ ### Added
6
+
7
+ - Enable optional Harness instructions in `/harness-settings` and edit the prompt while the switch is on. The switch defaults to Off. The CLI can also enable, sync, or remove the Harness block in the global `APPEND_SYSTEM.md`. Pi loads the instructions at startup and preserves them across compaction.
8
+
9
+ ## [0.51.3] - 2026-11-22
10
+
11
+ ### Fixed
12
+
13
+ - Preserve Subagent results when dismissal overlaps completion. Prepare isolated Git workspaces without blocking the launch host, report shared Git index restrictions, and load the installed LiteLLM provider in isolated workers. (#302, #314, #381, #591)
14
+ - Limit live Goal settlement to scheduler records and resolve SSH control socket paths before checking their length. (#547, #554)
15
+ - Load settings locks in compiled Pi and bundle Subagents 0.37.1, Background Tasks 0.20.1, Goal 0.16.1, Sandbox 0.15.2, and SSH 0.1.7. Background Tasks and Subagents carry Server 0.7.1. (#556)
16
+
3
17
  ## [0.51.2] - 2026-11-22
4
18
 
5
19
  ### Changed
package/README.md CHANGED
@@ -261,6 +261,47 @@ prompt; in Instructions, it restores the prompt while preserving model/effort.
261
261
  A user Markdown override is archived when its prompt is reset. Saved defaults
262
262
  survive sessions and upgrades.
263
263
 
264
+ ### Harness instructions
265
+
266
+ Open `/harness-settings` and toggle **Harness instructions** from **Off** to
267
+ **On**. Choose **Instructions prompt → Edit** to edit the current Markdown.
268
+ Saving updates the Harness block and stores the text in the global Pi settings
269
+ under `piBetterHarness.instructionsPrompt`. Turning the switch off removes the
270
+ block. Turning it back on restores the saved text. Changes apply on the next
271
+ startup or explicit `/reload`.
272
+
273
+ The CLI manages the same switch. To enable it from the command line:
274
+
275
+ ```sh
276
+ npx pi-better-harness instructions enable
277
+ ```
278
+
279
+ By default, Harness copies its bundled `AGENTS.md` into a marked block in
280
+ `<agent-dir>/APPEND_SYSTEM.md`. It preserves text outside the markers,
281
+ including blocks owned by other extensions. To use your own Markdown, set
282
+ `piBetterHarness.instructionsFile` in the global Pi `settings.json` to an
283
+ absolute path or a path relative to the agent directory (normally
284
+ `~/.pi/agent`), then run `instructions sync`. A prompt saved in the editor takes precedence
285
+ over this file. Remove `instructionsPrompt` and sync to use the file again.
286
+
287
+ | Command | Effect |
288
+ | --- | --- |
289
+ | `npx pi-better-harness instructions enable` | Create or refresh the block. |
290
+ | `npx pi-better-harness instructions sync` | Refresh an existing block after editing the source or changing its path. |
291
+ | `npx pi-better-harness instructions disable` | Remove the block and preserve the surrounding file. |
292
+
293
+ A global Harness CLI install refreshes an enabled block. A global CLI uninstall
294
+ removes it. If you remove the package directly with Pi, disable the block first.
295
+ Setting `instructionsFile` to `false` removes the block on the next sync.
296
+ The CLI stops on missing or duplicate delimiters in an existing block.
297
+ Keep other extensions' content outside the Harness markers.
298
+
299
+ Pi loads the file as a system prompt addendum. Ordinary turns and compaction
300
+ retain the loaded text. A new Pi process or an explicit `/reload` reads the
301
+ current file. Pi gives a trusted project's `.pi/APPEND_SYSTEM.md` precedence
302
+ over the global file. Explicit `--append-system-prompt` sources also take
303
+ precedence over automatic discovery.
304
+
264
305
  Next-prompt inference is deferred pending safe public auth/header resolution in
265
306
  Pi's SDK. It is not loaded by the bundle, has no toggle or preference store in
266
307
  this version, and makes no auxiliary model requests. The integration blocker is
@@ -0,0 +1,4 @@
1
+ # Harness defaults
2
+
3
+ Follow the current project's instructions when they give more specific guidance.
4
+ When reporting work tracked by Harness, distinguish completed results from work still running or awaiting verification.
@@ -1,4 +1,6 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
1
+ import { getAgentDir, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { currentInstructions, manageInstructions, validateInstructionsPrompt } from "../../lib/instructions.mjs";
3
+ import { readHarnessSetting, updateHarnessSetting } from "../shared-harness-settings.ts";
2
4
  import { chooseHarnessSetting } from "./page.ts";
3
5
  import { createSettingsRegistry } from "./registry.ts";
4
6
  import { changeCallbackSetting, getCallbackSettings, saveCallbackDefault } from "pi-better-background-tasks/src/shared-callback-batcher.ts";
@@ -31,17 +33,52 @@ export default function harnessSettingsExtension(pi: ExtensionAPI): void {
31
33
  };
32
34
  while (true) {
33
35
  const links = registry.list();
36
+ const agentDir = getAgentDir();
37
+ let prompt: string | undefined;
38
+ let readError: Error | undefined;
39
+ try { prompt = currentInstructions(agentDir); }
40
+ catch (error) { readError = error instanceof Error ? error : new Error(String(error)); }
41
+ const state = readError ? "Unavailable" : prompt === undefined ? "Off" : "On";
34
42
  try {
35
43
  selected = await chooseHarnessSetting(ctx, links, selected, {
36
44
  get: readSettings,
37
45
  change: mode => changeCallbackSetting(pi, ctx, mode),
38
46
  save: () => saveCallbackDefault(readSettings().mode),
39
- }, registry.controls(), view);
47
+ }, registry.controls(), view, [
48
+ { id: "instructions:toggle", label: "Harness instructions", currentValue: state, values: [state],
49
+ description: "Toggle the global APPEND_SYSTEM.md block. Applies on startup or /reload." },
50
+ ...(prompt === undefined ? [] : [{ id: "instructions:edit", label: "Instructions prompt", currentValue: "Edit",
51
+ values: ["Edit"], description: "Edit the Markdown included in the Harness block." }]),
52
+ ]);
40
53
  } catch (error) {
41
54
  ctx.ui.notify(`Settings unavailable: ${error instanceof Error ? error.message : String(error)}`, "error");
42
55
  return;
43
56
  }
44
57
  if (!selected) return;
58
+ if (selected.startsWith("instructions:")) {
59
+ try {
60
+ if (readError) throw readError;
61
+ if (selected === "instructions:edit" && prompt !== undefined) {
62
+ const edited = await ctx.ui.editor("Harness instructions", prompt);
63
+ if (edited === undefined) continue;
64
+ const next = validateInstructionsPrompt(edited);
65
+ manageInstructions("sync", agentDir, {
66
+ previous: prompt,
67
+ saveSource: () => updateHarnessSetting("instructionsPrompt", () => next),
68
+ });
69
+ } else if (prompt === undefined) {
70
+ if (readHarnessSetting("instructionsFile") === false) {
71
+ updateHarnessSetting("instructionsFile", current => current === false ? undefined : current);
72
+ }
73
+ manageInstructions("enable", agentDir);
74
+ } else {
75
+ manageInstructions("disable", agentDir);
76
+ }
77
+ } catch (error) {
78
+ ctx.ui.notify(`Harness instructions: ${error instanceof Error ? error.message : String(error)}`, "error");
79
+ }
80
+ continue;
81
+ }
45
82
  const link = links.find(item => `link:${item.id}` === selected);
46
83
  if (!link) continue;
47
84
  try { await link.open(ctx); }
@@ -58,7 +58,7 @@ function presentLink(link: SettingsLink): SettingItem {
58
58
  };
59
59
  }
60
60
 
61
- export async function chooseHarnessSetting(ctx: ExtensionCommandContext, links: SettingsLink[], selected?: string, callbacks?: CallbackSettingsControl, controls: SettingsControl[] = [], navigatorView?: SettingsControl): Promise<string | undefined> {
61
+ export async function chooseHarnessSetting(ctx: ExtensionCommandContext, links: SettingsLink[], selected?: string, callbacks?: CallbackSettingsControl, controls: SettingsControl[] = [], navigatorView?: SettingsControl, actions: SettingItem[] = []): Promise<string | undefined> {
62
62
  return ctx.ui.custom((tui, theme: Theme, _kb, done: (id?: string) => void) => {
63
63
  const currentCallback = callbacks?.get();
64
64
  let callbackMode = currentCallback?.mode ?? "hold";
@@ -75,6 +75,7 @@ export async function chooseHarnessSetting(ctx: ExtensionCommandContext, links:
75
75
  ...(callbackSetting ? [callbackSetting] : []),
76
76
  ...entries.map(({ item }) => item),
77
77
  ...links.map(presentLink),
78
+ ...actions,
78
79
  ].sort((a, b) => (position.get(a.id) ?? position.size) - (position.get(b.id) ?? position.size));
79
80
  const feedback = new Text("", 2, 0);
80
81
  let changing = false;
@@ -1,14 +1,11 @@
1
1
  // Generated from packages/harness-settings/index.ts. Do not edit directly.
2
2
  import { existsSync, lstatSync, realpathSync, readFileSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { randomUUID } from "node:crypto";
4
- import { createRequire } from "node:module";
5
4
  import { join } from "node:path";
6
5
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
+ // A static import lets the compiled Pi loader resolve dependencies of the settings lock.
7
+ import lockfile from "proper-lockfile";
7
8
 
8
- // Match Pi's settings lock without depending on a private SDK import.
9
- const lockfile = createRequire(import.meta.url)("proper-lockfile") as {
10
- lockSync(path: string, options: { realpath: boolean }): () => void;
11
- };
12
9
  const NAMESPACE = "piBetterHarness";
13
10
  export interface HarnessSettingsSeams { agentDir?: () => string }
14
11
 
@@ -3,13 +3,10 @@ import {
3
3
  closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync,
4
4
  renameSync, unlinkSync, writeSync,
5
5
  } from "node:fs";
6
- import { createRequire } from "node:module";
6
+ import lockfile from "proper-lockfile";
7
7
  import { basename, dirname, join, resolve } from "node:path";
8
8
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
9
9
 
10
- const lockfile = createRequire(import.meta.url)("proper-lockfile") as {
11
- lockSync(path: string, options: { realpath: boolean }): () => void;
12
- };
13
10
 
14
11
  export const WORK_LEDGER_SCHEMA = 1 as const;
15
12
  export const WORK_LEDGER_STATUSES = ["active", "completed", "cancelled"] as const;
package/lib/cli.mjs CHANGED
@@ -3,6 +3,7 @@ import { readFileSync } from "node:fs";
3
3
  import { dirname, resolve } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { configureHarnessResources, preflightHarnessInstall } from "./install-settings.mjs";
6
+ import { manageInstructions } from "./instructions.mjs";
6
7
 
7
8
  const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
8
9
  const { version } = JSON.parse(readFileSync(resolve(packageRoot, "package.json"), "utf8"));
@@ -20,8 +21,10 @@ export const componentPackages = [
20
21
  ];
21
22
 
22
23
  const usage = `Usage: pi-better-harness <install|uninstall> [--local]
24
+ pi-better-harness instructions <enable|sync|disable>
23
25
 
24
26
  Commands:
27
+ instructions Manage the Harness block in the global APPEND_SYSTEM.md
25
28
  install Configure all Pi Better Harness component packages
26
29
  uninstall Remove all Pi Better Harness component packages
27
30
 
@@ -55,6 +58,16 @@ export function run(argv, options = {}) {
55
58
  const local = argv.includes("--local") || argv.includes("-l");
56
59
  const positional = argv.filter((arg) => !["--local", "-l"].includes(arg));
57
60
  const command = positional[0];
61
+ if (command === "instructions" && !local && positional.length === 2 && ["enable", "sync", "disable"].includes(positional[1])) {
62
+ try {
63
+ const changed = manageInstructions(positional[1], options.agentDir);
64
+ stdout.write(changed ? "Updated the Harness block in APPEND_SYSTEM.md.\n" : "No change to APPEND_SYSTEM.md.\n");
65
+ return 0;
66
+ } catch (error) {
67
+ stderr.write(`Could not update Harness instructions: ${error.message}\n`);
68
+ return 1;
69
+ }
70
+ }
58
71
  if (!command || positional.length !== 1 || !["install", "uninstall"].includes(command)) {
59
72
  stderr.write(`${usage}\n`);
60
73
  return 2;
@@ -113,5 +126,13 @@ export function run(argv, options = {}) {
113
126
  return 1;
114
127
  }
115
128
  }
129
+ if (!local) {
130
+ try {
131
+ manageInstructions(command === "install" ? "sync" : "disable", options.agentDir);
132
+ } catch (error) {
133
+ stderr.write(`Package operation completed, but the Harness instructions could not be updated: ${error.message}\n`);
134
+ return 1;
135
+ }
136
+ }
116
137
  return 0;
117
138
  }
@@ -85,7 +85,7 @@ function readSettings(path, { allowMissing = false } = {}) {
85
85
  return parseSettings(text, path);
86
86
  }
87
87
 
88
- function writeDestination(path) {
88
+ export function writeDestination(path) {
89
89
  let stat;
90
90
  try {
91
91
  stat = lstatSync(path);
@@ -104,7 +104,7 @@ function writeDestination(path) {
104
104
  }
105
105
  }
106
106
 
107
- function acquire(path) {
107
+ export function acquire(path) {
108
108
  for (let attempt = 0; attempt < 10; attempt++) {
109
109
  try {
110
110
  return lockfile.lockSync(path, { realpath: false });
@@ -0,0 +1,7 @@
1
+ export function currentInstructions(agentDir: string): string | undefined;
2
+ export function validateInstructionsPrompt(prompt: string): string;
3
+ export function manageInstructions(action: "enable" | "sync" | "disable", agentDir?: string): boolean;
4
+ export function manageInstructions(action: "sync", agentDir: string, edit: {
5
+ previous: string;
6
+ saveSource(): void;
7
+ }): boolean;
@@ -0,0 +1,121 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { chmodSync, existsSync, linkSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { acquire, writeDestination } from "./install-settings.mjs";
7
+
8
+ const begin = "<!-- pi-better-harness:instructions:begin -->";
9
+ const end = "<!-- pi-better-harness:instructions:end -->";
10
+ const bundled = fileURLToPath(new URL("../extensions/harness-instructions/AGENTS.md", import.meta.url));
11
+
12
+ function sourceText(agentDir, target) {
13
+ const settingsPath = join(agentDir, "settings.json");
14
+ const settings = existsSync(settingsPath) ? JSON.parse(readFileSync(settingsPath, "utf8")) : {};
15
+ const source = settings.piBetterHarness?.instructionsFile;
16
+ if (source === false) return null;
17
+ const prompt = settings.piBetterHarness?.instructionsPrompt;
18
+ if (typeof prompt === "string") return validateInstructionsPrompt(prompt);
19
+ if (source !== undefined && (typeof source !== "string" || !source.trim())) {
20
+ throw new Error("piBetterHarness.instructionsFile must be a file path or false.");
21
+ }
22
+ const path = source === undefined ? bundled : resolve(agentDir, source);
23
+ if (resolve(path) === resolve(target) || realpathSync(path) === target) {
24
+ throw new Error("The instructions source must be separate from APPEND_SYSTEM.md.");
25
+ }
26
+ return validateInstructionsPrompt(readFileSync(path, "utf8"));
27
+ }
28
+
29
+ export function validateInstructionsPrompt(prompt) {
30
+ const text = prompt.trim();
31
+ if (text.includes(begin) || text.includes(end)) throw new Error("Instructions contain reserved block markers.");
32
+ return text;
33
+ }
34
+
35
+ function blockRange(text) {
36
+ const start = text.indexOf(begin);
37
+ const finish = text.indexOf(end);
38
+ if (start === -1 && finish === -1) return undefined;
39
+ const lineStart = i => i === 0 || text[i - 1] === "\n";
40
+ const lineEnding = i => text.slice(i).match(/^(?:\r\n|\n|$)/)?.[0];
41
+ const after = finish + end.length;
42
+ if (start < 0 || finish < start || start !== text.lastIndexOf(begin) || finish !== text.lastIndexOf(end)
43
+ || !lineStart(start) || !lineStart(finish) || !lineEnding(start + begin.length) || lineEnding(after) === undefined) {
44
+ throw new Error("Ambiguous Harness block markers in APPEND_SYSTEM.md. Repair the markers before syncing.");
45
+ }
46
+ return [start, after + lineEnding(after).length];
47
+ }
48
+
49
+ function readTarget(path) {
50
+ try {
51
+ if (!statSync(path).isFile()) throw new Error(`Expected a regular file at ${path}`);
52
+ return readFileSync(path);
53
+ }
54
+ catch (error) { if (error.code === "ENOENT") return undefined; throw error; }
55
+ }
56
+
57
+ function blockPrompt(text, range) {
58
+ if (!range) return undefined;
59
+ return text.slice(range[0] + begin.length, text.indexOf(end)).trim().replace(/\r\n/g, "\n");
60
+ }
61
+
62
+ // Return undefined for Off. An enabled, empty prompt still has both markers.
63
+ export function currentInstructions(agentDir) {
64
+ const path = join(agentDir, "APPEND_SYSTEM.md");
65
+ const text = readTarget(writeDestination(path))?.toString("utf8").replace(/^\uFEFF/, "") ?? "";
66
+ return blockPrompt(text, blockRange(text));
67
+ }
68
+
69
+ // The marker pair is the opt-in. Only enable may create it. Sync always
70
+ // rereads the shared file under the lock, including changes by other tools.
71
+ export function manageInstructions(action, agentDir = process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent"), edit) {
72
+ const path = join(agentDir, "APPEND_SYSTEM.md");
73
+ if (action === "enable") mkdirSync(agentDir, { recursive: true });
74
+ else if (!lstatSync(path, { throwIfNoEntry: false })) {
75
+ if (edit) throw new Error("Harness instructions were disabled while editing.");
76
+ return false;
77
+ }
78
+ const target = writeDestination(path);
79
+ const release = acquire(target);
80
+ let pending;
81
+ try {
82
+ const original = readTarget(target);
83
+ const raw = original?.toString("utf8") ?? "";
84
+ if (original && !Buffer.from(raw).equals(original)) throw new Error(`Invalid UTF-8 in ${path}`);
85
+ const bom = raw.startsWith("\uFEFF") ? "\uFEFF" : "";
86
+ const text = raw.slice(bom.length);
87
+ const range = blockRange(text);
88
+ if (edit) {
89
+ if (blockPrompt(text, range) !== edit.previous) {
90
+ throw new Error("Harness instructions changed. Reopen the editor to use the latest prompt.");
91
+ }
92
+ // Save the source under the block lock so another Harness editor cannot
93
+ // slip between the comparison and the sync. A failed sync is retryable.
94
+ edit.saveSource();
95
+ }
96
+ if (!range && action !== "enable") return false;
97
+ const content = action === "disable" ? null : sourceText(agentDir, target);
98
+ if (content === null && action === "enable") throw new Error("Set instructionsFile to a path or remove the false setting before enabling.");
99
+ const eol = text.match(/\r?\n/)?.[0] ?? "\n";
100
+ const block = content === null ? "" : [begin, content.replace(/\r?\n/g, eol), end, ""].join(eol);
101
+ const [start, finish] = range ?? [0, 0];
102
+ const updated = bom + text.slice(0, start) + block + text.slice(finish);
103
+ if (updated === raw) return false;
104
+
105
+ pending = join(dirname(target), `.harness-instructions-${randomUUID()}.tmp`);
106
+ writeFileSync(pending, updated, { flag: "wx", mode: 0o600 });
107
+ if (original) {
108
+ chmodSync(pending, statSync(target).mode & 0o777);
109
+ if (writeDestination(path) !== target || !readTarget(target)?.equals(original)) {
110
+ throw new Error(`${path} changed while updating. Retry with the latest contents.`);
111
+ }
112
+ renameSync(pending, target);
113
+ } else {
114
+ // A non-cooperating writer may create the file while we hold our lock.
115
+ linkSync(pending, target);
116
+ }
117
+ return true;
118
+ } finally {
119
+ try { if (pending) rmSync(pending, { force: true }); } finally { release(); }
120
+ }
121
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-background-tasks",
3
- "version": "0.20.0",
3
+ "version": "0.20.1",
4
4
  "description": "Pi extension for durable background shell tasks, watchers, logs, and status inspection.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"5bd2e8ad130e4ee494caf40bb7129c5c9c1f787d486de66304ec9a7fa5fcb45e","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.0","contentId":"be4b4f5c05d403d84c98a0e34f407fbf65fb8f90e4e9d07930404c8f408665eb"},"sha256":"701e694c1047bcb5ef4652c6a05cfbee0798eb90a4a1e57574118c0b3df59d18"}
1
+ {"build":{"format":1,"sourceDigest":"89acf48f3b114cd55d76e9fa984b61e8418fa7238d738e9be21ec730d09b586d","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.1","contentId":"b2900559d4574e66ab874e702ddda6dffac370c4823615b7b971e51cccd9ec18"},"sha256":"11c82c8c7702d556ef2fcdd911e5504119508ce4c1c83630108424b1a1b4a06d"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"5bd2e8ad130e4ee494caf40bb7129c5c9c1f787d486de66304ec9a7fa5fcb45e","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.0","contentId":"3db710d017c57fdc43d18531bcd3144de15767b9021223fcc262d39107db55f6"},"sha256":"4f88a4c1bf931f4af0805f227f5d473336f796f74cacad45020bad79e3962232"}
1
+ {"build":{"format":1,"sourceDigest":"89acf48f3b114cd55d76e9fa984b61e8418fa7238d738e9be21ec730d09b586d","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.1","contentId":"78bffc25f9d84fdc0c74f5ab462e65060da6bac66d4ab42fb537245f53e45a1b"},"sha256":"0f1ce73bc7fff2008ee44ae922f248380a4a792b7eb293e0a1b67cd75df958b8"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"5bd2e8ad130e4ee494caf40bb7129c5c9c1f787d486de66304ec9a7fa5fcb45e","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.0","contentId":"93a5ca8f14a1667ff653465e5844577f34c3f48c79b1ac87daea77f52eba65e3"},"sha256":"24938d0af26379b8b068e09e1e92d3a4c87d88ea04894a676100a4ed19d90649"}
1
+ {"build":{"format":1,"sourceDigest":"89acf48f3b114cd55d76e9fa984b61e8418fa7238d738e9be21ec730d09b586d","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.1","contentId":"c5ba7a583694596c2eca942348565bfc012a82118c5ca5fbd05aacdb50f5ddce"},"sha256":"c91d50d2735fd6be00d5d846692a7fac831e223bec00df8dd97c1de19eb6bc7e"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"5bd2e8ad130e4ee494caf40bb7129c5c9c1f787d486de66304ec9a7fa5fcb45e","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.0","contentId":"71973a617087e76c008eb1eb0b6e50d4ec51f2e6617af432828dba6bdf4baaa1"},"sha256":"b5f918fde231b83e9351dc194ec10bd60f5d8641c452c4925f0bbbffa5eeebd9"}
1
+ {"build":{"format":1,"sourceDigest":"89acf48f3b114cd55d76e9fa984b61e8418fa7238d738e9be21ec730d09b586d","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.1","contentId":"8a3f220c38074de27c8ae13c53d034f02cee1e48700feec37f42331d4d63ac3f"},"sha256":"34f45899b72e22a00ca5f7ee2cdda6e4a436a087580b40e0495f576959144372"}
@@ -1,14 +1,11 @@
1
1
  // Generated from packages/harness-settings/index.ts. Do not edit directly.
2
2
  import { existsSync, lstatSync, realpathSync, readFileSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { randomUUID } from "node:crypto";
4
- import { createRequire } from "node:module";
5
4
  import { join } from "node:path";
6
5
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
+ // A static import lets the compiled Pi loader resolve dependencies of the settings lock.
7
+ import lockfile from "proper-lockfile";
7
8
 
8
- // Match Pi's settings lock without depending on a private SDK import.
9
- const lockfile = createRequire(import.meta.url)("proper-lockfile") as {
10
- lockSync(path: string, options: { realpath: boolean }): () => void;
11
- };
12
9
  const NAMESPACE = "piBetterHarness";
13
10
  export interface HarnessSettingsSeams { agentDir?: () => string }
14
11
 
@@ -249,9 +249,9 @@ function sameOperation(a: DiagnosticRecord, b: DiagnosticRecord): boolean {
249
249
  return a.context === b.context && a.tool === b.tool && a.operationFingerprint === b.operationFingerprint;
250
250
  }
251
251
  interface Journal { records: DiagnosticRecord[]; losses: DiagnosticLosses }
252
- function load(dir: string, key: Buffer): Journal {
252
+ function load(dir: string, key: Buffer): Journal & { needsRepair: boolean } {
253
253
  const path = join(dir, "events.jsonl");
254
- if (!stat(path)) return { records: [], losses: emptyLosses() };
254
+ if (!stat(path)) return { records: [], losses: emptyLosses(), needsRepair: false };
255
255
  chmodSync(path, 0o600);
256
256
  const raw = readSafe(path, MAX_BYTES);
257
257
  const lines = raw.split("\n");
@@ -273,7 +273,8 @@ function load(dir: string, key: Buffer): Journal {
273
273
  } else losses.tampered++;
274
274
  } else losses.malformed++;
275
275
  } catch { losses.malformed++; }
276
- if (header && (header.count !== lines.length || header.digest !== digest(key, "journal", lines.join("\n")))) losses.tampered++;
276
+ const headerMatches = header && header.count === lines.length && header.digest === digest(key, "journal", lines.join("\n"));
277
+ if (header && !headerMatches) losses.tampered++;
277
278
  const records: DiagnosticRecord[] = [];
278
279
  const seen = new Set<string>();
279
280
  const denied = new Map<string, DiagnosticRecord>();
@@ -293,7 +294,7 @@ function load(dir: string, key: Buffer): Journal {
293
294
  seen.add(record.fingerprint);
294
295
  records.push(record);
295
296
  }
296
- return { records, losses };
297
+ return { records, losses, needsRepair: !headerMatches || records.length !== lines.length };
297
298
  }
298
299
  function encode(journal: Journal, key: Buffer): string {
299
300
  const lines = journal.records.map(record => JSON.stringify({ ...record, mac: digest(key, "event", JSON.stringify(record)) }));
@@ -385,27 +386,21 @@ export class SandboxDiagnostics {
385
386
  const dir = directory(this.options, input.outcome === "denied");
386
387
  if (!dir) return;
387
388
  if (input.outcome === "succeeded" && !stat(join(dir, "events.jsonl"))) return;
388
- locked(dir, () => {
389
+ const repaired = locked(dir, () => {
389
390
  const key = installationKey(dir, input.outcome === "denied");
390
391
  const journal = load(dir, key);
391
- const before = JSON.stringify(journal.losses);
392
392
  const pruned = retain(journal, key, now);
393
393
  const fingerprint = imported ? digest(key, "relay-event-identity", identity([imported.runIdentity, imported.value.idFingerprint])) :
394
394
  digest(key, "event-identity", randomBytes(32).toString("hex"));
395
395
  // Signed record identities survive parent reloads and full log rescans.
396
- if (imported && journal.records.some(r => r.fingerprint === fingerprint)) {
397
- if (pruned || journal.losses.malformed || journal.losses.tampered) atomic(join(dir, "events.jsonl"), encode(journal, key));
398
- if (issues(journal.losses).length) this.report(new Error("Diagnostics collection has gaps."));
399
- return;
400
- }
396
+ const duplicate = imported && journal.records.some(r => r.fingerprint === fingerprint);
401
397
  const operationFingerprint = digest(key, "operation", operation);
402
398
  const recovered = new Set(journal.records.flatMap(r => r.recoveryOf ? [r.recoveryOf] : []));
403
399
  const prior = [...journal.records].reverse().find(r => r.outcome === "denied" && r.context === this.options.context &&
404
400
  r.tool === tool && r.operationFingerprint === operationFingerprint && r.timestamp <= now);
405
- if (input.outcome === "succeeded" && (!prior || recovered.has(prior.fingerprint))) {
406
- if (pruned || issues(journal.losses).some(i => i !== "retention-loss")) atomic(join(dir, "events.jsonl"), encode(journal, key));
407
- if (issues(journal.losses).length) this.report(new Error("Diagnostics collection has gaps."));
408
- return;
401
+ if (duplicate || (input.outcome === "succeeded" && (!prior || recovered.has(prior.fingerprint)))) {
402
+ if (pruned || journal.needsRepair) atomic(join(dir, "events.jsonl"), encode(journal, key));
403
+ return journal.needsRepair;
409
404
  }
410
405
  const backend = imported?.value.backend ?? this.options.backend();
411
406
  const version = imported?.value.version ?? this.options.version;
@@ -425,8 +420,9 @@ export class SandboxDiagnostics {
425
420
  journal.records.push(record);
426
421
  retain(journal, key, now);
427
422
  atomic(join(dir, "events.jsonl"), encode(journal, key));
428
- if (before !== JSON.stringify(journal.losses) || journal.losses.malformed || journal.losses.tampered) this.report(new Error("Diagnostics collection has gaps."));
423
+ return journal.needsRepair;
429
424
  });
425
+ if (repaired) this.report(new Error("Diagnostics collection has gaps."));
430
426
  } catch (error) { this.report(this.options.relay || imported ? new Error("Diagnostics collection has gaps.") : error); }
431
427
  }
432
428
  }
@@ -328,7 +328,7 @@ export function wrapRemoteBashCommand(input: RemoteBashCommandInput): string {
328
328
 
329
329
  export function defaultSshControlPathRoot(): string {
330
330
  const agentDirectory = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
331
- const root = join(agentDirectory, "ssh-control");
331
+ const root = resolve(agentDirectory, "ssh-control");
332
332
  // A long agent directory would push the socket past the unix path limit; fall back to a short per-user root.
333
333
  if (Buffer.byteLength(join(root, MUX_CONTROL_PATH_NAME_TEMPLATE)) <= MAX_SSH_CONTROL_PATH_BYTES) return root;
334
334
  return join("/tmp", `pi-ssh-${process.getuid?.() ?? "user"}`);
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-goal",
3
- "version": "0.16.0",
3
+ "version": "0.16.1",
4
4
  "description": "Pi extension for goal tracking with background-aware continuation.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,14 +1,11 @@
1
1
  // Generated from packages/harness-settings/index.ts. Do not edit directly.
2
2
  import { existsSync, lstatSync, realpathSync, readFileSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { randomUUID } from "node:crypto";
4
- import { createRequire } from "node:module";
5
4
  import { join } from "node:path";
6
5
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
+ // A static import lets the compiled Pi loader resolve dependencies of the settings lock.
7
+ import lockfile from "proper-lockfile";
7
8
 
8
- // Match Pi's settings lock without depending on a private SDK import.
9
- const lockfile = createRequire(import.meta.url)("proper-lockfile") as {
10
- lockSync(path: string, options: { realpath: boolean }): () => void;
11
- };
12
9
  const NAMESPACE = "piBetterHarness";
13
10
  export interface HarnessSettingsSeams { agentDir?: () => string }
14
11
 
@@ -1,5 +1,6 @@
1
1
  import { execFile } from "node:child_process";
2
- import { cpSync, existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
2
+ import { readFileSync, readdirSync, statSync } from "node:fs";
3
+ import { mkdir, mkdtemp, readdir, readFile, rm, stat, utimes, writeFile } from "node:fs/promises";
3
4
  import { tmpdir } from "node:os";
4
5
  import { dirname, join } from "node:path";
5
6
 
@@ -139,18 +140,54 @@ async function settlementScheduler(script: string, runDir: string, timeoutMs?: n
139
140
 
140
141
  // --peek suppresses seen bookkeeping, not syncRun's issue-tree write. Give the live
141
142
  // probe private inputs; keep cwd so relative workspace paths retain their meaning.
143
+ const budget = timeoutMs ?? SCHEDULER_SYNC_TIMEOUT_MS;
144
+ const startedAt = performance.now();
145
+ const signal = AbortSignal.timeout(budget);
142
146
  let snapshot: string | undefined;
143
147
  try {
144
- snapshot = mkdtempSync(join(tmpdir(), "pi-goal-scheduler-"));
145
- for (const name of ["task-plan.json", "issue-tree.json", "next-actions-seen.json", "reviews", "results"]) {
148
+ snapshot = await mkdtemp(join(tmpdir(), "pi-goal-scheduler-"));
149
+ for (const name of ["task-plan.json", "issue-tree.json", "next-actions-seen.json"]) {
150
+ await copySchedulerRecord(join(runDir, name), join(snapshot, name), signal);
151
+ }
152
+ // next-actions reads top-level JSON records. Review checkout trees and worker
153
+ // artifacts can be much larger and aren't inputs to the settlement decision.
154
+ for (const name of ["reviews", "results"]) {
155
+ signal.throwIfAborted();
146
156
  const source = join(runDir, name);
147
- if (existsSync(source)) cpSync(source, join(snapshot, name), { recursive: true, dereference: true });
157
+ const names = await readdir(source).catch((error: NodeJS.ErrnoException) => {
158
+ if (error.code === "ENOENT") return [];
159
+ throw error;
160
+ });
161
+ if (!names.length) continue;
162
+ const target = join(snapshot, name);
163
+ await mkdir(target);
164
+ for (const file of names) {
165
+ if (file.endsWith(".json")) {
166
+ await copySchedulerRecord(join(source, file), join(target, file), signal);
167
+ }
168
+ }
148
169
  }
149
- return await executeScheduler(script, snapshot, timeoutMs ?? SCHEDULER_SYNC_TIMEOUT_MS, true, runDir);
170
+ const remaining = budget - Math.ceil(performance.now() - startedAt);
171
+ if (signal.aborted || remaining <= 0) return { ok: false, reason: `the live scheduler check timed out after ${budget} ms` };
172
+ return await executeScheduler(script, snapshot, remaining, true, runDir);
150
173
  } catch (error) {
174
+ if (signal.aborted) return { ok: false, reason: `the live scheduler check timed out after ${budget} ms` };
151
175
  return { ok: false, reason: `could not prepare the live scheduler check (${String(error).slice(0, DETAIL_LIMIT)})` };
152
176
  } finally {
153
- if (snapshot) rmSync(snapshot, { recursive: true, force: true });
177
+ if (snapshot) await rm(snapshot, { recursive: true, force: true });
178
+ }
179
+ }
180
+
181
+ async function copySchedulerRecord(source: string, target: string, signal: AbortSignal): Promise<void> {
182
+ signal.throwIfAborted();
183
+ try {
184
+ const info = await stat(source);
185
+ if (!info.isFile()) return;
186
+ await writeFile(target, await readFile(source, { signal }), { signal });
187
+ // Review mtimes tell the scheduler when the last round was written.
188
+ await utimes(target, info.atime, info.mtime);
189
+ } catch (error) {
190
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
154
191
  }
155
192
  }
156
193