@oh-my-pi-zen/hashline 16.3.6-zen.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.
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Result returned by {@link Filesystem.writeText}. The patcher echoes back
3
+ * `text` so adapters that transform on serialization (e.g. notebooks) can
4
+ * report what actually landed on disk.
5
+ */
6
+ export interface WriteResult {
7
+ /** Final text that was persisted. May differ from the input if the FS transformed it. */
8
+ text: string;
9
+ }
10
+ import type { FileOp } from "./types";
11
+ /** Optional hints for {@link Filesystem.preflightWrite}. */
12
+ export interface PreflightWriteOptions {
13
+ fileOp?: FileOp;
14
+ }
15
+ /**
16
+ * ENOENT-like error thrown by {@link Filesystem.readText} when a path is
17
+ * missing. Carrying a `code` property keeps the contract compatible with
18
+ * `node:fs` callers that already check `err.code === "ENOENT"`.
19
+ */
20
+ export declare class NotFoundError extends Error {
21
+ readonly code = "ENOENT";
22
+ constructor(path: string, cause?: unknown);
23
+ }
24
+ /** Type guard for {@link NotFoundError} and structurally-compatible errors. */
25
+ export declare function isNotFound(error: unknown): boolean;
26
+ /**
27
+ * Abstract storage backend the {@link Patcher} reads from and writes to.
28
+ * Subclass for new backends; the package ships {@link InMemoryFilesystem} and
29
+ * {@link NodeFilesystem} for the most common cases.
30
+ *
31
+ * Implementations work with raw text — the patcher handles BOM stripping and
32
+ * line-ending normalization itself. `readText` MUST throw {@link
33
+ * NotFoundError} (or any error for which {@link isNotFound} returns true)
34
+ * when the path doesn't exist; that's how the patcher detects a create-vs-
35
+ * update.
36
+ */
37
+ export declare abstract class Filesystem {
38
+ /** Read the file's full text content. Throw on missing file. */
39
+ abstract readText(path: string): Promise<string>;
40
+ /** Read raw bytes for backends whose text is a direct decode of persisted bytes. */
41
+ readBinary?(path: string): Promise<Uint8Array | undefined>;
42
+ /** Validate that `path` is writable before a prepared batch starts committing. */
43
+ preflightWrite(_path: string, _options?: PreflightWriteOptions): Promise<void>;
44
+ /** Persist `content` at `path`. Returns the actual final text that was written. */
45
+ abstract writeText(path: string, content: string): Promise<WriteResult>;
46
+ /** Delete the file at `path`. Default: not supported. */
47
+ delete(path: string): Promise<void>;
48
+ /**
49
+ * Move/rename `from` to `to`. When `content` is provided the destination
50
+ * receives that text; otherwise implementations may preserve the source bytes.
51
+ */
52
+ move(from: string, to: string, content?: string): Promise<void>;
53
+ /** Return true when the path exists and can be read. Default: probe via {@link readText}. */
54
+ exists(path: string): Promise<boolean>;
55
+ /**
56
+ * Canonical path used as a key by external caches (e.g. snapshot
57
+ * stores). The default is identity; override to return an absolute or
58
+ * otherwise canonicalised path so producers and consumers of cached
59
+ * snapshots agree on the key without each having to redo the resolution.
60
+ */
61
+ canonicalPath(path: string): string;
62
+ /**
63
+ * Whether a section whose authored path is missing may be redirected to
64
+ * the file its snapshot tag names (tag-based path recovery in
65
+ * {@link Patcher.prepare}). `resolvedPath` is the canonical path the
66
+ * redirect would read and write. Default: allow.
67
+ *
68
+ * Hosts that grant write privileges by path shape override this to refuse
69
+ * redirects that could escalate beyond what the caller approved — e.g. an
70
+ * internal-URL authored target (approved read-only), or a `resolvedPath`
71
+ * outside the working tree (a sandbox/vault/out-of-tree write).
72
+ */
73
+ allowTagPathRecovery(_authoredPath: string, _resolvedPath: string): boolean;
74
+ }
75
+ /**
76
+ * In-memory {@link Filesystem}. Useful for tests, sandboxes, dry-runs, and as
77
+ * a building block for stacked adapters (e.g. an LRU layer on top).
78
+ */
79
+ export declare class InMemoryFilesystem extends Filesystem {
80
+ #private;
81
+ constructor(initial?: Iterable<readonly [string, string]>);
82
+ readText(path: string): Promise<string>;
83
+ writeText(path: string, content: string): Promise<WriteResult>;
84
+ delete(path: string): Promise<void>;
85
+ move(from: string, to: string, content?: string): Promise<void>;
86
+ exists(path: string): Promise<boolean>;
87
+ /** Synchronous helper for setting up fixtures without awaiting. */
88
+ set(path: string, content: string): void;
89
+ /** Synchronous helper for inspecting state without awaiting. */
90
+ get(path: string): string | undefined;
91
+ /** Wipe all entries. */
92
+ clear(): void;
93
+ /** Iterate `[path, content]` pairs. */
94
+ entries(): IterableIterator<[string, string]>;
95
+ }
96
+ /**
97
+ * Disk-backed {@link Filesystem} using Bun's file APIs. The default for CLI
98
+ * use. Paths are accepted as-is; callers responsible for any cwd or
99
+ * jail/sandbox resolution should wrap this with their own subclass.
100
+ */
101
+ export declare class NodeFilesystem extends Filesystem {
102
+ readText(path: string): Promise<string>;
103
+ readBinary(path: string): Promise<Uint8Array>;
104
+ writeText(path: string, content: string): Promise<WriteResult>;
105
+ delete(path: string): Promise<void>;
106
+ move(from: string, to: string, content?: string): Promise<void>;
107
+ canonicalPath(path: string): string;
108
+ exists(path: string): Promise<boolean>;
109
+ }
@@ -0,0 +1,17 @@
1
+ export * from "./apply";
2
+ export * from "./block";
3
+ export * from "./diff-preview";
4
+ export * from "./format";
5
+ export * from "./fs";
6
+ export * from "./input";
7
+ export * from "./messages";
8
+ export * from "./mismatch";
9
+ export * from "./normalize";
10
+ export * from "./parser";
11
+ export * from "./patcher";
12
+ export * from "./prefixes";
13
+ export * from "./recovery";
14
+ export * from "./snapshots";
15
+ export * from "./stream";
16
+ export * from "./tokenizer";
17
+ export * from "./types";
@@ -0,0 +1,110 @@
1
+ import type { ApplyResult, BlockResolver, Edit, FileOp, SplitOptions } from "./types";
2
+ interface RawSection {
3
+ path: string;
4
+ fileHash?: string;
5
+ diff: string;
6
+ }
7
+ /**
8
+ * Returns true when the input contains at least one line that the tokenizer
9
+ * recognizes as a hashline op. Used by streaming previews to decide whether
10
+ * the partial input is worth treating as a hashline patch yet.
11
+ */
12
+ export declare function containsRecognizableHashlineOperations(input: string): boolean;
13
+ /**
14
+ * Snapshot of one section in a parsed {@link Patch}: a target file plus the
15
+ * lazily-parsed list of edits that should land on it. Constructed by
16
+ * {@link Patch.parse}; consumers usually iterate `patch.sections` rather
17
+ * than build these directly.
18
+ */
19
+ export declare class PatchSection {
20
+ #private;
21
+ readonly path: string;
22
+ readonly fileHash: string | undefined;
23
+ readonly diff: string;
24
+ constructor(raw: RawSection);
25
+ /**
26
+ * Parse this section's diff body. Cached: subsequent calls return the
27
+ * same `{ edits, fileOp?, warnings }` object so callers can safely call this from
28
+ * multiple paths (preflight, apply, diff-preview).
29
+ */
30
+ parse(): {
31
+ edits: Edit[];
32
+ fileOp?: FileOp;
33
+ warnings: readonly string[];
34
+ };
35
+ /** Parsed edits for this section. */
36
+ get edits(): readonly Edit[];
37
+ /** Optional whole-file operation (`REM` / `MV`). */
38
+ get fileOp(): FileOp | undefined;
39
+ /** Warnings emitted during parsing of this section. */
40
+ get warnings(): readonly string[];
41
+ /**
42
+ * True when at least one edit anchors to concrete file content. Pure
43
+ * `insert head:` / `insert tail:` literal inserts do not count: those are
44
+ * safe to apply to files that don't yet exist.
45
+ */
46
+ get hasAnchorScopedEdit(): boolean;
47
+ /** Anchor lines touched by this section, sorted ascending and deduplicated. */
48
+ collectAnchorLines(): readonly number[];
49
+ /**
50
+ * Apply this section's edits to `text` and return the post-edit result.
51
+ * Pure: does no I/O, does not validate the section snapshot tag. The
52
+ * {@link Patcher} owns tag validation and recovery; reach for this
53
+ * method directly when you've already validated the file content and
54
+ * just want the result.
55
+ *
56
+ * `blockResolver` resolves any `replace_block N:` edits against `text`; an
57
+ * unresolvable block throws (this is the final, authoritative preview path).
58
+ */
59
+ applyTo(text: string, blockResolver?: BlockResolver): ApplyResult;
60
+ /**
61
+ * Streaming-tolerant counterpart to {@link applyTo}. Uses
62
+ * {@link parsePatchStreaming} so a trailing in-flight op (no payload yet,
63
+ * or a per-token parse error mid-stream) does not throw or emit a phantom
64
+ * empty-payload edit. Intended for incremental diff previews; the writer
65
+ * path should always use {@link applyTo}.
66
+ *
67
+ * `blockResolver` resolves any `replace_block N:` edits against `text`; an
68
+ * unresolvable block is silently dropped so a half-written file does not
69
+ * throw mid-stream.
70
+ */
71
+ applyPartialTo(text: string, blockResolver?: BlockResolver): ApplyResult;
72
+ /**
73
+ * A copy of this section rebound to a different target `path`, preserving
74
+ * the snapshot tag, diff body, and any cached parse result. Used by the
75
+ * patcher's tag-based path recovery to redirect an edit whose authored
76
+ * path does not exist onto the file its snapshot tag actually names.
77
+ */
78
+ withPath(path: string): PatchSection;
79
+ }
80
+ /**
81
+ * A parsed hashline patch — zero or more {@link PatchSection}s, each rooted
82
+ * at a `[PATH#HASH]` header. Construct via {@link Patch.parse}.
83
+ *
84
+ * `Patch` is pure data: parsing is line-anchored and does not look at the
85
+ * filesystem. To apply a patch, hand it to {@link Patcher.apply}.
86
+ */
87
+ export declare class Patch {
88
+ readonly sections: readonly PatchSection[];
89
+ private constructor();
90
+ /**
91
+ * Parse `input` into a {@link Patch}. `options.cwd` resolves absolute
92
+ * paths inside headers to cwd-relative form; `options.path` provides a
93
+ * fallback when the input lacks a header but contains hashline ops
94
+ * (useful for streaming previews).
95
+ *
96
+ * Consecutive sections targeting the same path are merged into a single
97
+ * section with concatenated diff bodies. Anchors authored against the
98
+ * same file snapshot must be applied as one batch; otherwise the first
99
+ * sub-edit shifts line numbers out from under the second's anchors and
100
+ * validation fails.
101
+ */
102
+ static parse(input: string, options?: SplitOptions): Patch;
103
+ /**
104
+ * Parse `input` and return only the first section. Throws if the input
105
+ * has zero sections. Convenience for the single-section case where the
106
+ * caller already knows the patch is one hunk.
107
+ */
108
+ static parseSingle(input: string, options?: SplitOptions): PatchSection;
109
+ }
110
+ export {};
@@ -0,0 +1,147 @@
1
+ /** Centralized error/warning text for the hashline parser, applier, and patcher. */
2
+ /** Lines of context shown either side of a hash mismatch. */
3
+ export declare const MISMATCH_CONTEXT = 2;
4
+ /**
5
+ * Numbered `LINE:TEXT` rows around `anchorLines` (±{@link MISMATCH_CONTEXT}),
6
+ * `*`-marking anchors, `...` between non-adjacent runs. Out-of-range anchors
7
+ * contribute no rows.
8
+ */
9
+ export declare function formatAnchoredContext(anchorLines: readonly number[], fileLines: readonly string[]): string[];
10
+ /** Optional patch envelope start marker; silently consumed. */
11
+ export declare const BEGIN_PATCH_MARKER = "*** Begin Patch";
12
+ /** Optional patch envelope end marker; terminates parsing. */
13
+ export declare const END_PATCH_MARKER = "*** End Patch";
14
+ /**
15
+ * Truncation sentinel emitted by an agent loop mid-call. Ends parsing like
16
+ * {@link END_PATCH_MARKER}, without a warning.
17
+ */
18
+ export declare const ABORT_MARKER = "*** Abort";
19
+ /** Two consecutive hunks targeted the exact same concrete range. */
20
+ export declare const REPLACE_PAIR_COALESCED_WARNING = "Two hunks targeted the same range; kept only the second. One `SWAP N.=M:` hunk per range \u2014 the body is the final content, never old+new.";
21
+ /** Bare body rows auto-converted to literal `+` rows. */
22
+ export declare const BARE_BODY_AUTO_PIPED_WARNING = "Auto-prefixed bare body row(s) with `+`. Body rows must be `+TEXT` literal lines.";
23
+ /** Unified-diff-style `-` row in a hunk body. */
24
+ export declare const MINUS_ROW_REJECTED = "`-` rows are not valid; the range already names the lines being changed. For Markdown bullets or other literal `-` lines, prefix the literal row with `+`: `+- item`.";
25
+ /** Replace hunk with no body. */
26
+ export declare const EMPTY_REPLACE = "`SWAP N.=M:` needs at least one `+TEXT` body row. To delete lines, use `DEL N.=M`.";
27
+ /** `replace_block N:` hunk with no body. */
28
+ export declare const EMPTY_BLOCK = "`SWAP.BLK N:` needs at least one `+TEXT` body row. To delete a block, use `DEL.BLK N`.";
29
+ /**
30
+ * Block-anchored replace/delete could not resolve to a syntactic block
31
+ * (unsupported language, blank/out-of-range line, no node beginning on N, or
32
+ * parse error). Appends a {@link formatAnchoredContext} preview when
33
+ * `fileLines` is given. `insert_after_block N:` never reaches this — it is
34
+ * lowered to plain `insert after N:` instead (see
35
+ * {@link insertAfterBlockUnresolvedLoweredWarning}).
36
+ */
37
+ export declare function blockUnresolvedMessage(line: number, op?: "replace" | "delete", fileLines?: readonly string[]): string;
38
+ /** Block-anchored edit reached a path with no {@link BlockResolver} wired in — a host-configuration bug. */
39
+ export declare const BLOCK_RESOLVER_UNAVAILABLE = "`SWAP.BLK`/`DEL.BLK`/`INS.BLK.POST` are not available here (no block resolver configured). Use a concrete line range.";
40
+ /**
41
+ * `insert_after_block N:` anchored on a closing-delimiter line, lowered to
42
+ * plain `insert after N:` — the closer ends a block, and inserting after it
43
+ * is exactly what the plain form does.
44
+ */
45
+ export declare function insertAfterBlockCloserLoweredWarning(line: number): string;
46
+ /**
47
+ * `insert_after_block N:` anchor unresolvable (unsupported language, blank
48
+ * line, parse error, or no resolver), lowered to plain `insert after N:` —
49
+ * applying with a warning beats failing the patch.
50
+ */
51
+ export declare function insertAfterBlockUnresolvedLoweredWarning(line: number): string;
52
+ /**
53
+ * Internal invariant: `applyEdits` received an unresolved `replace_block N:`
54
+ * edit; `resolveBlockEdits` must run first. Wiring bug, not authored input.
55
+ */
56
+ export declare const UNRESOLVED_BLOCK_INTERNAL = "internal error: unresolved `SWAP.BLK` edit reached the applier (resolveBlockEdits was not run).";
57
+ /** Delete hunk received a body row. */
58
+ export declare const DELETE_TAKES_NO_BODY = "`DEL N.=M` does not take body rows. Remove the body, or use `SWAP N.=M:`.";
59
+ /** `REM` received a body row or coexists with line edits. */
60
+ export declare const REM_TAKES_NO_BODY = "`REM` deletes the whole file and takes no body rows or line ops. Issue it alone under the header.";
61
+ /** `MV` received a body row. */
62
+ export declare const MOVE_TAKES_NO_BODY = "`MV DEST` does not take body rows. Put line edits above the `MV` row; the destination path follows `MV` on the same line.";
63
+ /** `delete_block N` hunk received a body row. */
64
+ export declare const DELETE_BLOCK_TAKES_NO_BODY = "`DEL.BLK N` does not take body rows. Remove the body, or use `SWAP.BLK N:`.";
65
+ /** Insert hunk with no body. */
66
+ export declare const EMPTY_INSERT = "`INS` needs at least one `+TEXT` body row.";
67
+ /**
68
+ * `insert after` body indented shallower than the anchor: the landing slid
69
+ * forward past trailing closer lines — the common "anchored on the last line
70
+ * I read instead of after the block" mistake.
71
+ */
72
+ export declare function afterInsertLandingShiftWarning(anchorLine: number, landingLine: number, crossed: number): string;
73
+ /**
74
+ * `insert_after_block N:` body indented deeper than the block's closer: the
75
+ * landing was pulled inside the block — a deeper body almost always means
76
+ * "append inside the block's body".
77
+ */
78
+ export declare function blockInsertLandingShiftWarning(blockStart: number, closerLine: number, landingLine: number): string;
79
+ /** `Recovery`: an external write matched a cached snapshot. */
80
+ export declare const RECOVERY_EXTERNAL_WARNING = "Recovered from a stale file hash using a previous read snapshot (file changed externally between read and edit).";
81
+ /** `Recovery`: a prior in-session edit advanced the hash. */
82
+ export declare const RECOVERY_SESSION_CHAIN_WARNING = "Recovered from a stale file hash using an earlier in-session snapshot (a prior edit in this session advanced the hash).";
83
+ /**
84
+ * `Recovery`: session-chain replay fast-path. Less certain than
85
+ * {@link RECOVERY_SESSION_CHAIN_WARNING} — the 3-way merge refused, the
86
+ * anchor-content gate passed, but a coincidental insert+delete earlier in
87
+ * the chain could still misplace an anchor — hence the verify hedge.
88
+ */
89
+ export declare const RECOVERY_SESSION_REPLAY_WARNING = "Recovered by replaying your edits onto the current file content (a prior in-session edit changed the lines you re-targeted with a stale hash). Verify the diff matches your intent.";
90
+ /** `Recovery`: stale anchors were relocated to unchanged live lines after drift. */
91
+ export declare const RECOVERY_LINE_REMAP_WARNING = "Recovered by remapping stale line anchors to unchanged current lines (file changed since the tagged read). Verify the diff matches your intent.";
92
+ /**
93
+ * `insert head:`/`insert tail:` applied despite a stale snapshot tag.
94
+ * Head/tail position is content-independent, so drift is non-fatal: apply
95
+ * onto live content and warn instead of hard-failing.
96
+ */
97
+ export declare const HEADTAIL_DRIFT_WARNING = "Applied the `INS.HEAD:`/`INS.TAIL:` edit despite a stale snapshot tag (file changed since your read) \u2014 head/tail position is content-independent. Re-read if the drift was unexpected.";
98
+ /**
99
+ * Section omitted the mandatory snapshot tag. Shared by the apply
100
+ * ({@link Patcher.prepare}) and preview/diff paths so both stay in lockstep.
101
+ */
102
+ export declare function missingSnapshotTagMessage(sectionPath: string): string;
103
+ /**
104
+ * A section named a path that does not exist, but its filename and snapshot
105
+ * tag together match exactly one file read earlier this session — the model
106
+ * gave the bare filename (or wrong directory) for a file it just read. The
107
+ * edit was rebound to that file's full path. Surfaced as a warning so the
108
+ * model (and user) learn the corrected path and stop reusing the wrong one.
109
+ */
110
+ export declare function pathRecoveredFromTagMessage(authoredPath: string, resolvedPath: string, tag: string): string;
111
+ /** One anchored line whose actual content is being surfaced in an error message. */
112
+ export interface RevealedLine {
113
+ line: number;
114
+ text: string;
115
+ }
116
+ /**
117
+ * Content preview handed to {@link unseenLinesMessage}. `lines` are the
118
+ * unseen anchor lines whose actual file content we surface inline (from the
119
+ * tagged snapshot the caller matched). `truncated` = true means the anchor
120
+ * range exceeded the inline reveal cap; the caller only revealed a prefix
121
+ * and the remaining unseen lines still require a range re-read.
122
+ */
123
+ export interface UnseenLinesReveal {
124
+ lines: readonly RevealedLine[];
125
+ truncated: boolean;
126
+ }
127
+ /**
128
+ * An anchored edit referenced lines the read that minted the cited tag never
129
+ * displayed (a partial range, or a structural summary that collapsed bodies).
130
+ * Editing lines you have not read is the off-by-memory failure that mangles
131
+ * files. When `reveal.lines` is non-empty, the caller has already inlined the
132
+ * actual file content at those lines and merged them into the snapshot's
133
+ * seen-line set, so the message points the model at a straight retry with the
134
+ * same `[path#tag]` header; when the reveal is empty or truncated, the
135
+ * message falls back to instructing a range re-read.
136
+ */
137
+ export declare function unseenLinesMessage(sectionPath: string, unseenLines: readonly number[], tag: string, reveal?: UnseenLinesReveal): string;
138
+ /** Op kind of a deferred block edit, for {@link blockSingleLineMessage}. */
139
+ export type BlockOp = "replace" | "delete" | "insert_after";
140
+ /**
141
+ * A `replace_block`/`delete_block`/`insert_after_block` anchor resolved to a
142
+ * single line — almost always a bare statement the model mis-anchored, not a
143
+ * multi-line construct. The plain op is unambiguous for one line; the block
144
+ * form only earns its keep when it spares counting a closing line you cannot
145
+ * see. Reject and point at both fixes.
146
+ */
147
+ export declare function blockSingleLineMessage(line: number, op: BlockOp): string;
@@ -0,0 +1,44 @@
1
+ /** Format the required-shape diagnostic shown when a line reference is malformed. */
2
+ export declare function formatFullAnchorRequirement(raw?: string): string;
3
+ /** Parse a decorated bare line-number anchor like `42`, `*42:foo`, ` > 7`. */
4
+ export declare function parseTag(ref: string): {
5
+ line: number;
6
+ };
7
+ export interface MismatchDetails {
8
+ path?: string;
9
+ expectedFileHash: string;
10
+ actualFileHash: string;
11
+ fileLines: string[];
12
+ anchorLines?: readonly number[];
13
+ /**
14
+ * `true` when the section's expected hash resolved to a recorded snapshot
15
+ * (file content drifted since that snapshot), `false` when no snapshot
16
+ * was ever recorded for the hash (likely fabricated or carried over from
17
+ * a prior session). Drives a more actionable rejection message; defaults
18
+ * to `true` for backward compatibility with direct callers.
19
+ */
20
+ hashRecognized?: boolean;
21
+ }
22
+ /**
23
+ * Raised when a hashline section's snapshot tag doesn't match the live file's
24
+ * content (and recovery, if configured, declined the merge). Carries the
25
+ * file lines plus anchored lines so renderers can produce a richer
26
+ * diagnostic via {@link MismatchError.displayMessage}.
27
+ */
28
+ export declare class MismatchError extends Error {
29
+ readonly path: string | undefined;
30
+ readonly expectedFileHash: string;
31
+ readonly actualFileHash: string;
32
+ readonly fileLines: string[];
33
+ readonly anchorLines: readonly number[];
34
+ readonly hashRecognized: boolean;
35
+ constructor(details: MismatchDetails);
36
+ get displayMessage(): string;
37
+ static rejectionHeader(details: MismatchDetails): string[];
38
+ static formatDisplayMessage(details: MismatchDetails): string;
39
+ static formatMessage(details: MismatchDetails): string;
40
+ }
41
+ /** Throws when the line reference is out of bounds for the given file. */
42
+ export declare function validateLineRef(ref: {
43
+ line: number;
44
+ }, fileLines: string[]): void;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Minimal text-shape normalization: line-ending detection / round-trip and
3
+ * BOM stripping. The patcher uses these to canonicalize text to LF before
4
+ * applying edits and to restore the original shape on write-back.
5
+ */
6
+ export type LineEnding = "\r\n" | "\n";
7
+ /** Detect the first line ending style in `content`. Defaults to LF when neither is present. */
8
+ export declare function detectLineEnding(content: string): LineEnding;
9
+ /** Normalize every line ending to LF. */
10
+ export declare function normalizeToLF(text: string): string;
11
+ /** Re-encode LF text with the requested line ending. */
12
+ export declare function restoreLineEndings(text: string, ending: LineEnding): string;
13
+ export interface BomResult {
14
+ /** Either the empty string or the BOM sequence (currently UTF-8 BOM). */
15
+ bom: string;
16
+ /** Text with any leading BOM removed. */
17
+ text: string;
18
+ }
19
+ /** Strip a UTF-8 BOM if present and return both the BOM and the trailing text. */
20
+ export declare function stripBom(content: string): BomResult;
@@ -0,0 +1,27 @@
1
+ import { type Token } from "./tokenizer";
2
+ import type { Edit, FileOp } from "./types";
3
+ export declare class Executor {
4
+ #private;
5
+ feed(token: Token): void;
6
+ end(): {
7
+ edits: Edit[];
8
+ fileOp?: FileOp;
9
+ warnings: string[];
10
+ };
11
+ endStreaming(): {
12
+ edits: Edit[];
13
+ fileOp?: FileOp;
14
+ warnings: string[];
15
+ };
16
+ reset(): void;
17
+ }
18
+ export declare function parsePatch(diff: string): {
19
+ edits: Edit[];
20
+ fileOp?: FileOp;
21
+ warnings: string[];
22
+ };
23
+ export declare function parsePatchStreaming(diff: string): {
24
+ edits: Edit[];
25
+ fileOp?: FileOp;
26
+ warnings: string[];
27
+ };
@@ -0,0 +1,118 @@
1
+ import type { Filesystem } from "./fs";
2
+ import type { Patch, PatchSection } from "./input";
3
+ import { type LineEnding } from "./normalize";
4
+ import { Recovery } from "./recovery";
5
+ import type { SnapshotStore } from "./snapshots";
6
+ import type { ApplyResult, BlockResolution, BlockResolver, FileOp } from "./types";
7
+ export interface PatcherOptions {
8
+ /** Storage backend used for all reads and writes. */
9
+ fs: Filesystem;
10
+ /** Snapshot store that minted and resolves hashline section tags. Required. */
11
+ snapshots: SnapshotStore;
12
+ /**
13
+ * Resolves `replace_block N:` anchors to concrete line spans via tree-sitter.
14
+ * Optional: when omitted, any `replace_block N:` edit throws on apply (the
15
+ * host did not wire a resolver). Plain line-range ops never need it.
16
+ */
17
+ blockResolver?: BlockResolver;
18
+ }
19
+ /** Per-section result returned by {@link Patcher.apply} / {@link Patcher.commit}. */
20
+ export interface PatchSectionResult {
21
+ /** Section path (as authored, after cwd-resolution at parse time). */
22
+ path: string;
23
+ /** Filesystem-canonical key for this section (e.g. absolute path). */
24
+ canonicalPath: string;
25
+ /** `"noop"` when the apply produced no change; `"delete"` removes the file; otherwise `"create"` / `"update"`. */
26
+ op: "create" | "update" | "delete" | "noop";
27
+ /** Pre-edit text (LF-normalized, BOM-stripped). */
28
+ before: string;
29
+ /** Post-edit text (LF-normalized, BOM-stripped). For `"noop"` equals `before`. */
30
+ after: string;
31
+ /** Same text as `after` but with the original BOM and line ending restored. */
32
+ persisted: string;
33
+ /** Final text that the {@link Filesystem} actually wrote (may differ if the FS transformed it). */
34
+ written: string;
35
+ /** 4-hex content-hash tag for `after`. Use to anchor follow-up edits. */
36
+ fileHash: string;
37
+ /** Hashline section header (`[path#tag]`) of the post-edit content. */
38
+ header: string;
39
+ /** 1-indexed first changed line in `after`, or `undefined` for noops. */
40
+ firstChangedLine?: number;
41
+ /** Warnings collected by the parser, applier, and (optionally) recovery. */
42
+ warnings: string[];
43
+ /** Destination path when this section includes `MV DEST`. */
44
+ moveDest?: string;
45
+ /**
46
+ * Resolved spans for any `replace_block`/`delete_block` ops, present when the
47
+ * apply matched the tagged content. Undefined for patches with no block ops
48
+ * (and for resolutions routed through drift recovery, where numbers shift).
49
+ */
50
+ blockResolutions?: BlockResolution[];
51
+ }
52
+ export interface PatcherApplyResult {
53
+ sections: PatchSectionResult[];
54
+ }
55
+ /**
56
+ * Opaque token returned by {@link Patcher.prepare}. Carries the section, the
57
+ * raw file content read off disk, and the in-memory apply result.
58
+ * {@link Patcher.commit} just writes the {@link PreparedSection.applyResult}.
59
+ */
60
+ export declare class PreparedSection {
61
+ readonly section: PatchSection;
62
+ readonly canonicalPath: string;
63
+ readonly exists: boolean;
64
+ readonly rawContent: string;
65
+ readonly bom: string;
66
+ readonly lineEnding: LineEnding;
67
+ readonly normalized: string;
68
+ readonly applyResult: ApplyResult;
69
+ readonly parseWarnings: readonly string[];
70
+ readonly fileOp: FileOp | undefined;
71
+ /** @internal */
72
+ constructor(section: PatchSection, canonicalPath: string, exists: boolean, rawContent: string, bom: string, lineEnding: LineEnding, normalized: string, applyResult: ApplyResult, parseWarnings: readonly string[], fileOp: FileOp | undefined);
73
+ /** Convenience: returns true when the apply produced no change and no file op. */
74
+ get isNoop(): boolean;
75
+ }
76
+ /**
77
+ * High-level patcher. Wires a {@link Filesystem} and a required
78
+ * {@link SnapshotStore} together with the parsing + applying core.
79
+ *
80
+ * Construct once per FS configuration; reuse across patches.
81
+ */
82
+ export declare class Patcher {
83
+ #private;
84
+ readonly fs: Filesystem;
85
+ readonly snapshots: SnapshotStore;
86
+ readonly recovery: Recovery;
87
+ readonly blockResolver: BlockResolver | undefined;
88
+ constructor(options: PatcherOptions);
89
+ /**
90
+ * Apply every section in `patch`. `prepare` runs the full apply for each
91
+ * section in memory before any write hits the filesystem, so a
92
+ * multi-section batch is naturally all-or-nothing. Returns one
93
+ * {@link PatchSectionResult} per section in the original patch order.
94
+ */
95
+ apply(patch: Patch): Promise<PatcherApplyResult>;
96
+ /**
97
+ * Run the preflight pass only: read, parse, validate, apply-in-memory.
98
+ * No writes hit the filesystem. Use for CI checks and dry runs.
99
+ */
100
+ preflight(patch: Patch): Promise<void>;
101
+ /**
102
+ * Read a section's target file, parse the section, validate the snapshot
103
+ * tag (with recovery), and apply the edits in memory. Returns a
104
+ * {@link PreparedSection} which can be fed to {@link commit} to land
105
+ * the result on the filesystem.
106
+ *
107
+ * Throws on parse error, missing-file-for-anchored-edit, or unrecovered
108
+ * tag mismatch ({@link MismatchError}).
109
+ */
110
+ prepare(section: PatchSection): Promise<PreparedSection>;
111
+ /**
112
+ * Commit a previously {@link prepare}d section to the filesystem.
113
+ * Restores line endings and BOM, writes via the {@link Filesystem}, and
114
+ * records a fresh snapshot in the {@link SnapshotStore} keyed by the
115
+ * filesystem-canonical path.
116
+ */
117
+ commit(prepared: PreparedSection): Promise<PatchSectionResult>;
118
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * When a hashline payload is authored against `read`/`search` output, each
3
+ * line is prefixed with either a hashline-mode line number (`123:`) or, for
4
+ * diff-style echoes, a leading `+`. These helpers detect that and recover
5
+ * the raw text. Two strip modes are exposed:
6
+ *
7
+ * - {@link stripNewLinePrefixes} — opportunistic: strips when the input
8
+ * clearly carries hashline or diff prefixes, leaves it alone otherwise.
9
+ * - {@link stripHashlinePrefixes} — strict: only strips when every non-empty
10
+ * content line is hashline-prefixed.
11
+ *
12
+ * These run *before* the tokenizer; they exist because hashline mode is the
13
+ * common case for echoed file content, and erroneously echoed prefixes will
14
+ * otherwise turn every content line into a (malformed) op.
15
+ */
16
+ /**
17
+ * Single-pass variant of {@link stripLeadingHashlinePrefixes} that strips at
18
+ * most one leading hashline prefix (`N:`, `>>>N:`, `+N:` etc.) and does NOT
19
+ * loop. Use this when the input carries at most one snapshot prefix (e.g. a
20
+ * bare body row paste from `read` output) — recursive stripping would corrupt
21
+ * content whose own text starts with `digits:`.
22
+ */
23
+ export declare function stripOneLeadingHashlinePrefix(line: string): string;
24
+ /**
25
+ * Strip whichever prefix scheme the lines appear to be carrying:
26
+ * - hashline line-number prefixes (`123:`) when every content line has one
27
+ * - leading `+` (diff style) when at least half the lines have one
28
+ * - mixed `+<n>:` form when present
29
+ *
30
+ * Returns the lines untouched if no scheme is recognized.
31
+ */
32
+ export declare function stripNewLinePrefixes(lines: string[]): string[];
33
+ /**
34
+ * Strict variant: strip hashline prefixes only when every content line is
35
+ * hashline-prefixed. Returns the lines unchanged otherwise.
36
+ */
37
+ export declare function stripHashlinePrefixes(lines: string[]): string[];
38
+ /**
39
+ * Normalize line payloads by stripping read/search line prefixes. `null` /
40
+ * `undefined` yield `[]`; a single multiline string is split on `\n`.
41
+ */
42
+ export declare function hashlineParseText(edit: string[] | string | null | undefined): string[];