dsh-better-edit 0.1.9 → 0.2.1

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 (58) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +168 -52
  3. package/README.zh.md +122 -46
  4. package/assets/logo.svg +183 -18
  5. package/lib/contract.js +95 -0
  6. package/lib/drift.js +1 -1
  7. package/lib/edit-diff.js +2 -2
  8. package/lib/edit-engine.js +456 -0
  9. package/lib/edit-pipeline.js +41 -116
  10. package/lib/file-reader.js +1 -2
  11. package/lib/fs-bridge.js +2 -2
  12. package/lib/fs-write.js +3 -46
  13. package/lib/guidance.js +282 -0
  14. package/lib/hash-store.js +246 -13
  15. package/lib/hashline/apply.js +2 -2
  16. package/lib/hashline/hash.js +16 -206
  17. package/lib/hashline/index.js +4 -3
  18. package/lib/hashline/parse.js +1 -1
  19. package/lib/hashline/pure.js +213 -0
  20. package/lib/hashline/resolve.js +1 -5
  21. package/lib/hashline/served.js +2 -2
  22. package/lib/index.js +48 -32
  23. package/lib/paths.js +55 -1
  24. package/lib/prompts.js +53 -49
  25. package/lib/read-and-serve.js +46 -0
  26. package/lib/schema.js +1 -1
  27. package/lib/served-store.js +144 -183
  28. package/lib/tool-batch-edit.js +28 -280
  29. package/lib/tool-edit.js +37 -32
  30. package/lib/tool-read.js +8 -31
  31. package/lib/tool-undo.js +4 -13
  32. package/lib/types/contract.d.ts +39 -0
  33. package/lib/types/edit-engine.d.ts +179 -0
  34. package/lib/types/edit-pipeline.d.ts +10 -17
  35. package/lib/types/fs-write.d.ts +0 -1
  36. package/lib/types/guidance.d.ts +98 -0
  37. package/lib/types/hash-store.d.ts +73 -25
  38. package/lib/types/hashline/hash.d.ts +8 -13
  39. package/lib/types/hashline/index.d.ts +4 -3
  40. package/lib/types/hashline/pure.d.ts +26 -0
  41. package/lib/types/hashline/resolve.d.ts +0 -1
  42. package/lib/types/index.d.ts +4 -0
  43. package/lib/types/paths.d.ts +9 -0
  44. package/lib/types/prompts.d.ts +19 -9
  45. package/lib/types/read-and-serve.d.ts +39 -0
  46. package/lib/types/schema.d.ts +2 -16
  47. package/lib/types/served-store.d.ts +63 -32
  48. package/lib/types/tool-batch-edit.d.ts +4 -1
  49. package/lib/types/tool-undo.d.ts +1 -1
  50. package/lib/undo-edit.js +16 -1
  51. package/lib/write-hook.js +30 -50
  52. package/package.json +5 -3
  53. package/lib/served-state.js +0 -34
  54. package/lib/snapshot-store.js +0 -108
  55. package/lib/types/served-state.d.ts +0 -3
  56. package/lib/types/snapshot-store.d.ts +0 -14
  57. package/lib/types/undo-store.d.ts +0 -14
  58. package/lib/undo-store.js +0 -43
@@ -0,0 +1,179 @@
1
+ /**
2
+ * The edit-sequence engine shared by `edit`, `batch_edit`, and previews:
3
+ * apply-one-edit against in-memory content with served verification, the
4
+ * multi-edit sequencer that drives a whole file's item list against evolving
5
+ * content, the noop-loop guard, and the persist-undo → write → restore
6
+ * transaction both mutating tools run.
7
+ *
8
+ * The model-facing contract lives here unchanged: [E_BATCH_ABORT],
9
+ * [E_NOOP_LOOP], [E_UNDO_UNAVAILABLE] carry byte-identical messages, and
10
+ * reject-and-serve records the same echo serves.
11
+ * @module dsh-better-edit/edit-engine
12
+ */
13
+ import type { ToolExecution } from "@deepseek-ai/dsh-tools";
14
+ import type { SandboxExecutionPolicy } from "@deepseek-ai/dsh-sandbox";
15
+ import type { FileIO } from "./fs-bridge.js";
16
+ import type { HashStore } from "./hash-store.js";
17
+ import type { LineEnding } from "./edit-diff.js";
18
+ import { type HEdit, type NEdit } from "./hashline/index.js";
19
+ import { type ResolvedRange, type ServeRecordPolicy, type ServedRow } from "./hashline/served.js";
20
+ import type { FsSandboxController } from "./sandbox.js";
21
+ export interface PreparedItem {
22
+ index: number;
23
+ path: string;
24
+ absolutePath: string;
25
+ remove_from: string;
26
+ remove_to: string;
27
+ replacement_text: string;
28
+ pathWarning?: string;
29
+ }
30
+ export interface FileEditResult {
31
+ displayPath: string;
32
+ absolutePath: string;
33
+ originalNormalized: string;
34
+ result: string;
35
+ bom: string;
36
+ originalEnding: LineEnding;
37
+ hadUtf8DecodeErrors: boolean;
38
+ warnings: string[];
39
+ originalHashes: string[];
40
+ resultHashes: string[];
41
+ appliedCount: number;
42
+ noopCount: number;
43
+ totalAddedLines: number;
44
+ totalRemovedLines: number;
45
+ driftNotice: string | undefined;
46
+ range: ResolvedRange;
47
+ }
48
+ /**
49
+ * Resolve a request's missing `path` from its anchors: the only file whose
50
+ * stored hashes contain both anchors. Returns the path plus an autocorrect
51
+ * warning, or undefined when no resolution is possible.
52
+ */
53
+ export declare function resolveMissingPath(request: Record<string, unknown>): Promise<{
54
+ path: string;
55
+ warning: string;
56
+ } | undefined>;
57
+ /** The hashes a range edit removes, for stable re-hash bookkeeping. */
58
+ export declare function collectRemovedHashes(edit: HEdit, originalHashes: string[]): Set<string>;
59
+ /** Added/removed line counts for one resolved edit against a file's original hashes. */
60
+ export declare function countLineChanges(edit: HEdit, originalHashes: string[], isNoop: boolean, removedAutoFixes: number): {
61
+ totalAddedLines: number;
62
+ totalRemovedLines: number;
63
+ };
64
+ export interface ApplyOneInput {
65
+ content: string;
66
+ hashes: string[];
67
+ served: (string | null)[];
68
+ removeFrom: string;
69
+ removeTo: string;
70
+ replacementText: string;
71
+ absolutePath: string;
72
+ displayPath: string;
73
+ signal?: AbortSignal;
74
+ /** Shared warnings array; resEdit warnings are pushed here. */
75
+ warnings: string[];
76
+ /**
77
+ * The hashes to count added/removed lines against. Defaults to `hashes`;
78
+ * the batch sequencer passes the file's ORIGINAL hashes so later edits in
79
+ * a sequence still count against the file as first served.
80
+ */
81
+ countHashes?: string[];
82
+ store?: HashStore;
83
+ persist: boolean;
84
+ /** Pre-resolved edit (single path keeps resEdit before IO for error order). */
85
+ edit?: HEdit;
86
+ }
87
+ export interface ApplyOneResult {
88
+ result: string;
89
+ /** Stable re-hash after the edit (equals `hashes` for a noop). */
90
+ hashes: string[];
91
+ range: ResolvedRange;
92
+ noop: boolean;
93
+ edit: HEdit;
94
+ noopEdit?: NEdit;
95
+ firstChangedLine?: number;
96
+ lastChangedLine?: number;
97
+ removedHashes: Set<string> | undefined;
98
+ totalAddedLines: number;
99
+ totalRemovedLines: number;
100
+ anchorWarnings: string[] | undefined;
101
+ }
102
+ /**
103
+ * One edit against in-memory content: resolve (unless a pre-resolved edit was
104
+ * given) → apply with served verification → stable re-hash → line counts.
105
+ *
106
+ * `onReject` owns the reject-and-serve policy: it receives resolve/verify
107
+ * failures (and the edit that failed, when resolved) and MUST throw. The
108
+ * single path rethrows the original anchor error after recording echo serves;
109
+ * the batch path wraps with [E_BATCH_ABORT] plus the current-range echo.
110
+ */
111
+ export declare function applyOne(input: ApplyOneInput, onReject: (error: unknown, edit: HEdit | undefined) => Promise<never>): Promise<ApplyOneResult>;
112
+ export interface NoopLoopOptions {
113
+ absolutePath: string;
114
+ removeFrom: string;
115
+ removeTo: string;
116
+ replacementText: string;
117
+ displayPath: string;
118
+ /** Batch item index; undefined = single-edit flavor. */
119
+ index?: number;
120
+ count: number;
121
+ sessionKey: string;
122
+ originalHashes: string[];
123
+ originalNormalized: string;
124
+ /** Single-edit flavor only: the edit's range, for the echo rows. */
125
+ range?: ResolvedRange;
126
+ /** Batch flavor: precomputed echo rows for the failed item (may be absent). */
127
+ echoRows?: ServedRow[];
128
+ }
129
+ /**
130
+ * The shared noop-loop guard. Returns the "twice in a row" notice for the
131
+ * caller to append to warnings, or throws [E_NOOP_LOOP] (after recording the
132
+ * echo serves) once the payload has been submitted NOOP_LOOP_THRESHOLD times
133
+ * with no change. Messages are byte-identical to the pre-engine tools.
134
+ */
135
+ export declare function enforceNoopLoop(opts: NoopLoopOptions): Promise<string | undefined>;
136
+ /**
137
+ * Run a file's item list against freshly-read content with served
138
+ * verification, evolving content/hashes, union range, noop tracking, and a
139
+ * per-file drift notice. All-or-nothing is enforced by the caller's
140
+ * transaction ({@link persistUndoAndWrite}): nothing here writes to disk.
141
+ */
142
+ export declare function runFileEdits(io: FileIO, items: PreparedItem[], opts: {
143
+ signal?: AbortSignal;
144
+ sessionKey: string;
145
+ }): Promise<FileEditResult>;
146
+ export interface UndoWriteFile {
147
+ absolutePath: string;
148
+ displayPath: string;
149
+ originalNormalized: string;
150
+ bom: string;
151
+ originalEnding: LineEnding;
152
+ originalHashes: string[];
153
+ result: string;
154
+ }
155
+ export interface PersistWriteOptions {
156
+ io: FileIO;
157
+ files: UndoWriteFile[];
158
+ exec: ToolExecution;
159
+ sandbox: FsSandboxController;
160
+ sandboxPolicy: SandboxExecutionPolicy | undefined;
161
+ signal?: AbortSignal;
162
+ /** [E_UNDO_UNAVAILABLE] message builder, per tool flavor. */
163
+ undoUnavailableMessage: (displayPath: string) => string;
164
+ /**
165
+ * On write failure, also restore undo entries of files that were saved but
166
+ * never written. The single-edit tool restores its one entry; the batch
167
+ * tool keeps current behavior and restores only written files.
168
+ */
169
+ restoreUnwrittenUndos?: boolean;
170
+ }
171
+ /**
172
+ * The persist-undo → write-all → restore-on-failure transaction shared by
173
+ * `edit` (one file) and `batch_edit` (many files). Every file's undo entry is
174
+ * persisted before anything is written; if a write fails, already-written
175
+ * files are restored (original content written back, undo entry restored) and
176
+ * the sandbox-mapped error rethrown.
177
+ */
178
+ export declare function persistUndoAndWrite(opts: PersistWriteOptions): Promise<void>;
179
+ export type { ServeRecordPolicy };
@@ -1,22 +1,20 @@
1
1
  /**
2
- * The single-edit pipeline shared by `edit`, `batch_edit`, and previews:
3
- * resolve → normalize → hash → verify anchors against served state → apply →
4
- * re-hash with stable anchors → drift notice. All IO goes through the
5
- * {@link FileIO} bridge so the same pipeline runs on `ctx.fs` and on the host
6
- * filesystem.
2
+ * The single-edit pipeline shared by `edit`, previews, and (through the
3
+ * engine) `batch_edit`: resolve → normalize → hash → verify anchors against
4
+ * served state → apply → re-hash with stable anchors → drift notice. The
5
+ * apply/reject/re-hash computation lives in the edit engine
6
+ * ({@link edit-engine}); this module keeps the single-edit orchestration
7
+ * shape, preview-mode options, and the pipeline result type. All IO goes
8
+ * through the {@link FileIO} bridge so the same pipeline runs on `ctx.fs` and
9
+ * on the host filesystem.
7
10
  * @module dsh-better-edit/edit-pipeline
8
11
  */
9
12
  import type { HashStore } from './hash-store.js';
10
13
  import type { FileIO } from './fs-bridge.js';
11
14
  import type { LineEnding } from './edit-diff.js';
12
- import { type HEdit, type NEdit } from './hashline/index.js';
15
+ import { type NEdit } from './hashline/index.js';
13
16
  import type { ResolvedRange } from './hashline/served.js';
14
- import type { EditParams } from './schema.js';
15
- export declare function assertReq(request: unknown): asserts request is EditParams;
16
- export declare function resolveMissingPath(request: Record<string, unknown>): Promise<{
17
- path: string;
18
- warning: string;
19
- } | undefined>;
17
+ import type { EditParams } from './contract.js';
20
18
  export interface PipelineResult {
21
19
  path: string;
22
20
  absolutePath: string;
@@ -42,11 +40,6 @@ export interface ExecPipelineOptions {
42
40
  noPersist?: boolean;
43
41
  sessionKey?: string;
44
42
  }
45
- export declare function collectRemovedHashes(edit: HEdit, originalHashes: string[]): Set<string>;
46
- export declare function countLineChanges(edit: HEdit, originalHashes: string[], isNoop: boolean, removedAutoFixes: number): {
47
- totalAddedLines: number;
48
- totalRemovedLines: number;
49
- };
50
43
  export declare function execPipeline(io: FileIO, params: EditParams, cwd: string, options?: ExecPipelineOptions): Promise<PipelineResult>;
51
44
  /** Resolve the display path a caller names against the session cwd. */
52
45
  export declare function resolveDisplayPath(path: string, cwd: string): string;
@@ -1,2 +1 @@
1
- export declare function resolveTarget(path: string): Promise<string>;
2
1
  export declare function writeAtomic(path: string, content: string): Promise<void>;
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Per-preset guidance overrides for the hashline tool sections.
3
+ *
4
+ * Each of the four `tool:*` prompt sections the plugin registers has a
5
+ * compiled default rendered from `prompts.ts` (byte-identical to the inline
6
+ * rendering `src/index.ts` uses today). A user can override any section's text
7
+ * and `order` with a plain markdown file keyed by agent preset: the override
8
+ * files live in the plugin's shared home (`$DSH_HOME/plugins/dsh-better-edit`,
9
+ * never the workspace store) and are resolved per section as
10
+ * `<preset>/<section>.md` → compiled default.
11
+ *
12
+ * An override file is pure prose unless it opens with a valid YAML front-matter
13
+ * fence carrying only an `order` key (`---` / `order: N` / `---`); anything
14
+ * else — a missing closing fence, a non-integer `order`, an unknown key —
15
+ * degrades the WHOLE file to prose so the mistake stays visible in the
16
+ * rendered section.
17
+ *
18
+ * Resolution is pure: no cordis services, no harness wiring. The installer
19
+ * ticket reads the resolved sections once per agent at session-start;
20
+ * nothing here watches or caches files.
21
+ * @module dsh-better-edit/guidance
22
+ */
23
+ /** The presets shipped by the harness, each seeded with editable guidance. */
24
+ export declare const DEFAULT_PRESETS: readonly string[];
25
+ /** One overridable tool section. */
26
+ export interface GuidanceSection {
27
+ /** Registry section name, e.g. `tool:edit`. */
28
+ name: string;
29
+ /** Override file name inside a preset directory, e.g. `edit.md`. */
30
+ file: string;
31
+ /** Order used when the override file carries no front-matter `order`. */
32
+ defaultOrder: number;
33
+ /** The compiled default text, byte-identical to today's inline rendering. */
34
+ renderDefault(): string;
35
+ }
36
+ /** The four sections, in default-order sequence. */
37
+ export declare const GUIDANCE_SECTIONS: readonly GuidanceSection[];
38
+ /** Render the compiled default text for one section. */
39
+ export declare function renderSectionDefault(name: string): string;
40
+ /** The parsed content of one override file. */
41
+ export interface ParsedSection {
42
+ /** Front-matter `order`, when present and valid. */
43
+ order?: number;
44
+ /** The section text: the file body, or the whole file when front-matter is absent or malformed. */
45
+ text: string;
46
+ }
47
+ /**
48
+ * Parse an override file. Only a leading `---` fence whose lines are empty or
49
+ * `order: <integer>` is accepted; every other shape (no fence, no closing
50
+ * fence, unknown key, non-integer value) yields the whole file as prose.
51
+ */
52
+ export declare function parseSectionFile(content: string): ParsedSection;
53
+ /** Options for resolving one section's guidance. */
54
+ export interface ResolveGuidanceOptions {
55
+ /** Agent preset id, or undefined to skip the preset layer. */
56
+ presetId?: string;
57
+ /** Plugin shared home directory (`$DSH_HOME/plugins/dsh-better-edit`). */
58
+ homeDir: string;
59
+ }
60
+ /** The resolved text and order for one section. */
61
+ export interface GuidanceResolution {
62
+ order: number;
63
+ text: string;
64
+ }
65
+ /**
66
+ * Resolve one section's guidance: the first override file that exists wins,
67
+ * falling back to the compiled default. A missing file (ENOENT) advances the
68
+ * chain; any other read error propagates.
69
+ */
70
+ export declare function resolveSection(name: string, options: ResolveGuidanceOptions): Promise<GuidanceResolution>;
71
+ /** The resolved configuration of one section, ready for the systemPrompt registry. */
72
+ export interface SectionOverride {
73
+ name: string;
74
+ order: number;
75
+ text: string;
76
+ }
77
+ /**
78
+ * Resolve all four sections for a preset. `presetId === undefined` skips the
79
+ * `<preset>/` layer and resolves straight to the compiled defaults.
80
+ */
81
+ export declare function composeSections(presetId: string | undefined, homeDir: string): Promise<SectionOverride[]>;
82
+ /**
83
+ * The root README: the per-preset customization convention users see in the
84
+ * plugin home.
85
+ */
86
+ export declare const GUIDANCE_HOME_README = "# dsh-better-edit guidance\n\nEach agent preset has its own guidance directory here: `<preset>/<section>.md`.\nOn first boot the plugin seeds the shipped presets (`standard`, `code`,\n`minimal`, `cordis`) with the compiled defaults; existing files are never\noverwritten, so your edits survive.\n\nEach file is one tool section:\n\n- `read.md` -> `tool:read`\n- `edit.md` -> `tool:edit`\n- `batch_edit.md` -> `tool:batch_edit`\n- `undo_last_edit.md` -> `tool:undo_last_edit`\n\n## Customize\n\nEdit the `<section>.md` file for the preset and section you want to change \u2014\nthe file body IS the text the model reads for that section. Files are read once\nper agent at session-start, so edits apply to new sessions.\n\nAn optional YAML front-matter fence places the section at a custom position in\nthe assembled system prompt:\n\n ---\n order: 150\n ---\n\n <section text>\n\nA file without front-matter keeps the default order. A malformed fence (a\nmissing closing `---`, a non-integer `order`, an unknown key) makes the whole\nfile plain prose.\n\n## Fallback\n\nA preset with no directory here, or a missing section file, falls back to the\ncompiled defaults in the plugin bundle. To customize a preset that has no\nseeded directory, copy a seeded one to its name.\n";
87
+ export declare const GUIDANCE_HOME_README_ZH = "# dsh-better-edit \u6307\u5F15\n\n\u6BCF\u4E2A agent preset \u5728\u8FD9\u91CC\u90FD\u6709\u81EA\u5DF1\u7684\u6307\u5F15\u76EE\u5F55\uFF1A`<preset>/<section>.md`\u3002\u9996\u6B21\u542F\u52A8\u65F6\n\u63D2\u4EF6\u4F1A\u4E3A\u968F\u9644\u7684 preset\uFF08`standard`\u3001`code`\u3001`minimal`\u3001`cordis`\uFF09\u5199\u5165\u7F16\u8BD1\u5185\u7F6E\u7684\n\u9ED8\u8BA4\u5185\u5BB9\uFF1B\u5DF2\u6709\u6587\u4EF6\u7EDD\u4E0D\u88AB\u8986\u76D6\uFF0C\u56E0\u6B64\u4F60\u7684\u7F16\u8F91\u4F1A\u4FDD\u7559\u3002\n\n\u6BCF\u4E2A\u6587\u4EF6\u5BF9\u5E94\u4E00\u4E2A\u5DE5\u5177\u7247\u6BB5\uFF1A\n\n- `read.md` -> `tool:read`\n- `edit.md` -> `tool:edit`\n- `batch_edit.md` -> `tool:batch_edit`\n- `undo_last_edit.md` -> `tool:undo_last_edit`\n\n## \u81EA\u5B9A\u4E49\n\n\u7F16\u8F91\u4F60\u60F3\u4FEE\u6539\u7684 preset \u4E0E\u7247\u6BB5\u7684 `<section>.md` \u6587\u4EF6\u5373\u53EF\u2014\u2014\u6587\u4EF6\u6B63\u6587\u5C31\u662F\u8BE5\u7247\u6BB5\u5448\n\u73B0\u7ED9\u6A21\u578B\u7684\u6587\u672C\u3002\u6587\u4EF6\u5728 agent \u7684 session-start \u65F6\u8BFB\u53D6\u4E00\u6B21\uFF0C\u56E0\u6B64\u4FEE\u6539\u53EA\u5F71\u54CD\u65B0\u4F1A\u8BDD\u3002\n\n\u53EF\u4EE5\u7528\u53EF\u9009\u7684 YAML front-matter \u6805\u680F\u628A\u7247\u6BB5\u653E\u5230\u7EC4\u88C5\u540E\u7CFB\u7EDF\u63D0\u793A\u4E2D\u7684\u81EA\u5B9A\u4E49\u4F4D\u7F6E\uFF1A\n\n ---\n order: 150\n ---\n\n <\u7247\u6BB5\u6587\u672C>\n\n\u6CA1\u6709 front-matter \u7684\u6587\u4EF6\u4FDD\u6301\u9ED8\u8BA4\u987A\u5E8F\u3002\u683C\u5F0F\u9519\u8BEF\u7684\u6805\u680F\uFF08\u7F3A\u5C11\u6536\u5C3E `---`\u3001\u975E\u6574\u6570\n`order`\u3001\u672A\u77E5\u952E\uFF09\u4F1A\u8BA9\u6574\u4E2A\u6587\u4EF6\u9000\u5316\u4E3A\u7EAF\u6587\u672C\u3002\n\n## \u56DE\u9000\n\n\u8FD9\u91CC\u6CA1\u6709\u5BF9\u5E94\u76EE\u5F55\u7684 preset\u3001\u6216\u7F3A\u5931\u67D0\u4E2A\u7247\u6BB5\u6587\u4EF6\u65F6\uFF0C\u4F1A\u56DE\u9000\u5230\u63D2\u4EF6\u5305\u5185\u7684\u7F16\u8BD1\u5185\u7F6E\u9ED8\u8BA4\n\u503C\u3002\u8981\u81EA\u5B9A\u4E49\u6CA1\u6709\u79CD\u5B50\u76EE\u5F55\u7684 preset\uFF0C\u628A\u4E00\u4E2A\u79CD\u5B50\u76EE\u5F55\u590D\u5236\u6210\u5B83\u7684\u540D\u5B57\u5373\u53EF\u3002\n";
88
+ /**
89
+ * Materialize per-preset guidance directories in the plugin home.
90
+ *
91
+ * For each of \`DEFAULT_PRESETS\` creates \`<preset>/{read,edit,batch_edit,
92
+ * undo_last_edit}.md\` rendered from the compiled defaults (with order
93
+ * front-matter), plus a root \`README.md\` documenting the convention.
94
+ * Idempotent: existing files are never rewritten (a user-edited file survives
95
+ * repeated calls) and missing directories are created on demand. Each file is
96
+ * written exclusively, so two concurrent first runs race safely.
97
+ */
98
+ export declare function ensurePresetGuidance(homeDir: string): Promise<void>;
@@ -1,25 +1,75 @@
1
- type SqlParams = (string | number)[];
2
- interface Prepared {
3
- get: (...params: SqlParams) => Record<string, unknown> | undefined;
4
- allPaths: (...params: SqlParams) => Record<string, unknown>[];
5
- allHashes: (...params: SqlParams) => Record<string, unknown>[];
6
- deleteOne: (...params: SqlParams) => void;
7
- upsert: (...params: SqlParams) => void;
8
- undoUpsert: (...params: SqlParams) => void;
9
- undoGet: (...params: SqlParams) => Record<string, unknown> | undefined;
10
- undoDelete: (...params: SqlParams) => void;
11
- servedGet: (...params: SqlParams) => Record<string, unknown> | undefined;
12
- servedUpsert: (...params: SqlParams) => void;
13
- servedReportedUpsert: (...params: SqlParams) => void;
14
- servedReportedClear: (...params: SqlParams) => void;
15
- servedDelete: (...params: SqlParams) => void;
16
- servedDeletePath: (...params: SqlParams) => void;
17
- servedWipe: (...params: SqlParams) => void;
18
- servedPruneOlderThan: (...params: SqlParams) => void;
1
+ /**
2
+ * The hash store — ONE deep persistence module for the hashline domain.
3
+ *
4
+ * Owns the sqlite db, the schema and migrations, corruption quarantine,
5
+ * busy-retry, WAL, the legacy-JSON migration, AND the three narrow row APIs
6
+ * the rest of the plugin needs: hash snapshots, undo entries, and served
7
+ * rows. The prepared statements are a private implementation detail — callers
8
+ * use domain methods, never SQL.
9
+ *
10
+ * Corrupt-row handling (parse the JSON column → validate against the hash
11
+ * alphabet → delete the corrupt row) lives here, once, for every row family.
12
+ * Cross-table cleanup (pruneMissing) lives here too — a sibling module never
13
+ * reaches into another family's rows.
14
+ * @module dsh-better-edit/hash-store
15
+ */
16
+ /** The legacy JSON snapshot shape (pre-sqlite stores). */
17
+ export interface LegacySnapshot {
18
+ content: string;
19
+ hashes: string[];
20
+ }
21
+ export declare function isValidHashList(value: unknown): value is string[];
22
+ export declare function isValidSnapshot(value: unknown): value is LegacySnapshot;
23
+ /** A served-row array: per-position hash, or null for never-served slots. */
24
+ export declare function isValidServedList(value: unknown): value is (string | null)[];
25
+ /** The undo row contract shared by undo-edit and the store. */
26
+ export interface UndoRecord {
27
+ content: string;
28
+ bom: string;
29
+ ending: string;
30
+ hashes: string[];
31
+ resultContent: string;
19
32
  }
33
+ /**
34
+ * The domain face of the hash store. Each row family gets a narrow API;
35
+ * corruption healing (parse → validate → delete) happens inside the getters.
36
+ */
20
37
  export interface HashStore {
21
- readonly stmts: Prepared;
22
38
  readonly engine: "node:sqlite";
39
+ /** The stored hashes for a path+content, or undefined on a miss; a corrupt row is deleted (when deleteCorrupt) and treated as a miss. */
40
+ getSnapshot(path: string, content: string, deleteCorrupt?: boolean): string[] | undefined;
41
+ upsertSnapshot(path: string, checksum: string, lineCount: number, hashes: string[]): void;
42
+ /** Every path referenced by any row family (snapshots ∪ undo ∪ served). */
43
+ allKnownPaths(): {
44
+ path: string;
45
+ }[];
46
+ /** Every snapshot's path and raw hashes JSON (for path-by-hash scans). */
47
+ allSnapshotHashes(): {
48
+ path: string;
49
+ hashes: string;
50
+ }[];
51
+ deleteSnapshot(path: string): void;
52
+ /** Paths whose stored snapshot hashes contain every given anchor. */
53
+ findSnapshotPaths(hashes: string[]): string[];
54
+ /** The undo row for a path, healing a corrupt row (parse → validate → delete). */
55
+ getUndo(path: string): UndoRecord | undefined;
56
+ upsertUndo(path: string, entry: UndoRecord): void;
57
+ deleteUndo(path: string): void;
58
+ /** The served hashes array for a session+path, healing a corrupt row; [] when nothing was served. */
59
+ getServed(sessionKey: string, path: string): (string | null)[];
60
+ /** The reported-drift hash set for a session+path (lenient parse, never deletes). */
61
+ getServedReported(sessionKey: string, path: string): Set<string>;
62
+ /** Persist the hashes JSON column for a session+path. */
63
+ upsertServed(sessionKey: string, path: string, hashesJson: string): void;
64
+ /** Persist the reported-drift JSON column for a session+path (inserting a fresh empty hashes row). */
65
+ upsertServedReported(sessionKey: string, path: string, reportedJson: string): void;
66
+ clearServedReported(sessionKey: string, path: string): void;
67
+ deleteServed(sessionKey: string, path: string): void;
68
+ deleteServedByPath(path: string): void;
69
+ wipeServed(sessionKey: string): void;
70
+ pruneServedOlderThan(ts: number): void;
71
+ /** Delete every row family's entries for paths that no longer exist on disk. */
72
+ pruneMissing(): Promise<void>;
23
73
  }
24
74
  export declare function isCorruptionError(error: unknown): boolean;
25
75
  /**
@@ -37,9 +87,7 @@ export declare function shutdownHashStore(): void;
37
87
  * caller has already loaded the store in every in-process path).
38
88
  */
39
89
  export declare function withStore(fn: () => void): void;
40
- export { getSnapshot, upsertSnapshot, findSnapshotPaths, pruneMissing, isValidHashList, isValidSnapshot, } from "./snapshot-store.js";
41
- export type { LegacySnapshot } from "./snapshot-store.js";
42
- export { getServed, upsertServed, recordServes, getReported, addReported, clearReported, deleteServed, wipeServed, } from "./served-store.js";
43
- export type { ServedEntry } from "./served-store.js";
44
- export { upsertUndo, getUndoEntry, deleteUndo, } from "./undo-store.js";
45
- export type { UndoRecord } from "./undo-store.js";
90
+ /** Find files whose stored snapshot hashes contain every given anchor. */
91
+ export declare function findSnapshotPathsByHashes(hashes: string[]): Promise<string[]>;
92
+ /** Persist a hash snapshot for one path (async over the active store). */
93
+ export declare function upsertSnapshotFor(path: string, checksum: string, lineCount: number, hashes: string[]): Promise<void>;
@@ -1,17 +1,12 @@
1
1
  import { type HashStore } from "../hash-store.js";
2
- import { initHasher } from "./hasher.js";
3
- import { HASH_LEN, ALPH_RE, HASH_CLASS } from "./alphabet.js";
4
- export { initHasher, HASH_LEN, ALPH_RE, HASH_CLASS };
5
- export declare const ANCHOR_LEN = 3;
6
- export declare const HASH_SEP = "\u2502";
7
- export declare const HASH_SPACE: number;
8
- export declare const MAX_HASH_LINES: number;
9
- export declare const HASH_PROBE_STRIDE: number;
10
- export declare const HL_PREFIX_PLUS_RE: RegExp;
11
- export declare const HL_PREFIX_MINUS_RE: RegExp;
12
- export declare const HL_BARE_PREFIX_RE: RegExp;
13
- export declare function canon(line: string): string;
14
- export declare function _lineHashesPure(content: string): string[];
2
+ /**
3
+ * Persistence-aware hash-anchor assignment: the pure hasher
4
+ * ({@link lineHashesPure} / {@link mapStableHashes} in ./pure.js) composed
5
+ * with snapshot load/upsert in the hash store, keyed by
6
+ * (path, content checksum, line count). Without a `path` this never touches
7
+ * the store and is exactly the pure path. With `previous` the stable re-hash
8
+ * mapping keeps surviving anchors stable across edits.
9
+ */
15
10
  export declare function lineHashes(content: string, path?: string, previous?: {
16
11
  content: string;
17
12
  hashes: string[];
@@ -1,4 +1,5 @@
1
- export { HASH_LEN, ANCHOR_LEN, HASH_SEP, HASH_CLASS, HASH_SPACE, HASH_PROBE_STRIDE, MAX_HASH_LINES, HL_PREFIX_PLUS_RE, HL_PREFIX_MINUS_RE, HL_BARE_PREFIX_RE, lineHashes, _lineHashesPure, initHasher, canon, } from "./hash.js";
1
+ export { ANCHOR_LEN, HASH_SEP, HASH_SPACE, HASH_PROBE_STRIDE, MAX_HASH_LINES, lineHashesPure, initHasher, canon, } from "./pure.js";
2
+ export { lineHashes } from "./hash.js";
2
3
  export { parseHashRef, parseText, type Anchor, } from "./parse.js";
3
- export { type RAnchor, type HEdit, type RHEdit, type HTEdit, type NEdit, type BDup, type AutoFix, resEdit, valEdit, stripBarePrefixes, stripDiffPrefixes, swapReversedRanges, fmtMismatch, findNewEdge, } from "./resolve.js";
4
- export { buildIdx, applyEdit, fmtRegion, changedRange, } from "./apply.js";
4
+ export { type HEdit, type HTEdit, type NEdit, resEdit, } from "./resolve.js";
5
+ export { applyEdit, fmtRegion, changedRange, } from "./apply.js";
@@ -0,0 +1,26 @@
1
+ import { initHasher } from "./hasher.js";
2
+ import { HASH_LEN, ALPH_RE, HASH_CLASS } from "./alphabet.js";
3
+ export { initHasher, HASH_LEN, ALPH_RE, HASH_CLASS };
4
+ export declare const ANCHOR_LEN = 3;
5
+ export declare const HASH_SEP = "\u2502";
6
+ export declare const HASH_SPACE: number;
7
+ export declare const MAX_HASH_LINES: number;
8
+ export declare const HASH_PROBE_STRIDE: number;
9
+ export declare const HL_PREFIX_PLUS_RE: RegExp;
10
+ export declare const HL_PREFIX_MINUS_RE: RegExp;
11
+ export declare const HL_BARE_PREFIX_RE: RegExp;
12
+ export declare function canon(line: string): string;
13
+ /**
14
+ * Pure hash-anchor assignment: every line of `content` gets a unique 3-char
15
+ * anchor derived from its canonicalized content via xxhash32 + probe-stride
16
+ * allocation. No I/O, no store — the persistence-aware wrapper
17
+ * {@link lineHashes} (in ./hash.js) composes this with snapshot load/upsert.
18
+ */
19
+ export declare function lineHashesPure(content: string): string[];
20
+ /**
21
+ * Pure stable re-hash: given the pre-edit content + anchors and the new
22
+ * content (plus the hashes removed by the edit), map surviving lines to
23
+ * their old anchors, re-claim removed anchors for identical lines, and
24
+ * allocate fresh anchors for the rest. No I/O, no store.
25
+ */
26
+ export declare function mapStableHashes(oldContent: string, oldHashes: string[], newContent: string, removedHashes?: Set<string>): string[];
@@ -37,7 +37,6 @@ export type HTEdit = {
37
37
  remove_from: string;
38
38
  remove_to: string;
39
39
  };
40
- export declare function fmtMismatch(mismatches: HMismatch[], fileLines: string[], fileHashes: string[], filePath?: string): string;
41
40
  export declare function fmtMismatchWithServes(mismatches: HMismatch[], fileLines: string[], fileHashes: string[], filePath?: string): {
42
41
  message: string;
43
42
  servedRows: ServedRow[];
@@ -9,6 +9,10 @@
9
9
  * automatically when the agent is disposed. The built-in `write` stays in
10
10
  * place; a scoped `tools/post-execute` listener appends the fresh hashline
11
11
  * preview to write results.
12
+ *
13
+ * The four `tool:*` guidance sections resolve per agent preset from override
14
+ * files in the shared home (see `src/guidance.ts`); deployments without the
15
+ * `agentPresets` service keep the compiled defaults unchanged.
12
16
  * @module dsh-better-edit
13
17
  */
14
18
  import type { Context } from "@deepseek-ai/cordis";
@@ -13,3 +13,12 @@ export declare function hashStorePath(cwd?: string): string;
13
13
  export declare function legacyHashStorePath(cwd?: string): string;
14
14
  export declare function hashStoreDir(cwd?: string): string;
15
15
  export declare function toCwd(filePath: string, cwd: string): string;
16
+ /**
17
+ * Canonicalize a path, resolving every symlink component to its target
18
+ * (loop-guarded, ELOOP on cycles). Non-existent final components resolve
19
+ * lexically — the canonical form of a not-yet-created file. The hashline
20
+ * tools key their state by canonical absolute paths, so the same file reached
21
+ * through different symlink spellings lands on the same store rows.
22
+ * @param path - the path to canonicalize (absolute or relative).
23
+ */
24
+ export declare function resolveTarget(path: string): Promise<string>;
@@ -1,17 +1,27 @@
1
1
  /**
2
2
  * Model-facing prompt text for the hashline tools, embedded so the bundle
3
- * ships no external prompt files. Each tool's description is short; the
4
- * `tool:*` system-prompt sections carry the full usage guidance the model
5
- * reads when the tools are presented.
3
+ * ships no external prompt files. Each tool's schema `description` is short;
4
+ * the `tool:*` system-prompt sections carry the brief guidance the model
5
+ * reads when the tools are presented. Guidance is uniform: a one-line opener
6
+ * followed by tight bullets.
6
7
  * @module dsh-better-edit/prompts
7
8
  */
9
+ /**
10
+ * One tool's guidance: a brief opener plus concise bullets. The `intro` is
11
+ * shown above the bullets; it does not duplicate the tool-schema `description`
12
+ * (that already reaches the model through the tool catalog).
13
+ */
14
+ export interface ToolGuidance {
15
+ /** One-line lead shown above the bullets. */
16
+ intro: string;
17
+ /** Concise bullets; each is self-contained within its section. */
18
+ lines: readonly string[];
19
+ }
8
20
  export declare const EDIT_DESCRIPTION: string;
9
- export declare const EDIT_SNIPPET = "Edit lines in a text file via bare 3-char HASH anchors from read \u2014 hash only, never line content; anchor exactly the lines that change; one edit per tool call";
10
- export declare const EDIT_GUIDELINES: string[];
21
+ export declare const EDIT_GUIDANCE: ToolGuidance;
11
22
  export declare const READ_DESCRIPTION: string;
12
- export declare const READ_SNIPPET = "Read a file; each line returned as HASH\u2502content";
13
- export declare const READ_GUIDELINES: string[];
23
+ export declare const READ_GUIDANCE: ToolGuidance;
14
24
  export declare const BATCH_EDIT_DESCRIPTION: string;
15
- export declare const BATCH_EDIT_GUIDELINES: string[];
25
+ export declare const BATCH_EDIT_GUIDANCE: ToolGuidance;
16
26
  export declare const UNDO_DESCRIPTION: string;
17
- export declare const UNDO_GUIDELINES: string[];
27
+ export declare const UNDO_GUIDANCE: ToolGuidance;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The shared read-and-serve operation: resolve → read → normalize → render
3
+ * the hashline preview → record the served rows → clear the drift marks →
4
+ * append the UTF-8 rewrite note. Used by the `read` tool and by the write
5
+ * auto-read hook, so the model is always shown fresh anchors the same way no
6
+ * matter which tool produced the read.
7
+ * @module dsh-better-edit/read-and-serve
8
+ */
9
+ import type { FileIO } from "./fs-bridge.js";
10
+ import type { ServedRow } from "./hashline/served.js";
11
+ /** Appended when the file had non-UTF-8 bytes; editing rewrites it as UTF-8. */
12
+ export declare const UTF8_REWRITE_NOTE = "[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]";
13
+ export interface ReadAndServeOptions {
14
+ /** The session whose served rows these lines belong to. */
15
+ sessionKey: string;
16
+ signal?: AbortSignal;
17
+ /** Pagination for the rendered preview (undefined = from the start). */
18
+ offset?: number;
19
+ limit?: number;
20
+ }
21
+ export interface ReadAndServeResult {
22
+ /** The model-facing read text, including the UTF-8 note when applicable. */
23
+ text: string;
24
+ /** The rows recorded as served (empty when nothing was shown). */
25
+ served: ServedRow[];
26
+ hadUtf8DecodeErrors: boolean;
27
+ absolutePath: string;
28
+ }
29
+ /**
30
+ * Perform one read-and-serve: normalize the file at `rawPath`, render its
31
+ * hashline preview, record the shown rows as served for the session, and clear
32
+ * the reported-drift marks (a fresh read resets them). The returned text
33
+ * carries the UTF-8 rewrite note when the file had decode errors.
34
+ *
35
+ * Emits nothing on the fs-observation gate — callers that need the
36
+ * observation recorded (the `read` tool) do that themselves with their exec
37
+ * context.
38
+ */
39
+ export declare function readAndServe(io: FileIO, rawPath: string, cwd: string, options: ReadAndServeOptions): Promise<ReadAndServeResult>;
@@ -3,7 +3,7 @@
3
3
  * the dsh schema DSL (not TypeBox). `path` is deliberately NOT `required` at
4
4
  * the schema level: the tools accept the built-in `file_path` spelling too
5
5
  * (the implicit parameter root stays open), and enforce path presence in
6
- * `assertReq` after `normalizeFilePath` aliasing.
6
+ * `assertEditRequest` after `normalizeFilePath` aliasing.
7
7
  * @module dsh-better-edit/schema
8
8
  */
9
9
  export declare const replacementTextSchema: {
@@ -22,18 +22,4 @@ export declare const pathSchema: {
22
22
  readonly type: "string";
23
23
  readonly description: "Path to edit. Required — always provide it explicitly; it is only auto-resolved from the anchors as a fallback when omitted by mistake.";
24
24
  };
25
- export interface EditParams {
26
- path: string;
27
- remove_from: string;
28
- remove_to: string;
29
- replacement_text: string;
30
- }
31
- export interface BatchItemParams {
32
- path?: string;
33
- remove_from: string;
34
- remove_to: string;
35
- replacement_text: string;
36
- }
37
- export interface BatchEditParams {
38
- edits: BatchItemParams[];
39
- }
25
+ export type { EditParams, BatchItemParams, BatchEditParams, } from "./contract.js";