Skip to main content

aft/hashline/integration/
schema.rs

1//! Edit schema selection and governed schema/manifest artifacts.
2//!
3//! One binary ships both arms. The installed session effective value selects
4//! exactly one agent-visible `edit` schema. This module is the exclusive owner
5//! of the hashline-side governed schema and manifest definitions; host wiring
6//! regenerates committed artifacts from these constants.
7
8use serde_json::{json, Value};
9
10use super::binding::effective_for_capture;
11use super::binding::BindingGuard;
12
13/// Which edit schema arm a session publishes.
14#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
15pub enum EditSchemaArm {
16    /// Legacy match/line/symbol edit surface (gate-off / unregistered).
17    Legacy,
18    /// Hashline patch language with required `patch` field (gate-on).
19    Hashline,
20}
21
22impl EditSchemaArm {
23    pub const fn as_str(self) -> &'static str {
24        match self {
25            Self::Legacy => "legacy",
26            Self::Hashline => "hashline",
27        }
28    }
29
30    pub const fn is_hashline(self) -> bool {
31        matches!(self, Self::Hashline)
32    }
33}
34
35/// Select the sole edit schema arm from effective mode.
36pub fn select_edit_schema(effective: bool) -> EditSchemaArm {
37    if effective {
38        EditSchemaArm::Hashline
39    } else {
40        EditSchemaArm::Legacy
41    }
42}
43
44/// Select from an optional captured binding (unregistered → legacy).
45pub fn select_edit_schema_for_capture(guard: Option<&BindingGuard>) -> EditSchemaArm {
46    select_edit_schema(effective_for_capture(guard))
47}
48
49/// Agent-visible description for the legacy edit tool.
50pub const LEGACY_EDIT_DESCRIPTION: &str = "Edit a file by finding and replacing text, or by targeting named symbols. To write or overwrite a whole file, use the `write` tool — `edit` requires an explicit edit mode and will not silently overwrite a file from `content` alone.";
51
52/// Agent-visible description for the hashline edit tool.
53pub const HASHLINE_EDIT_DESCRIPTION: &str = concat!(
54    "Apply a hashline patch. Arguments are exactly `{patch}` where `patch` is a non-empty string. ",
55    "Server-owned preview control is outside this schema.\n\n",
56    "Quick reference:\n",
57    "- Header: `[path#TAG]`; TAG is exactly four hexadecimal digits from a current tagged read. ",
58    "Read every addressed row and gap boundary; REM and MV require a whole-file tagged read. ",
59    "Re-read after an edit before chaining: an edit-response tag can retain only changed context.\n",
60    "- Same canonical path: multiple sections compose in patch order against pre-request coordinates.\n",
61    "- Addresses: `0` (BOF), `N` (one line), `N.=M` (range; `N..=M`/`N..M` also work), ",
62    "`<N`/`>N` (gap before/after), `N*`/`<N*`/`>N*` (block), and `$`/`$-K` (EOF-relative). ",
63    "A plain `N` PUT replaces; use `<N` or `>N` to insert.\n",
64    "- PUT text: `PUT <address>:` followed by one or more `+` body rows (`+` alone is blank). ",
65    "A final patch newline is allowed. PUT without `:` copies `@name` (or the anonymous register) and takes no body; names use `@` plus ASCII letters, digits, `_`, or `-`.\n",
66    "- CUT: `CUT <address> [@name]`. REM: bare `REM` only, removing the whole file. ",
67    "MV: `MV <destination>` (one whitespace-free path, optional matching quotes), once and after any line operations. ",
68    "`*** Begin Patch`/`*** End Patch` is an optional envelope."
69);
70
71/// JSON Schema for the legacy edit arm (gate-off).
72pub fn legacy_edit_schema() -> Value {
73    json!({
74        "$schema": "https://json-schema.org/draft/2020-12/schema",
75        "type": "object",
76        "properties": {
77            "filePath": {
78                "description": "Path to the file to edit (absolute or relative to project root)",
79                "type": "string"
80            },
81            "symbol": {
82                "description": "Named symbol to replace (function, class, type)",
83                "type": "string"
84            },
85            "content": {
86                "description": "Replacement content for symbol mode. For whole-file writes, use the `write` tool.",
87                "type": "string"
88            },
89            "appendContent": {
90                "description": "Text to append to the end of path; creates the file if needed",
91                "type": "string"
92            },
93            "edits": {
94                "description": "Batch edits — non-empty array of { oldString, newString }, { oldString, newString, replaceAll: true }, or { startLine, endLine, content } objects",
95                "minItems": 1,
96                "type": "array",
97                "items": {
98                    "type": "object",
99                    "properties": {
100                        "oldString": {
101                            "description": "Text to find for a batch find/replace edit",
102                            "type": "string"
103                        },
104                        "newString": {
105                            "description": "Replacement text for a batch find/replace edit",
106                            "type": "string"
107                        },
108                        "replaceAll": {
109                            "description": "Replace every occurrence for this batch item",
110                            "type": "boolean"
111                        },
112                        "occurrence": {
113                            "description": "1-based occurrence for this batch item (1 = first match)",
114                            "type": "integer",
115                            "minimum": 1
116                        },
117                        "startLine": {
118                            "description": "1-based start line for a batch line-range edit",
119                            "type": "integer",
120                            "minimum": 1
121                        },
122                        "endLine": {
123                            "description": "1-based end line for a batch line-range edit",
124                            "type": "integer",
125                            "minimum": 1
126                        },
127                        "content": {
128                            "description": "Replacement text for a batch line-range edit",
129                            "type": "string"
130                        }
131                    }
132                }
133            }
134        },
135        "required": ["filePath"],
136        "description": LEGACY_EDIT_DESCRIPTION
137    })
138}
139
140/// JSON Schema for the hashline edit arm (gate-on).
141pub fn hashline_edit_schema() -> Value {
142    json!({
143        "$schema": "https://json-schema.org/draft/2020-12/schema",
144        "type": "object",
145        "additionalProperties": false,
146        "properties": {
147            "patch": {
148                "type": "string",
149                "minLength": 1,
150                "description": "Hashline patch text with one or more [path#TAG] sections and PUT/CUT/REM/MV operations"
151            }
152        },
153        "required": ["patch"],
154        "description": HASHLINE_EDIT_DESCRIPTION
155    })
156}
157
158/// Schema JSON for the selected arm.
159pub fn edit_schema_for(arm: EditSchemaArm) -> Value {
160    match arm {
161        EditSchemaArm::Legacy => legacy_edit_schema(),
162        EditSchemaArm::Hashline => hashline_edit_schema(),
163    }
164}
165
166/// Description string for the selected arm.
167pub fn edit_description_for(arm: EditSchemaArm) -> &'static str {
168    match arm {
169        EditSchemaArm::Legacy => LEGACY_EDIT_DESCRIPTION,
170        EditSchemaArm::Hashline => HASHLINE_EDIT_DESCRIPTION,
171    }
172}
173
174/// Native command name translation routes to when gate-on.
175pub const HASHLINE_EDIT_COMMAND: &str = "hashline_edit";
176
177/// Native command name for syntactic preflight (Phase-1 parse only).
178pub const HASHLINE_PREFLIGHT_COMMAND: &str = "hashline_preflight";
179
180/// Governed tool-manifest entry for one edit arm.
181#[derive(Clone, Debug, Eq, PartialEq)]
182pub struct GovernedEditManifestEntry {
183    pub name: &'static str,
184    pub arm: EditSchemaArm,
185    pub description: &'static str,
186    pub schema: Value,
187    pub supports_tool: bool,
188    pub hoisted: bool,
189    pub lane: &'static str,
190}
191
192/// Build the governed manifest entry hosts lock against for registration parity.
193pub fn governed_edit_manifest_entry(arm: EditSchemaArm) -> GovernedEditManifestEntry {
194    GovernedEditManifestEntry {
195        name: "edit",
196        arm,
197        description: edit_description_for(arm),
198        schema: edit_schema_for(arm),
199        supports_tool: true,
200        hoisted: true,
201        lane: "mutation",
202    }
203}
204
205/// Serialize both arms into the governed dual-mode artifact document.
206///
207/// Regeneration of committed `subc_tool_schemas.json` / plugin manifests must
208/// source the hashline arm exclusively from this document. The legacy arm is
209/// included so a single binary can publish either without rebuilding.
210pub fn regenerate_governed_edit_artifacts() -> Value {
211    let legacy = governed_edit_manifest_entry(EditSchemaArm::Legacy);
212    let hashline = governed_edit_manifest_entry(EditSchemaArm::Hashline);
213    json!({
214        "tool": "edit",
215        "dual_mode": true,
216        "selection": "session_effective_hashline",
217        "arms": {
218            "legacy": {
219                "arm": legacy.arm.as_str(),
220                "description": legacy.description,
221                "schema": legacy.schema,
222                "supports_tool": legacy.supports_tool,
223                "hoisted": legacy.hoisted,
224                "lane": legacy.lane,
225                "command": "edit",
226            },
227            "hashline": {
228                "arm": hashline.arm.as_str(),
229                "description": hashline.description,
230                "schema": hashline.schema,
231                "supports_tool": hashline.supports_tool,
232                "hoisted": hashline.hoisted,
233                "lane": hashline.lane,
234                "command": HASHLINE_EDIT_COMMAND,
235                "preflight_command": HASHLINE_PREFLIGHT_COMMAND,
236            }
237        },
238        "invariant": "a session never exposes both edit schemas",
239    })
240}
241
242/// Gate-on translation: accept only `{patch}` and route to `hashline_edit`.
243///
244/// Must run before shared path-argument normalization and every legacy edit-shape
245/// check. Legacy keys are never ignored or routed to a legacy handler.
246pub fn translate_gate_on_edit(
247    arguments: &Value,
248) -> Result<GateOnTranslation, crate::hashline::syntax::HashlineRejection> {
249    let request = crate::hashline::syntax::validate_raw_arguments(arguments)?;
250    Ok(GateOnTranslation {
251        command: HASHLINE_EDIT_COMMAND,
252        patch: request.patch,
253    })
254}
255
256/// Successful gate-on translation product.
257#[derive(Clone, Debug, Eq, PartialEq)]
258pub struct GateOnTranslation {
259    pub command: &'static str,
260    pub patch: String,
261}
262
263impl GateOnTranslation {
264    pub fn to_native_args(&self) -> Value {
265        json!({ "patch": self.patch })
266    }
267}
268
269/// Dispatch edit translation using the captured binding's effective mode.
270///
271/// - Effective on → hashline arm only (`hashline_edit`).
272/// - Effective off / unregistered → caller keeps the legacy translation path;
273///   this returns `None` so existing gate-off goldens stay byte-identical.
274pub fn translate_edit_for_session(
275    guard: Option<&BindingGuard>,
276    arguments: &Value,
277) -> Result<Option<GateOnTranslation>, crate::hashline::syntax::HashlineRejection> {
278    if !effective_for_capture(guard) {
279        return Ok(None);
280    }
281    Ok(Some(translate_gate_on_edit(arguments)?))
282}