Skip to content

Add hashline format + fs_edit_hashline + fs_grep built-in tools - #26

Merged
FMXExpress merged 4 commits into
mainfrom
claude/pr26-hashline-port
May 27, 2026
Merged

FMXExpress merged 4 commits into
mainfrom
claude/pr26-hashline-port

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

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_read now returns:

¶src/foo.pas#a3f1
1:unit Foo;
2:
3:interface
...

What the model writes (new fs_edit_hashline)

¶src/foo.pas#a3f1
42:
|the new line 42 content
↑a line inserted above 42
↓a line inserted below 42

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_grep

Recursive substring search whose output is itself hashline-formatted — the model can paste matched anchors straight into fs_edit_hashline without re-reading.

What's in the PR

  • src/pkg/hashline/PasClaw.Hashline.pas — format primitives:
    • xxHash32 matching upstream Bun.hash.xxHash32 so the 4-hex file hash is interchangeable
    • ComputeFileHash (CR-stripped + line-rtrimmed UTF-8 → xxHash32 → low16 → 4-hex)
    • FormatHashlineRead / FormatNumberedLines / FormatHashlineHeader
    • StripHashlinePrefixes (defensive, only strips when every non-empty line has a LINENO: 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_read emits hashline by default with {"plain": true} escape hatch; fs_write strips prefixes defensively; new fs_edit_hashline and fs_grep tools
  • Build wiring for both Makefile (FPC) and PasClaw.dproj (Delphi)

Constants are declared as literal Unicode characters ('¶', '↑', '↓'), not raw #$C2#$B6 byte sequences — that's the cross-compiler-correct way: Delphi UnicodeString stores one WideChar per codepoint and FPC {$MODE DELPHI} {$H+} AnsiString stores 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

  • Delphi Win64 build: clean
  • FPC 3.2+ build: clean
  • fs_read against a small file: returns ¶path#hash header + 1:line per line
  • fs_read {"plain": true}: returns raw bytes (no header, no prefixes)
  • fs_edit_hashline with a single-line replace, an insert-above, an insert-below: writes the expected file
  • fs_edit_hashline with a stale hash: aborts with (header hash X, file hash Y) — re-read and rebase and leaves file untouched
  • fs_grep src/pkg/hashline 'XXHash': returns one section, header + match lines
  • Round-trip: agent reads a file, sends a 1-line edit patch, file changes correctly
  • fs_write against content the model accidentally prefixed: succeeds and reports (stripped hashline prefixes)

Future work (not in this PR)

  • Recovery heuristics (auto-absorb duplicates, boundary fixups)
  • LSP/diagnostic integration for edit feedback
  • A --no-hashline config knob if specific models do worse with the format

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/pkg/tools/PasClaw.Tools.FS.pas Outdated
ErrMsg := Format('section %d (%s): %s', [i + 1, Sections[i].Path, ApplyErr]);
Exit('');
end;
WriteFileText(Sections[i].Path, NewBody);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment thread src/pkg/tools/PasClaw.Tools.FS.pas Outdated
Exit('');
end;
FileBody := ReadFileText(Sections[i].Path);
if Sections[i].HasFileHash then

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

claude added 3 commits May 27, 2026 19:26
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants