@criogaid/pi-hashline-edit 0.1.0 → 0.1.2

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.
@@ -40,14 +40,18 @@ test("hashFileLines empty file", () => {
40
40
  assert.deepEqual(hashFileLines([]), []);
41
41
  });
42
42
 
43
- test("hashFileLines: identical content lines get distinct hashes (no collision, no length bloat)", () => {
44
- // runs of identical lines — the case neighbor-aware hashing explodes on
43
+ test("hashFileLines normally disambiguates repeated content without changing hash length", () => {
45
44
  const lines = ["", "", "", "", "", "}", "}", "}", "return", "return", ",", ","];
46
45
  const hashes = hashFileLines(lines);
47
- assert.equal(new Set(hashes).size, hashes.length, "duplicate hashes");
46
+ assert.equal(new Set(hashes).size, hashes.length, "unexpected collision in fixture");
48
47
  for (const h of hashes) assert.equal(h.length, 4, `hash ${h} is not 4 chars`);
49
48
  });
50
49
 
50
+ test("truncated checksums can collide", () => {
51
+ assert.equal(computeLineHash(1, "const value = 558;", 4), "TM02");
52
+ assert.equal(computeLineHash(1, "const value = 9344;", 4), "TM02");
53
+ });
54
+
51
55
  test("hashFileLines respects the length parameter", () => {
52
56
  assert.equal(hashFileLines(["a", "b"], 6)[0].length, 6);
53
57
  assert.equal(hashFileLines(["a", "b"], 4)[0].length, 4);
package/src/core/hash.ts CHANGED
@@ -1,10 +1,9 @@
1
1
  /**
2
2
  * Per-line content hash.
3
3
  *
4
- * The hash mixes the 1-based line number into the line content, so every line
5
- * gets a unique hash by construction — line numbers are unique, therefore no
6
- * in-file collision is possible, and no length extension / fallback is ever
7
- * needed.
4
+ * The hash mixes the 1-based line number into the line content. It is a compact
5
+ * checksum of (position, content), not a unique identifier: truncation and the
6
+ * 32-bit source hash permit collisions.
8
7
  *
9
8
  * Why line + content (not content alone, not content + neighbors):
10
9
  *
@@ -15,8 +14,8 @@
15
14
  * would change an unchanged line's hash when an adjacent line is edited — a
16
15
  * spurious dependency with no benefit under this design's position-fixed
17
16
  * apply.)
18
- * - Content alone would leave identical lines (blank lines, `}`) sharing a
19
- * hash; mixing the line number disambiguates them for free.
17
+ * - Content alone would make identical lines (blank lines, `}`) share the same
18
+ * checksum systematically; mixing the line number avoids that common case.
20
19
  *
21
20
  * @module pi-hashline-edit/core
22
21
  */
@@ -59,10 +58,7 @@ export function computeLineHash(line: number, content: string, len = 4): string
59
58
  return toBase32(fnv1a32(`${line}\n${content}`), len);
60
59
  }
61
60
 
62
- /**
63
- * Compute per-line hashes for a file. Unique by construction — the 1-based line
64
- * number is part of each hash, so two identical content lines always differ.
65
- */
61
+ /** Compute compact per-line checksums; callers must treat collisions as possible. */
66
62
  export function hashFileLines(lines: readonly string[], len = 4): string[] {
67
63
  return lines.map((content, i) => computeLineHash(i + 1, content, len));
68
64
  }
package/src/core/index.ts CHANGED
@@ -10,4 +10,5 @@
10
10
  export * from "./types.ts";
11
11
  export { computeLineHash, hashFileLines } from "./hash.ts";
12
12
  export { splitLines, detectLineEnding, hasFinalNewline } from "./lines.ts";
13
+ export { decodeUtf8, decodeEditableText } from "./text.ts";
13
14
  export { applyEdits } from "./apply.ts";
@@ -0,0 +1,15 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { decodeEditableText, decodeUtf8 } from "./text.ts";
4
+
5
+ test("decodeUtf8 rejects malformed input instead of replacing bytes", () => {
6
+ assert.throws(() => decodeUtf8(Uint8Array.from([0xc3, 0x28])), /UNSUPPORTED_ENCODING/);
7
+ });
8
+
9
+ test("decodeUtf8 preserves a leading BOM", () => {
10
+ assert.equal(decodeUtf8(Uint8Array.from([0xef, 0xbb, 0xbf, 0x61])), "\ufeffa");
11
+ });
12
+
13
+ test("decodeEditableText rejects NUL bytes", () => {
14
+ assert.throws(() => decodeEditableText(Uint8Array.from([0x61, 0, 0x62])), /UNSUPPORTED_TEXT/);
15
+ });
@@ -0,0 +1,18 @@
1
+ import { TextDecoder } from "node:util";
2
+
3
+ const UTF8_DECODER = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
4
+
5
+ /** Decode UTF-8 without replacing malformed bytes; preserve a leading BOM for byte-stable rewrites. */
6
+ export function decodeUtf8(bytes: Uint8Array): string {
7
+ try {
8
+ return UTF8_DECODER.decode(bytes);
9
+ } catch (error) {
10
+ throw new Error("UNSUPPORTED_ENCODING: expected valid UTF-8.", { cause: error });
11
+ }
12
+ }
13
+
14
+ /** Reject byte-oriented/binary content before entering a text mutation pipeline. */
15
+ export function decodeEditableText(bytes: Uint8Array): string {
16
+ if (bytes.includes(0)) throw new Error("UNSUPPORTED_TEXT: NUL bytes are not editable.");
17
+ return decodeUtf8(bytes);
18
+ }
package/src/core/types.ts CHANGED
@@ -67,8 +67,7 @@ export interface AnchorFailure {
67
67
  /** Batch-level failure. `anchor` carries every per-anchor failure collected across the batch. */
68
68
  export type ApplyFailure =
69
69
  | { readonly kind: "anchor"; readonly failures: readonly AnchorFailure[] }
70
- | { readonly kind: "range"; readonly message: string }
71
- | { readonly kind: "noop"; readonly message: string };
70
+ | { readonly kind: "input" | "range" | "noop"; readonly message: string };
72
71
 
73
72
  /**
74
73
  * Apply result. On success, `touchedLines` lists the 0-based line indices in
package/src/index.ts CHANGED
@@ -22,6 +22,7 @@ import { makeReplaceTool } from "./pi/replace-tool.ts";
22
22
  import { makeWriteOverride } from "./pi/write-tool.ts";
23
23
  import { createActionFusionExecutor } from "./pi/action-fusion.ts";
24
24
  import { registerFusionCards } from "./pi/fusion-card.ts";
25
+ import { withMutationStatus } from "./pi/render.ts";
25
26
 
26
27
  export default function (pi: ExtensionAPI) {
27
28
  const cwd = process.cwd();
@@ -34,9 +35,9 @@ export default function (pi: ExtensionAPI) {
34
35
  if (state.config.enabled) {
35
36
  const reportProgress = registerFusionCards(pi);
36
37
  const fusion = state.config.actionFusion ? createActionFusionExecutor(undefined, reportProgress) : undefined;
37
- pi.registerTool(makeWriteOverride(cwd, fusion));
38
- pi.registerTool(makeEditOverride(cwd, fusion));
39
- pi.registerTool(makeReplaceTool(cwd, fusion));
38
+ for (const tool of [makeWriteOverride(cwd, fusion), makeEditOverride(cwd, fusion), makeReplaceTool(cwd, fusion)]) {
39
+ pi.registerTool(fusion ? withMutationStatus(tool) : tool);
40
+ }
40
41
 
41
42
  pi.registerTool(makeReadOverride(cwd));
42
43
  pi.registerTool(makeGrepOverride(cwd));
@@ -251,6 +251,33 @@ test("noIgnore searches ignored files while explicit excluding globs still apply
251
251
  }
252
252
  });
253
253
 
254
+ test("explicit file paths obey ordered glob filters without inheriting ignore rules", async () => {
255
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-file-glob-"));
256
+ try {
257
+ const kept = join(directory, "keep.ts");
258
+ const excluded = join(directory, "drop.test.ts");
259
+ const ignored = join(directory, "ignored.ts");
260
+ await writeFile(join(directory, ".ignore"), "ignored.ts\n");
261
+ await Promise.all([kept, excluded, ignored].map((path) => writeFile(path, "needle\n")));
262
+ const tool = makeGrepOverrideWithBackend(directory, {});
263
+ const result: any = await tool.execute("0", {
264
+ pattern: "needle",
265
+ path: [kept, excluded, ignored],
266
+ glob: ["*.ts", "!**/*.test.ts"],
267
+ outputMode: "files",
268
+ }, undefined, undefined);
269
+ const files = new Set(result.content[0].text.split("\n"));
270
+ assert.deepEqual(files, new Set(["keep.ts", "ignored.ts"]));
271
+
272
+ const none: any = await tool.execute("0", {
273
+ pattern: "needle", path: excluded, glob: "!**/*.test.ts",
274
+ }, undefined, undefined);
275
+ assert.equal(none.content[0].text, "No matches found");
276
+ } finally {
277
+ await rm(directory, { recursive: true, force: true });
278
+ }
279
+ });
280
+
254
281
  test("follow returns a resolved target path that edit can update without replacing the link", async (t) => {
255
282
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-follow-"));
256
283
  try {
@@ -388,3 +415,23 @@ test("owned rg rejects an oversized JSONL record", async () => {
388
415
  await rm(directory, { recursive: true, force: true });
389
416
  }
390
417
  });
418
+
419
+ test("real rg accepts wildcard-only regexes and preserves limits and literal mode", async () => {
420
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-wildcard-"));
421
+ try {
422
+ await writeFile(join(directory, "fixture.txt"), "first\n\n.*\n");
423
+ const tool = makeGrepOverrideWithBackend(directory, {});
424
+ for (const [pattern, expected] of [[".*", 3], ["^.+$", 2], [".?", 3]] as const) {
425
+ const result: any = await tool.execute("count", { pattern, outputMode: "count" }, undefined, undefined);
426
+ assert.match(result.content[0].text, new RegExp(`Total: ${expected} matches in 1 file`));
427
+ }
428
+ const limited: any = await tool.execute("limited", { pattern: ".*", limit: 1 }, undefined, undefined);
429
+ assert.match(limited.content[0].text, /1#[0-9A-Z]+│first/);
430
+ assert.doesNotMatch(limited.content[0].text, /[23]#[0-9A-Z]+│/);
431
+ const literal: any = await tool.execute("literal", { pattern: ".*", literal: true }, undefined, undefined);
432
+ assert.match(literal.content[0].text, /3#[0-9A-Z]+│\.\*/);
433
+ await assert.rejects(tool.execute("invalid", { pattern: "*", literal: false }, undefined, undefined), /regex parse error/);
434
+ } finally {
435
+ await rm(directory, { recursive: true, force: true });
436
+ }
437
+ });
@@ -9,6 +9,7 @@ import { makeWriteOverride } from "./write-tool.ts";
9
9
  import { computeLineHash } from "../core/hash.ts";
10
10
  import type { ActionFusionProgress } from "./action-fusion.ts";
11
11
  import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor, THEN_RUN_FAILED, THEN_RUN_SKIPPED, THEN_RUN_SUCCEEDED } from "./action-fusion.ts";
12
+ import { byteRevision } from "./file-commit.ts";
12
13
 
13
14
  async function tempDir(): Promise<string> {
14
15
  return mkdtemp(join(tmpdir(), "hashline-action-fusion-"));
@@ -66,7 +67,7 @@ test("mutation failure skips the command and command failure does not roll back"
66
67
  assert.equal(calls, 0);
67
68
  const target = join(dir, "changed.txt");
68
69
  await writeFile(target, "changed\n");
69
- const result = await fusion({ toolCallId: "y", absolutePath: target, thenRun: { command: "check" }, mutate: async () => ({ content: [{ type: "text", text: "mutation" }], details: { ok: true } }), signal: undefined, ctx: ctx(dir) });
70
+ const result = await fusion({ toolCallId: "y", absolutePath: target, thenRun: { command: "check" }, mutate: async () => ({ content: [{ type: "text", text: "mutation" }], details: { ok: true, publishedRevision: byteRevision("changed\n") } }), signal: undefined, ctx: ctx(dir) });
70
71
  assert.equal(result.content[0].type === "text" && result.content[0].text, "mutation");
71
72
  const diagnostic = result.content[1].type === "text" ? result.content[1].text : "";
72
73
  assert.ok(diagnostic.includes(THEN_RUN_FAILED) && diagnostic.includes(commandFailure));
@@ -103,7 +104,7 @@ test("default runner executes a real local command", async () => {
103
104
  toolCallId: "real",
104
105
  absolutePath: target,
105
106
  thenRun: { command: "node -e \"process.stdout.write('real runner')\"" },
106
- mutate: async () => { await writeFile(target, "after\n"); return { content: [{ type: "text", text: "mutated" }], details: { ok: true } }; },
107
+ mutate: async () => { await writeFile(target, "after\n"); return { content: [{ type: "text", text: "mutated" }], details: { ok: true, publishedRevision: byteRevision("after\n") } }; },
107
108
  signal: undefined,
108
109
  ctx: { ...ctx(dir), sessionManager: { getSessionId: () => "test", getSessionFile: () => undefined } } as any,
109
110
  });
@@ -124,7 +125,7 @@ test("marks anchors stale when then_run changes the target", async () => {
124
125
  toolCallId: "stale",
125
126
  absolutePath: target,
126
127
  thenRun: { command: "mutate target" },
127
- mutate: async () => { await writeFile(target, "after mutation\n"); return { content: [{ type: "text", text: "mutated" }], details: {} }; },
128
+ mutate: async () => { await writeFile(target, "after mutation\n"); return { content: [{ type: "text", text: "mutated" }], details: { publishedRevision: byteRevision("after mutation\n") } }; },
128
129
  signal: undefined,
129
130
  ctx: ctx(dir),
130
131
  });
@@ -207,7 +208,8 @@ test("all mutation tools forward command progress before completion in RPC mode"
207
208
  updates.length = 0;
208
209
  await writeFile(join(dir, "progress.txt"), "before\n");
209
210
  await tool.execute(tool.name, { path: "progress.txt", ...input, then_run: { command: "check" } }, undefined, (update: any) => updates.push(update), { cwd: dir, mode: "rpc" });
210
- assert.deepEqual(events.map((event) => event.command), ["waiting", "running", "running", "succeeded"]);
211
+ assert.deepEqual(events.map((event) => event.command), ["waiting", "waiting", "running", "running", "succeeded"]);
212
+ assert.deepEqual(events.map((event) => event.mutationCompleted), [false, true, true, true, true]);
211
213
  assert.equal(events.at(-1)?.output, "final output");
212
214
  assert.equal(events.at(-1)?.publication, "PUBLISHED");
213
215
  assert.equal(updates.at(-1).details.actionFusion.command, "succeeded");
@@ -235,7 +237,7 @@ test("progress reports skipped mutations and failed commands without rolling bac
235
237
  events.length = 0;
236
238
  const failed = await makeWriteOverride(dir, fusion).execute("fail", { path: "failed.txt", content: "published\n", then_run: { command: "check" } }, undefined, undefined, ctx(dir));
237
239
  assert.equal(failed.details.actionFusion.command, "failed");
238
- assert.deepEqual(events.map((event) => event.command), ["waiting", "running", "failed"]);
240
+ assert.deepEqual(events.map((event) => event.command), ["waiting", "waiting", "running", "failed"]);
239
241
  assert.match(events.at(-1)!.output, /diagnostic[\s\S]*code 7/);
240
242
  assert.equal(await readFile(join(dir, "failed.txt"), "utf8"), "published\n");
241
243
  } finally {
@@ -4,6 +4,7 @@ import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/p
4
4
  import { createBashToolDefinition, type ExtensionContext } from "@earendil-works/pi-coding-agent";
5
5
  import { Type } from "typebox";
6
6
  import { fileRevision, FileMutationError, type PublicationStatus } from "./file-commit.ts";
7
+ import { finalizeMutationResult, observedFreshness } from "./mutation-result.ts";
7
8
 
8
9
  export const THEN_RUN_SUCCEEDED = "[then_run:succeeded]";
9
10
  export const THEN_RUN_FAILED = "[then_run:failed]";
@@ -35,6 +36,8 @@ export interface ActionFusionProgress extends Omit<ActionFusionDetails, "command
35
36
  commandText: string;
36
37
  command: Exclude<CommandStatus, "not_requested"> | "waiting" | "running";
37
38
  output: string;
39
+ /** True only after mutation execution and result generation both succeed. */
40
+ mutationCompleted: boolean;
38
41
  }
39
42
 
40
43
  type ProgressReporter = (progress: ActionFusionProgress, ctx: ExtensionContext) => void;
@@ -52,11 +55,11 @@ type MutationResult<TDetails> = AgentToolResult<TDetails>;
52
55
  type MutationFinalizer<TDetails> = (result: MutationResult<TDetails>, publishAnchors: boolean) => MutationResult<TDetails>;
53
56
 
54
57
  function staleAnchorNotice<TDetails>(result: MutationResult<TDetails>): string {
55
- const revision = (result.details as { revision?: unknown } | undefined)?.revision;
58
+ const publishedRevision = (result.details as { publishedRevision?: unknown } | undefined)?.publishedRevision;
56
59
  return [
57
60
  `${THEN_RUN_STALE} Target freshness was not confirmed unchanged after then_run.`,
58
61
  "Pre-command anchors are omitted. Re-read before further edits.",
59
- ...(typeof revision === "string" ? ["The mutation revision may not describe the final file."] : []),
62
+ ...(typeof publishedRevision === "string" ? ["The published revision may not describe the final file."] : []),
60
63
  ].join("\n");
61
64
  }
62
65
 
@@ -111,6 +114,11 @@ function mutationPublication<TDetails>(result: MutationResult<TDetails>): Public
111
114
  return details?.publication ?? "PUBLISHED";
112
115
  }
113
116
 
117
+ function mutationPublishedRevision<TDetails>(result: MutationResult<TDetails>): string | undefined {
118
+ const revision = (result.details as { publishedRevision?: unknown } | undefined)?.publishedRevision;
119
+ return typeof revision === "string" && revision.length > 0 ? revision : undefined;
120
+ }
121
+
114
122
  function commandStatus(error: unknown, signal: AbortSignal | undefined): CommandStatus {
115
123
  if (signal?.aborted) return "cancelled";
116
124
  return /timeout|timed out/i.test(errorText(error)) ? "timeout" : "failed";
@@ -185,14 +193,20 @@ export function createActionFusionExecutor(commandRunner: CommandRunner = defaul
185
193
  }): Promise<MutationResult<TDetails>> {
186
194
  if (thenRun !== undefined) validateThenRun(thenRun);
187
195
  let completedMutation: MutationResult<TDetails> | undefined;
196
+ let progressFailure: string | undefined;
188
197
  const report = (command: ActionFusionProgress["command"], publication: PublicationStatus, freshness: Freshness, output = "") => {
189
198
  if (!thenRun) return;
190
- const progress: ActionFusionProgress = { toolCallId, path: absolutePath, commandText: thenRun.command, command, publication, freshness, output };
191
- onProgress?.(progress, ctx);
192
- onUpdate?.({
193
- content: [...(completedMutation?.content ?? []), { type: "text", text: `then_run ${command}: ${thenRun.command}\n${output}` }],
194
- details: { ...(completedMutation?.details as object ?? {}), actionFusion: progress },
195
- } as MutationResult<TDetails>);
199
+ const progress: ActionFusionProgress = { toolCallId, path: absolutePath, commandText: thenRun.command, command, publication, freshness, output, mutationCompleted: completedMutation !== undefined };
200
+ // Display callbacks are observers: their failures must not change publication or command execution.
201
+ for (const notify of [
202
+ () => onProgress?.(progress, ctx),
203
+ () => onUpdate?.({
204
+ content: [...(completedMutation?.content ?? []), { type: "text", text: `then_run ${command}: ${thenRun.command}\n${output}` }],
205
+ details: { ...(completedMutation?.details as object ?? {}), actionFusion: progress },
206
+ } as MutationResult<TDetails>),
207
+ ]) {
208
+ try { notify(); } catch (error) { progressFailure ??= errorText(error); }
209
+ }
196
210
  };
197
211
  report("waiting", "NOT_PUBLISHED", "unknown");
198
212
  return withQueue(absolutePath, async () => {
@@ -213,22 +227,25 @@ export function createActionFusionExecutor(commandRunner: CommandRunner = defaul
213
227
  }
214
228
 
215
229
  const publication = mutationPublication(mutationResult);
230
+ report("waiting", publication, "unknown");
216
231
  if (thenRun === undefined) {
217
- const finalized = finalizeMutation?.(mutationResult, true) ?? mutationResult;
232
+ const finalized = finalizeMutation ? finalizeMutationResult(mutationResult, finalizeMutation) : mutationResult;
218
233
  return {
219
234
  ...finalized,
220
- details: { ...(finalized.details as object ?? {}), actionFusion: { publication, command: "not_requested", freshness: "unknown" } satisfies ActionFusionDetails },
235
+ details: { ...(finalized.details as object ?? {}), actionFusion: { publication, command: "not_requested", freshness: observedFreshness(mutationResult) } satisfies ActionFusionDetails },
221
236
  } as MutationResult<TDetails>;
222
237
  }
223
238
 
224
- let baseline: string | undefined;
239
+ const baseline = mutationPublishedRevision(mutationResult);
240
+ if (baseline === undefined) {
241
+ throw new ActionFusionError("Missing published revision; cannot validate fused command freshness.", { publication, command: "skipped", freshness: "unknown" });
242
+ }
225
243
  try {
226
- baseline = await fileRevision(absolutePath);
227
244
  signal?.throwIfAborted();
228
245
  await assertUnchangedBeforeCommand(absolutePath, baseline);
229
246
  signal?.throwIfAborted();
230
247
  } catch (error) {
231
- const freshness = baseline ? await readFreshness(absolutePath, baseline) : "unknown";
248
+ const freshness = await readFreshness(absolutePath, baseline);
232
249
  throw new ActionFusionError("mutation completed; the command was not run", { publication, command: signal?.aborted ? "cancelled" : "skipped", freshness }, { cause: error });
233
250
  }
234
251
 
@@ -244,14 +261,14 @@ export function createActionFusionExecutor(commandRunner: CommandRunner = defaul
244
261
  commandError = error;
245
262
  output = "";
246
263
  }
247
- const freshness = baseline ? await readFreshness(absolutePath, baseline) : "unknown";
264
+ const freshness = await readFreshness(absolutePath, baseline);
248
265
  if (commandError !== undefined) {
249
266
  throw new ActionFusionError("mutation completed; then_run did not complete successfully", { publication, command: commandStatus(commandError, signal), freshness }, { cause: commandError });
250
267
  }
251
268
 
252
269
  const actionFusion: ActionFusionDetails = { publication, command: "succeeded", freshness };
253
270
  report("succeeded", publication, freshness, output);
254
- const finalized = finalizeMutation?.(mutationResult, freshness === "unchanged") ?? mutationResult;
271
+ const finalized = finalizeMutation ? finalizeMutationResult(mutationResult, finalizeMutation, freshness === "unchanged") : mutationResult;
255
272
  const commandText = freshness === "unchanged"
256
273
  ? (output ? `${THEN_RUN_SUCCEEDED}\n${output}` : THEN_RUN_SUCCEEDED)
257
274
  : `${THEN_RUN_SUCCEEDED}\n${
@@ -266,11 +283,11 @@ export function createActionFusionExecutor(commandRunner: CommandRunner = defaul
266
283
  } as MutationResult<TDetails>;
267
284
  }).catch((error: unknown) => {
268
285
  report(error instanceof ActionFusionError ? error.command as ActionFusionProgress["command"] : "skipped",
269
- error instanceof ActionFusionError ? error.publication : "NOT_PUBLISHED",
286
+ error instanceof ActionFusionError || error instanceof FileMutationError ? error.publication : completedMutation ? mutationPublication(completedMutation) : "NOT_PUBLISHED",
270
287
  error instanceof ActionFusionError ? error.freshness : "unknown", errorText(error));
271
288
  // A completed mutation remains successful; command failure belongs to its own card.
272
289
  if (completedMutation && error instanceof ActionFusionError) {
273
- const finalized = finalizeMutation?.(completedMutation, error.freshness === "unchanged") ?? completedMutation;
290
+ const finalized = finalizeMutation ? finalizeMutationResult(completedMutation, finalizeMutation, error.freshness === "unchanged") : completedMutation;
274
291
  const anchorNotice = finalizeMutation && error.freshness !== "unchanged" ? `\n${staleAnchorNotice(finalized)}` : "";
275
292
  return {
276
293
  ...finalized,
@@ -278,7 +295,11 @@ export function createActionFusionExecutor(commandRunner: CommandRunner = defaul
278
295
  content: [...finalized.content, { type: "text", text: `${error.message}${anchorNotice}` }],
279
296
  } as MutationResult<TDetails>;
280
297
  }
298
+ if (progressFailure && error instanceof Error) error.message += `\nProgress reporting failed: ${progressFailure}`;
281
299
  throw error;
282
- });
300
+ }).then((result) => progressFailure ? {
301
+ ...result,
302
+ content: [...result.content, { type: "text" as const, text: `Progress reporting failed: ${progressFailure}` }],
303
+ } : result);
283
304
  };
284
305
  }
@@ -20,3 +20,26 @@ test("actionFusion defaults off and can be enabled without changing other defaul
20
20
  await rm(root, { recursive: true, force: true });
21
21
  }
22
22
  });
23
+
24
+ test("config rejects fractional values and tolerates malformed settings shapes", async () => {
25
+ const root = await mkdtemp(join(tmpdir(), "hashline-config-"));
26
+ try {
27
+ await mkdir(join(root, ".pi"));
28
+ const path = join(root, ".pi", "settings.json");
29
+ for (const value of [3.5, -1, "4", null]) {
30
+ await writeFile(path, JSON.stringify({ hashlineEdit: { hashLen: value, shiftRadius: value } }));
31
+ assert.deepEqual(loadConfig(root), { enabled: true, actionFusion: false, hashLen: 4, shiftRadius: 15 });
32
+ }
33
+ for (const rootValue of [null, [], 42, "settings", { hashlineEdit: [] }, { hashlineEdit: "invalid" }]) {
34
+ await writeFile(path, JSON.stringify(rootValue));
35
+ const config = loadConfig(root);
36
+ assert.ok(Number.isInteger(config.hashLen));
37
+ assert.ok(Number.isInteger(config.shiftRadius));
38
+ }
39
+ await writeFile(path, JSON.stringify({ hashlineEdit: { hashLen: 8, shiftRadius: 0 } }));
40
+ assert.equal(loadConfig(root).hashLen, 8);
41
+ assert.equal(loadConfig(root).shiftRadius, 0);
42
+ } finally {
43
+ await rm(root, { recursive: true, force: true });
44
+ }
45
+ });
package/src/pi/config.ts CHANGED
@@ -27,7 +27,8 @@ const DEFAULT_CONFIG: HashlineEditConfig = { enabled: true, actionFusion: false,
27
27
  function readSettings(filePath: string): Record<string, unknown> {
28
28
  try {
29
29
  if (!fs.existsSync(filePath)) return {};
30
- return JSON.parse(fs.readFileSync(filePath, "utf-8")) as Record<string, unknown>;
30
+ const value: unknown = JSON.parse(fs.readFileSync(filePath, "utf-8"));
31
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
31
32
  } catch {
32
33
  return {};
33
34
  }
@@ -40,16 +41,17 @@ function readSettings(filePath: string): Record<string, unknown> {
40
41
  export function loadConfig(cwd?: string): HashlineEditConfig {
41
42
  const globalSettings = readSettings(path.join(getAgentDir(), "settings.json"));
42
43
  const projectSettings = cwd ? readSettings(path.join(cwd, ".pi", "settings.json")) : {};
43
- const raw = (projectSettings.hashlineEdit ?? globalSettings.hashlineEdit ?? {}) as Record<string, unknown>;
44
+ const value = projectSettings.hashlineEdit ?? globalSettings.hashlineEdit;
45
+ const raw = value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
44
46
  return {
45
47
  enabled: typeof raw.enabled === "boolean" ? raw.enabled : DEFAULT_CONFIG.enabled,
46
48
  actionFusion: raw.actionFusion === true,
47
49
  hashLen:
48
- typeof raw.hashLen === "number" && raw.hashLen >= 2 && raw.hashLen <= 8
50
+ typeof raw.hashLen === "number" && Number.isInteger(raw.hashLen) && raw.hashLen >= 2 && raw.hashLen <= 8
49
51
  ? raw.hashLen
50
52
  : DEFAULT_CONFIG.hashLen,
51
53
  shiftRadius:
52
- typeof raw.shiftRadius === "number" && raw.shiftRadius >= 0 && raw.shiftRadius <= 100
54
+ typeof raw.shiftRadius === "number" && Number.isInteger(raw.shiftRadius) && raw.shiftRadius >= 0 && raw.shiftRadius <= 100
53
55
  ? raw.shiftRadius
54
56
  : DEFAULT_CONFIG.shiftRadius,
55
57
  };