@criogaid/pi-hashline-edit 0.1.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/LICENSE +21 -0
- package/README.md +279 -0
- package/package.json +50 -0
- package/src/core/apply.test.ts +327 -0
- package/src/core/apply.ts +264 -0
- package/src/core/hash.test.ts +54 -0
- package/src/core/hash.ts +68 -0
- package/src/core/index.ts +13 -0
- package/src/core/lines.test.ts +33 -0
- package/src/core/lines.ts +52 -0
- package/src/core/types.ts +87 -0
- package/src/index.ts +44 -0
- package/src/integration/grep-rg.test.ts +390 -0
- package/src/pi/action-fusion.test.ts +244 -0
- package/src/pi/action-fusion.ts +284 -0
- package/src/pi/config.test.ts +22 -0
- package/src/pi/config.ts +56 -0
- package/src/pi/edit-tool.ts +367 -0
- package/src/pi/execute.test.ts +521 -0
- package/src/pi/failure-context.test.ts +88 -0
- package/src/pi/failure-context.ts +98 -0
- package/src/pi/failure-path.test.ts +60 -0
- package/src/pi/file-commit.test.ts +200 -0
- package/src/pi/file-commit.ts +185 -0
- package/src/pi/fusion-card.test.ts +69 -0
- package/src/pi/fusion-card.ts +78 -0
- package/src/pi/grep-tool.ts +795 -0
- package/src/pi/grep.test.ts +515 -0
- package/src/pi/pi.test.ts +19 -0
- package/src/pi/read-tool.ts +178 -0
- package/src/pi/registration.test.ts +41 -0
- package/src/pi/render.ts +103 -0
- package/src/pi/replace-tool.ts +303 -0
- package/src/pi/replace.test.ts +287 -0
- package/src/pi/rg-line-filter.test.ts +79 -0
- package/src/pi/rg-line-filter.ts +358 -0
- package/src/pi/rg-line-ranges.test.ts +30 -0
- package/src/pi/rg-line-ranges.ts +106 -0
- package/src/pi/state.ts +27 -0
- package/src/pi/write-tool.ts +83 -0
- package/src/pi/write.test.ts +126 -0
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import { realpath } from "node:fs/promises";
|
|
2
|
+
import { basename, dirname, resolve } from "node:path";
|
|
3
|
+
import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
|
|
4
|
+
import { createBashToolDefinition, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { Type } from "typebox";
|
|
6
|
+
import { fileRevision, FileMutationError, type PublicationStatus } from "./file-commit.ts";
|
|
7
|
+
|
|
8
|
+
export const THEN_RUN_SUCCEEDED = "[then_run:succeeded]";
|
|
9
|
+
export const THEN_RUN_FAILED = "[then_run:failed]";
|
|
10
|
+
export const THEN_RUN_SKIPPED = "[then_run:skipped]";
|
|
11
|
+
export const THEN_RUN_STALE = "[then_run:stale]";
|
|
12
|
+
|
|
13
|
+
export const ACTION_FUSION_GUIDELINES = [
|
|
14
|
+
"Before each file mutation, identify its next command. If that command is known, authorized, and ready once the mutation succeeds, you MUST include it in then_run instead of making a separate command call (for example, write a script and execute it, or finish edits and run a typecheck).",
|
|
15
|
+
"When several edits are prerequisites, attach then_run to the last one. Separate the command only when its choice or arguments depend on inspecting the mutation result, or a required approval or user reload is still pending.",
|
|
16
|
+
"Check the command outcome before claiming validation passed.",
|
|
17
|
+
];
|
|
18
|
+
|
|
19
|
+
export interface ThenRunInput {
|
|
20
|
+
command: string;
|
|
21
|
+
timeout?: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type CommandStatus = "not_requested" | "skipped" | "succeeded" | "failed" | "timeout" | "cancelled";
|
|
25
|
+
export type Freshness = "unchanged" | "changed" | "missing" | "unknown";
|
|
26
|
+
export interface ActionFusionDetails {
|
|
27
|
+
publication: PublicationStatus;
|
|
28
|
+
command: CommandStatus;
|
|
29
|
+
freshness: Freshness;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ActionFusionProgress extends Omit<ActionFusionDetails, "command"> {
|
|
33
|
+
toolCallId: string;
|
|
34
|
+
path: string;
|
|
35
|
+
commandText: string;
|
|
36
|
+
command: Exclude<CommandStatus, "not_requested"> | "waiting" | "running";
|
|
37
|
+
output: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
type ProgressReporter = (progress: ActionFusionProgress, ctx: ExtensionContext) => void;
|
|
41
|
+
|
|
42
|
+
export function createThenRunSchema(description: string) {
|
|
43
|
+
return Type.Optional(Type.Object({
|
|
44
|
+
command: Type.String({ minLength: 1, description: "Bash command to run" }),
|
|
45
|
+
timeout: Type.Optional(Type.Number({ exclusiveMinimum: 0, description: "Timeout in seconds (optional, no default timeout)" })),
|
|
46
|
+
}, { description }));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
type CommandRunner = (toolCallId: string, input: ThenRunInput, signal: AbortSignal | undefined, ctx: ExtensionContext, onUpdate?: AgentToolUpdateCallback<unknown>) => Promise<string>;
|
|
50
|
+
|
|
51
|
+
type MutationResult<TDetails> = AgentToolResult<TDetails>;
|
|
52
|
+
type MutationFinalizer<TDetails> = (result: MutationResult<TDetails>, publishAnchors: boolean) => MutationResult<TDetails>;
|
|
53
|
+
|
|
54
|
+
function staleAnchorNotice<TDetails>(result: MutationResult<TDetails>): string {
|
|
55
|
+
const revision = (result.details as { revision?: unknown } | undefined)?.revision;
|
|
56
|
+
return [
|
|
57
|
+
`${THEN_RUN_STALE} Target freshness was not confirmed unchanged after then_run.`,
|
|
58
|
+
"Pre-command anchors are omitted. Re-read before further edits.",
|
|
59
|
+
...(typeof revision === "string" ? ["The mutation revision may not describe the final file."] : []),
|
|
60
|
+
].join("\n");
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function errorText(error: unknown): string {
|
|
64
|
+
return error instanceof Error ? error.message : String(error);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function readFreshness(path: string, baseline: string): Promise<Freshness> {
|
|
68
|
+
try {
|
|
69
|
+
return (await fileRevision(path)) === baseline ? "unchanged" : "changed";
|
|
70
|
+
} catch (error) {
|
|
71
|
+
if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return "missing";
|
|
72
|
+
return "unknown";
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function assertUnchangedBeforeCommand(path: string, baseline: string): Promise<void> {
|
|
77
|
+
try {
|
|
78
|
+
const before = await fileRevision(path);
|
|
79
|
+
await new Promise<void>((resolve) => setImmediate(resolve));
|
|
80
|
+
const after = await fileRevision(path);
|
|
81
|
+
if (before !== baseline || after !== baseline) {
|
|
82
|
+
throw new Error("target content changed after the fused mutation");
|
|
83
|
+
}
|
|
84
|
+
} catch (error) {
|
|
85
|
+
throw new Error(`${THEN_RUN_SKIPPED} ${errorText(error)}; the command was not run.`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export class ActionFusionError extends Error {
|
|
90
|
+
readonly publication: PublicationStatus;
|
|
91
|
+
readonly command: CommandStatus;
|
|
92
|
+
readonly freshness: Freshness;
|
|
93
|
+
|
|
94
|
+
constructor(message: string, state: { publication: PublicationStatus; command: CommandStatus; freshness: Freshness }, options?: { cause?: unknown }) {
|
|
95
|
+
const fileState = state.publication === "PUBLISHED" ? "File changes are saved."
|
|
96
|
+
: state.publication === "NOT_PUBLISHED" ? "No file changes were published." : "File state is uncertain; read before retrying.";
|
|
97
|
+
const nextStep = state.publication === "PUBLISHED" && state.freshness !== "unchanged"
|
|
98
|
+
? " Re-read the file before further edits." : "";
|
|
99
|
+
super(`${message} ${state.command === "skipped" || state.command === "cancelled" ? THEN_RUN_SKIPPED : state.command === "succeeded" ? THEN_RUN_SUCCEEDED : THEN_RUN_FAILED}\n${fileState} Command ${state.command}.${nextStep}`, options);
|
|
100
|
+
// Pi exposes error.message to the model, but does not serialize Error.cause.
|
|
101
|
+
if (options?.cause !== undefined) this.message += `\n${errorText(options.cause)}`;
|
|
102
|
+
this.name = "ActionFusionError";
|
|
103
|
+
this.publication = state.publication;
|
|
104
|
+
this.command = state.command;
|
|
105
|
+
this.freshness = state.freshness;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function mutationPublication<TDetails>(result: MutationResult<TDetails>): PublicationStatus {
|
|
110
|
+
const details = result.details as { publication?: PublicationStatus } | undefined;
|
|
111
|
+
return details?.publication ?? "PUBLISHED";
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function commandStatus(error: unknown, signal: AbortSignal | undefined): CommandStatus {
|
|
115
|
+
if (signal?.aborted) return "cancelled";
|
|
116
|
+
return /timeout|timed out/i.test(errorText(error)) ? "timeout" : "failed";
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function validateThenRun(input: ThenRunInput): void {
|
|
120
|
+
if (!input.command.trim()) throw new Error("then_run command must not be empty");
|
|
121
|
+
if (input.timeout !== undefined && (!Number.isFinite(input.timeout) || input.timeout <= 0)) {
|
|
122
|
+
throw new Error("then_run timeout must be a finite positive number of seconds");
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function defaultCommandRunner(toolCallId: string, input: ThenRunInput, signal: AbortSignal | undefined, ctx: ExtensionContext, onUpdate?: AgentToolUpdateCallback<unknown>): Promise<string> {
|
|
127
|
+
const bash = createBashToolDefinition(ctx.cwd);
|
|
128
|
+
const result = await bash.execute(`${toolCallId}:then_run`, input, signal, onUpdate, ctx);
|
|
129
|
+
return result.content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function canonicalQueueKey(path: string): Promise<string> {
|
|
133
|
+
const resolved = resolve(path);
|
|
134
|
+
let current = resolved;
|
|
135
|
+
const missing: string[] = [];
|
|
136
|
+
while (true) {
|
|
137
|
+
try { return resolve(await realpath(current), ...missing); }
|
|
138
|
+
catch (error) {
|
|
139
|
+
if (!(typeof error === "object" && error !== null && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))) throw error;
|
|
140
|
+
const parent = dirname(current);
|
|
141
|
+
if (parent === current) return resolved;
|
|
142
|
+
missing.unshift(basename(current));
|
|
143
|
+
current = parent;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function createActionFusionExecutor(commandRunner: CommandRunner = defaultCommandRunner, onProgress?: ProgressReporter) {
|
|
149
|
+
const queueTails = new Map<string, Promise<void>>();
|
|
150
|
+
|
|
151
|
+
async function withQueue<T>(path: string, work: () => Promise<T>): Promise<T> {
|
|
152
|
+
const key = await canonicalQueueKey(path);
|
|
153
|
+
const previous = queueTails.get(key) ?? Promise.resolve();
|
|
154
|
+
let release!: () => void;
|
|
155
|
+
const owned = new Promise<void>((resolve) => { release = resolve; });
|
|
156
|
+
const tail = previous.then(() => owned);
|
|
157
|
+
queueTails.set(key, tail);
|
|
158
|
+
await previous;
|
|
159
|
+
try {
|
|
160
|
+
return await work();
|
|
161
|
+
} finally {
|
|
162
|
+
release();
|
|
163
|
+
if (queueTails.get(key) === tail) queueTails.delete(key);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return async function execute<TDetails>({
|
|
168
|
+
toolCallId,
|
|
169
|
+
absolutePath,
|
|
170
|
+
thenRun,
|
|
171
|
+
mutate,
|
|
172
|
+
signal,
|
|
173
|
+
ctx,
|
|
174
|
+
onUpdate,
|
|
175
|
+
finalizeMutation,
|
|
176
|
+
}: {
|
|
177
|
+
toolCallId: string;
|
|
178
|
+
absolutePath: string;
|
|
179
|
+
thenRun: ThenRunInput | undefined;
|
|
180
|
+
mutate: () => Promise<MutationResult<TDetails>>;
|
|
181
|
+
signal: AbortSignal | undefined;
|
|
182
|
+
ctx: ExtensionContext;
|
|
183
|
+
onUpdate?: AgentToolUpdateCallback<TDetails>;
|
|
184
|
+
finalizeMutation?: MutationFinalizer<TDetails>;
|
|
185
|
+
}): Promise<MutationResult<TDetails>> {
|
|
186
|
+
if (thenRun !== undefined) validateThenRun(thenRun);
|
|
187
|
+
let completedMutation: MutationResult<TDetails> | undefined;
|
|
188
|
+
const report = (command: ActionFusionProgress["command"], publication: PublicationStatus, freshness: Freshness, output = "") => {
|
|
189
|
+
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>);
|
|
196
|
+
};
|
|
197
|
+
report("waiting", "NOT_PUBLISHED", "unknown");
|
|
198
|
+
return withQueue(absolutePath, async () => {
|
|
199
|
+
try { signal?.throwIfAborted(); } catch (error) {
|
|
200
|
+
if (thenRun !== undefined) throw new ActionFusionError("mutation was cancelled before it started; the command was not run", { publication: "NOT_PUBLISHED", command: "cancelled", freshness: "unknown" }, { cause: error });
|
|
201
|
+
throw error;
|
|
202
|
+
}
|
|
203
|
+
let mutationResult: MutationResult<TDetails>;
|
|
204
|
+
try {
|
|
205
|
+
mutationResult = await mutate();
|
|
206
|
+
completedMutation = mutationResult;
|
|
207
|
+
} catch (error) {
|
|
208
|
+
const publication = error instanceof FileMutationError ? error.publication : "NOT_PUBLISHED";
|
|
209
|
+
if (thenRun !== undefined) {
|
|
210
|
+
throw new ActionFusionError(`mutation ${error instanceof FileMutationError ? error.stage : "failed"}; the command was not run`, { publication, command: "skipped", freshness: "unknown" }, { cause: error });
|
|
211
|
+
}
|
|
212
|
+
throw error;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const publication = mutationPublication(mutationResult);
|
|
216
|
+
if (thenRun === undefined) {
|
|
217
|
+
const finalized = finalizeMutation?.(mutationResult, true) ?? mutationResult;
|
|
218
|
+
return {
|
|
219
|
+
...finalized,
|
|
220
|
+
details: { ...(finalized.details as object ?? {}), actionFusion: { publication, command: "not_requested", freshness: "unknown" } satisfies ActionFusionDetails },
|
|
221
|
+
} as MutationResult<TDetails>;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
let baseline: string | undefined;
|
|
225
|
+
try {
|
|
226
|
+
baseline = await fileRevision(absolutePath);
|
|
227
|
+
signal?.throwIfAborted();
|
|
228
|
+
await assertUnchangedBeforeCommand(absolutePath, baseline);
|
|
229
|
+
signal?.throwIfAborted();
|
|
230
|
+
} catch (error) {
|
|
231
|
+
const freshness = baseline ? await readFreshness(absolutePath, baseline) : "unknown";
|
|
232
|
+
throw new ActionFusionError("mutation completed; the command was not run", { publication, command: signal?.aborted ? "cancelled" : "skipped", freshness }, { cause: error });
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
report("running", publication, "unchanged");
|
|
236
|
+
let output: string;
|
|
237
|
+
let commandError: unknown;
|
|
238
|
+
try {
|
|
239
|
+
output = await commandRunner(toolCallId, thenRun, signal, ctx, (partial) => {
|
|
240
|
+
const text = partial.content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
|
|
241
|
+
report("running", publication, "unknown", text);
|
|
242
|
+
});
|
|
243
|
+
} catch (error) {
|
|
244
|
+
commandError = error;
|
|
245
|
+
output = "";
|
|
246
|
+
}
|
|
247
|
+
const freshness = baseline ? await readFreshness(absolutePath, baseline) : "unknown";
|
|
248
|
+
if (commandError !== undefined) {
|
|
249
|
+
throw new ActionFusionError("mutation completed; then_run did not complete successfully", { publication, command: commandStatus(commandError, signal), freshness }, { cause: commandError });
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const actionFusion: ActionFusionDetails = { publication, command: "succeeded", freshness };
|
|
253
|
+
report("succeeded", publication, freshness, output);
|
|
254
|
+
const finalized = finalizeMutation?.(mutationResult, freshness === "unchanged") ?? mutationResult;
|
|
255
|
+
const commandText = freshness === "unchanged"
|
|
256
|
+
? (output ? `${THEN_RUN_SUCCEEDED}\n${output}` : THEN_RUN_SUCCEEDED)
|
|
257
|
+
: `${THEN_RUN_SUCCEEDED}\n${
|
|
258
|
+
finalizeMutation
|
|
259
|
+
? staleAnchorNotice(finalized)
|
|
260
|
+
: `${THEN_RUN_STALE} Re-read the file before further edits; previous anchors may no longer match.`
|
|
261
|
+
}${output ? `\n${output}` : ""}`;
|
|
262
|
+
return {
|
|
263
|
+
...finalized,
|
|
264
|
+
details: { ...(finalized.details as object ?? {}), actionFusion },
|
|
265
|
+
content: [...finalized.content, { type: "text", text: commandText }],
|
|
266
|
+
} as MutationResult<TDetails>;
|
|
267
|
+
}).catch((error: unknown) => {
|
|
268
|
+
report(error instanceof ActionFusionError ? error.command as ActionFusionProgress["command"] : "skipped",
|
|
269
|
+
error instanceof ActionFusionError ? error.publication : "NOT_PUBLISHED",
|
|
270
|
+
error instanceof ActionFusionError ? error.freshness : "unknown", errorText(error));
|
|
271
|
+
// A completed mutation remains successful; command failure belongs to its own card.
|
|
272
|
+
if (completedMutation && error instanceof ActionFusionError) {
|
|
273
|
+
const finalized = finalizeMutation?.(completedMutation, error.freshness === "unchanged") ?? completedMutation;
|
|
274
|
+
const anchorNotice = finalizeMutation && error.freshness !== "unchanged" ? `\n${staleAnchorNotice(finalized)}` : "";
|
|
275
|
+
return {
|
|
276
|
+
...finalized,
|
|
277
|
+
details: { ...(finalized.details as object ?? {}), actionFusion: { publication: error.publication, command: error.command, freshness: error.freshness } satisfies ActionFusionDetails },
|
|
278
|
+
content: [...finalized.content, { type: "text", text: `${error.message}${anchorNotice}` }],
|
|
279
|
+
} as MutationResult<TDetails>;
|
|
280
|
+
}
|
|
281
|
+
throw error;
|
|
282
|
+
});
|
|
283
|
+
};
|
|
284
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { test } from "node:test";
|
|
6
|
+
import { loadConfig } from "./config.ts";
|
|
7
|
+
|
|
8
|
+
test("actionFusion defaults off and can be enabled without changing other defaults", async () => {
|
|
9
|
+
const root = await mkdtemp(join(tmpdir(), "hashline-config-"));
|
|
10
|
+
try {
|
|
11
|
+
await mkdir(join(root, ".pi"));
|
|
12
|
+
await writeFile(join(root, ".pi", "settings.json"), JSON.stringify({ hashlineEdit: {} }));
|
|
13
|
+
assert.equal(loadConfig(root).actionFusion, false);
|
|
14
|
+
await writeFile(join(root, ".pi", "settings.json"), JSON.stringify({ hashlineEdit: { actionFusion: true } }));
|
|
15
|
+
const config = loadConfig(root);
|
|
16
|
+
assert.equal(config.actionFusion, true);
|
|
17
|
+
assert.equal(config.hashLen, 4);
|
|
18
|
+
assert.equal(config.shiftRadius, 15);
|
|
19
|
+
} finally {
|
|
20
|
+
await rm(root, { recursive: true, force: true });
|
|
21
|
+
}
|
|
22
|
+
});
|
package/src/pi/config.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Config loading: project `.pi/settings.json` replaces global, per-field `??`
|
|
3
|
+
* falls back to DEFAULT. Config field `hashlineEdit` (drop the `pi-` prefix,
|
|
4
|
+
* camelCase).
|
|
5
|
+
*
|
|
6
|
+
* @module pi-hashline-edit/pi
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
10
|
+
import * as fs from "node:fs";
|
|
11
|
+
import * as path from "node:path";
|
|
12
|
+
|
|
13
|
+
export interface HashlineEditConfig {
|
|
14
|
+
/** Master switch: when false the extension registers no tools — pi's built-ins remain. */
|
|
15
|
+
enabled: boolean;
|
|
16
|
+
/** Run an optional command after edit/replace succeeds. Disabled by default. */
|
|
17
|
+
actionFusion: boolean;
|
|
18
|
+
/** Line hash length (default 4). */
|
|
19
|
+
hashLen: number;
|
|
20
|
+
/** ±line radius for shifted-anchor recovery (default 15; 0 disables rescue). */
|
|
21
|
+
shiftRadius: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const DEFAULT_CONFIG: HashlineEditConfig = { enabled: true, actionFusion: false, hashLen: 4, shiftRadius: 15 };
|
|
25
|
+
|
|
26
|
+
/** Parse JSON directly without stripping comments (standard JSON forbids comments; on error fall back to default). */
|
|
27
|
+
function readSettings(filePath: string): Record<string, unknown> {
|
|
28
|
+
try {
|
|
29
|
+
if (!fs.existsSync(filePath)) return {};
|
|
30
|
+
return JSON.parse(fs.readFileSync(filePath, "utf-8")) as Record<string, unknown>;
|
|
31
|
+
} catch {
|
|
32
|
+
return {};
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Load config. The `hashlineEdit` in project `cwd/.pi/settings.json` replaces
|
|
38
|
+
* the global one wholesale; missing fields fall back to DEFAULT_CONFIG.
|
|
39
|
+
*/
|
|
40
|
+
export function loadConfig(cwd?: string): HashlineEditConfig {
|
|
41
|
+
const globalSettings = readSettings(path.join(getAgentDir(), "settings.json"));
|
|
42
|
+
const projectSettings = cwd ? readSettings(path.join(cwd, ".pi", "settings.json")) : {};
|
|
43
|
+
const raw = (projectSettings.hashlineEdit ?? globalSettings.hashlineEdit ?? {}) as Record<string, unknown>;
|
|
44
|
+
return {
|
|
45
|
+
enabled: typeof raw.enabled === "boolean" ? raw.enabled : DEFAULT_CONFIG.enabled,
|
|
46
|
+
actionFusion: raw.actionFusion === true,
|
|
47
|
+
hashLen:
|
|
48
|
+
typeof raw.hashLen === "number" && raw.hashLen >= 2 && raw.hashLen <= 8
|
|
49
|
+
? raw.hashLen
|
|
50
|
+
: DEFAULT_CONFIG.hashLen,
|
|
51
|
+
shiftRadius:
|
|
52
|
+
typeof raw.shiftRadius === "number" && raw.shiftRadius >= 0 && raw.shiftRadius <= 100
|
|
53
|
+
? raw.shiftRadius
|
|
54
|
+
: DEFAULT_CONFIG.shiftRadius,
|
|
55
|
+
};
|
|
56
|
+
}
|