dsh-hashline-edit 0.3.11 → 0.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.
@@ -0,0 +1,175 @@
1
+ /**
2
+ * SAFETY: MutationEngine — deep module behind the mutation seam.
3
+ *
4
+ * Small interface: `execute` + `preview`. Deep implementation: load → parse
5
+ * → mutate → finalize → drift → persist → serve hidden inside the pipeline.
6
+ * Internal seams (validate, verify, mutate, guard, persist, record) stay
7
+ * private — not exported. The interface is the test surface.
8
+ *
9
+ * Typed boundaries: validate once at admission (normalized edit-request types),
10
+ * trust inside. Errors fail loud with typed `MutationFailure`.
11
+ */
12
+
13
+ import { apply as pipelineApply, previewEdits as pipelinePreview } from "./pipeline.js";
14
+ import { genDiff } from "../edit-diff.js";
15
+ import { DIFF_PREVIEW_CONTEXT } from "../constants.js";
16
+ import type { PipelineOptions } from "./types.js";
17
+ import type { MutationResult } from "../mutation-result.js";
18
+ import type { NormalizedEditRequest } from "./edit-request.js";
19
+ import { DomainError, badPayloadMessageOf, type DomainErrorCode } from "../domain-errors.js";
20
+ import { readEnvelope, type ErrorEnvelope } from "../error-envelope.js";
21
+
22
+ function failureFromEnvelope(args: {
23
+ code: DomainErrorCode;
24
+ message: string;
25
+ env: ErrorEnvelope;
26
+ payloadMessage?: string;
27
+ }): MutationResult {
28
+ const { code, message, env, payloadMessage } = args;
29
+ return {
30
+ ok: false,
31
+ code,
32
+ message,
33
+ ...(payloadMessage !== undefined ? { payloadMessage } : {}),
34
+ ...(env.servedRows !== undefined && env.servedRows.length > 0
35
+ ? { servedRows: env.servedRows }
36
+ : {}),
37
+ ...(env.servedBlock !== undefined ? { servedBlock: env.servedBlock } : {}),
38
+ ...(env.cause !== undefined ? { cause: env.cause, details: { code, cause: env.cause } } : {}),
39
+ };
40
+ }
41
+
42
+ function toFailure(error: unknown): MutationResult {
43
+ // WHY: registry errors carry their code, rows, block, and diagnosis as typed
44
+ // WHY: fields — the code is read, never scraped from the message, so a
45
+ // WHY: `[MODEL]`-only message can never surface as `code: "MODEL"`.
46
+ if (error instanceof DomainError) {
47
+ // WHY: a rendered refusal cannot be re-attributed at the tool seam.
48
+ // WHY: The RAW payload message travels beside it, undefined for every other code.
49
+ const payloadMessage = badPayloadMessageOf(error);
50
+ return failureFromEnvelope({
51
+ code: error.code,
52
+ message: error.message,
53
+ env: readEnvelope(error) ?? {},
54
+ ...(payloadMessage !== undefined ? { payloadMessage } : {}),
55
+ });
56
+ }
57
+ const message = error instanceof Error ? error.message : String(error);
58
+ // WHY: the batch-abort wrapper preserves the failing item's own code as a
59
+ // WHY: plain field — a registry member routes the typed path, while
60
+ // WHY: errno-style codes (ENOENT) and unexpected throws fall through to
61
+ // WHY: `E_UNKNOWN` instead of leaking a scraped token as the code. The
62
+ // WHY: envelope reader owns that validation: a non-registry code reads back
63
+ // WHY: as no code at all, which is exactly the fall-through condition.
64
+ const env = readEnvelope(error);
65
+ if (env !== undefined && env.code !== undefined) {
66
+ return failureFromEnvelope({ code: env.code, message, env });
67
+ }
68
+ // WHY: unexpected errors emit `E_UNKNOWN` through the registry: the first
69
+ // WHY: message line only, never the verbatim `String(error)` dump.
70
+ const unknown = new DomainError("E_UNKNOWN", {
71
+ errorName: error instanceof Error ? error.name : typeof error,
72
+ message,
73
+ });
74
+ return failureFromEnvelope({
75
+ code: unknown.code,
76
+ message: unknown.message,
77
+ env: readEnvelope(unknown) ?? {},
78
+ });
79
+ }
80
+
81
+ /**
82
+ * SAFETY: Execute a mutation against the file system (persist + undo + serve).
83
+ * Returns discriminated `MutationResult` — callers must switch on `ok`.
84
+ *
85
+ * No `any` threading: input is `NormalizedEditRequest` (validated at
86
+ * admission), output is typed. Failures are `ok:false` with `code`, not
87
+ * loose `isError` flags.
88
+ */
89
+ export async function execute(
90
+ request: NormalizedEditRequest,
91
+ cwd: string,
92
+ options?: PipelineOptions,
93
+ ): Promise<MutationResult> {
94
+ try {
95
+ const { result, diff, drift, metrics, raw, toolResult } = await pipelineApply(
96
+ request,
97
+ cwd,
98
+ options,
99
+ );
100
+ if (!metrics) throw new Error("missing metrics from pipeline — invariant violation");
101
+ return {
102
+ ok: true,
103
+ result,
104
+ diff,
105
+ drift,
106
+ metrics,
107
+ raw,
108
+ toolResult,
109
+ };
110
+ } catch (error) {
111
+ return toFailure(error);
112
+ }
113
+ }
114
+
115
+ /**
116
+ * SAFETY: Preview a mutation without persisting (noPersist). Same seam as `execute`,
117
+ * same `MutationResult` — one interface, N call sites (preview + apply share
118
+ * the internal path via `runMutations` with `noPersist:true`).
119
+ */
120
+ export async function preview(
121
+ request: NormalizedEditRequest,
122
+ cwd: string,
123
+ options?: Omit<PipelineOptions, "noPersist">,
124
+ ): Promise<MutationResult> {
125
+ try {
126
+ // WHY: pipelinePreview does not persist and does not write undo — but still
127
+ // WHY: runs the full mutate→finalize→drift path. An edit call targets one file, so there
128
+ // WHY: is no second plan to project.
129
+ const file = await pipelinePreview(request, cwd, options);
130
+ // WHY: #174 single-projection contract — the preview diff IS the `genDiff` projection,
131
+ // WHY: produced here at the same seam that returns execute's projected `diff`, with the
132
+ // WHY: preview pane's context (`DIFF_PREVIEW_CONTEXT`). The display path (`edit-tool
133
+ // WHY: preview` → preview-controller → edit-render) consumes this text and never
134
+ // WHY: re-projects; `file` already carries everything `genDiff` needs, so no side
135
+ // WHY: decision of an empty diff is synthesized here.
136
+ const diff = genDiff(
137
+ file.originalNormalized,
138
+ file.result,
139
+ DIFF_PREVIEW_CONTEXT,
140
+ file.resultHashes,
141
+ file.originalHashes,
142
+ ).diff;
143
+ const metrics: import("../edit-response.js").RMetrics = {
144
+ classification: (file.appliedCount > 0 ? "applied" : "noop") as "applied" | "noop",
145
+ edits_attempted: file.appliedCount + file.noopCount,
146
+ edits_noop: file.noopCount,
147
+ warnings: file.warnings.length,
148
+ added_lines: file.totalAddedLines,
149
+ removed_lines: file.totalRemovedLines,
150
+ ...(file.literalDeclarations > 0 ? { literalDeclarations: file.literalDeclarations } : {}),
151
+ };
152
+ const details: import("../edit-response.js").EditDetails = {
153
+ diff,
154
+ ...(file.warnings.length > 0 ? { warnings: file.warnings } : {}),
155
+ ...(file.driftNotice !== undefined ? { driftNotice: file.driftNotice } : {}),
156
+ metrics,
157
+ servedRows: [],
158
+ };
159
+ return {
160
+ ok: true,
161
+ result: file.result,
162
+ diff,
163
+ drift: file.driftNotice,
164
+ metrics,
165
+ raw: file,
166
+ toolResult: { content: [{ type: "text", text: diff }], details },
167
+ };
168
+ } catch (error) {
169
+ return toFailure(error);
170
+ }
171
+ }
172
+
173
+ // WHY: Re-export for callers that need the throw-based legacy path.
174
+
175
+ export { toFailure };
@@ -0,0 +1,37 @@
1
+ import type { DomainErrorCode, RangeCause, ServedRow } from "./domain-errors.js";
2
+ import type { EditDetails, RMetrics } from "./edit-response.js";
3
+ import type { ProcessedEditFile } from "./mutation-engine/types.js";
4
+
5
+ export interface MutationSuccess {
6
+ ok: true;
7
+ result: string;
8
+ diff: string;
9
+ drift: string | undefined;
10
+ metrics: RMetrics;
11
+ raw: ProcessedEditFile;
12
+ toolResult: {
13
+ content: Array<{ type: "text"; text: string }>;
14
+ details: EditDetails;
15
+ };
16
+ }
17
+
18
+ interface MutationFailure {
19
+ ok: false;
20
+ code: DomainErrorCode;
21
+ message: string;
22
+ servedBlock?: string;
23
+ servedRows?: ServedRow[];
24
+ payloadMessage?: string;
25
+ cause?: RangeCause;
26
+ details?: { code: DomainErrorCode; cause: RangeCause };
27
+ }
28
+
29
+ export type MutationResult = MutationSuccess | MutationFailure;
30
+
31
+ export function isMutationSuccess(r: MutationResult): r is MutationSuccess {
32
+ return r.ok === true;
33
+ }
34
+
35
+ export function isMutationFailure(r: MutationResult): r is MutationFailure {
36
+ return r.ok === false;
37
+ }