@criogaid/pi-hashline-edit 0.12.0 → 0.13.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 (88) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +59 -16
  3. package/README.zh-CN.md +59 -16
  4. package/package.json +2 -2
  5. package/src/core/AGENTS.md +2 -2
  6. package/src/core/apply.test.ts +13 -0
  7. package/src/core/apply.ts +5 -9
  8. package/src/core/case-fold.test.ts +16 -25
  9. package/src/core/case-fold.ts +4 -4
  10. package/src/core/character-set.test.ts +1 -6
  11. package/src/core/character-set.ts +7 -61
  12. package/src/core/regex.ts +2 -36
  13. package/src/core/search-analysis.test.ts +66 -61
  14. package/src/core/search-analysis.ts +24 -39
  15. package/src/core/search-matrix.test.ts +2 -2
  16. package/src/core/search-matrix.testing.ts +6 -16
  17. package/src/core/search-schema.ts +0 -1
  18. package/src/core/search.test.ts +6 -19
  19. package/src/core/search.ts +10 -8
  20. package/src/index.ts +27 -2
  21. package/src/integration/config-registration.test.ts +77 -4
  22. package/src/integration/fusion-dispatch.test.ts +47 -2
  23. package/src/integration/grep-errors.test.ts +31 -0
  24. package/src/integration/grep-flags.test.ts +13 -196
  25. package/src/integration/grep-js-completeness.test.ts +41 -8
  26. package/src/integration/grep-line-candidates.test.ts +3 -33
  27. package/src/integration/grep-matrix.test.ts +1 -1
  28. package/src/integration/grep-path-matrix.test.ts +59 -65
  29. package/src/integration/grep-prefilter-coverage.test.ts +15 -8
  30. package/src/integration/grep-process-limits.test.ts +46 -0
  31. package/src/integration/grep-regex.test.ts +7 -2
  32. package/src/integration/grep-rg.test.ts +63 -12
  33. package/src/integration/grep-translation.test.ts +14 -7
  34. package/src/integration/model-budget-lifecycle.test.ts +41 -2
  35. package/src/integration/npm-package.testing.ts +2 -3
  36. package/src/integration/replace-package.testing.ts +2 -2
  37. package/src/pi/AGENTS.md +21 -13
  38. package/src/pi/action-fusion.test.ts +38 -4
  39. package/src/pi/action-fusion.ts +23 -19
  40. package/src/pi/argument-diagnostics.ts +28 -48
  41. package/src/pi/argument-validation.test.ts +61 -27
  42. package/src/pi/argument-validation.ts +34 -0
  43. package/src/pi/budgets.ts +19 -10
  44. package/src/pi/config.test.ts +1 -1
  45. package/src/pi/diagnostic-buffer.test.ts +1 -0
  46. package/src/pi/edit-tool.ts +1 -1
  47. package/src/pi/failure-context.test.ts +23 -2
  48. package/src/pi/failure-context.ts +36 -42
  49. package/src/pi/failure-path.test.ts +8 -3
  50. package/src/pi/file-commit.test.ts +109 -52
  51. package/src/pi/file-commit.ts +62 -56
  52. package/src/pi/fusion-card.ts +3 -2
  53. package/src/pi/grep-candidates.test.ts +5 -5
  54. package/src/pi/grep-candidates.ts +81 -50
  55. package/src/pi/grep-matrix.test.ts +14 -29
  56. package/src/pi/grep-order.test.ts +132 -9
  57. package/src/pi/grep-output.ts +169 -51
  58. package/src/pi/grep-render.ts +40 -34
  59. package/src/pi/grep-rg.testing.ts +9 -6
  60. package/src/pi/grep-scope.ts +51 -29
  61. package/src/pi/grep-search.ts +96 -71
  62. package/src/pi/grep-tool.ts +13 -22
  63. package/src/pi/grep.test.ts +310 -84
  64. package/src/pi/model-budgets.test.ts +56 -6
  65. package/src/pi/model-budgets.ts +7 -4
  66. package/src/pi/mutation-result.test.ts +25 -1
  67. package/src/pi/mutation-result.ts +7 -2
  68. package/src/pi/mutation-runner.ts +3 -4
  69. package/src/pi/output-budgets.test.ts +3 -1
  70. package/src/pi/path.ts +18 -4
  71. package/src/pi/pi.test.ts +22 -0
  72. package/src/pi/read-delegation.test.ts +119 -0
  73. package/src/pi/read-tool.ts +109 -61
  74. package/src/pi/read.test.ts +306 -17
  75. package/src/pi/regex-worker.test.ts +42 -0
  76. package/src/pi/regex-worker.ts +17 -11
  77. package/src/pi/registration.test.ts +157 -102
  78. package/src/pi/render.test.ts +54 -0
  79. package/src/pi/render.ts +9 -9
  80. package/src/pi/replace-tool.ts +5 -2
  81. package/src/pi/report-schema.ts +52 -31
  82. package/src/pi/report.test.ts +60 -10
  83. package/src/pi/rg-process.ts +41 -5
  84. package/src/pi/rg-regex.test.ts +12 -52
  85. package/src/pi/rg-regex.ts +29 -77
  86. package/src/pi/text-stream.test.ts +3 -0
  87. package/src/pi/text-stream.ts +1 -1
  88. package/src/testing/regex-translation-corpus.ts +39 -96
package/src/pi/AGENTS.md CHANGED
@@ -4,49 +4,57 @@ Pi integration. Cross-cutting contracts live in the root `AGENTS.md`; this file
4
4
 
5
5
  ## Registration
6
6
 
7
- `src/index.ts` loads the config once; each tool captures that snapshot for its lifetime, and a reload registers the tools again. When `enabled` is false it registers nothing. Otherwise it registers the model-budget provider (`registerModelBudgets`) and the Action Fusion cards (`registerFusionCards`, always, so saved then_run cards render while Action Fusion is off), builds the Action Fusion executor from the cards' progress reporter only when `actionFusion` is on, and passes each tool factory 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. One helper appends `NEXT_GUIDELINE` from `report-schema.ts` to every tool's `promptGuidelines` (Pi prints the shared guideline once); the mutation tools are also wrapped with `withMutationStatus` when the executor exists. Their shared `mutationToolBase` (`mutation-runner.ts`) adds the `then_run` field (`withThenRunSchema`), its selection instructions in the description (`withThenRunDescription`), and `ACTION_FUSION_GUIDELINES` only when `fusion` exists; the field's `command` description carries the Windows path note only when `process.platform` is `win32`.
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.
8
8
 
9
9
  ## Argument funnel
10
10
 
11
- - Tool files (`read-tool.ts`, `grep-tool.ts`, `edit-tool.ts`, `replace-tool.ts`, `write-tool.ts`) define TypeBox schemas and each mutation tool's description names its alternative (edit ↔ replace ↔ write). Each tool's `prepareArguments` comes from `argument-validation.ts`, then Pi validates against the schema again, and only then calls `execute`. Caller arguments are never rewritten. Each tool supplies only the semantic checks the schema cannot express or name precisely: edit rejects fields an operation's `action` does not take or requires but lacks, an empty `lines` array, `lines` entries that cannot be written as UTF-8, line numbers beyond the safe-integer range, anchors of another hash length, and reversed ranges; replace rejects unwritable replacement text; replace and grep share `checkRegexArguments`, which reports flags V8 rejects and compiles regex-mode patterns; write rejects unwritable content. File-dependent checks stay in execution. Shared integer rules live in `schema.ts`. 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. 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.
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.
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
+ - 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
+ - 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.
12
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.
13
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.
14
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.
15
18
 
16
19
  ## Mutations
17
20
 
18
- - `mutation-runner.ts` owns the definition the mutation tools share (`mutationToolBase`: name, then_run field, description and guideline, argument preparation, strict sampling, and `execute`); each tool supplies its schema, text, semantic checks, and `run`, and adds its own renderers. It also owns the call sequence shared by `edit`/`replace`/`write` after Pi has validated the arguments: separating `then_run`, path resolution, `withFileMutationQueue`, the hand-off to Action Fusion, and finalization. Each tool's `run` returns a tool-indexed `MutationOutcome` (commit facts, details, schema-derived outcome facts), Action Fusion returns `FusedMutation` facts, and the runner's single `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`, so each tool supplies only a `TextChange` (new text, outcome facts).
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`.
19
22
  - `file-read.ts` provides guarded stream and whole-file reads; byte revision checks stay in the search and commit owners.
20
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.
21
- - `file-commit.ts` is the only publication path: file revisions (`fileRevision`), no-op detection, a temp file in a sibling dir, then `link` (create) or `rename` (overwrite). It handles symlinks and hard links, 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 failed step is the `message`, its underlying error the `cause`. `edit`/`replace` commit with `baseRevision`, the revision of the bytes they read; `CommitOptions` admits it only with `overwrite`. Its target type distinguishes missing from existing files with required revision and mode facts; commit results distinguish creation, replacement, and no-op. It also owns freshness: `commitFreshness` from the commit result and `observeFreshness` for Fusion's later observations; only unknown freshness carries an observation error.
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.
22
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.
23
26
 
24
27
  ## grep
25
28
 
26
- - 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). Grep scans each candidate file once through `text-stream.ts` (via `scanTextFile`) for NUL, UTF-8 validity, its revision, and the lossy LF view it matches; content mode reads each matched file again in `grep-reread`. 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. README defines resource limits and physical-line reporting; document file and worker budgets there.
27
- - 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 string expansion and 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.
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
+ - 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.
28
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.
29
- - `grep-candidates.ts` decides which rg runs to make: line candidates through `rg-regex.ts` (workers re-check only those lines through `searchLines`), else candidate files (`--files-with-matches` over the necessary literals, or `--files` when none is necessary or they exceed `MAX_RG_PATTERN_UNITS`). Byte-level pattern flags are defined once there.
30
- - 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, but propagate cancellation without waiting for earlier files.
32
+ - `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.
31
34
  - `grep-scope.ts` classifies scope errors: only `ENOENT` means `PATH_NOT_FOUND`; preserve other filesystem errors.
32
35
 
33
36
  ## Regex workers
34
37
 
35
- `regex-worker.ts` owns timeout, cancellation, and cleanup for grep and replace workers; each caller awaits a request before sending another to the same worker. Each worker (`grep-worker.ts` runs `core/search.ts`; `replace-worker.ts` runs `core/replace.ts`) is started through its `.mjs` bootstrap, which loads TypeScript through `jiti`, because workers do not inherit Pi's loader; workers never import the Pi runtime and trust inputs validated at tool entry. `replace-regex.ts` owns the replacement request and sends regex batches to `core/replace.ts`; literal-only batches remain in-process. `config.ts` owns both timeout settings. The host validates exactly-one-result replies with `regex-worker-contract.ts`, using code-specific facts from `report-schema.ts` and each engine's result schema (`core/replace-schema.ts`, `core/search-schema.ts`). Bound worker failures only in the receiving tool.
38
+ `regex-worker.ts` owns timeout, cancellation, and cleanup for grep and replace workers; each caller awaits a request before sending another to the same worker. Each worker (`grep-worker.ts` runs `core/search.ts`; `replace-worker.ts` runs `core/replace.ts`) is started through its `.mjs` bootstrap, which loads TypeScript through `jiti`, because workers do not inherit Pi's loader; workers never import the Pi runtime and trust inputs validated at tool entry. `replace-regex.ts` owns the replacement request and sends regex batches to `core/replace.ts`; literal-only batches remain in-process. `config.ts` owns both timeout settings. The host validates exactly-one-result replies with `regex-worker-contract.ts`, using code-specific facts from `report-schema.ts` and each engine's result schema (`core/replace-schema.ts`, `core/search-schema.ts`); that schema check is a reply's only check, and the host trusts the engine's semantics. Bound worker failures only in the receiving tool.
36
39
 
37
40
  ## Reports and rendering
38
41
 
42
+ - 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.
44
+ - 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
+ - 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
+
39
47
  - `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.
40
- - `report.ts` builds reports and owns their one model-facing serialization (`renderReport`: one JSON object, fields in schema order). It filters the derived model omission set (`MODEL_OMITTED_FIELDS`) and omits the call's own `tool`/`path` plus TUI-only facts from result text while retaining them in `details.report`; renderers pass their tool name to `reportOf`, which reads `details.report` (checked once by `detailsReport`) or else decodes a text-only 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.
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.
41
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.
42
50
  - `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`.
43
- - 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. The model omission set is derived from the declarations; do not add a parallel list in `report.ts`. To change an error code, edit `ERROR_DEFINITIONS` and follow the type errors to every throw site and the worker contract.
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.
44
52
  - `error-text.ts` holds the Pi-layer error forms (cancellation, file changed during read or search). `diagnostic-buffer.ts` bounds stderr and search diagnostics.
45
53
 
46
54
  ## Budgets and config
47
55
 
48
- - `budgets.ts` derives model-facing byte budgets from the selected model's declared `contextWindow`, with bounded defaults for unknown limits. Every tool factory receives the provider as `ToolEnvironment.budgets` (`config.ts`); internal helpers require the resolved budget or an explicit byte limit. `model-budgets.ts` derives the budgets from the live selected model on each request; preparation shares its provider, and each execution captures its budgets before its asynchronous work. Model-derived content budgets share the `MAX_CONTENT_KIB` ceiling that the explicit `read.maxKiB` range also uses.
49
- - `config.ts` defines the `hashlineEdit` settings as one TypeBox schema: top-level `enabled`, `actionFusion`, `hashLen`, `shiftRadius` control shared behavior; the `read`, `grep`, and `replace` groups hold tool-specific settings. Missing or invalid optional `read.maxKiB` selects automatic model sizing.
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.
50
58
 
51
59
  ## Action Fusion
52
60
 
@@ -32,16 +32,28 @@ const mutationFactories = [
32
32
  makeWriteOverride,
33
33
  ];
34
34
 
35
+ test("Fusion executor toggled → mutation descriptions stay identical without then_run instructions", () => {
36
+ const fusion = createActionFusionExecutor(() => {});
37
+ for (const makeTool of mutationFactories) {
38
+ const disabled = makeTool("/tmp");
39
+ const enabled = makeTool("/tmp", fusion);
40
+ assert.equal(enabled.description, disabled.description, enabled.name);
41
+ assert.doesNotMatch(enabled.description, /then_run|separate bash call/i);
42
+ }
43
+ });
44
+
35
45
  test("mutation tools expose Fusion schemas and guidance when supplied an executor", () => {
36
46
  const fusion = createActionFusionExecutor(() => {});
37
47
  for (const makeTool of mutationFactories) {
38
48
  const disabled = makeTool("/tmp");
39
49
  const enabled = makeTool("/tmp", fusion);
40
50
  assert.equal(Object.hasOwn(disabled.parameters.properties, "then_run"), false);
41
- assert.ok(
42
- "then_run" in enabled.parameters.properties && enabled.parameters.properties.then_run,
43
- );
44
- assert.match(enabled.description, /set the then_run parameter/i);
51
+ assert.ok("then_run" in enabled.parameters.properties);
52
+ const thenRun = enabled.parameters.properties.then_run;
53
+ assert.partialDeepStrictEqual(thenRun, {
54
+ description: `Command to run once after ${enabled.name} succeeds; failure does not roll back the file.`,
55
+ properties: { command: { description: "Bash command to run." } },
56
+ });
45
57
  assert.deepEqual(enabled.promptGuidelines, [
46
58
  ...(disabled.promptGuidelines ?? []),
47
59
  ...ACTION_FUSION_GUIDELINES,
@@ -54,6 +66,28 @@ test("mutation tools expose Fusion schemas and guidance when supplied an executo
54
66
  }
55
67
  });
56
68
 
69
+ test("Fusion platform guidance → only Windows gets the path note", async () => {
70
+ const original = Object.getOwnPropertyDescriptor(process, "platform");
71
+ assert.ok(original);
72
+ const base =
73
+ "Set then_run on edit, replace, or write for a check that can run right after that change. Use a separate bash call when the command requires approval, needs information from the tool's result, must wait for reload, or covers several changes; run that check once after all of them.";
74
+ const windowsNote =
75
+ " then_run commands run in Bash on Windows: avoid Unix-only paths such as /tmp.";
76
+ try {
77
+ for (const platform of ["win32", "linux"] as const) {
78
+ Object.defineProperty(process, "platform", { ...original, value: platform });
79
+ const fusion: typeof import("./action-fusion.ts") = await import(
80
+ new URL(`./action-fusion.ts?platform=${platform}`, import.meta.url).href
81
+ );
82
+ assert.deepEqual(fusion.ACTION_FUSION_GUIDELINES, [
83
+ base + (platform === "win32" ? windowsNote : ""),
84
+ ]);
85
+ }
86
+ } finally {
87
+ Object.defineProperty(process, "platform", original);
88
+ }
89
+ });
90
+
57
91
  test("then_run schemas reject invalid commands, unknown keys, and excessive timeouts", async (t) => {
58
92
  const dir = await tempDir();
59
93
  try {
@@ -9,8 +9,8 @@
9
9
  * a later fused call on the same file waits until this command finishes and
10
10
  * cannot change the revision the command started from. Its key resolves the nearest
11
11
  * existing ancestor and folds case on Windows, so it is never looser than
12
- * Pi's key. It is always taken first and Pi's queue never waits on it, so
13
- * the nesting cannot deadlock.
12
+ * Pi's key. Nested tool calls during the command cannot wait on an occupied
13
+ * Fusion queue: they might be waiting for their own command to finish.
14
14
  *
15
15
  * Writers outside these queues are not blocked; the commit layer's freshness
16
16
  * observation against `publishedRevision` detects them, and the command is
@@ -21,6 +21,7 @@
21
21
  * @module pi-hashline-edit/pi
22
22
  */
23
23
 
24
+ import { AsyncLocalStorage } from "node:async_hooks";
24
25
  import { realpath } from "node:fs/promises";
25
26
  import { basename, dirname, resolve } from "node:path";
26
27
  import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
@@ -49,14 +50,14 @@ const MILLISECONDS_PER_SECOND = 1_000;
49
50
  // Pi's built-in Bash rejects timeouts above the setTimeout millisecond limit.
50
51
  const MAX_BASH_TIMEOUT_SECONDS = 2_147_483_647 / MILLISECONDS_PER_SECOND;
51
52
 
52
- // Pi's Bash runs on this host, and Pi's prompt does not name the OS; only Windows needs the path note.
53
- const COMMAND_DESCRIPTION =
54
- process.platform === "win32"
55
- ? "Bash command to run. This host is Windows: avoid Unix-only paths such as /tmp."
56
- : "Bash command to run.";
57
-
53
+ // The one place the model is told when to use then_run; the tools' descriptions stay their own.
58
54
  export const ACTION_FUSION_GUIDELINES = [
59
- "When a check covers several changes, run it once after all of those changes.",
55
+ `Set then_run on edit, replace, or write for a check that can run right after that change. Use a separate bash call when the command requires approval, needs information from the tool's result, must wait for reload, or covers several changes; run that check once after all of them.${
56
+ // Pi's Bash runs on this host, and Pi's prompt does not name the OS; only Windows needs the path note.
57
+ process.platform === "win32"
58
+ ? " then_run commands run in Bash on Windows: avoid Unix-only paths such as /tmp."
59
+ : ""
60
+ }`,
60
61
  ];
61
62
 
62
63
  type ProgressReporter = (progress: ActionFusionProgress) => void;
@@ -65,7 +66,7 @@ function createThenRunSchema(tool: MutationToolName) {
65
66
  return Type.Optional(
66
67
  Type.Object(
67
68
  {
68
- command: Type.String({ pattern: "\\S", description: COMMAND_DESCRIPTION }),
69
+ command: Type.String({ pattern: "\\S", description: "Bash command to run." }),
69
70
  timeout: Type.Optional(
70
71
  Type.Number({
71
72
  exclusiveMinimum: 0,
@@ -98,13 +99,6 @@ export function withThenRunSchema<P extends TProperties>(
98
99
 
99
100
  export type ThenRunInput = NonNullable<Static<ReturnType<typeof createThenRunSchema>>>;
100
101
 
101
- /** Name then_run in a mutation tool's description when Action Fusion is enabled. */
102
- export function withThenRunDescription(description: string, actionFusion: boolean): string {
103
- return actionFusion
104
- ? `${description} Set the then_run parameter for checks that can run immediately after this change. Use a separate bash call when the command requires approval, needs information from this tool's result, must wait for reload, or checks several changes from one response.`
105
- : description;
106
- }
107
-
108
102
  /** What a fused call leaves for the mutation runner to report; Fusion builds no result itself. */
109
103
  export interface FusedMutation<TDetails, TTool extends MutationToolName> {
110
104
  readonly outcome: MutationOutcome<TDetails, TTool>;
@@ -145,7 +139,7 @@ async function runCommand(
145
139
  typeof structured === "object" &&
146
140
  "exit_code" in structured &&
147
141
  typeof structured.exit_code === "number";
148
- // Pi 0.99.1 supplies exit_code for ordinary exits, but serializes a thrown
142
+ // Pi's Bash supplies exit_code for ordinary exits, but serializes a thrown
149
143
  // timeout as text. Only recognize its final diagnostic for the requested
150
144
  // timeout; a failed command's output may itself mention or quote a timeout.
151
145
  const timeoutDiagnostic = `Command timed out after ${input.timeout} seconds`;
@@ -265,10 +259,16 @@ function createProgressTracker<TDetails extends object>({
265
259
 
266
260
  export function createActionFusionExecutor(onProgress: ProgressReporter) {
267
261
  const queueTails = new Map<string, Promise<void>>();
262
+ const commandScope = new AsyncLocalStorage<{ active: boolean }>();
268
263
 
269
264
  async function withQueue<T>(path: string, work: () => Promise<T>): Promise<T> {
270
265
  const key = await canonicalQueueKey(path);
271
266
  const previous = queueTails.get(key) ?? Promise.resolve();
267
+ if (queueTails.has(key) && commandScope.getStore()?.active) {
268
+ throw new Error(
269
+ "A then_run command cannot call a mutation tool for a target with a pending mutation.",
270
+ );
271
+ }
272
272
  let release!: () => void;
273
273
  const owned = new Promise<void>((resolve) => {
274
274
  release = resolve;
@@ -353,15 +353,19 @@ export function createActionFusionExecutor(onProgress: ProgressReporter) {
353
353
  if (before.freshness !== "unchanged") return settle(before, { status: "skipped" });
354
354
 
355
355
  progress.report("running", "unchanged");
356
+ const scope = { active: true };
356
357
  let command: CommandOutcome;
357
358
  try {
358
- command = await runCommand(thenRun, signal, ctx, progress.followCommand);
359
+ command = await commandScope.run(scope, () =>
360
+ runCommand(thenRun, signal, ctx, progress.followCommand),
361
+ );
359
362
  } catch (error) {
360
363
  command = {
361
364
  status: signal?.aborted ? "cancelled" : "failed",
362
365
  result: { content: [{ type: "text", text: errorMessage(error) }] },
363
366
  };
364
367
  } finally {
368
+ scope.active = false;
365
369
  progress.stopHeartbeat();
366
370
  }
367
371
  progress.commandSettled(command.result);
@@ -63,6 +63,11 @@ function projectValueSchema(
63
63
  }
64
64
  return schema;
65
65
  }
66
+ // A field can be forbidden by the operation regardless of its value's type.
67
+ if (!IsObject(schema) && projection.explained.has(path)) {
68
+ projection.applicable.add(path);
69
+ return Type.Unknown();
70
+ }
66
71
  if ("type" in schema && !Value.Check(Type.Unknown({ type: schema.type }), value)) return schema;
67
72
  projection.applicable.add(path);
68
73
  // An issue on a whole object, such as a choice between its fields, explains
@@ -79,7 +84,6 @@ function projectValueSchema(
79
84
  );
80
85
  return Type.Object(properties, ObjectOptions(schema));
81
86
  }
82
- if (projection.explained.has(path)) return Type.Unknown();
83
87
  if (IsArray(schema) && Array.isArray(value)) {
84
88
  const items = value.map((item, index) =>
85
89
  projectSchema(schema.items, item, `${path}[${index}]`, projection),
@@ -99,46 +103,19 @@ function propertyPath(path: string, key: string): string {
99
103
  : `${path}[${JSON.stringify(key)}]`;
100
104
  }
101
105
 
102
- const unescapePointer = (part: string) => part.replaceAll("~1", "/").replaceAll("~0", "~");
103
-
106
+ /** Declared tool fields do not contain slashes or tildes. TypeBox emits unknown keys verbatim. */
104
107
  function pointerParts(pointer: string): readonly string[] {
105
- return pointer.split("/").slice(1).map(unescapePointer);
108
+ return pointer.split("/").slice(1);
106
109
  }
107
110
 
108
- /**
109
- * The projection paths of the value at `pointer` and of its parent; the root is "". Pi's TypeBox
110
- * leaves `/` and `~` in property names unescaped, so a name spans the fewest segments that form
111
- * an own key, read escaped or as is.
112
- */
113
- function valuePaths(pointer: string, prepared: unknown): { path: string; parent: string } {
114
- const segments = pointer.split("/").slice(1);
111
+ function valuePath(parts: readonly string[], prepared: unknown): string {
115
112
  let value = prepared;
116
113
  let path = "";
117
- let parent = "";
118
- for (let index = 0; index < segments.length; index++) {
119
- let part = unescapePointer(segments[index]);
120
- if (typeof value === "object" && value !== null && !Array.isArray(value)) {
121
- const object = value;
122
- for (let end = index + 1; end <= segments.length; end++) {
123
- const raw = segments.slice(index, end).join("/");
124
- const key = [unescapePointer(raw), raw].find((name) => Object.hasOwn(object, name));
125
- if (key !== undefined) {
126
- part = key;
127
- index = end - 1;
128
- break;
129
- }
130
- }
131
- }
132
- parent = path;
114
+ for (const part of parts) {
133
115
  path = Array.isArray(value) ? `${path}[${part}]` : propertyPath(path, part);
134
116
  value = typeof value === "object" && value !== null ? Reflect.get(value, part) : undefined;
135
117
  }
136
- return { path, parent };
137
- }
138
-
139
- function fieldPath(pointer: string, prepared: unknown, key?: string): string {
140
- const { path } = valuePaths(pointer, prepared);
141
- return (key === undefined ? path : propertyPath(path, key)) || "$";
118
+ return path;
142
119
  }
143
120
 
144
121
  /** One declaration's meaning: its description, labeled with its values when it is a choice. */
@@ -206,36 +183,39 @@ function aggregateErrors(
206
183
  const add = (field: string, reason: string, fix?: string) =>
207
184
  issues.push(fix === undefined ? { field, reason } : { field, reason, fix });
208
185
  for (const error of errors) {
186
+ const parts = pointerParts(error.instancePath);
209
187
  switch (error.keyword) {
210
188
  case "required": {
211
- const parts = pointerParts(error.instancePath);
212
189
  for (const key of error.params.requiredProperties)
213
190
  add(
214
- fieldPath(error.instancePath, prepared, key),
191
+ propertyPath(valuePath(parts, prepared), key),
215
192
  "is required",
216
193
  fieldExplanation(parameters, [...parts, key]),
217
194
  );
218
195
  break;
219
196
  }
220
197
  case "additionalProperties": {
221
- const { path } = valuePaths(error.instancePath, prepared);
198
+ const path = valuePath(parts, prepared);
222
199
  const fix = shapeExplanation(objects.get(path));
223
200
  for (const key of error.params.additionalProperties)
224
- add(fieldPath(error.instancePath, prepared, key), "is not allowed", fix);
201
+ add(propertyPath(path, key), "is not allowed", fix);
225
202
  break;
226
203
  }
227
204
  case "pattern":
228
- add(
229
- fieldPath(error.instancePath, prepared),
230
- error.message,
231
- fieldExplanation(parameters, pointerParts(error.instancePath)),
232
- );
205
+ add(valuePath(parts, prepared) || "$", error.message, fieldExplanation(parameters, parts));
233
206
  break;
234
207
  case "boolean": {
235
- // Once TypeBox's error capacity ends before `additionalProperties`, this is the only report.
236
- const { parent } = valuePaths(error.instancePath, prepared);
208
+ // TypeBox emits a false-schema error per unknown key before its grouped error.
209
+ // Count declared path steps to preserve the entire unknown key, even if it contains '/'.
210
+ const depth = error.schemaPath
211
+ .split("/")
212
+ .filter(
213
+ (segment) =>
214
+ segment === "properties" || segment === "items" || segment === "prefixItems",
215
+ ).length;
216
+ const parent = valuePath(parts.slice(0, depth), prepared);
237
217
  add(
238
- fieldPath(error.instancePath, prepared),
218
+ propertyPath(parent, parts.slice(depth).join("/")),
239
219
  "is not allowed",
240
220
  shapeExplanation(objects.get(parent)),
241
221
  );
@@ -243,13 +223,13 @@ function aggregateErrors(
243
223
  }
244
224
  case "enum":
245
225
  add(
246
- fieldPath(error.instancePath, prepared),
226
+ valuePath(parts, prepared) || "$",
247
227
  `expected one of: ${error.params.allowedValues.map((value) => JSON.stringify(value)).join(", ")}`,
248
- fieldExplanation(parameters, pointerParts(error.instancePath)),
228
+ fieldExplanation(parameters, parts),
249
229
  );
250
230
  break;
251
231
  default:
252
- add(fieldPath(error.instancePath, prepared), error.message);
232
+ add(valuePath(parts, prepared) || "$", error.message);
253
233
  }
254
234
  }
255
235
  return combineIssues(issues);
@@ -26,27 +26,30 @@ const {
26
26
  makeWriteOverride,
27
27
  } = await import("./tool-factories.testing.ts");
28
28
 
29
- test("grep has invalid flags alongside invalid literal or pattern → reports independent fields", async (t) => {
30
- const tool = makeGrepOverride(process.cwd(), DEFAULT_CONFIG);
31
- for (const args of [
32
- { pattern: ["text"], flags: "x" },
33
- { pattern: ["text"], literal: {}, flags: "x" },
34
- { pattern: {}, literal: true, flags: "x" },
35
- ]) {
36
- await t.test(JSON.stringify(args), async () => {
37
- await assert.rejects(callTool(tool, args), (error: unknown) => {
38
- const fields = argumentError(error).issues.map((issue) => issue.field);
39
- assert.ok(fields.includes("flags"), JSON.stringify(fields));
40
- assert.ok(
41
- fields.some((field) =>
42
- Array.isArray(args.pattern) ? field === "literal" : field.startsWith("pattern"),
43
- ),
44
- JSON.stringify(fields),
45
- );
46
- return true;
47
- });
48
- });
49
- }
29
+ test('grep receives flags: "i" → rejects INVALID_ARGUMENTS before searching', async () => {
30
+ let searches = 0;
31
+ const discover = async () => {
32
+ searches++;
33
+ return { code: 1, stderr: "", stopped: false };
34
+ };
35
+ const tool = makeMockGrep(process.cwd(), DEFAULT_CONFIG, {
36
+ runRgPaths: discover,
37
+ runRgLines: discover,
38
+ });
39
+ await assert.rejects(
40
+ callTool(tool, { pattern: ["text"], literal: true, flags: "i" }),
41
+ (error: unknown) => {
42
+ const report = argumentError(error);
43
+ assert.equal(report.error, "INVALID_ARGUMENTS");
44
+ assert.deepEqual(
45
+ report.issues.map((issue) => issue.field),
46
+ ["flags"],
47
+ );
48
+ assert.match(report.issues[0].reason, /not allowed/);
49
+ return true;
50
+ },
51
+ );
52
+ assert.equal(searches, 0);
50
53
  });
51
54
 
52
55
  const invalidCommand = { command: "", timeout: 0 };
@@ -219,16 +222,11 @@ test("blank then_run command with Fusion → reports exactly one command issue",
219
222
  }
220
223
  });
221
224
 
222
- test("grep and replace flags → accept V8 modes and reject invalid flags before patterns or file reads", async (t) => {
225
+ test("replace flags → accept V8 modes and reject invalid flags before patterns or file reads", async (t) => {
223
226
  const cwd = await mkdtemp(join(tmpdir(), "hashline-flags-"));
224
227
  t.after(() => rm(cwd, { recursive: true, force: true }));
225
228
  const path = join(cwd, "missing.txt");
226
229
  const tools = [
227
- {
228
- tool: makeGrepOverride(cwd, DEFAULT_CONFIG),
229
- args: (find: string, literal: boolean, flags: string) => ({ pattern: find, literal, flags }),
230
- field: "flags",
231
- },
232
230
  {
233
231
  tool: makeReplaceTool(cwd, DEFAULT_CONFIG),
234
232
  args: (find: string, literal: boolean, flags: string) => ({
@@ -642,6 +640,24 @@ test("one field violates independent constraints → combine its reasons without
642
640
  );
643
641
  });
644
642
 
643
+ test("edit receives a forbidden field with the wrong type → reports the field prohibition", async () => {
644
+ const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
645
+ await assert.rejects(
646
+ callTool(tool, {
647
+ path: "unused.txt",
648
+ steps: [{ action: "append", lines: ["text"], anchor: {} }],
649
+ }),
650
+ (error: unknown) => {
651
+ const { issues } = argumentError(error);
652
+ assert.equal(issues.length, 1);
653
+ assert.equal(issues[0].field, "steps[0].anchor");
654
+ assert.equal(issues[0].reason, "is not allowed");
655
+ assert.ok(issues[0].fix);
656
+ return true;
657
+ },
658
+ );
659
+ });
660
+
645
661
  test("edit fields contain semantic errors → checks only fields accepted by their action", async (t) => {
646
662
  const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
647
663
  for (const scenario of actionCases) {
@@ -971,3 +987,21 @@ test("20 unknown keys including a slash → bounded issues retain one accepted-f
971
987
  },
972
988
  );
973
989
  });
990
+
991
+ test("bounded additional-property diagnostics → preserve exact keys despite pointer-like spelling", async () => {
992
+ const extras = Object.fromEntries([
993
+ ...["a/b", "a", "a~1b"].map((key) => [key, true]),
994
+ ...Array.from({ length: 20 }, (_, index) => [`extra${index}`, true]),
995
+ ]);
996
+ const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
997
+ await assert.rejects(
998
+ callTool(tool, { path: "unused.txt", steps: [{ action: "append", lines: ["ok"], ...extras }] }),
999
+ (error: unknown) => {
1000
+ const report = argumentError(error);
1001
+ assert.equal(report.schemaLimited, true);
1002
+ const fields = report.issues.map((issue) => issue.field);
1003
+ assert.deepEqual(fields.slice(0, 3), ['steps[0]["a/b"]', "steps[0].a", 'steps[0]["a~1b"]']);
1004
+ return true;
1005
+ },
1006
+ );
1007
+ });
@@ -10,6 +10,7 @@ import { compile } from "@earendil-works/pi-schema";
10
10
  import { formats } from "@earendil-works/pi-schema/formats";
11
11
  import type { Static, TObject } from "typebox";
12
12
  import { errorMessage } from "../core/errors.ts";
13
+ import { buildRegex } from "../core/regex.ts";
13
14
  import { diagnoseArguments } from "./argument-diagnostics.ts";
14
15
  import { formatArgumentError } from "./argument-error.ts";
15
16
  import type { OutputBudgetProvider } from "./budgets.ts";
@@ -19,6 +20,39 @@ import type { ArgumentIssue, ReportTool } from "./report-schema.ts";
19
20
  export type ReportArgumentIssue = (field: string, reason: string, fix?: string) => void;
20
21
  export type CheckArguments = (args: unknown, report: ReportArgumentIssue) => void;
21
22
 
23
+ /**
24
+ * Report V8's diagnostics for a rule's flags and, in regex mode, for each pattern that
25
+ * buildRegex would reject. Invalid flags stop the check, since every pattern compiles with
26
+ * them; values that are not strings are left to schema validation.
27
+ */
28
+ export function checkRegexArguments(
29
+ flagsField: string,
30
+ flags: string | undefined,
31
+ literal: boolean,
32
+ patterns: readonly (readonly [field: string, value: unknown])[],
33
+ report: ReportArgumentIssue,
34
+ ): void {
35
+ try {
36
+ buildRegex("", true, flags);
37
+ } catch (error) {
38
+ report(flagsField, errorMessage(error));
39
+ return;
40
+ }
41
+ if (literal) return;
42
+ for (const [field, value] of patterns) {
43
+ if (typeof value !== "string") continue;
44
+ try {
45
+ buildRegex(value, false, flags);
46
+ } catch (error) {
47
+ report(
48
+ field,
49
+ errorMessage(error),
50
+ "For an exact-text match, set literal to true; otherwise correct the regex syntax.",
51
+ );
52
+ }
53
+ }
54
+ }
55
+
22
56
  /** Inspect arrays and the singleton objects Pi may coerce, without changing input. */
23
57
  export function argumentItems(value: unknown): readonly unknown[] {
24
58
  return Array.isArray(value) ? value : value !== null && typeof value === "object" ? [value] : [];