Repository navigation
Add hashline format + fs_edit_hashline + fs_grep built-in tools - #26
Conversation
Hashline lets the model edit by stable line-number anchors instead of
perfect-text reproduction, addressing the same failure mode that
str_replace hits ~50% of the time on many models. Pure-Pascal port of
the upstream oh-my-pi format primitives (Apache-2.0), both compilers.
New unit src/pkg/hashline/PasClaw.Hashline.pas:
- HL_* sigil constants (¶ header prefix, # hash separator, : line
separator, | replace, ↑ above, ↓ below) declared as literal
Unicode chars so each compiler stores them in its native string
form (Delphi UnicodeString one WideChar each, FPC UTF-8 AnsiString
with multi-byte encoding)
- xxHash32 implementation matching upstream Bun.hash so the 4-hex
file hash is byte-compatible with patches generated by oh-my-pi
- ComputeFileHash: CR-stripped + line-rtrimmed UTF-8 -> xxHash32 ->
low 16 bits -> 4-hex
- FormatHashlineRead: prepend ¶path#hash header + N: line prefixes
- StripHashlinePrefixes: defensive — strip N: prefixes only when
every non-empty content line carries one
- ParseHashlinePatch: tokenize multi-section patch into edit list
per file
- ApplyHashlineEdits: two-pass applier (collect deletes + bucket
inserts by anchor; rebuild output line-by-line with before/after
buckets); preserves trailing-newline shape
Tool changes in src/pkg/tools/PasClaw.Tools.FS.pas:
fs_read - now returns ¶path#hash header + N:line per source line
by default; pass {"plain": true} for raw bytes
fs_write - opportunistically strips N: prefixes when the model
copied them back from read output (reports it in the
success message)
fs_edit_hashline (NEW) - takes a {patch} arg; parses, validates the
¶path#hash header hash against the file on disk for
staleness, applies, writes back. Aborts cleanly on
stale/out-of-range without writing.
fs_grep (NEW) - recursive substring search; output is hashline-
formatted (one section per matched file, header +
LINENO:line per match) so the model can paste anchors
straight into fs_edit_hashline. Skips dotdirs, optional
include= comma-separated globs (filename mask).
Build wiring:
- Makefile UNIT_DIRS gains src/pkg/hashline (FPC)
- PasClaw.dproj DCCReference + DCC_UnitSearchPath updated (Delphi)
Recovery heuristics from the upstream package (multi-line dup auto-
absorb, structural-bracket boundary fixups, comment-line skipping
inside payloads) are deliberately omitted — they only matter once
production traffic surfaces the failure modes they were written for.
The format and the basic apply path are faithful so we can add them
incrementally without rework.
https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a146eb07d9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ErrMsg := Format('section %d (%s): %s', [i + 1, Sections[i].Path, ApplyErr]); | ||
| Exit(''); | ||
| end; | ||
| WriteFileText(Sections[i].Path, NewBody); |
There was a problem hiding this comment.
Defer writes until all sections validate
When a multi-section patch has an early section that applies cleanly and a later section with a stale hash, missing file, or out-of-range anchor, this writes the earlier file before returning an error for the later section. That violates the advertised all-or-nothing stale-patch behavior and leaves callers with a partially applied patch; validate/apply every section into memory first, then perform the writes only after all sections succeed.
Useful? React with 👍 / 👎.
| Exit(''); | ||
| end; | ||
| FileBody := ReadFileText(Sections[i].Path); | ||
| if Sections[i].HasFileHash then |
There was a problem hiding this comment.
Reject hashline patches that omit the hash
For patches whose header is just ¶path without #hash, TryParseHeader accepts the section with HasFileHash = False, and this branch skips the stale-file check entirely. In that scenario fs_edit_hashline can apply line-number edits to a file that has changed since the caller last read it, despite the tool contract saying the header hash must match; reject hashless sections or require validation before applying.
Useful? React with 👍 / 👎.
Multi-section fs_edit_hashline previously interleaved validation and
writes inside one loop. If section 0 applied and was written, then
section 1 failed validation (stale hash, missing file, or out-of-range
anchor), the handler returned an error while section 0's file was
already mutated on disk. That contradicted the advertised all-or-
nothing abort contract and left callers with a partial patch.
Two-pass now:
Pass 1 — read each file, validate path/hash, ApplyHashlineEdits to
an in-memory NewBody. Any failure exits before any write.
Pass 2 — only reached when every section applied cleanly; WriteFileText
each staged NewBody.
A disk-level write failure mid-pass-2 (out of space, permission denied
on a later file) can still partially commit; that's a filesystem-
atomicity concern beyond the hashline-format contract. The valid-but-
stale and structurally-broken cases — which is what the reviewer
flagged — now leave the working tree untouched.
https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
ParseHashlinePatch accepts both ¶path and ¶path#hash header forms — the optional-hash shape is documented upstream as useful for streaming previews and abbreviated diffs. But the fs_edit_hashline tool advertises the stronger contract that the header hash must match the file on disk, and the previous code's `if Sections[i].HasFileHash then` guard silently skipped the staleness check when the hash was absent. A model that omitted the hash could apply line-anchored edits to a file that had drifted since the read — exactly the silent corruption the format was designed to prevent. Fail the section with a clear instruction to re-read the file when the header has no #hash, so the format library stays liberal while the tool stays safe. Move the staleness check out of its conditional now that HasFileHash is guaranteed True at that point. https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
For models that struggle with the ¶path#hash + LINENO: prefixes, opt
out of hashline mode entirely. Wired through every command that builds
a tool registry:
pasclaw agent --no-hashline
pasclaw gateway --no-hashline
pasclaw serve --no-hashline
pasclaw tui --no-hashline
What it does (matched at the RegisterFSTools boundary so the model sees
a consistent set):
fs_read - returns raw bytes (no header, no LINENO: prefixes);
per-call {"plain": true} also becomes the only
mode (the no-op is silently honored).
fs_write - description loses the hashline-strip note (the
defensive strip still runs; it's a no-op for raw
content so leaving it on costs nothing).
fs_list - unchanged.
fs_edit_hashline - NOT REGISTERED. The tool isn't visible to the
model so it can't accidentally call it with a
hashless patch we'd reject.
fs_grep - NOT REGISTERED for the same reason — its only
output format is hashline-prefixed.
Wiring details:
- RegisterFSTools gains an optional UseHashline: Boolean = True so
every existing two-arg call site keeps compiling. Sets a unit-level
GHashlineEnabled that Tool_FSRead consults to decide its default
output mode.
- Hashline-only tool registrations are gated by `if UseHashline`.
- PasClaw.Cmd.Agent.NewBuiltinRegistry gains an optional UseHashline
parameter too, plumbed from A.NoHashline through both RunSingleTurn
and RunInteractive call sites.
https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Summary
Adds hashline support — the line-anchored edit format from oh-my-pi that lets the model identify edits by stable line-number anchors instead of perfect-text reproduction (the same failure mode str_replace hits ~50% of the time on many models, per the blog post you linked).
Not MCP. Hashline is a format + tool integration pattern, so it lives as PasClaw built-in tools.
What the model sees
fs_readnow returns:What the model writes (new
fs_edit_hashline)Sigils:
|replace in place,↑insert above,↓insert below. Anchors can be a single line (42:) or a range (7-10:). The header hash must match the file on disk; stale patches abort without writing a single byte.New
fs_grepRecursive substring search whose output is itself hashline-formatted — the model can paste matched anchors straight into
fs_edit_hashlinewithout re-reading.What's in the PR
src/pkg/hashline/PasClaw.Hashline.pas— format primitives:xxHash32matching upstreamBun.hash.xxHash32so the 4-hex file hash is interchangeableComputeFileHash(CR-stripped + line-rtrimmed UTF-8 → xxHash32 → low16 → 4-hex)FormatHashlineRead/FormatNumberedLines/FormatHashlineHeaderStripHashlinePrefixes(defensive, only strips when every non-empty line has aLINENO:prefix)ParseHashlinePatch(multi-section tokenizer)ApplyHashlineEdits(two-pass applier with before/after buckets per anchor; preserves trailing-newline shape)src/pkg/tools/PasClaw.Tools.FS.pas—fs_reademits hashline by default with{"plain": true}escape hatch;fs_writestrips prefixes defensively; newfs_edit_hashlineandfs_greptoolsMakefile(FPC) andPasClaw.dproj(Delphi)Constants are declared as literal Unicode characters (
'¶','↑','↓'), not raw#$C2#$B6byte sequences — that's the cross-compiler-correct way: DelphiUnicodeStringstores oneWideCharper codepoint and FPC{$MODE DELPHI}{$H+}AnsiStringstores the UTF-8 bytes.Length()/Copy()are unit-consistent per compiler, so the same parser walks the string correctly in both.Recovery heuristics from the upstream package (multi-line dup auto-absorb, structural-bracket boundary fixups, comment-line skipping inside payloads) are deliberately omitted — they only matter once production traffic surfaces the failure modes. Format and basic apply path are faithful so we can layer them incrementally.
Test plan
fs_readagainst a small file: returns¶path#hashheader +1:lineper linefs_read {"plain": true}: returns raw bytes (no header, no prefixes)fs_edit_hashlinewith a single-line replace, an insert-above, an insert-below: writes the expected filefs_edit_hashlinewith a stale hash: aborts with(header hash X, file hash Y) — re-read and rebaseand leaves file untouchedfs_grep src/pkg/hashline 'XXHash': returns one section, header + match linesfs_writeagainst content the model accidentally prefixed: succeeds and reports(stripped hashline prefixes)Future work (not in this PR)
--no-hashlineconfig knob if specific models do worse with the formathttps://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Generated by Claude Code