8000 [pull] main from can1357:main by pull[bot] · Pull Request #97 · ericrihm/oh-my-pi · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
8000
Diff view
  •  
  •  
  •  
6 changes: 6 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

120 changes: 116 additions & 4 deletions crates/pi-edit/src/modes/sloppy/apply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
//! Port of `packages/coding-agent/src/edit/sloppy.ts` lines 1651–4258.

use std::{
borrow::Cow,
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
path::Path,
};

use super::{
parse::{has_marker_lines, missing_unmarked_lines, operation_payload, parse_operations},
types::{
ATOMICITY_NOTICE, Candidate, CandidateResult, LiteralFallback, MAX_CANDIDATES,
ATOMICITY_NOTICE, Candidate, CandidateResult, EdgeGaps, LiteralFallback, MAX_CANDIDATES,
MAX_COMBINATIONS, NormalizedText, Occurrence, Operation, OperationRewrite, ParsedPattern,
PatternToken, PlannedEdit, SelectionPair,
markers::{GAP, SELECT_CLOSE, SELECT_DIVIDER, SELECT_OPEN},
Expand Down Expand Up @@ -97,6 +98,7 @@ pub(crate) fn parse_pattern(
text: pattern.to_owned(),
normalized,
}],
edge_gaps: EdgeGaps::default(),
selection_start: 0,
selection_end: 1,
insertion: false,
Expand Down Expand Up @@ -178,8 +180,31 @@ pub(crate) fn parse_pattern(
tokens.remove(0);
stripped_leading += 1;
}
let mut stripped_trailing = 0;
while matches!(tokens.last(), Some(PatternToken::Gap { 8000 .. })) {
tokens.pop();
stripped_trailing += 1;
}
let edge_gaps = EdgeGaps { leading: stripped_leading > 0, trailing: stripped_trailing > 0 };
// An edge gap spans nothing inside the match: the newline joining a
// whole-line `…` to its neighbour belongs to the gap, not the anchor, and
// the surviving captures renumber from zero.
if edge_gaps.leading
&& let Some(PatternToken::Literal { text, .. }) = tokens.first_mut()
&& let Some(rest) = text.strip_prefix('\n')
{
*text = rest.strip_prefix('\r').unwrap_or(rest).to_owned();
}
if edge_gaps.trailing
&& let Some(PatternToken::Literal { text, .. }) = tokens.last_mut()
&& let Some(rest) = text.strip_suffix('\n')
{
*text = rest.strip_suffix('\r').unwrap_or(rest).to_owned();
}
for token in &mut tokens {
if let PatternToken::Gap { capture_index, .. } = token {
*capture_index -= stripped_leading;
}
}
for boundary in &mut selection_boundaries {
*boundary = boundary.saturating_sub(stripped_leading).min(tokens.len());
Expand Down Expand Up @@ -294,6 +319,7 @@ pub(crate) fn parse_pattern(
};
Ok(ParsedPattern {
tokens,
edge_gaps,
selection_start,
selection_end,
insertion,
Expand Down Expand Up @@ -704,6 +730,7 @@ fn collect_candidates(
.iter()
.map(|index| self.chosen[index].start)
.collect(),
literal_gaps: false,
};
if let Some(existing) = self.candidates.iter_mut().find(|existing| {
existing.start == candidate.start
Expand Down Expand Up @@ -1049,6 +1076,7 @@ pub(crate) fn locate(
.then_some(vec![(start, end)])
.unwrap_or_default(),
tuple: vec![occurrence.start],
literal_gaps: true,
}
})
.collect::<Vec<_>>();
Expand Down Expand Up @@ -1333,10 +1361,79 @@ fn decode_literal_markers(text: String) -> String {
.replace("\0V8LITDIV\0", SELECT_DIVIDER)
}

/// Drop the `<SM:PUT>` ellipses that re-emit `<SM:FIND>`'s open edges. An
/// edge gap captured nothing, so re-emitting it writes nothing; a whole-line
/// edge `…` takes the newline joining it to the rest of the rewrite with it.
/// The leading edge is positional; the trailing one is only claimed by an
/// ellipsis left over after the inner captures, since `…` re-emits captures
/// in order.
fn strip_edge_gaps(rewrite: &str, edges: EdgeGaps, inner: usize) -> Cow<'_, str> {
// A rewrite that is nothing but edge ellipses is context elision, not a
// deletion; leave it for `render_rewrite` to reject.
let keep = |stripped: String, current: &str| {
if stripped.trim().is_empty() {
current.to_owned()
} else {
stripped
}
};
let mut text = Cow::Borrowed(rewrite);
if edges.leading {
let at = text.len() - text.trim_start().len();
if text[at..].starts_with(GAP) {
let after = at + GAP.len();
let line_end = text[after..]
.find('\n')
.map_or(text.len(), |offset| after + offset);
let stripped = if text[after..line_end].trim().is_empty() {
let line_start = text[..at].rfind('\n').map_or(0, |offset| offset + 1);
format!("{}{}", &text[..line_start], &text[(line_end + 1).min(text.len())..])
} else {
format!("{}{}", &text[..at], &text[after..])
};
text = Cow::Owned(keep(stripped, &text));
}
}
if edges.trailing && text.matches(GAP).count() > inner {
let end = text.trim_end().len();
if text[..end].ends_with(GAP) {
let at = end - GAP.len();
let line_start = text[..at].rfind('\n').map_or(0, |offset| offset + 1);
let cut = if text[line_start..at].trim().is_empty() {
text[..line_start]
.strip_suffix('\n')
.map_or(line_start, |rest| rest.strip_suffix('\r').map_or(rest.len(), str::len))
} else {
at
};
let stripped = text[..cut].to_owned();
text = Cow::Owned(keep(stripped, &text));
}
}
text
}

/// Edges of `<SM:FIND>` that an inline selection borders; its replacement may
/// re-emit them.
fn selection_edges(
pattern: &ParsedPattern,
candidate: &Candidate,
pair: &SelectionPair,
) -> EdgeGaps {
if candidate.literal_gaps {
return EdgeGaps::default();
}
EdgeGaps {
leading: pattern.edge_gaps.leading && pair.start == 0,
trailing: pattern.edge_gaps.trailing && pair.end == pattern.tokens.len(),
}
}

fn render_rewrite(
rewrite: &str,
indices: &[usize],
captures: &[String],
edges: EdgeGaps,
operation_number: usize,
) -> Result<String, EditError> {
if rewrite.contains(SELECT_OPEN) || rewrite.contains(SELECT_CLOSE) {
Expand All @@ -1345,6 +1442,8 @@ fn render_rewrite(
text, <SM:PUT> is final text."
)));
}
let stripped = strip_edge_gaps(rewrite, edges, indices.len());
let rewrite = stripped.as_ref();
let mut rendered = String::new();
let mut marker = 0;
let mut index = 0;
Expand Down Expand Up @@ -1634,6 +1733,7 @@ fn prepare_inline(
span: (usize, usize),
selection: &SelectionPair,
rewrite: &str,
edges: EdgeGaps,
operation_number: usize,
lenient: bool,
) -> Result<(Candidate, String, Option<String>), EditError> {
Expand Down Expand Up @@ -1674,8 +1774,13 @@ fn prepare_inline(
} else {
desired.to_owned()
};
let replacement =
render_rewrite(&framed, &selection.capture_indices, &candidate.captures, operation_number)?;
let replacement = render_rewrite(
&framed,
&selection.capture_indices,
&candidate.captures,
edges,
operation_number,
)?;
if replacement.is_empty() && start != end {
let deleted = content[start..end].to_owned();
candidate = expand_full_line_deletion(content, &candidate);
Expand Down Expand Up @@ -2236,12 +2341,14 @@ fn apply_operations(
.collect::<Vec<_>>();
selections.sort_by_key(|(_, (start, _))| std::cmp::Reverse(*start));
for (selection_index, span) in selections {
let pair = &pattern.selection_pairs[selection_index];
let (prepared, replacement, deleted) = prepare_inline(
content,
candidate,
span,
&pattern.selection_pairs[selection_index],
pair,
&replacements[selection_index],
selection_edges(&pattern, candidate, pair),
number,
operation.whitespace_matched,
)?;
Expand Down Expand Up @@ -2393,6 +2500,11 @@ fn apply_operations(
&pattern.selected_capture_indices
},
&candidate.captures,
if candidate.literal_gaps {
EdgeGaps::default()
} else {
pattern.edge_gaps
},
number,
)?;
let replacement = align_boundary_echoes(content, &candidate, &rendered);
Expand Down
15 changes: 15 additions & 0 deletions crates/pi-edit/src/modes/sloppy/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,21 @@ pub struct SelectionPair {
pub gap_only: bool,
}

/// Open-ended `…` edges of a `<SM:FIND>`.
///
/// An edge gap spans no text inside the match: it is dropped from the token
/// stream (taking the newline that joined it to its neighbour with it), and a
/// `…` on the same edge of `<SM:PUT>` re-emits it as nothing.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct EdgeGaps {
pub leading: bool,
pub trailing: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedPattern {
pub tokens: Vec<PatternToken>,
pub edge_gaps: EdgeGaps,
pub selection_start: usize,
pub selection_end: usize,
pub insertion: bool,
Expand Down Expand Up @@ -147,6 +159,9 @@ pub struct Candidate {
pub captures: Vec<String>,
pub selection_spans: Vec<(usize, usize)>,
pub tuple: Vec<usize>,
/// Located through the literal fallback: the pattern's `…` matched file
/// text verbatim, so `<SM:PUT>` ellipses are literal too.
pub literal_gaps: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
Expand Down
82 changes: 82 additions & 0 deletions crates/pi-edit/tests/fixtures/sloppy/apply.json
10BC8
Original file line number Diff line number Diff line change
Expand Up @@ -1442,6 +1442,88 @@
"a.ts": "function loadUser(id: string) {\n const cached = cache.get(id);\n if (cached) return cached;\n const user = await database.users.read(id);\n return user;\n}\n"
}
}
},
{
"name": "re-emits an open trailing line-end gap as nothing",
"files": {
"a.ts": " const x = 1;\n return `<button class=\"file-row${sel}\" data-id=\"${file.id}\">${name}</button>`;\n done();\n"
},
"args": {
"input": "<SM:EDIT path=\"a.ts\">\n<SM:FIND>\n return `<button class=\"file-row…\n</SM:FIND>\n<SM:PUT>\n return `<button class=\"row…\n</SM:PUT>\n</SM:EDIT>"
},
"expect": {
"files": {
"a.ts": " const x = 1;\n return `<button class=\"row${sel}\" data-id=\"${file.id}\">${name}</button>`;\n done();\n"
}
}
},
{
"name": "reports no change when <SM:FIND> and <SM:PUT> differ only by an open trailing gap",
"files": {
"a.ts": " const x = 1;\n return `<button class=\"file-row${sel}\" data-id=\"${file.id}\">${name}</button>`;\n done();\n"
},
"args": {
"input": "<SM:EDIT path=\"a.ts\">\n<SM:FIND>\n return `<button class=\"file-row…\n</SM:FIND>\n<SM:PUT>\n return `<button class=\"file-row…\n</SM:PUT>\n</SM:EDIT>"
},
"expect": {
"error": "Operation 1 makes no change to a.ts.",
"writes": 0
}
},
{
"name": "re-emits open whole-line edge gaps as nothing around an inner capture",
"files": {
"a.ts": "before();\nfunction legacy(a) {\n stage(a);\n}\nafter();\n"
},
"args": {
"input": "<SM:EDIT path=\"a.ts\">\n<SM:FIND>\n…\nfunction legacy(a) {\n…\n}\n…\n</SM:FIND>\n<SM:PUT>\n…\nfunction modern(a) {\n…\n}\n…\n</SM:PUT>\n</SM:EDIT>"
},
"expect": {
"files": {
"a.ts": "before();\nfunction modern(a) {\n stage(a);\n}\nafter();\n"
}
}
},
{
"name": "leaves the newline joining a whole-line edge gap to its anchor in the file",
"files": {
"a.ts": "before();\nconst value = old;\nafter();\n"
},
"args": {
"input": "<SM:EDIT path=\"a.ts\">\n<SM:FIND>\nconst value = old;\n…\n</SM:FIND>\n<SM:PUT>\nconst value = new;\n</SM:PUT>\n</SM:EDIT>"
},
"expect": {
"files": {
"a.ts": "before();\nconst value = new;\nafter();\n"
}
}
},
{
"name": "keeps CRLF intact when whole-line edge gaps are re-emitted",
"files": {
"a.ts": "a\r\nconst value = old;\r\nb\r\n"
},
"args": {
"input": "<SM:EDIT path=\"a.ts\">\n<SM:FIND>\n…\r\nconst value = old;\r\n…\n</SM:FIND>\n<SM:PUT>\n…\r\nconst value = new;\r\n…\n</SM:PUT>\n</SM:EDIT>"
},
"expect": {
"files": {
"a.ts": "a\r\nconst value = new;\r\nb\r\n"
}
}
},
{
"name": "rejects a <SM:PUT> made only of edge ellipses",
"files": {
"a.ts": "before();\nconst value = old;\nafter();\n"
},
"args": {
"input": "<SM:EDIT path=\"a.ts\">\n<SM:FIND>\n…\nconst value = old;\n…\n</SM:FIND>\n<SM:PUT>\n…\n…\n</SM:PUT>\n</SM:EDIT>"
},
"expect": {
"error": "whole-line … with no <SM:FIND> gap to re-emit",
"writes": 0
}
}
]
}
14 changes: 7 additions & 7 deletions docs/tools/debug.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@
- `packages/coding-agent/src/dap/types.ts` — request/response/capability shapes
- `packages/coding-agent/src/tools/tool-timeouts.ts` — per-tool timeout clamp
- `packages/coding-agent/src/debug/index.ts` — interactive debug selector menu
- `packages/coding-agent/src/debug/log-viewer.ts` — recent-log TUI viewer
- `packages/coding-agent/src/debug/raw-sse.ts` — raw SSE TUI viewer
- `packages/coding-agent/src/debug/raw-sse-buffer.ts` — bounded SSE capture buffer
- `packages/tui/src/apps/debug/log-viewer.ts` — recent-log TUI viewer
- `packages/tui/src/apps/debug/raw-sse.ts` — raw SSE TUI viewer
- `packages/tui/src/apps/debug/raw-sse-buffer.ts` — bounded SSE capture buffer
- `packages/coding-agent/src/debug/remote-debugger.ts` — one-shot JavaScriptCore remote inspector socket
- `packages/coding-agent/src/debug/profiler.ts` — CPU/heap profiling helpers
- `packages/coding-agent/src/debug/report-bundle.ts` — `.tar.gz` report bundling, log source, cache cleanup
- `packages/coding-agent/src/debug/system-info.ts` — system snapshot collection and env redaction
- `packages/coding-agent/src/debug/terminal-info.ts` — terminal state collection/formatting
- `packages/coding-agent/src/debug/protocol-probe.ts` — terminal protocol probe panel and sample image
- `packages/tui/src/apps/debug/terminal-info.ts` — terminal state collection/formatting
- `packages/tui/src/apps/debug/protocol-probe.ts` — terminal protocol probe panel and sample image

## Inputs

Expand Down Expand Up @@ -304,11 +304,11 @@ GDB example for an OpenOCD remote target:
- Output capture cap: `MAX_OUTPUT_BYTES = 128 * 1024`; whole chunks are dropped from the front (then the front chunk is byte-sliced so exactly the cap remains) and `outputTruncated` is recorded.
- Initial stop capture timeout after launch/attach: `STOP_CAPTURE_TIMEOUT_MS = 5_000`.
- Socket-mode adapter readiness timeout: `10_000` ms in `waitForCondition()` and TCP connect timeout logic in `packages/coding-agent/src/dap/client.ts`.
- Raw SSE buffer caps in `packages/coding-agent/src/debug/raw-sse-buffer.ts`:
- Raw SSE buffer caps in `packages/tui/src/apps/debug/raw-sse-buffer.ts`:
- `MAX_RAW_SSE_EVENTS = 1_000`
- `MAX_RAW_SSE_CHARS = 512_000`
- `MAX_RAW_SSE_EVENT_CHARS = 64_000` per event; over-budget events first get `tools` schemas compacted (name kept, schema/description elided), then a head+tail trim that keeps the first and last portions with a `: omp-debug-elided chars=...` comment in the middle and a final `: omp-debug-truncated originalChars=...` marker
- Log viewer window in `packages/coding-agent/src/debug/log-viewer.ts`:
- Log viewer window in `packages/tui/src/apps/debug/log-viewer.ts`:
- `INITIAL_LOG_CHUNK = 50`
- `LOAD_OLDER_CHUNK = 50`
- Report/log ingestion caps in `packages/coding-agent/src/debug/report-bundle.ts`:
Expand Down
Loading
Loading
0