@leolastforce/chalice-hashline-edit 0.0.0-stage → 4.4.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 +153 -2
- package/index.ts +282 -0
- package/package.json +79 -4
- package/prompts/find-guidelines.md +2 -0
- package/prompts/find-snippet.md +1 -0
- package/prompts/find.md +1 -0
- package/prompts/grep-guidelines.md +2 -0
- package/prompts/grep-snippet.md +1 -0
- package/prompts/grep.md +1 -0
- package/prompts/insert-guidelines.md +1 -0
- package/prompts/insert-snippet.md +1 -0
- package/prompts/insert.md +1 -0
- package/prompts/read-guidelines.md +2 -0
- package/prompts/read-snippet.md +1 -0
- package/prompts/read.md +1 -0
- package/prompts/replace-guidelines.md +4 -0
- package/prompts/replace-snippet.md +1 -0
- package/prompts/replace.md +1 -0
- package/prompts/undo-last-change-guidelines.md +1 -0
- package/prompts/undo-last-change-snippet.md +1 -0
- package/prompts/undo-last-change.md +1 -0
- package/src/anchor-registry.ts +977 -0
- package/src/auto-read-all-state.ts +27 -0
- package/src/auto-read-all.ts +477 -0
- package/src/batch.ts +767 -0
- package/src/commit.ts +137 -0
- package/src/config-ui.ts +212 -0
- package/src/config.ts +235 -0
- package/src/constants.ts +26 -0
- package/src/edit-common.ts +206 -0
- package/src/file-kind.ts +191 -0
- package/src/file-reader.ts +135 -0
- package/src/find.ts +244 -0
- package/src/fs-write.ts +231 -0
- package/src/glob.ts +186 -0
- package/src/grep.ts +690 -0
- package/src/hash-store/cache.ts +18 -0
- package/src/hash-store/retry.ts +44 -0
- package/src/hash-store/validation.ts +62 -0
- package/src/hash-store.ts +609 -0
- package/src/hashline/alphabet.ts +21 -0
- package/src/hashline/anchor-table.json +1 -0
- package/src/hashline/apply.ts +297 -0
- package/src/hashline/hash.ts +119 -0
- package/src/hashline/hasher.ts +47 -0
- package/src/hashline/index.ts +50 -0
- package/src/hashline/parse.ts +84 -0
- package/src/hashline/resolve.ts +373 -0
- package/src/insert.ts +258 -0
- package/src/normalize.ts +27 -0
- package/src/paths.ts +56 -0
- package/src/payload-contract.ts +133 -0
- package/src/prompts.ts +13 -0
- package/src/read.ts +286 -0
- package/src/replace-diff.ts +610 -0
- package/src/replace-render.ts +390 -0
- package/src/replace-response.ts +166 -0
- package/src/replace-undo.ts +270 -0
- package/src/replace.ts +318 -0
- package/src/served.ts +36 -0
- package/src/utils.ts +387 -0
- package/src/validation.ts +45 -0
- package/src/write-hook.ts +53 -0
package/src/commit.ts
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import type { PipelineResult } from "./replace";
|
|
3
|
+
import { abortIf, assertByteLimit, errCode, splitLines } from "./utils";
|
|
4
|
+
import { buildChanged, buildNoop, type RMeta, type TResult } from "./replace-response";
|
|
5
|
+
import { saveUndo } from "./replace-undo";
|
|
6
|
+
import { getDiffContextLines } from "./config";
|
|
7
|
+
import { safeSnapId } from "./file-reader";
|
|
8
|
+
import { writeAtomic } from "./fs-write";
|
|
9
|
+
import { servedHashesFromDiff, serveRows } from "./served";
|
|
10
|
+
import { lineHashes } from "./hashline";
|
|
11
|
+
import { spanForEdit } from "./replace";
|
|
12
|
+
import { restoreEndings, stripBOM, toLF } from "./normalize";
|
|
13
|
+
export interface CommitMeta {
|
|
14
|
+
editAnchors?: [string, string];
|
|
15
|
+
path: string;
|
|
16
|
+
absolutePath: string;
|
|
17
|
+
mutationTargetPath: string;
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
verb?: string;
|
|
20
|
+
noopNoun?: string;
|
|
21
|
+
prefixWarnings?: string[];
|
|
22
|
+
foldedAnchorLines?: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function commitEdit(pipe: PipelineResult, meta: CommitMeta): Promise<TResult> {
|
|
26
|
+
const { path, absolutePath, mutationTargetPath, signal } = meta;
|
|
27
|
+
const warnings = [...(meta.prefixWarnings ?? []), ...pipe.warnings];
|
|
28
|
+
const editsAttempted = 1;
|
|
29
|
+
|
|
30
|
+
if (pipe.result === pipe.originalNormalized) {
|
|
31
|
+
const noopSnapshotId = await safeSnapId(absolutePath, "noop edit");
|
|
32
|
+
return buildNoop(
|
|
33
|
+
{
|
|
34
|
+
path,
|
|
35
|
+
noopEdit: pipe.noopEdit,
|
|
36
|
+
snapshotId: noopSnapshotId,
|
|
37
|
+
editMeta: {
|
|
38
|
+
editsAttempted,
|
|
39
|
+
noopEditsCount: pipe.noopEdit ? 1 : 0,
|
|
40
|
+
addedLines: 0,
|
|
41
|
+
removedLines: 0,
|
|
42
|
+
},
|
|
43
|
+
warnings,
|
|
44
|
+
},
|
|
45
|
+
meta.noopNoun,
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const finalFileBytes = pipe.bom + restoreEndings(pipe.result, pipe.originalEnding);
|
|
50
|
+
assertByteLimit(finalFileBytes, path);
|
|
51
|
+
|
|
52
|
+
if (pipe.hadUtf8DecodeErrors) {
|
|
53
|
+
warnings.push(
|
|
54
|
+
"Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.",
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
abortIf(signal);
|
|
59
|
+
let currentRaw: string | undefined;
|
|
60
|
+
try {
|
|
61
|
+
currentRaw = await readFile(mutationTargetPath, "utf-8");
|
|
62
|
+
} catch (error) {
|
|
63
|
+
const code = errCode(error);
|
|
64
|
+
if (code === "ENOENT") currentRaw = undefined;
|
|
65
|
+
else if (code === "EACCES" || code === "EPERM") throw new Error(`[E_ACCESS] File is not readable: ${path}`);
|
|
66
|
+
else if (code === "ELOOP") throw new Error(`[E_ACCESS] Too many symbolic links while resolving: ${path}`);
|
|
67
|
+
else throw error;
|
|
68
|
+
}
|
|
69
|
+
if (currentRaw === undefined) {
|
|
70
|
+
throw new Error(`[E_OP_ABORTED] Edit aborted: the file was deleted after the edit started.`);
|
|
71
|
+
}
|
|
72
|
+
if (toLF(stripBOM(currentRaw).text) !== pipe.originalNormalized) {
|
|
73
|
+
throw new Error(`[E_OP_ABORTED] Edit aborted: the file changed after the edit started. Call read for fresh anchors and retry.`);
|
|
74
|
+
}
|
|
75
|
+
const undo = await saveUndo(mutationTargetPath, {
|
|
76
|
+
content: pipe.originalNormalized,
|
|
77
|
+
bom: pipe.bom,
|
|
78
|
+
originalEnding: pipe.originalEnding,
|
|
79
|
+
hashes: pipe.originalHashes,
|
|
80
|
+
resultContent: pipe.result,
|
|
81
|
+
});
|
|
82
|
+
if (!undo.persisted) {
|
|
83
|
+
throw new Error(
|
|
84
|
+
`[E_UNDO_UNAVAILABLE] Could not persist undo history for ${path}.`
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
abortIf(signal);
|
|
89
|
+
await writeAtomic(
|
|
90
|
+
absolutePath,
|
|
91
|
+
finalFileBytes,
|
|
92
|
+
pipe.identity,
|
|
93
|
+
);
|
|
94
|
+
} catch (error) {
|
|
95
|
+
await undo.restore();
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
const updatedSnapshotId = await safeSnapId(absolutePath, "post-edit");
|
|
99
|
+
|
|
100
|
+
const editMeta: RMeta = {
|
|
101
|
+
editsAttempted,
|
|
102
|
+
noopEditsCount: pipe.noopEdit ? 1 : 0,
|
|
103
|
+
firstChangedLine: pipe.firstChangedLine,
|
|
104
|
+
lastChangedLine: pipe.lastChangedLine,
|
|
105
|
+
addedLines: Math.max(0, pipe.totalAddedLines - (meta.foldedAnchorLines ?? 0)),
|
|
106
|
+
removedLines: pipe.totalRemovedLines,
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const span = meta.editAnchors ? spanForEdit(pipe.originalHashes, meta.editAnchors[0], meta.editAnchors[1], pipe.result) : undefined;
|
|
110
|
+
let resultHashes: string[];
|
|
111
|
+
try {
|
|
112
|
+
resultHashes = await lineHashes(pipe.result, mutationTargetPath, {
|
|
113
|
+
content: pipe.originalNormalized,
|
|
114
|
+
hashes: pipe.originalHashes,
|
|
115
|
+
spans: span ? [span] : undefined,
|
|
116
|
+
});
|
|
117
|
+
} catch (error) {
|
|
118
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
119
|
+
throw new Error(`${detail} File was written; anchor finalization failed. One undo reverts. Call read for fresh anchors.`);
|
|
120
|
+
}
|
|
121
|
+
const successInput = {
|
|
122
|
+
path,
|
|
123
|
+
originalNormalized: pipe.originalNormalized,
|
|
124
|
+
originalHashes: pipe.originalHashes,
|
|
125
|
+
result: pipe.result,
|
|
126
|
+
resultHashes,
|
|
127
|
+
warnings,
|
|
128
|
+
snapshotId: updatedSnapshotId,
|
|
129
|
+
editMeta,
|
|
130
|
+
...(span ? { spans: [span] } : {}),
|
|
131
|
+
};
|
|
132
|
+
const changed = buildChanged(successInput, meta.verb, await getDiffContextLines());
|
|
133
|
+
if (changed.details.diff) {
|
|
134
|
+
serveRows(mutationTargetPath, resultHashes, splitLines(pipe.result), servedHashesFromDiff(changed.details.diff));
|
|
135
|
+
}
|
|
136
|
+
return changed;
|
|
137
|
+
}
|
package/src/config-ui.ts
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { Key, matchesKey, visibleWidth } from "@earendil-works/pi-tui";
|
|
2
|
+
import type { Theme } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { readConfig, type Config } from "./config";
|
|
4
|
+
|
|
5
|
+
export type ConfigToggleKey = "autoRead" | "autoReadAll" | "autoReadAllIgnore" | "anchorGrepEnabled" | "requirePath" | "strictInput" | "diffContextLines";
|
|
6
|
+
|
|
7
|
+
export interface ConfigRow {
|
|
8
|
+
key: ConfigToggleKey;
|
|
9
|
+
label: string;
|
|
10
|
+
hint: string;
|
|
11
|
+
enabled: boolean;
|
|
12
|
+
mode?: string;
|
|
13
|
+
cycle?: string[];
|
|
14
|
+
value?: number;
|
|
15
|
+
folders?: string[];
|
|
16
|
+
disabled?: boolean;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function configRows(config: Config): ConfigRow[] {
|
|
20
|
+
return [
|
|
21
|
+
{ key: "autoRead", label: "Auto-read", hint: "Anchors after write + post-edit diffs", enabled: config.autoRead !== false },
|
|
22
|
+
{ key: "autoReadAll", label: "Auto-read all", hint: "Attach files on the first turn: off, on, git (git repos only)", enabled: (config.autoReadAll ?? "off") !== "off", mode: config.autoReadAll ?? "off", cycle: ["off", "on", "git"] },
|
|
23
|
+
{ key: "autoReadAllIgnore", label: "Ignore folders/files", hint: "Extra folders, files, or globs skipped by auto-read all (comma-separated)", enabled: (config.autoReadAllIgnore ?? []).length > 0, folders: config.autoReadAllIgnore ?? [] },
|
|
24
|
+
{ key: "diffContextLines", label: "Diff context", hint: "Surrounding lines in post-edit diffs (needs Auto-read)", enabled: config.autoRead !== false, value: config.diffContextLines ?? 1, disabled: config.autoRead === false },
|
|
25
|
+
{ key: "anchorGrepEnabled", label: "Anchor grep", hint: "anchor_grep tool (builtin grep off while on)", enabled: config.anchorGrepEnabled === true },
|
|
26
|
+
{ key: "requirePath", label: "Require path", hint: "replace + insert need path (RPC visibility)", enabled: config.requirePath === true },
|
|
27
|
+
{ key: "strictInput", label: "Strict input", hint: "Reject auto-fixable slips instead of warnings", enabled: config.strictInput === true },
|
|
28
|
+
];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function padRow(theme: Theme, innerWidth: number, content: string): string {
|
|
32
|
+
const padded = content + " ".repeat(Math.max(0, innerWidth - visibleWidth(content)));
|
|
33
|
+
return theme.fg("border", "│") + padded + theme.fg("border", "│");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function modeBox(theme: Theme, mode: string): string {
|
|
37
|
+
if (mode === "off") return theme.fg("dim", `[${mode}]`);
|
|
38
|
+
if (mode === "strict") return theme.fg("accent", `[${mode}]`);
|
|
39
|
+
return theme.fg("success", `[${mode}]`);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function numberBox(theme: Theme, value: number, disabled?: boolean): string {
|
|
43
|
+
if (disabled) return theme.fg("dim", `[${value}]`);
|
|
44
|
+
return theme.fg("accent", `[${value}]`);
|
|
45
|
+
}
|
|
46
|
+
function ignoreBox(theme: Theme, folders: string[]): string {
|
|
47
|
+
return theme.fg("accent", `[${folders.length}]`);
|
|
48
|
+
}
|
|
49
|
+
function formatIgnoreFolders(folders: string[]): string {
|
|
50
|
+
if (folders.length === 0) return "(empty)";
|
|
51
|
+
const joined = folders.join(", ");
|
|
52
|
+
return joined.length > 40 ? `${joined.slice(0, 37)}...` : joined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export class HashlineConfigOverlay {
|
|
56
|
+
private rows: ConfigRow[];
|
|
57
|
+
private selected = 0;
|
|
58
|
+
private editingIgnore = false;
|
|
59
|
+
private editBuffer = "";
|
|
60
|
+
|
|
61
|
+
constructor(private readonly opts: { tui: { requestRender(force?: boolean): void }; theme: Theme; done: () => void; onToggle: (key: ConfigToggleKey, delta?: number, value?: string) => Promise<void> }) {
|
|
62
|
+
this.rows = [];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async load(): Promise<void> {
|
|
66
|
+
this.rows = configRows(await readConfig());
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
private runToggle(row: ConfigRow, delta?: number, value?: string): void {
|
|
70
|
+
this.opts.tui.requestRender(true);
|
|
71
|
+
void this.opts.onToggle(row.key, delta, value).then(async () => {
|
|
72
|
+
this.rows = configRows(await readConfig());
|
|
73
|
+
this.editingIgnore = false;
|
|
74
|
+
this.opts.tui.requestRender(true);
|
|
75
|
+
}).catch((error: unknown) => {
|
|
76
|
+
console.error("Failed to toggle hashline setting:", error);
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
private startIgnoreEdit(row: ConfigRow): void {
|
|
80
|
+
this.editingIgnore = true;
|
|
81
|
+
this.editBuffer = (row.folders ?? []).join(", ");
|
|
82
|
+
this.opts.tui.requestRender(true);
|
|
83
|
+
}
|
|
84
|
+
private commitIgnoreEdit(): void {
|
|
85
|
+
const row = this.rows[this.selected];
|
|
86
|
+
if (!row || row.key !== "autoReadAllIgnore") {
|
|
87
|
+
this.editingIgnore = false;
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
const value = this.editBuffer;
|
|
91
|
+
this.editingIgnore = false;
|
|
92
|
+
this.runToggle(row, undefined, value);
|
|
93
|
+
}
|
|
94
|
+
private cancelIgnoreEdit(): void {
|
|
95
|
+
this.editingIgnore = false;
|
|
96
|
+
this.opts.tui.requestRender(true);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
private toggleSelected(): void {
|
|
100
|
+
const row = this.rows[this.selected];
|
|
101
|
+
if (!row || row.disabled) return;
|
|
102
|
+
if (row.key === "autoReadAllIgnore") {
|
|
103
|
+
this.startIgnoreEdit(row);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (row.value !== undefined) {
|
|
107
|
+
row.value += 1;
|
|
108
|
+
this.runToggle(row, 1);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
if (row.cycle && row.mode !== undefined) {
|
|
112
|
+
const next = row.cycle[(row.cycle.indexOf(row.mode) + 1) % row.cycle.length] ?? row.cycle[0];
|
|
113
|
+
if (next === undefined) return;
|
|
114
|
+
row.mode = next;
|
|
115
|
+
row.enabled = next !== "off";
|
|
116
|
+
} else {
|
|
117
|
+
row.enabled = !row.enabled;
|
|
118
|
+
}
|
|
119
|
+
this.runToggle(row);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
private adjustSelected(delta: number): void {
|
|
123
|
+
const row = this.rows[this.selected];
|
|
124
|
+
if (!row || row.disabled || row.value === undefined) return;
|
|
125
|
+
row.value += delta;
|
|
126
|
+
this.runToggle(row, delta);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
handleInput(data: string): void {
|
|
130
|
+
if (this.editingIgnore) {
|
|
131
|
+
if (matchesKey(data, Key.escape) || data === "\x1b") {
|
|
132
|
+
this.cancelIgnoreEdit();
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
if (matchesKey(data, Key.enter) || data === "\r" || data === "\n") {
|
|
136
|
+
this.commitIgnoreEdit();
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
if (data === "\x7f" || data === "\b" || data === "\x08") {
|
|
140
|
+
this.editBuffer = this.editBuffer.slice(0, -1);
|
|
141
|
+
this.opts.tui.requestRender(true);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (data === "\x15") {
|
|
145
|
+
this.editBuffer = "";
|
|
146
|
+
this.opts.tui.requestRender(true);
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
if (data.length >= 1 && [...data].every((ch) => ch.charCodeAt(0) >= 32 && ch !== "\x7f")) {
|
|
150
|
+
this.editBuffer += data;
|
|
151
|
+
this.opts.tui.requestRender(true);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
if (matchesKey(data, Key.up) || data === "k") {
|
|
157
|
+
this.selected = (this.selected + this.rows.length - 1) % this.rows.length;
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (matchesKey(data, Key.down) || data === "j") {
|
|
161
|
+
this.selected = (this.selected + 1) % this.rows.length;
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
if (matchesKey(data, Key.right) || data === "+" || data === "=") {
|
|
165
|
+
this.adjustSelected(1);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (matchesKey(data, Key.left) || data === "-" || data === "_") {
|
|
169
|
+
this.adjustSelected(-1);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
if (matchesKey(data, Key.space) || matchesKey(data, Key.enter) || data === " " || data === "\r" || data === "\n") {
|
|
173
|
+
this.toggleSelected();
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
const row = this.rows[this.selected];
|
|
177
|
+
if ((data === "e" || data === "E") && row && row.key === "autoReadAllIgnore" && !row.disabled) {
|
|
178
|
+
this.startIgnoreEdit(row);
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
if (matchesKey(data, Key.escape) || data === "q") {
|
|
182
|
+
this.opts.done();
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
invalidate(): void {
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
render(width: number): string[] {
|
|
190
|
+
const theme = this.opts.theme;
|
|
191
|
+
const innerWidth = width - 2;
|
|
192
|
+
const lines: string[] = [];
|
|
193
|
+
lines.push(theme.fg("border", `╭${"─".repeat(innerWidth)}╮`));
|
|
194
|
+
lines.push(padRow(theme, innerWidth, ` ${theme.fg("accent", theme.bold("Hashline Config"))}`));
|
|
195
|
+
lines.push(theme.fg("border", `├${"─".repeat(innerWidth)}┤`));
|
|
196
|
+
this.rows.forEach((row, index) => {
|
|
197
|
+
const cursor = index === this.selected ? theme.fg("accent", "> ") : " ";
|
|
198
|
+
const box = row.folders !== undefined ? ignoreBox(theme, row.folders) : row.value !== undefined ? numberBox(theme, row.value, row.disabled) : row.mode !== undefined ? modeBox(theme, row.mode) : row.enabled ? theme.fg("success", "[x]") : theme.fg("dim", "[ ]");
|
|
199
|
+
const label = row.disabled ? theme.fg("dim", row.label) : index === this.selected ? theme.fg("accent", theme.bold(row.label)) : row.label;
|
|
200
|
+
const suffix = row.folders !== undefined ? ` — ${row.hint}: ${formatIgnoreFolders(row.folders)}` : ` — ${row.hint}`;
|
|
201
|
+
lines.push(padRow(theme, innerWidth, `${cursor}${box} ${label} ${theme.fg("dim", suffix)}`));
|
|
202
|
+
if (row.key === "autoReadAllIgnore" && index === this.selected && this.editingIgnore) {
|
|
203
|
+
lines.push(padRow(theme, innerWidth, ` ${theme.fg("accent", "edit:")} ${this.editBuffer}█ ${theme.fg("dim", "(Enter save · Esc cancel · Ctrl-U clear)")}`));
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
lines.push(theme.fg("border", `├${"─".repeat(innerWidth)}┤`));
|
|
207
|
+
const footer = this.editingIgnore ? " type to edit · Enter save · Esc cancel" : " ↑↓ navigate · space toggle · ←/→ or -/+ adjust · e edit list · q close";
|
|
208
|
+
lines.push(padRow(theme, innerWidth, theme.fg("dim", footer)));
|
|
209
|
+
lines.push(theme.fg("border", `╰${"─".repeat(innerWidth)}╯`));
|
|
210
|
+
return lines;
|
|
211
|
+
}
|
|
212
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { mkdir, readFile, rename, rm, stat } from "node:fs/promises";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { configPath } from "./paths";
|
|
4
|
+
import { errCode, isRec } from "./utils";
|
|
5
|
+
import { writeAtomic } from "./fs-write";
|
|
6
|
+
export type AutoReadAllMode = "off" | "on" | "git";
|
|
7
|
+
const AUTO_READ_ALL_MODES: AutoReadAllMode[] = ["off", "on", "git"];
|
|
8
|
+
|
|
9
|
+
export const DEFAULT_DIFF_CONTEXT_LINES = 1;
|
|
10
|
+
export const MIN_DIFF_CONTEXT_LINES = 0;
|
|
11
|
+
export const MAX_DIFF_CONTEXT_LINES = 10;
|
|
12
|
+
|
|
13
|
+
export interface Config {
|
|
14
|
+
autoRead: boolean;
|
|
15
|
+
anchorGrepEnabled: boolean;
|
|
16
|
+
autoReadAll?: AutoReadAllMode;
|
|
17
|
+
autoReadAllIgnore?: string[];
|
|
18
|
+
requirePath?: boolean;
|
|
19
|
+
strictInput?: boolean;
|
|
20
|
+
diffContextLines?: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const DEFAULT_CONFIG: Config = {
|
|
24
|
+
autoRead: true,
|
|
25
|
+
anchorGrepEnabled: true,
|
|
26
|
+
autoReadAll: "off",
|
|
27
|
+
autoReadAllIgnore: [],
|
|
28
|
+
requirePath: false,
|
|
29
|
+
strictInput: false,
|
|
30
|
+
diffContextLines: DEFAULT_DIFF_CONTEXT_LINES
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
function parseAutoReadAllMode(value: unknown): AutoReadAllMode {
|
|
34
|
+
if (value === "off" || value === "on" || value === "git") return value;
|
|
35
|
+
if (value === true) return "on";
|
|
36
|
+
if (value === false) return "off";
|
|
37
|
+
return DEFAULT_CONFIG.autoReadAll ?? "off";
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function normalizeAutoReadAllIgnoreEntry(entry: string): string {
|
|
41
|
+
return entry.trim().replace(/\\/g, "/").replace(/^\/+|\/+$/g, "").replace(/\/{2,}/g, "/");
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function parseAutoReadAllIgnore(value: unknown): string[] {
|
|
45
|
+
const raw = typeof value === "string" ? value.split(",") : Array.isArray(value) ? value : [];
|
|
46
|
+
const seen = new Set<string>();
|
|
47
|
+
const out: string[] = [];
|
|
48
|
+
for (const item of raw) {
|
|
49
|
+
if (typeof item !== "string") continue;
|
|
50
|
+
const cleaned = normalizeAutoReadAllIgnoreEntry(item);
|
|
51
|
+
if (cleaned.length === 0) continue;
|
|
52
|
+
const lower = cleaned.toLowerCase();
|
|
53
|
+
if (seen.has(lower)) continue;
|
|
54
|
+
seen.add(lower);
|
|
55
|
+
out.push(cleaned);
|
|
56
|
+
}
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function normalizeDiffContextLines(value: unknown): number {
|
|
61
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return DEFAULT_DIFF_CONTEXT_LINES;
|
|
62
|
+
const floored = Math.floor(value);
|
|
63
|
+
if (floored < MIN_DIFF_CONTEXT_LINES) return MIN_DIFF_CONTEXT_LINES;
|
|
64
|
+
if (floored > MAX_DIFF_CONTEXT_LINES) return MAX_DIFF_CONTEXT_LINES;
|
|
65
|
+
return floored;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function parseConfig(content: string): Config {
|
|
69
|
+
const parsed = JSON.parse(content) as unknown;
|
|
70
|
+
if (!isRec(parsed) || (parsed.autoRead !== undefined && typeof parsed.autoRead !== "boolean")) {
|
|
71
|
+
throw new Error("config.json must be an object with a boolean autoRead field");
|
|
72
|
+
}
|
|
73
|
+
const autoRead = parsed.autoRead;
|
|
74
|
+
const anchorGrepEnabled = parsed.anchorGrepEnabled;
|
|
75
|
+
const autoReadAll = parsed.autoReadAll;
|
|
76
|
+
const requirePath = parsed.requirePath;
|
|
77
|
+
const strictInput = parsed.strictInput;
|
|
78
|
+
const diffContextLines = parsed.diffContextLines;
|
|
79
|
+
const autoReadAllIgnore = parsed.autoReadAllIgnore;
|
|
80
|
+
return {
|
|
81
|
+
autoRead: typeof autoRead === "boolean" ? autoRead : DEFAULT_CONFIG.autoRead,
|
|
82
|
+
anchorGrepEnabled: typeof anchorGrepEnabled === "boolean" ? anchorGrepEnabled : DEFAULT_CONFIG.anchorGrepEnabled,
|
|
83
|
+
autoReadAll: parseAutoReadAllMode(autoReadAll),
|
|
84
|
+
requirePath: typeof requirePath === "boolean" ? requirePath : DEFAULT_CONFIG.requirePath,
|
|
85
|
+
strictInput: typeof strictInput === "boolean" ? strictInput : DEFAULT_CONFIG.strictInput,
|
|
86
|
+
diffContextLines: normalizeDiffContextLines(diffContextLines),
|
|
87
|
+
autoReadAllIgnore: parseAutoReadAllIgnore(autoReadAllIgnore),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function loadConfigFile(): Promise<{ config: Config; corrupted: boolean }> {
|
|
92
|
+
let content: string;
|
|
93
|
+
try {
|
|
94
|
+
content = await readFile(configPath(), "utf-8");
|
|
95
|
+
} catch (error: unknown) {
|
|
96
|
+
if (errCode(error) === "ENOENT") return { config: { ...DEFAULT_CONFIG }, corrupted: false };
|
|
97
|
+
console.error("Config file unreadable, using defaults:", error);
|
|
98
|
+
return { config: { ...DEFAULT_CONFIG }, corrupted: false };
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
return { config: parseConfig(content), corrupted: false };
|
|
102
|
+
} catch (error: unknown) {
|
|
103
|
+
try {
|
|
104
|
+
const badPath = configPath();
|
|
105
|
+
await rename(badPath, `${badPath}.corrupt-${Date.now()}-${process.pid}-${Math.random().toString(36).slice(2)}`);
|
|
106
|
+
} catch { }
|
|
107
|
+
console.error("Config file corrupted, quarantined, using defaults:", error);
|
|
108
|
+
return { config: { ...DEFAULT_CONFIG }, corrupted: true };
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
export async function readConfig(): Promise<Config> {
|
|
112
|
+
return (await loadConfigFile()).config;
|
|
113
|
+
}
|
|
114
|
+
export async function readConfigWithStatus(): Promise<{ config: Config; corrupted: boolean }> {
|
|
115
|
+
return loadConfigFile();
|
|
116
|
+
}
|
|
117
|
+
const CONFIG_LOCK_DELAY_MS = 25;
|
|
118
|
+
const CONFIG_LOCK_STALE_MS = 5000;
|
|
119
|
+
const CONFIG_LOCK_RETRIES = Math.ceil(CONFIG_LOCK_STALE_MS / CONFIG_LOCK_DELAY_MS) * 2;
|
|
120
|
+
|
|
121
|
+
interface ConfigLock {
|
|
122
|
+
path: string;
|
|
123
|
+
dev: number;
|
|
124
|
+
ino: number;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function acquireConfigLock(lockPath: string): Promise<ConfigLock> {
|
|
128
|
+
try {
|
|
129
|
+
await mkdir(dirname(lockPath), { recursive: true, mode: 0o700 });
|
|
130
|
+
} catch { }
|
|
131
|
+
for (let attempt = 0; attempt < CONFIG_LOCK_RETRIES; attempt++) {
|
|
132
|
+
try {
|
|
133
|
+
await mkdir(lockPath, { mode: 0o700 });
|
|
134
|
+
} catch (error) {
|
|
135
|
+
if (errCode(error) === "ENOENT") {
|
|
136
|
+
try {
|
|
137
|
+
await mkdir(dirname(lockPath), { recursive: true, mode: 0o700 });
|
|
138
|
+
} catch { }
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (errCode(error) !== "EEXIST") throw error;
|
|
142
|
+
try {
|
|
143
|
+
const st = await stat(lockPath);
|
|
144
|
+
if (Date.now() - st.mtimeMs > CONFIG_LOCK_STALE_MS) {
|
|
145
|
+
await rm(lockPath, { recursive: true, force: true });
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
} catch { }
|
|
149
|
+
await new Promise<void>((r) => setTimeout(r, CONFIG_LOCK_DELAY_MS));
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
try {
|
|
153
|
+
const st = await stat(lockPath);
|
|
154
|
+
return { path: lockPath, dev: st.dev, ino: st.ino };
|
|
155
|
+
} catch (error) {
|
|
156
|
+
if (errCode(error) !== "ENOENT") {
|
|
157
|
+
try {
|
|
158
|
+
await rm(lockPath, { recursive: true, force: true });
|
|
159
|
+
} catch { }
|
|
160
|
+
}
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
throw new Error(`[E_ACCESS] Could not acquire config lock: ${lockPath}`);
|
|
165
|
+
}
|
|
166
|
+
async function releaseConfigLock(lock: ConfigLock): Promise<void> {
|
|
167
|
+
try {
|
|
168
|
+
const st = await stat(lock.path);
|
|
169
|
+
if (st.dev !== lock.dev || st.ino !== lock.ino) return;
|
|
170
|
+
} catch {
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
try {
|
|
174
|
+
await rm(lock.path, { recursive: true, force: true });
|
|
175
|
+
} catch { }
|
|
176
|
+
}
|
|
177
|
+
export async function updateConfig(mut: (config: Config) => void): Promise<Config> {
|
|
178
|
+
const cfgPath = configPath();
|
|
179
|
+
const lockPath = `${cfgPath}.lock`;
|
|
180
|
+
const lock = await acquireConfigLock(lockPath);
|
|
181
|
+
try {
|
|
182
|
+
const config = await readConfig();
|
|
183
|
+
mut(config);
|
|
184
|
+
await writeConfig(config);
|
|
185
|
+
return config;
|
|
186
|
+
} finally {
|
|
187
|
+
await releaseConfigLock(lock);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
export async function writeConfig(config: Config): Promise<void> {
|
|
191
|
+
await writeAtomic(configPath(), JSON.stringify(config, null, 2));
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
type ToggleKey = "autoRead" | "anchorGrepEnabled" | "requirePath" | "strictInput";
|
|
196
|
+
|
|
197
|
+
async function toggleFlag(key: ToggleKey): Promise<boolean> {
|
|
198
|
+
const config = await updateConfig((c) => { c[key] = !(c[key] === true); });
|
|
199
|
+
return config[key] === true;
|
|
200
|
+
}
|
|
201
|
+
export const toggleAutoRead = (): Promise<boolean> => toggleFlag("autoRead");
|
|
202
|
+
export const toggleAnchorGrep = (): Promise<boolean> => toggleFlag("anchorGrepEnabled");
|
|
203
|
+
export async function cycleAutoReadAllMode(): Promise<AutoReadAllMode> {
|
|
204
|
+
let next: AutoReadAllMode = "off";
|
|
205
|
+
await updateConfig((c) => {
|
|
206
|
+
const current = c.autoReadAll ?? "off";
|
|
207
|
+
next = AUTO_READ_ALL_MODES[(AUTO_READ_ALL_MODES.indexOf(current) + 1) % AUTO_READ_ALL_MODES.length] ?? "off";
|
|
208
|
+
c.autoReadAll = next;
|
|
209
|
+
});
|
|
210
|
+
return next;
|
|
211
|
+
}
|
|
212
|
+
export const toggleRequirePath = (): Promise<boolean> => toggleFlag("requirePath");
|
|
213
|
+
export const toggleStrictInput = (): Promise<boolean> => toggleFlag("strictInput");
|
|
214
|
+
export async function getDiffContextLines(): Promise<number> {
|
|
215
|
+
return normalizeDiffContextLines((await readConfig()).diffContextLines);
|
|
216
|
+
}
|
|
217
|
+
export async function adjustDiffContextLines(delta: number): Promise<number> {
|
|
218
|
+
let next = DEFAULT_DIFF_CONTEXT_LINES;
|
|
219
|
+
await updateConfig((c) => {
|
|
220
|
+
next = normalizeDiffContextLines(normalizeDiffContextLines(c.diffContextLines) + delta);
|
|
221
|
+
c.diffContextLines = next;
|
|
222
|
+
});
|
|
223
|
+
return next;
|
|
224
|
+
}
|
|
225
|
+
export async function setAutoReadAllIgnore(dirs: string[]): Promise<string[]> {
|
|
226
|
+
let next: string[] = [];
|
|
227
|
+
await updateConfig((c) => {
|
|
228
|
+
next = parseAutoReadAllIgnore(dirs);
|
|
229
|
+
c.autoReadAllIgnore = next;
|
|
230
|
+
});
|
|
231
|
+
return next;
|
|
232
|
+
}
|
|
233
|
+
export async function setAutoReadAllIgnoreFromText(text: string): Promise<string[]> {
|
|
234
|
+
return setAutoReadAllIgnore(text.split(","));
|
|
235
|
+
}
|
package/src/constants.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export const SNIFF_BYTES = 8192;
|
|
2
|
+
export const MAX_BYTES = 100 * 1024 * 1024;
|
|
3
|
+
export const MAX_RANGE_STALE_LINES = 100;
|
|
4
|
+
export const MAX_OVERSIZED_WARNING_LINES = 100;
|
|
5
|
+
|
|
6
|
+
export const MAX_HASH_SOURCE_BYTES = 500;
|
|
7
|
+
export const MAX_GREP_LINE_BYTES = 500;
|
|
8
|
+
|
|
9
|
+
export const MAX_DIFF_INPUT_BYTES = 1024 * 1024;
|
|
10
|
+
|
|
11
|
+
export const HASH_STORE_BUSY_TIMEOUT = 1000;
|
|
12
|
+
export const HASH_STORE_VERSION = 8;
|
|
13
|
+
export const NEW_CONTENT_NOT_ARRAY_MSG =
|
|
14
|
+
`[E_BAD_SHAPE] "replacement_lines" must be an array of strings, one per line (use [] to delete).`;
|
|
15
|
+
|
|
16
|
+
export const NUL_CONTENT_MSG =
|
|
17
|
+
`[E_BAD_SHAPE] Content contains a NUL byte (U+0000); a text file cannot contain NUL, and writing it would break further reads and edits. Remove the NUL byte and retry. An empty replacement ([]) deletes a range or inserts nothing.`;
|
|
18
|
+
|
|
19
|
+
export const ANCHOR_POOL_EXHAUSTED_PREFIX =
|
|
20
|
+
"[E_FILE_TOO_LARGE] The session's anchor pool is exhausted";
|
|
21
|
+
|
|
22
|
+
export const AUTO_READ_ALL_CUSTOM_TYPE = "hashline-auto-read-all";
|
|
23
|
+
export const AUTO_READ_ALL_MAX_FILES = 500;
|
|
24
|
+
export const AUTO_READ_ALL_MAX_FILE_BYTES = 200_000;
|
|
25
|
+
export const AUTO_READ_ALL_MIN_BUDGET_BYTES = 200_000;
|
|
26
|
+
export const AUTO_READ_ALL_MAX_BUDGET_BYTES = 2_000_000;
|