@criogaid/pi-hashline-edit 0.13.0 → 0.15.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.
Files changed (152) hide show
  1. package/README.md +18 -12
  2. package/README.zh-CN.md +18 -12
  3. package/package.json +8 -1
  4. package/src/core/AGENTS.md +3 -1
  5. package/src/core/apply.ts +110 -117
  6. package/src/core/character-set.ts +2 -3
  7. package/src/core/copy-span.ts +15 -0
  8. package/src/core/errors.ts +24 -9
  9. package/src/core/lines.ts +71 -17
  10. package/src/core/ranges.ts +5 -4
  11. package/src/core/replace-schema.ts +3 -1
  12. package/src/core/replace.ts +50 -29
  13. package/src/core/search-analysis.ts +21 -22
  14. package/src/core/search.ts +15 -32
  15. package/src/core/types.ts +3 -0
  16. package/src/index.ts +47 -39
  17. package/src/pi/AGENTS.md +30 -19
  18. package/src/pi/action-fusion.ts +284 -211
  19. package/src/pi/argument-diagnostics.ts +50 -37
  20. package/src/pi/argument-error.ts +2 -2
  21. package/src/pi/argument-validation.ts +163 -66
  22. package/src/pi/budgets.ts +12 -0
  23. package/src/pi/diagnostic-buffer.ts +12 -11
  24. package/src/pi/edit-tool.ts +138 -115
  25. package/src/pi/error-text.ts +10 -2
  26. package/src/pi/failure-context.ts +24 -37
  27. package/src/pi/file-commit.ts +131 -164
  28. package/src/pi/file-read.ts +122 -31
  29. package/src/pi/fusion-arguments.ts +214 -0
  30. package/src/pi/fusion-card.ts +102 -60
  31. package/src/pi/grep-candidates.ts +35 -22
  32. package/src/pi/grep-output.ts +197 -190
  33. package/src/pi/grep-render.ts +22 -13
  34. package/src/pi/grep-reread.ts +7 -6
  35. package/src/pi/grep-scope.ts +31 -16
  36. package/src/pi/grep-search.ts +56 -47
  37. package/src/pi/grep-tool.ts +35 -33
  38. package/src/pi/grep-worker.ts +3 -4
  39. package/src/pi/mutation-diff.ts +238 -0
  40. package/src/pi/mutation-result.ts +102 -79
  41. package/src/pi/mutation-runner.ts +107 -84
  42. package/src/pi/native-bash.ts +41 -0
  43. package/src/pi/path.ts +59 -6
  44. package/src/pi/read-tool.ts +173 -138
  45. package/src/pi/regex-worker.ts +14 -8
  46. package/src/pi/render.ts +101 -54
  47. package/src/pi/replace-regex.ts +1 -1
  48. package/src/pi/replace-tool.ts +14 -7
  49. package/src/pi/report-cause.ts +34 -17
  50. package/src/pi/report-schema.ts +184 -85
  51. package/src/pi/report.ts +133 -64
  52. package/src/pi/rg-process.ts +68 -48
  53. package/src/pi/schema.ts +4 -0
  54. package/src/pi/text-stream.ts +81 -87
  55. package/src/pi/workspace-cwd.js +2 -0
  56. package/src/pi/workspace.ts +46 -0
  57. package/src/pi/write-tool.ts +19 -13
  58. package/src/core/apply.test.ts +0 -644
  59. package/src/core/case-fold.test.ts +0 -35
  60. package/src/core/character-set.test.ts +0 -97
  61. package/src/core/errors.test.ts +0 -39
  62. package/src/core/hash.test.ts +0 -64
  63. package/src/core/lines.test.ts +0 -63
  64. package/src/core/ranges.test.ts +0 -123
  65. package/src/core/replace.test.ts +0 -187
  66. package/src/core/search-analysis.test.ts +0 -210
  67. package/src/core/search-matrix.test.ts +0 -64
  68. package/src/core/search-matrix.testing.ts +0 -171
  69. package/src/core/search.test.ts +0 -132
  70. package/src/core/text.test.ts +0 -52
  71. package/src/integration/config-registration.test.ts +0 -291
  72. package/src/integration/fusion-dispatch.test.ts +0 -320
  73. package/src/integration/grep-errors.test.ts +0 -81
  74. package/src/integration/grep-flags.test.ts +0 -76
  75. package/src/integration/grep-js-completeness.test.ts +0 -278
  76. package/src/integration/grep-line-candidates.test.ts +0 -201
  77. package/src/integration/grep-matrix.test.ts +0 -118
  78. package/src/integration/grep-order.test.ts +0 -78
  79. package/src/integration/grep-path-matrix.test.ts +0 -128
  80. package/src/integration/grep-prefilter-coverage.test.ts +0 -204
  81. package/src/integration/grep-process-limits.test.ts +0 -122
  82. package/src/integration/grep-regex.test.ts +0 -412
  83. package/src/integration/grep-rg.test.ts +0 -1659
  84. package/src/integration/grep-scan-budget.test.ts +0 -111
  85. package/src/integration/grep-translation.test.ts +0 -199
  86. package/src/integration/large-text.test.ts +0 -70
  87. package/src/integration/model-budget-lifecycle.test.ts +0 -186
  88. package/src/integration/mutation-file-types.test.ts +0 -30
  89. package/src/integration/mutation-file-types.testing.ts +0 -33
  90. package/src/integration/npm-package.test.ts +0 -19
  91. package/src/integration/npm-package.testing.ts +0 -243
  92. package/src/integration/publication-read-changes.test.ts +0 -454
  93. package/src/integration/read-changes.test.ts +0 -98
  94. package/src/integration/replace-package.test.ts +0 -22
  95. package/src/integration/replace-package.testing.ts +0 -36
  96. package/src/integration/replace-worker-boundary.test.ts +0 -127
  97. package/src/integration/report-replay.test.ts +0 -91
  98. package/src/integration/utf8-errors.test.ts +0 -46
  99. package/src/pi/action-fusion.test.ts +0 -659
  100. package/src/pi/action-fusion.testing.ts +0 -38
  101. package/src/pi/anchor-format.test.ts +0 -124
  102. package/src/pi/argument-error.testing.ts +0 -46
  103. package/src/pi/argument-format.test.ts +0 -196
  104. package/src/pi/argument-validation.test.ts +0 -1007
  105. package/src/pi/codemode.test.ts +0 -101
  106. package/src/pi/config.test.ts +0 -204
  107. package/src/pi/diagnostic-buffer.test.ts +0 -115
  108. package/src/pi/directory-sync.test.ts +0 -57
  109. package/src/pi/execute.test.ts +0 -1257
  110. package/src/pi/extension-loading.test.ts +0 -14
  111. package/src/pi/extension-loading.testing.ts +0 -3
  112. package/src/pi/failure-context.test.ts +0 -370
  113. package/src/pi/failure-path.test.ts +0 -289
  114. package/src/pi/file-commit.test.ts +0 -628
  115. package/src/pi/file-read.test.ts +0 -29
  116. package/src/pi/file-snapshot.test.ts +0 -22
  117. package/src/pi/fusion-card-interaction.test.ts +0 -143
  118. package/src/pi/fusion-card.test.ts +0 -353
  119. package/src/pi/grep-candidates.test.ts +0 -26
  120. package/src/pi/grep-matrix.test.ts +0 -68
  121. package/src/pi/grep-order.test.ts +0 -447
  122. package/src/pi/grep-output.testing.ts +0 -24
  123. package/src/pi/grep-rg.testing.ts +0 -73
  124. package/src/pi/grep.test.ts +0 -1670
  125. package/src/pi/model-budgets.test.ts +0 -96
  126. package/src/pi/mutation-outcome.testing.ts +0 -20
  127. package/src/pi/mutation-result.test.ts +0 -96
  128. package/src/pi/output-budgets.test.ts +0 -221
  129. package/src/pi/pi.test.ts +0 -158
  130. package/src/pi/read-delegation.test.ts +0 -119
  131. package/src/pi/read.test.ts +0 -735
  132. package/src/pi/regex-worker.test.ts +0 -42
  133. package/src/pi/registration.test.ts +0 -549
  134. package/src/pi/render.test.ts +0 -841
  135. package/src/pi/replace.test.ts +0 -634
  136. package/src/pi/report-failure.testing.ts +0 -27
  137. package/src/pi/report.test.ts +0 -533
  138. package/src/pi/result-safety.test.ts +0 -597
  139. package/src/pi/rg-process.test.ts +0 -133
  140. package/src/pi/rg-regex.test.ts +0 -40
  141. package/src/pi/text-stream.test.ts +0 -281
  142. package/src/pi/tool-call.testing.ts +0 -61
  143. package/src/pi/tool-factories.testing.ts +0 -59
  144. package/src/pi/write.test.ts +0 -256
  145. package/src/testing/extension-loader.testing.ts +0 -24
  146. package/src/testing/installation.testing.ts +0 -77
  147. package/src/testing/process.testing.ts +0 -33
  148. package/src/testing/regex-host.testing.ts +0 -20
  149. package/src/testing/regex-translation-corpus.ts +0 -267
  150. package/src/testing/rg-line-listing.fixture.mjs +0 -7
  151. package/src/testing/run-tests.ts +0 -47
  152. package/src/testing/session.testing.ts +0 -127
package/src/pi/AGENTS.md CHANGED
@@ -4,34 +4,37 @@ Pi integration. Cross-cutting contracts live in the root `AGENTS.md`; this file
4
4
 
5
5
  ## Registration
6
6
 
7
- `src/index.ts` obtains the workspace from the Pi loader's default `pi.exec()` cwd, then loads config once and registers nothing when `enabled` is false. Tools and entry renderers register in the factory because Pi can rebuild history before `session_start` on reload. Each tool factory receives one environment: `ToolEnvironment` (`cwd`, `config`, and the `budgets` provider; `config.ts`) for `read` and `grep`, and `MutationToolEnvironment` (the same plus `fusion`, undefined when Action Fusion is off; `mutation-runner.ts`) for `write`, `edit`, and `replace`. Tools register in the order write, edit, replace, read, grep. The Action Fusion cards register even when Action Fusion is off, so saved then_run cards render. One helper appends `NEXT_GUIDELINE` from `report-schema.ts` to every tool's `promptGuidelines` (Pi prints the shared guideline once). The `then_run` field and `ACTION_FUSION_GUIDELINES` exist only when `fusion` does; that guideline is the one place the model is told when to use then_run.
7
+ `workspace.ts` queries the Pi loader's default `pi.exec()` cwd: Windows uses `workspace-cwd.js` through Windows Script Host with a PowerShell fallback, and macOS and Linux use `/bin/pwd`. `src/index.ts` loads config once for that workspace and registers nothing when `enabled` is false. Tools and entry renderers register in the factory because Pi can rebuild history before `session_start` on reload. Each tool factory receives one environment: `ToolEnvironment` (`cwd`, `config`, and the `budgets` provider; `config.ts`) for `read` and `grep`, and `MutationToolEnvironment` (the same plus `schedule`, the mutation scheduler chosen once from `config.actionFusion`; `mutation-runner.ts`) for `write`, `edit`, and `replace`. Tools register in the order write, edit, replace, read, grep. The Action Fusion cards register even when Action Fusion is off, so saved then_run cards render. One helper appends `NEXT_GUIDELINE` from `report-schema.ts` to every tool's `promptGuidelines` (Pi prints the shared guideline once). The `then_run` field and `ACTION_FUSION_GUIDELINES` exist only when `config.actionFusion` is true; that guideline is the one place the model is told when to use then_run.
8
8
 
9
9
  ## Argument funnel
10
10
 
11
- - Call order: a tool's `prepareArguments` (from `argument-validation.ts`), then Pi's own schema validation, then `execute`. Caller arguments are never rewritten. File-dependent checks stay in execution.
11
+ - Call order: a tool's `prepareArguments`, then Pi's schema validation and mutable `tool_call` hooks, then an owned snapshot at `execute`. The tool checks that snapshot against the same schema and semantic rules without coercing hook edits. Caller arguments are never rewritten. File-dependent checks stay in execution.
12
12
  - Tool files define TypeBox schemas, and each mutation tool's description names its alternative (edit ↔ replace ↔ write). A tool supplies only the semantic checks its schema cannot express or name precisely: edit's per-action fields and ranges, text that cannot be written as UTF-8, and regex compilation through `checkRegexArguments` in `argument-validation.ts`, which reports flags V8 rejects and compiles regex-mode patterns under the flags each tool uses. Shared integer rules live in `schema.ts`.
13
13
  - Every tool declares `STRICT_SAMPLING` from `schema.ts` (mutation tools through `mutationToolBase`) and keeps its parameters convertible by Pi's strict converter: no object or array unions, so grep's multi-valued fields are arrays only and each edit item is one flat object whose `EDIT_OPS` table, not the schema, fixes the fields per action.
14
14
  - Some providers emit keys in declaration order and others alphabetically, so the `edit` and `replace` keys are declared in alphabetical order (`path`, `steps`, `then_run`; `action`, `anchor`, `end`, `lines`; `path`, `replacements`, `then_run`): both orders stream the file and each operation's action and range before the payload.
15
- - `argument-validation.ts` owns every tool's `prepareArguments` hook, issue collection, bounded diagnostic output, and the Pi schema validation adapter. Tools report semantic field issues through its callback and do not throw during collection. Successful schema conversion informs those checks without changing caller arguments. On schema failure, prepare diagnostic values with the public pi-schema coercer using Pi's formats and unresolved-reference policy; Pi alone decides acceptance. Do not reimplement coercion or optional-null rules.
15
+ - `argument-validation.ts` owns the shared preparation and final-snapshot checks, issue collection, bounded diagnostic output, and the Pi schema validation adapter. `fusion-arguments.ts` applies this boundary separately to the file operation and its optional `then_run`. It coerces one copy with Pi's schema engine, formats, and unresolved-reference policy. The schema check, semantic checks, and failure diagnostics use that copy. Tools report semantic field issues through the callback without throwing during collection. The boundary parses each local path spelling, reporting Node's reason for an invalid file URL. Execution receives the original spelling and the absolute path resolved against the tool's cwd. The edit check parses anchors during semantic validation and builds core steps only for the accepted execution snapshot. The boundary checks array shape on structured-clone snapshots of the arguments (enumerable own string-keyed properties of ordinary objects and arrays) before preparation coercion and before post-hook semantic checks. Arrays in either snapshot must have no holes or named properties. Both checks follow the item schema for a singleton at its original path, where Pi wraps it; the schema check still rejects a singleton a hook leaves at an array field. Execution uses the checked post-hook snapshot. Preparation hands Pi the same raw snapshot for coercion and validation. Pi's coercion is copy-on-write. Do not reimplement coercion or optional-null rules.
16
16
  - `argument-diagnostics.ts` owns failure-only schema projection and structured aggregation. Top-level tool fields have independent schemas; failure diagnosis derives field schemas with TypeBox and keeps Pi's coercion and per-field error limits. Derive choices and the explanations of missing, undeclared, pattern-mismatched, and out-of-choice fields from the declared schema: when a schema reason does not say how to correct the value, the `fix` of a missing field, a pattern mismatch, or a value outside the field's choices is the field's description (each choice's value and description), and an undeclared field's `fix` lists its object's accepted fields. A declared field is applicable even when absent, so a tool check may require it. An issue on a whole object leaves its fields' diagnostics in place. Suppress only inapplicable or already explained issues, and retain independent fields with bounded native diagnostics.
17
17
  - `argument-error.ts` owns the JSON argument-error envelope and its byte budget: retain exact field paths, omit whole issues with explicit counts, and never truncate serialized JSON or repeat the call's arguments. Preparation failures use the same envelope.
18
18
 
19
19
  ## Mutations
20
20
 
21
- - `mutation-runner.ts` owns what the mutation tools share: their definition (`mutationToolBase`) and the call sequence after validation (separating `then_run`, path resolution, `withFileMutationQueue`, the hand-off to Action Fusion, and finalization). A tool supplies its schema, text, semantic checks, `run`, and renderers. `run` returns a tool-indexed `MutationOutcome`, Action Fusion returns `FusedMutation` facts, and one `finalizeMutation` call turns them into a result; nothing downstream reads publication or revisions back from result details. `runTextMutation` owns the read-modify-write for `edit`/`replace`, which supply only a `TextChange`.
22
- - `file-read.ts` provides guarded stream and whole-file reads; byte revision checks stay in the search and commit owners.
23
- - `file-revision.ts` defines a revision once: the SHA-256 hex of exact bytes, whole (`byteRevision`) or streamed. `text-stream.ts` returns the revision of the bytes each scan read, so callers never hash.
24
- - `file-commit.ts` publishes: no-op detection, a temp file in a sibling directory, then `link` (create) or `rename` (overwrite). It stages overwrites beside the resolved target and rechecks the requested path and target admission before renaming. It preserves existing file modes (a new file follows the umask) and syncs the directory on POSIX. A failure with a publication status to state throws `FileMutationError`; every other failure stays a plain `HashlineError`, reported as `NOT_PUBLISHED`. `CommitOptions` admits `baseRevision` only with `overwrite`. It also owns freshness: `commitFreshness` from the commit result and `observeFreshness` for Fusion's later observations; only unknown freshness carries an observation error.
25
- - `mutation-result.ts` owns tool-indexed outcome facts, final success/failure details, and progress details. It builds diffs and finalizes one mutation report from commit, tool, freshness, and command facts. On failure, `describeMutationFailure` states what only a mutation knows (publication, and through `CommandNotRun` why a fused command never ran) and leaves classification to `describeFailure`. `failure-context.ts` turns anchor failures into a `HashlineError` with bounded facts (`failures`, `candidateNeighborhoods`); `anchor-format.ts` owns the `LINE#HASH` syntax, its schema pattern, and row parsing.
21
+ - `mutation-runner.ts` owns what the mutation tools share: their definition (`mutationToolBase`) and the call sequence after validation (`withFileMutationQueue`, the hand-off to the scheduler, and finalization). The `actionFusion` setting chooses the scheduler once at registration: `runAlone`, or Action Fusion's, which every mutation tool shares; the same setting adds `then_run` to the schema with its guideline and card. A tool supplies its schema, text, semantic checks, `run`, and renderers. The runner's per-call `publish` records the commit result before handing it to the tool. The publish call also records a `FileMutationError`'s publication if the commit throws. After a commit returns, every failure keeps its publication, including a no-op. `run` returns a tool-indexed `MutationOutcome`, the scheduler returns a `SettledMutation` (`alone`, or `fused` with its command facts), and one `finalizeMutation` call turns it into a result; nothing downstream reads publication or revisions back from result details. `runTextMutation` owns the read-modify-write for `edit`/`replace`, which supply only a `TextChange`.
22
+ - `file-read.ts` owns guarded byte acquisition and the mutation snapshot. It checks the opened handle and current path and hashes each chunk once. Mutation reads require the initial size of a regular file and reject premature EOF. Revision-only checks reuse one chunk buffer and retain only the digest. Editable snapshots retain filled chunks and join them for decoding when there is more than one. Text scans use Node's read-ahead to EOF, including virtual files that report zero size. `read` hands supported images to Pi's native read through Pi's image-detection API, delegates files containing NUL to it, and rejects all other invalid UTF-8; Pi owns those delegated reads. Delegated read uses Pi’s image-resize setting captured when the session starts, or on the first delegated read if the SDK reload skips `session_start`. Pi gives extensions no copy of the value it passed to its native read, so an SDK host that changes the setting after building the runtime and before the extension first reads it gets the new value in delegated reads and the old one in Pi's native read. The native MIME probe checks the target again at delegation because it can change after the dispatch probe.
23
+ - `file-revision.ts` defines a revision once as the SHA-256 hex of the exact bytes. `text-stream.ts` handles streaming text and returns the revision from `file-read.ts`.
24
+ - `file-commit.ts` publishes: no-op detection, a temp file in a sibling directory, then `link` (create) or `rename` (overwrite). It stages overwrites beside the resolved target and rechecks the requested path and target admission before renaming. It preserves existing file modes (a new file follows the umask) and syncs the directory on POSIX. A failure with a publication status to state throws `FileMutationError`; every other failure stays a plain `HashlineError`, reported as `NOT_PUBLISHED`. A commit intent is `create`, `overwrite`, or `update` (read-modify-write, the only one with a `baseRevision`); `planPublication` inspects the target once and returns the publish plan the rest of the commit follows, and the result states the freshness observed right after publication. It also owns freshness: the commit result's own, and `observeFreshness` for Fusion's later observations; only unknown freshness carries an observation error.
25
+ - `mutation-result.ts` owns final success/failure details and progress details. It builds diffs and finalizes each mutation from its tagged tool facts, commit, freshness, and command facts. On failure after a returned commit, `describeMutationFailure` wraps the original cause as `POST_PROCESS_FAILED`. It passes the recorded publication, known command status and first display error to `describeFailure`, which keeps those facts even when inspecting a thrown value fails. `failure-context.ts` turns anchor failures into a `HashlineError` with `failures` and bounded `candidateNeighborhoods`. The report layer bounds the `failures` list. `anchor-format.ts` owns the `LINE#HASH` syntax, its schema pattern, and row parsing.
26
+ - `mutation-diff.ts` keeps the Pi diff row format. Whole rows proven by copied spans delimit changed ranges. A BOM common to both snapshots stays with the file, so the first row's copied body can establish its identity independently of the BOM. When adding or removing a neighboring row changes the last line's terminator, a copied full body identifies the surviving row. jsdiff's `diffArrays` aligns each range under the line edit-distance budget. If the search exceeds the budget or leaves a proven row unmatched, the card preserves the proven match and shows the remaining original and replacement rows as blocks. Saved details carry the diff text.
26
27
 
27
28
  ## grep
28
29
 
29
- - Split into `grep-tool` (schema and execution order), `grep-scope` (paths and glob admission), `grep-candidates` (candidate strategy, fallback, whole-scope scan budget, and the empty-scope guard), `grep-search` (queue backpressure, worker pool, per-file matches with their revisions), `grep-reread` (content mode's bounded second read of each matched file and its revision check), `grep-output` (payload rows, file-header format and its parser, and every grep report fact, including empty and incomplete searches), and `grep-render` (TUI rows). Each candidate file is scanned once through `text-stream.ts` for NUL, UTF-8 validity, its revision, and the lossy LF view it matches. Each stage returns ordered `SearchWarning` records (`{ path?, reason }`) in its result rather than composing sentences; `grep-tool` joins stages in order, and only `grep-output` formats diagnostics with cwd-relative paths, de-duplicates them, and applies the field budget. The README documents grep's resource limits.
30
+ - Skip NUL files. Invalid UTF-8 output stays as plain preview rows, and matching uses the lossy preview text. Content mode re-reads each matched file and keeps it only when that read has the revision it was matched on; files and count modes report the searched snapshot without re-reading.
31
+ - Validate patterns with V8 at tool entry and resolve smart case once into `GrepQuery.ignoreCase`. Native `RegExp` in `core/search.ts` decides every match on the LF view; rg only lists candidates and never decides a match. Candidate derivation may widen but never narrow.
32
+ - Split into `grep-tool` (schema and execution order), `grep-scope` (paths and glob admission), `grep-candidates` (candidate strategy, fallback, whole-scope scan budget, and the empty-scope guard), `grep-search` (queue backpressure, worker pool, per-file matches with their revisions), `grep-reread` (content mode's bounded second read of each matched file and its revision check), `grep-output` (payload rows, the gap row between a file's groups of context rows, file-header format and its parser, and every grep report fact, including empty and incomplete searches), and `grep-render` (TUI rows). Each candidate file is scanned once through `text-stream.ts` for NUL, UTF-8 validity, its revision, and its decoded text (lossy for invalid UTF-8). Each stage returns ordered `SearchWarning` records (`{ path?, reason }`) in its result rather than composing sentences; `grep-tool` joins stages in order, and only `grep-output` formats diagnostics with cwd-relative paths, de-duplicates them, and applies the field budget. The README documents grep's resource limits.
30
33
  - Without `multiline`, `rg-regex.ts` translates each pattern into rg patterns that list every line the query matches: keep a construct only where both engines give it the same meaning over the original line bytes (CRLF, malformed UTF-8, surrogate halves included), and otherwise widen it; never narrow. Bound emitted patterns. Preserve every alternative. In a backreference's repeated text, membership keeps each node's original scoped case flags, and the reference's case widening is applied afterward through the existing byte translator (`scalarRanges`, `backreference`). A multiline query, unsupported or oversized translation, or pattern rg rejects before reporting a file uses the file prefilter.
31
- - `rg-process.ts` is the ripgrep process layer: spawning, bounded reading, and parsing rg's output protocols (`runRgPaths` reads NUL-delimited paths; `runRgLines` reads the per-file line numbers of `LINE_LISTING_ARGS`). It knows no candidate strategy. Completed-run diagnostics leave this layer as reason-only warning data; path formatting belongs to `grep-output`. Scope flags are produced only in `grep-scope.ts` and never parsed back.
34
+ - `rg-process.ts` is the ripgrep process layer: spawning, bounded reading, and parsing rg's output protocols (`runRgPaths` reads NUL-delimited paths; `runRgLines` reads the per-file line numbers of `LINE_LISTING_ARGS`). It knows no candidate strategy. Every rg run takes the tool workspace as its working directory, because rg resolves caller globs against it, and a missing workspace fails as it does for Pi's bash. Pi's built-in grep inherits the host's directory, so its globs resolve against the process directory in an embedded session; this difference from Pi is deliberate. Completed-run diagnostics leave this layer as reason-only warning data; path formatting belongs to `grep-output`. Scope flags are produced only in `grep-scope.ts` and never parsed back.
32
35
  - `grep-candidates.ts` decides which rg runs to make: line candidates through `rg-regex.ts`, then file candidates through `--files-with-matches` over necessary literals. A stage falls back only when its arguments exceed the command line, or when it exits with code 2 before listing any file and `rgRejectsPatterns` confirms rg rejects its patterns; a search that only hit unreadable paths stands. When the file filter is unavailable or falls back, `--files` lists every file in scope. Byte-level pattern flags are defined once there.
33
- - Keep grep matching in the bounded, cancellable worker pool of `grep-search.ts`: a lazily started pool, each worker sending `core/search.ts` whole lines in bounded requests, or the whole file for a multiline query. Commit file results, warnings, and fatal failures in listing order; retire a worker after a fatal file result, and replace it if a later NUL made its failure irrelevant. Propagate cancellation without waiting for earlier files.
34
- - `grep-scope.ts` classifies scope errors: only `ENOENT` means `PATH_NOT_FOUND`; preserve other filesystem errors.
36
+ - Keep grep matching in the bounded, cancellable worker pool of `grep-search.ts`: a lazily started pool, with each worker passing original decoded text to `core/search.ts` for CRLF normalization and matching. A request carries selected or contiguous whole lines with their original terminators, or the whole file for a multiline query. The host maps selected rows back to their file line numbers. Commit file results, warnings, and fatal failures in listing order; retire a worker after a fatal file result, and replace it if a later NUL made its failure irrelevant. Propagate cancellation without waiting for earlier files.
37
+ - `grep-scope.ts` classifies scope errors: only `ENOENT` means `PATH_NOT_FOUND`; preserve other filesystem errors. Caller globs reach rg as `--glob`, so a positive glob overrides ignore rules for what it matches, as in rg and Pi's built-in grep. `scopeArgs` appends `!.git` after the caller's globs, so no glob admits `.git`; Pi's grep has no such exclusion, and this difference is deliberate.
35
38
 
36
39
  ## Regex workers
37
40
 
@@ -40,24 +43,32 @@ Pi integration. Cross-cutting contracts live in the root `AGENTS.md`; this file
40
43
  ## Reports and rendering
41
44
 
42
45
  - Give each model-facing rule one home, chosen by what it decides. Choosing a tool, or a parameter of the call being written, belongs in that tool's `description` or the field's description; an obligation spanning several calls belongs in `promptGuidelines`; what to do about one result belongs only in that report's `next` (`src/pi/report-schema.ts`). State a tool's or field's facts once, where they belong. Guidelines never restate a `next`; `NEXT_GUIDELINE`, appended at registration in `src/index.ts`, ranks a report's `next` above them. Word rules as instructions with a concrete trigger and listed exceptions, not as preferences. Include text that applies to one platform only on that platform, decided from `process.platform` where the text is defined.
43
- - Every tool result states its facts in one report. A success report follows the content payload; a failure report is the whole `isError` result. Layers return structured facts and never append sentences or bracket notices; each fact has one owner, so it appears once. Throw sites classify failures as `HashlineError` with a code and the facts its schema requires; `message` describes only the throwing step, a failure beneath that step is `cause`; native diagnostics remain directly in `message`, without a synthetic wrapper, except that a missing path or a directory target gets one fixed message in every tool (`PATH_ERROR_MESSAGES`), with resolved paths in `missing`; `next` is derived from the code and publication (a throw site may only select one of the code's named alternatives). Text shared by success and failure (such as `REREAD`) is defined once in the schema module.
46
+ - Every tool result states its facts in one report. A success report follows the content payload; a failure report is the whole `isError` result. Layers return structured facts and never append sentences or bracket notices; each fact has one owner, so it appears once. Throw sites classify failures as `HashlineError` with a code and the facts its schema requires; `message` describes only the throwing step, a failure beneath that step is `cause`; native diagnostics remain directly in `message`, without a synthetic wrapper, except that a missing path or a target that is not a regular file gets one fixed message in every tool (`PATH_ERROR_MESSAGES`), with resolved paths in `missing`: producers and throw sites state them resolved, and the report layer (`boundFacts` in `report.ts`) spells them once with `serializeAbsolutePath` in success and failure reports alike, as headers spell paths, then cuts each list in `BOUNDED_LISTS` to whole entries within the diagnostic block and counts the omitted entries; `next` is derived from the code and publication (a throw site may only select one of the code's named alternatives). Text shared by success and failure (such as `REREAD`) is defined once in the schema module.
44
47
  - Send the model a result field only when its value changes the model's next call. Do not send a field that is a function of the call's own arguments, or that the same result already states (a payload header, a row, another field). What only a person can act on (diffs, progress, display-callback failures) goes to the TUI through `details`; revisions, candidate strategy, and timing stay out of results. In review, delete a field when nobody can say what the model does differently for another value of it.
45
48
  - A success report carries `next` only when the result is incomplete or the model would otherwise misread it. A failure's `next` names a tool or parameter whose values the same report supplies; a code with no such action has no `next`. Order `OUTCOME_NEXT` so that following an earlier rule makes a later one reappear on the following call.
46
49
 
47
50
  - `report-schema.ts` is the single definition of the result protocol: every report field in output order (each with one owning layer), its schema, audience, and model decision purpose, every error code with its facts schema and recovery (`next.default` plus named alternatives), and the success recovery order (`OUTCOME_NEXT`). `FACT_FIELDS` is the required declaration point; model omission is derived from its audience together with the call fields, so `report.ts` does not maintain a second field set. Checked report types retain their tool or error-code variant; absent fields remain readable as undefined. Types derive from it. Its closed wire schemas validate text-only reports, enforce legal tool names, and require code-specific facts.
48
- - `report.ts` builds reports and owns their one model-facing serialization (`renderReport`: one JSON object, fields in schema order). Result text omits the call's own `tool`/`path` and TUI-only facts, which stay in `details.report`. `reportResult` appends a success report after the tool's payload only when the report states a model-visible fact or the result has no payload. Every tool's `execute` runs inside `runTool`, which classifies a failure (`describeFailure`, structured `cause`, `next` from code and publication) and returns it as an `isError` result whose `details.report` the TUI renders. This module receives a mutation's failure facts from `mutation-result.ts` and does not depend on the commit layer.
49
- - `render.ts` (`reportLines`) is the one TUI renderer of a report and holds the shared tool renderers. Render inputs admit partial details independently of the current execution result. Renderers read reports only through `splitReport` (a success: the checked report and the content before its trailing report block, stripped only when that block equals `renderReport(details.report)`) or `renderToolError` (a failure). Failure rendering uses `details.report`; Pi raises argument errors before execution, so a text-only argument rejection decodes from the final content block through `reportOf`. Report text omits its tool, so every decode supplies the originating call's tool name. Invalid text-only reports remain raw.
51
+ - `report.ts` builds reports and owns their one model-facing serialization (`renderReport`: one JSON object, fields in schema order). Result text omits the call's own `tool`/`path` and TUI-only facts, which stay in `details.report`. `reportResult` appends a success report after the tool's payload only when the report states a model-visible fact or the result has no payload. When it appends a block, it records its zero-based position as `details.reportBlockIndex` for the TUI and session replay. After the execution-entry argument check, every tool runs inside `runTool`, which classifies a failure (`describeFailure`, structured `cause`, `next` from code and publication) and returns it as an `isError` result whose `details.report` the TUI renders. This module receives a mutation's failure facts from `mutation-result.ts` and does not depend on the commit layer.
52
+ - `reportBlockIndex` is present only when the success builder appends a report block. It belongs to the persisted TUI details format. Model-facing content, script output, and failure details use their own contracts. The [root replay contract](../../AGENTS.md#behavior-contracts) governs persisted format changes. Without a recorded index the success splitter leaves the content intact.
53
+ - `SCRIPT_OUTPUT_SCHEMAS` defines the full success facts for each tool. Producers derive their input types from it, so each mutation supplies `publication`, replace supplies `matches`, and grep supplies `matches` and `files`. The success wire schemas allow omitted fields when decoding reports. `reportResult` projects the complete facts into Pi's `structuredContent`, model payload, and report. Visibility flags carry no fact values. Counts already shown by grep's payload and a continuation already known from read's caller limit stay out of report text, its `next`, and `details.report`. The final session Bash text and image content blocks reach the model in order with native formatting, limits and truncation, without a Hashline field-budget pass; the separate report states the command's status. Scripts get `then_run.status` and native structured fields when supplied: `output` (raw stdout/stderr, possibly empty), `truncated`, optional `full_output_path`, `exit_code`, and `wall_time_seconds`. Permission blocks, timeouts, skipped commands, or overrides without a native structured result can have status alone, with diagnostics in content. The TUI retains native command card behavior. Scripts get the read or grep payload as `text`. A delegated image read passes Pi's image object through. A delegated read of a file containing NUL gives `{ text }` with Pi's output and no report facts.
54
+ - `render.ts` (`reportLines`) is the one TUI renderer of a report and holds the shared tool renderers. Render inputs admit partial details independently of the current execution result. Success renderers get the checked report and payload from `splitReport`. It strips a trailing text block only when its index equals `details.reportBlockIndex` and its text equals `renderReport` of the checked report. If a hook removes the report or changes its position or text without updating the corresponding details, the split preserves all content blocks and still returns any checked report facts. A hook that replaces a report with identical text at the same index can clear `reportBlockIndex` in its replacement details to mark that block as payload. Failure rendering uses `renderToolError` and `details.report`. The argument boundary throws before file access. A text-only argument rejection decodes from the final content block through `reportOf`. Both decoders check the same wire schema and require the originating call's tool. Only the text decoder fills in an omitted tool. Invalid text-only reports remain raw.
55
+ - A collapsed preview that hides rows ends with one marker in the form Pi's built-in cards use. Its expand hint comes from the render context's `keyHint`, because an imported `keyHint` can belong to another copy of Pi that does not see the host's keybindings. On a success card the report's facts follow the marker and stay visible when collapsed. `read` shows nothing when collapsed, as Pi's `read` does. A call line shows its path as Pi's cards do: the home directory as `~` (`shortenHomePath` in `path.ts`), and for `edit` and `replace` a link to the file where the terminal supports links (`formatHeaderPath`). `read` and `write` use Pi's own call renderers, and grep shortens without linking, as Pi's grep does. Pi exports neither path helper, so both are local. A card's body starts on the row under its call line, without the blank row Pi's built-in cards leave there. This difference from Pi is deliberate.
56
+ - A collapsed mutation card counts all diff rows for the header and overflow marker. Its preview passes only the visible rows and two rows of lookahead to Pi's `renderDiff`, which emits one row per input row and applies word highlighting only to a single removal followed by a single addition. The lookahead preserves that decision at the cutoff. Expanded cards pass the entire saved diff to Pi.
50
57
  - `report-cause.ts` transports structured causes without Pi runtime imports, preserving cause chains with cycle protection; reports and worker replies share it. Native failures state the original diagnostic and errno once in `message`, retaining only an actual underlying `Error.cause`.
51
- - To add or change a report field: (1) declare it in `FACT_FIELDS` under its owning layer's group, including its audience and, for model-visible facts, the decision it changes: the concrete call the model makes differently for each value (`decide whether…` and `account for…` name no call); (2) list it in each `SUCCESS_DEFINITIONS` tool or `ERROR_DEFINITIONS` code that carries it; (3) when it needs recovery, add one `OUTCOME_NEXT` rule or the code's `next`, never a sentence at the producing site; when the recovery depends on the call's arguments, the rule names alternatives and the producing layer selects one (`OutcomeVariant`, passed to `reportResult`), so the text never asks the model to branch; (4) produce it in that one layer, bounded by the call's budget, omitting whole items with a count; (5) leave `render.ts` alone unless a card presents the fact another way, and then name it in that card's shown set; (6) check the README passage for the tool. To change an error code, edit `ERROR_DEFINITIONS` and follow the type errors to every throw site and the worker contract.
58
+ - To add or change a report field: (1) declare it in `FACT_FIELDS` under its owning layer's group, including its audience and, for model-visible facts, the decision it changes: the concrete call the model makes differently for each value (`decide whether…` and `account for…` name no call); (2) include it in each tool's `SCRIPT_OUTPUT_SCHEMAS` entry, the success TUI fields, or each `ERROR_DEFINITIONS` code that carries it; (3) when it needs recovery, add one `OUTCOME_NEXT` rule or the code's `next`, never a sentence at the producing site; when the recovery depends on the call's arguments, the rule names alternatives and the producing layer selects one (`OutcomeVariant`, passed to `reportResult`), so the text never asks the model to branch; (4) produce it in that one layer, bounded by the call's budget; a list of whole items is instead listed in `BOUNDED_LISTS` with its omitted count, and the report layer bounds it; (5) leave `render.ts` alone unless a card presents the fact another way, and then name it in that card's shown set; (6) check the README passage for the tool. To change an error code, edit `ERROR_DEFINITIONS` and follow the type errors to every throw site and the worker contract.
52
59
  - `error-text.ts` holds the Pi-layer error forms (cancellation, file changed during read or search). `diagnostic-buffer.ts` bounds stderr and search diagnostics.
53
60
 
54
61
  ## Budgets and config
55
62
 
56
- - `budgets.ts` defines the model-facing byte budgets, and `model-budgets.ts` derives them from the live selected model on each request. Preparation shares the provider, and each execution captures its budgets before its asynchronous work; internal helpers require the resolved budget or an explicit byte limit. Model-derived budgets and the `read.maxKiB` range share the `MAX_CONTENT_KIB` ceiling.
57
- - `config.ts` defines the `hashlineEdit` settings as one TypeBox schema: shared top-level settings and the `read`, `grep`, and `replace` groups. A missing or invalid `read.maxKiB` selects automatic model sizing.
63
+ - `budgets.ts` defines the model-facing byte budgets, and `model-budgets.ts` derives them on each request only from the live selected model's declared capacity, never remaining context; an explicit `read.maxKiB` overrides only the read cap. Preparation shares the provider, and each execution captures its budgets before its asynchronous work; internal helpers require the resolved budget or an explicit byte limit. Model-derived budgets and the `read.maxKiB` range share the `MAX_CONTENT_KIB` ceiling.
64
+ - `config.ts` defines the `hashlineEdit` settings as one TypeBox schema, the only definition of their types, ranges, and defaults: shared top-level settings and the `read`, `grep`, and `replace` groups. A project's `.pi/settings.json` field replaces the global one (under `getAgentDir()`) as a whole; each setting is validated on its own and falls back to its default when missing or invalid. A missing or invalid `read.maxKiB` selects automatic model sizing. Tools receive the resolved configuration at registration and keep it for their lifetime; a change requires a reload.
58
65
 
59
66
  ## Action Fusion
60
67
 
61
- `action-fusion.ts` implements `then_run`. After a successful mutation it checks freshness against `publishedRevision`, then runs the command through the session Bash tool. Its own per-file queue wraps mutation and command around Pi's `withFileMutationQueue`; the module header explains the nesting. Fusion states only the command (`then_run` status and output, `terminate`) and returns it as facts without building a result; freshness and publication come from the mutation report. Fusion progress derives from `ACTION_FUSION_PROGRESS_SCHEMA` and retains the session command's original display content and details; `fusion-card.ts` validates saved command cards against that schema before restoring them. It renders the separate mutation and command TUI cards (`withMutationStatus`, `registerFusionCards`) and derives a not-run reason from the same facts.
68
+ `fusion-arguments.ts` keeps the concrete `then_run` fields in Pi's tool schema. Preparation rejects unknown caller fields. A rejected follow-up stays present across Pi's argument clone, carrying its diagnostic alongside an empty, non-executable command. A mutation hook can edit or replace the follow-up. The execution boundary checks that result without coercion. `action-fusion.ts` settles an invalid follow-up with the commit's actual publication and freshness, a failed command status and the diagnostic. For a valid follow-up it checks freshness against `publishedRevision`, then runs the command through the session's Bash with `ctx.executeTool("bash", ...)`, honoring overrides and the `tool_call` and `tool_result` hooks. The final session result decides the command's status, `terminate` passes on to the parent result, and a failed command does not roll back published files. Its own per-file queue wraps mutation and command around Pi's `withFileMutationQueue`; the module header explains the nesting. At Bash completion Fusion records `terminate` and each command fact as soon as Pi's result determines it. It reads indexed content into plain blocks once and gives progress subscribers a separate copy from the model payload. `native-bash.ts` takes the script fields from Pi's Bash output schema and shares the native definition with the card renderer. A finite `exit_code` establishes that the command exited even when the structured result is incomplete. Unreadable structured fields or display details are recorded in `progressError`. Model content, the known command outcome and the termination request survive those observer errors. A pre-run cancellation settles without reading output. Fusion progress derives from `ACTION_FUSION_PROGRESS_SCHEMA`. `fusion-card.ts` checks foreign card data, including restored session entries. The decoder verifies the progress schema and indexed content array before handing a result to Pi. Session entries receive a separate structured clone at each endpoint because `appendEntry` dispatches synchronously. Card snapshots copy the JSON representation of the fields Pi's Bash renderer reads: `fullOutputPath` and the `truncation` fields `truncated`, `truncatedBy`, `outputLines`, `totalLines`, and `maxBytes`. Other override details do not enter the card. It renders the separate mutation and command TUI cards (`withMutationStatus`, `registerFusionCards`) and derives a not-run reason from the same facts.
69
+
70
+ Fusion matches its nested Bash `tool_call` by parent ID inside the dispatch scope. Bash's first execution update fixes the displayed command and snapshots the hook-edited timeout for the countdown and final classification. For a silent override, Fusion reads the fallback timeout only for a final error with an execution duration and no numeric exit code. It checks for cancellation after timeout classification. Fusion reports `timeout` when Pi returns a final error with an execution duration, without a structured numeric exit code, and the final text matches or ends with Pi Bash's diagnostic for the observed timeout. Pi measures execution duration only for calls that ran. A silent override or result hook can change the shared input or final output, so this classification depends on them preserving the timeout and its diagnostic.
71
+
72
+ Cancellation releases a waiting call's turn without releasing its predecessor. The queue entry stays until its chained tail settles, so nested calls still see an occupied target.
62
73
 
63
74
  Command cards reuse Pi's public `ToolExecutionComponent`, with the real TUI supplied by a temporary empty widget factory. History may be rebuilt before `session_start`, so retain a deferred component until the UI is bound. Cache each native component by call ID and apply global expansion only when that setting changes, so custom-entry rebuilds preserve mouse expansion. Keep spacing adaptation separate from native mouse handling and retain the built-in Bash presentation; the supported Pi API does not expose another tool's renderer.