<!-- source: https://docs.dreamlake.ai/notes/api/editing @ 0.1.192 b2f973b1 -->
# Editing Memo source

**Implementation target — unreleased.** This page specifies the proposed unified
Memos editing API. It does not describe a released package or prove deployed
server support. Method names, selector flags, callable SDK handles and model-tool
names below require implementation. See the [API overview](/notes/api/) for
status and the [CLI stream contract](/notes/api/cli/) for input and output rules.

The same action appears in four tabs for each method. The API keeps the original
source baseline, validates selections and lets unrelated changes merge without
reinterpreting an old edit against a newly fetched document. The live browser
editor can retain its local-replica RTC interface; these snapshot-based commands
must reach the same authority and honor the same identity/conflict guarantees.

## Choose the operation

- `replace` changes one observed source span.
- `insert` adds source before/after an observed element or at an original cursor.
- `remove` deletes one observed span; it does not delete the Memo resource.
- `append` inserts verbatim source at the original document end.
- `write` describes a whole-body target from an original complete snapshot.
- `patch` submits an explicit original-source patch.

Stable Memo IDs are primary. Examples use `$NOTE_ID`, `noteId` or `note_id` for
the same ID. The configured SDK is `dl`; `dl.notes(noteId)` is the proposed local
handle factory, not a fetch. Source namespace is optional for an ID. If supplied,
`--namespace` / `--ns` asserts current ownership; it never means destination.
A slug requires explicit or configured lookup context. Project and deep folder
paths are separate values; see [moving resources](/notes/api/moving/).

## Baselines, source and positions

Read with the [reading API](/notes/api/reading/) and retain the original `note`,
exact source, RTC `revision`, hash and scope. SDK examples pass that result as
`at`; tools/CLI carry its original revision explicitly. A content hash and an
HTTP ETag are not RTC revisions. A later read, presence update or watch event
must not replace an edit's original baseline.

Mapped addresses identify exact original source spans. Replacing a section,
list or list item replaces every source character within that span, including
nested content. There is no hidden “inner text” interpretation. The returned
mapping must show the full range before an edit. Preserve siblings by selecting
their own returned paragraph/block addresses; do not assume paragraphs in list
items have independent addresses unless the mapper actually returns them.

`lines: [40, 42]` means source lines 40 through 42, 1-based and inclusive. A line
span includes its existing line terminators; a final unterminated line has no
terminator to add. Preserve CRLF versus LF and terminal-newline state unless
the proposed replacement deliberately changes it. Cursor offsets are zero-based,
end-exclusive Unicode-code-point positions; JavaScript UTF-16 string indexes
cannot be reused blindly around emoji. SDKs perform conversion/validation.

Exactly one selector or placement is allowed per edit. Reject invalid ranges,
unknown/multiply resolved addresses, incompatible source/Note identity and
ambiguous context before mutation. If several elements share one source line,
a line edit affects all selected line source: use an exact address/range or
reject the imprecise edit rather than promising to preserve neighboring text.

A focused read can support a targeted edit when it carries exact source ranges
and its original revision. It is not enough to construct an entire replacement
body. Generated mapping labels/comments are not source content and must never
be written back.

## Replace a source span

**Agreed target:** require `text`, the original baseline and exactly one of
`lines` or `address`. Default conflict behavior merges unrelated changes and
refuses overlap; explicit exact mode requires the whole original revision to
remain current. Empty replacement text deletes the selected source.

Every tab below replaces original lines 40–42 with exactly `- Updated item`
followed by one LF. It removes the original selected markers, indentation,
children and newlines; the new source contains only the supplied replacement.
The original Memo must contain those lines. The example is illustrative and
has not been run against a deployed target implementation.

**CLI**

```bash
set -euo pipefail
dl memos read "$NOTE_ID" --view source --json > original.json
BASE=$(jq -er '.revision' original.json)
printf '%s\n' '- Updated item' > replacement.md
dl memos replace "$NOTE_ID" --lines 40:42 --file replacement.md --base-revision "$BASE" --json > receipt.json
ACK=$(jq -er '.revision' receipt.json)
dl memos read "$NOTE_ID" --at "$ACK" --view source --json
```

**TypeScript**

```typescript
const note = dl.notes(noteId)
const original = await note.read()
const receipt = await note.replace({ lines: [40, 42], text: "- Updated item\n", at: original })
const acknowledged = await note.read({ at: receipt.revision })
```

**Python**

```python
note = dl.notes(note_id)
original = note.read()
receipt = note.replace(lines=(40, 42), text="- Updated item\n", at=original)
acknowledged = note.read(at=receipt.revision)
```

**Tool call**

```javascript
const original = await notes_read({ note: noteId, view: "source" })
const receipt = await notes_replace({ note: noteId, lines: [40, 42], text: "- Updated item\n", baseRevision: original.revision })
const acknowledged = await notes_read({ note: noteId, at: receipt.revision, view: "source" })
```

To use an observed element instead, replace the selector with `address: "s1.p2"`
(or CLI `--address s1.p2`). The example address must come from that original
revision's mapped read, not an address guessed from a newer document. The text
and conflict policy are otherwise identical. A stale overlapping edit returns
a conflict with no accepted edit receipt; preserve the proposed text.

## Insert source

**Agreed target:** require `text`, original baseline and exactly one placement:
`before: address`, `after: address` or `cursor: position`. Insert text verbatim,
adding no newline, indentation or list marker. Remove nothing. Default merge
preserves unrelated edits and refuses conflicts.

Each tab adds exactly `- New item` plus one LF after the full original span of
observed address `s1.p2`. The address must have been observed in the retained
baseline. The example does not mean “insert inside the paragraph.”

**CLI**

```bash
set -euo pipefail
dl memos read "$NOTE_ID" --view source --json > original.json
BASE=$(jq -er '.revision' original.json)
printf '%s\n' '- New item' > addition.md
dl memos insert "$NOTE_ID" --after s1.p2 --file addition.md --base-revision "$BASE" --json > receipt.json
ACK=$(jq -er '.revision' receipt.json)
dl memos read "$NOTE_ID" --at "$ACK" --view source --json
```

**TypeScript**

```typescript
const note = dl.notes(noteId)
const original = await note.read()
const receipt = await note.insert({ after: "s1.p2", text: "- New item\n", at: original })
const acknowledged = await note.read({ at: receipt.revision })
```

**Python**

```python
note = dl.notes(note_id)
original = note.read()
receipt = note.insert(after="s1.p2", text="- New item\n", at=original)
acknowledged = note.read(at=receipt.revision)
```

**Tool call**

```javascript
const original = await notes_read({ note: noteId, view: "source" })
const receipt = await notes_insert({ note: noteId, after: "s1.p2", text: "- New item\n", baseRevision: original.revision })
const acknowledged = await notes_read({ note: noteId, at: receipt.revision, view: "source" })
```

`before` means the start of the full original span; `after` means its end. A
cursor is an original-source code-point boundary, including position zero and
the original document end. Placement at the middle of a Markdown construct is
literal source insertion, not a structural repair operation. The caller decides
whether separators are needed. Concurrent insertions at the same boundary need
a documented native ordering/conflict rule; do not promise this insertion is
last after every peer's work.

## Remove selected source

**Agreed target:** require original baseline and exactly one of `lines` or
`address`. Do not accept `text`. Remove the exact selected source, including
its Markdown structure and existing newlines. Default merge preserves unrelated
changes and refuses overlaps. Whole-resource `delete` is a separate operation.

Each tab removes original source lines 40–42 and nothing outside their span.

**CLI**

```bash
set -euo pipefail
dl memos read "$NOTE_ID" --view source --json > original.json
BASE=$(jq -er '.revision' original.json)
dl memos remove "$NOTE_ID" --lines 40:42 --base-revision "$BASE" --json > receipt.json
ACK=$(jq -er '.revision' receipt.json)
dl memos read "$NOTE_ID" --at "$ACK" --view source --json
```

**TypeScript**

```typescript
const note = dl.notes(noteId)
const original = await note.read()
const receipt = await note.remove({ lines: [40, 42], at: original })
const acknowledged = await note.read({ at: receipt.revision })
```

**Python**

```python
note = dl.notes(note_id)
original = note.read()
receipt = note.remove(lines=(40, 42), at=original)
acknowledged = note.read(at=receipt.revision)
```

**Tool call**

```javascript
const original = await notes_read({ note: noteId, view: "source" })
const receipt = await notes_remove({ note: noteId, lines: [40, 42], baseRevision: original.revision })
const acknowledged = await notes_read({ note: noteId, at: receipt.revision, view: "source" })
```

Deleting a parent list/section address deletes the nested source within that
span too. To preserve a nested list, select only the actual parent-text source
range exposed by the mapping or the precise lines that exclude the children.
The implementation must not guess by stripping bullets or trailing newlines.
Adjacent lines can become adjacent text after removal; that is the specified
literal source result, not permission to silently insert a separator.

## Append verbatim text

**Target direction:** append at the original snapshot's document end, with
**no automatic separator LF**. The payload includes every intended newline.
This intentionally differs from inspected released CLI/Python append separator
behavior. The current TypeScript legacy `append` is also not this RTC operation.
Default merge is the proposed shared behavior for append; concurrent same-end
ordering still needs a protocol definition. Exact mode can explicitly require
the original revision to remain current.

Each tab appends exactly one LF, `Hello`, and one LF to the original source.
It does so even if the original already ends in LF, leaving a blank separator
in that case. Nothing trims or normalizes the original or payload.

**CLI**

```bash
set -euo pipefail
dl memos read "$NOTE_ID" --view source --json > original.json
BASE=$(jq -er '.revision' original.json)
printf '\nHello\n' > addition.md
dl memos append "$NOTE_ID" --file addition.md --base-revision "$BASE" --json > receipt.json
ACK=$(jq -er '.revision' receipt.json)
dl memos read "$NOTE_ID" --at "$ACK" --view source --json
```

**TypeScript**

```typescript
const note = dl.notes(noteId)
const original = await note.read()
const receipt = await note.append({ text: "\nHello\n", at: original })
const acknowledged = await note.read({ at: receipt.revision })
```

**Python**

```python
note = dl.notes(note_id)
original = note.read()
receipt = note.append(text="\nHello\n", at=original)
acknowledged = note.read(at=receipt.revision)
```

**Tool call**

```javascript
const original = await notes_read({ note: noteId, view: "source" })
const receipt = await notes_append({ note: noteId, text: "\nHello\n", baseRevision: original.revision })
const acknowledged = await notes_read({ note: noteId, at: receipt.revision, view: "source" })
```

For empty source this payload begins with LF; callers wanting `Hello` without
that prefix supply it. Empty addition/no-op behavior and its receipt still need
final definition. Appending at the original end must preserve other accepted
additions; it does not guarantee the new text remains last after concurrent
editing. Never implement “ensure last” by overwriting current source.

## Write a whole-body target

**Proposed target:** `write` requires a complete original snapshot and the exact
desired body. Compile its difference against that original source; do not make
an unguarded latest-body replacement or silently use an ETag path. A partial
read must be rejected as a whole-body baseline. Merge is the default across
clients. The following whole-body examples opt into exact explicitly because
they require the baseline to remain current.

Every tab requests precisely `Hello team.` plus one LF as the whole body,
requiring the original revision to remain current. This can remove any other
original content, which is why the original must be complete.

**CLI**

```bash
set -euo pipefail
dl memos read "$NOTE_ID" --view source --json > original.json
BASE=$(jq -er '.revision' original.json)
printf 'Hello team.\n' > target.md
dl memos write "$NOTE_ID" --file target.md --base-revision "$BASE" --exact --json > receipt.json
ACK=$(jq -er '.revision' receipt.json)
dl memos read "$NOTE_ID" --at "$ACK" --view source --json
```

**TypeScript**

```typescript
const note = dl.notes(noteId)
const original = await note.read()
const receipt = await note.write({ text: "Hello team.\n", at: original, mode: "exact" })
const acknowledged = await note.read({ at: receipt.revision })
```

**Python**

```python
note = dl.notes(note_id)
original = note.read()
receipt = note.write(text="Hello team.\n", at=original, mode="exact")
acknowledged = note.read(at=receipt.revision)
```

**Tool call**

```javascript
const original = await notes_read({ note: noteId, view: "source" })
const receipt = await notes_write({ note: noteId, text: "Hello team.\n", baseRevision: original.revision, mode: "exact" })
const acknowledged = await notes_read({ note: noteId, at: receipt.revision, view: "source" })
```

Empty source is a valid whole-body target and must preserve the distinction
between zero bytes and a single LF. An unchanged target should return a clear
no-op result with its baseline; its exact-mode check must not be bypassed simply
because the client computed no text difference. Body validator protection remains
valuable: the target replaces competing legacy/RTC edit contracts with one
retained-baseline operation rather than removing overwrite protection.

## Apply an explicit patch

**Contract:** require `patch`, `format` and original baseline. Default merge
preserves disjoint human edits; explicit exact requires an unchanged revision. The sample original
source must be exactly `Hello world.` plus LF. Each tab applies the same unified
line patch, with exact mode, to produce `Hello team.` plus LF.

**CLI**

```bash
set -euo pipefail
dl memos read "$NOTE_ID" --view source --json > original.json
BASE=$(jq -er '.revision' original.json)
cat > edit.diff <<'PATCH'
--- before.md
+++ after.md
@@ -1 +1 @@
-Hello world.
+Hello team.
PATCH
dl memos patch "$NOTE_ID" --format diff --file edit.diff --base-revision "$BASE" --exact --json > receipt.json
ACK=$(jq -er '.revision' receipt.json)
dl memos read "$NOTE_ID" --at "$ACK" --view source --json
```

**TypeScript**

```typescript
const note = dl.notes(noteId)
const original = await note.read()
const patch = "--- before.md\n+++ after.md\n@@ -1 +1 @@\n-Hello world.\n+Hello team.\n"
const receipt = await note.patch({ patch, format: "diff", at: original, mode: "exact" })
const acknowledged = await note.read({ at: receipt.revision })
```

**Python**

```python
note = dl.notes(note_id)
original = note.read()
patch = "--- before.md\n+++ after.md\n@@ -1 +1 @@\n-Hello world.\n+Hello team.\n"
receipt = note.patch(patch=patch, format="diff", at=original, mode="exact")
acknowledged = note.read(at=receipt.revision)
```

**Tool call**

```javascript
const original = await notes_read({ note: noteId, view: "source" })
const patch = "--- before.md\n+++ after.md\n@@ -1 +1 @@\n-Hello world.\n+Hello team.\n"
const receipt = await notes_patch({ note: noteId, patch, format: "diff", baseRevision: original.revision, mode: "exact" })
const acknowledged = await notes_read({ note: noteId, at: receipt.revision, view: "source" })
```

The file labels do not select a resource. Patch coordinates refer to the retained
original source; never attach a freshly fetched revision to an old patch just
to make it pass. Reject malformed/empty patches and mismatched old text. Preserve
CRLF and no-final-newline markers when present. Inline character patches, if
retained as an advanced format, must document escaping and code-point units
separately; do not make an agent hand-escape an entire Memo for a simple edit.

## Conflicts, acknowledgments and retries

The target default for replace/insert/remove merges compatible independent edits
and refuses overlapping intent. Exact mode is an optional stronger precondition
on the original revision. Neither mode permits shifting old line numbers or
re-resolving an old address against latest source. Append, whole-write and patch
mode defaults are merge across clients
from one client. Server support for identity-scoped merge must be verified:
the inspected backend's global revision conditional commit can refuse independent
writes under load; removing that guard without its atomic replacement is unsafe.

A successful content receipt includes stable Memo identity, accepted revision,
result hash, original baseline and requested mode, with a stable operation identity
when that protocol is implemented. A rejected result states no accepted write.
An unknown outcome must preserve the original request and expose reconciliation;
it must not be presented as a definitive no-write failure. A source read at the
accepted revision verifies exact content; a later read of latest can include peers'
edits and is not the same verification.

Stable public command identity/durable receipt lookup is a required protocol
addition, not established by these method names. Until supported, a lost HTTP
response cannot safely be “fixed” by a new append/insert request. Replaying a
frozen internal RTC request is not the same as issuing a fresh public command.
A `commandId` field should only be documented as runnable once the server binds
it to original intent and returns the same definitive receipt on replay.

Presence follows only successful reads/accepted edits with a defined mapping to
the accepted revision. An ancillary presence/link failure must preserve the
accepted write receipt and must not trigger a second mutation. See
[collaboration and watch](/notes/api/collaboration/).

## Input and compatibility memos

The target CLI consumes source/patch stdin only through explicit `--file -`.
`--text`, `--file PATH` and `--file -` are mutually exclusive. Files/stdin retain
exact UTF-8, whitespace and newline state. Normal stdout contains only the
result; `--json` emits one receipt. Diagnostics go to stderr. CLI examples use
Bash and `jq` deliberately to retain machine baselines/receipts; they are not
ordinary reading-format guidance. See [CLI I/O](/notes/api/cli/).

Current verified-package evidence is CLI/TypeScript 0.94.0 and Python 0.32.1,
not this target. Original-revision patch paths exist, but new selector flags,
`dl.notes(id)` handles, keyword/object signatures and tool names are not release
claims. TypeScript `write`/`append` use the legacy ETag/body path in that package;
CLI/Python append add separator LF. The target removes that legacy split only
after useful operations and safety behavior have equivalent RTC support. No
silent legacy fallback is allowed. Current built-in plugin registration is a
separate surface and does not make these proposed tool names available.

## Incremental insertion contract (proposed)

**Client availability checked on 15 November 2026:** the published TypeScript/CLI
package `@dreamlake/dreamlake-cli` 0.125.3 does not expose `streamInsert`,
`MemoStreamInterrupted`, `--no-stream` or `--stream-id`; Python `dreamlake` 0.52.2
does not expose `stream_insert` or `MemoStreamInterrupted`. The examples and
streaming defaults in this section are implementation targets, not commands to
run with those releases. Server continuation support alone does not provide
these client methods.

Generated additions use a known cursor and sequential acknowledged insertions
by default. Delivery is independent of concurrency: `merge` and `exact` both
commit through RTC; exact is an opt-in revision precondition for each chunk.
A stream owns its cursor and never follows a human selection.

A single nonempty pure insertion returns an optional
`continuation: {revision, cursor}` on its normal write receipt. The cursor is a
Unicode-code-point boundary immediately after the inserted text in the retained
ACK revision. The server computes it from actual merged placement and preserves
it on command replay. Use both values for the next insertion; never search for
text or increment an offset from an older snapshot. Edits elsewhere merge;
changes to the target gap or deleted anchors require reconciliation.

```typescript
const original = await note.read()
for await (const receipt of note.streamInsert({
  at: original, cursor: 0, chunks: generatedChunks, mode: "merge"
})) {
  // Persist each acknowledged receipt before requesting the next chunk.
}
```

```python
original = note.read()
for receipt in note.stream_insert(at=original, cursor=0, chunks=generated_chunks):
    persist_receipt(receipt)
```

TS supports iterable or async-iterable strings and an optional AbortSignal.
Python accepts iterable strings; closing the iterator stops further writes.
Each request is bounded to 2048 code points and waits for ACK before the next.
Producers should batch generated tokens. This adds no long-lived transport and
does not promise token-level latency. Empty chunks produce no writes.

The CLI streams `memos insert --file -` unless `--no-stream` is selected; with
`--json` it emits JSON Lines of receipts. Other file/literal inputs and dry-runs
remain one operation. `streamId` / `stream_id` / `--stream-id` prefixes unique
chunk command IDs; never restart a partially completed stream at index zero.

Built-in `dreamlake_notes_insert` calls carry completed bounded text, followed
by another completed call at `continuation.cursor` and its returned revisionRef
or revision. Partial model tool arguments are never executable chunks. Publish
intent and checkpoint the logical edit, rather than every chunk. Version saves
accept a retained `revision` so later human activity cannot change what is saved.

On uncertainty, `MemoStreamInterrupted` carries the last ACK and pending command.
Reconcile that command before continuing, without inventing a new retry ID.
An older server may accept a chunk without continuation: yield its ACK, then
stop. Never guess or resend. Cancellation preserves previously acknowledged text.

`revise` remains the CLI workflow for reviewed before/after checkpoints and
pending redlines. It defaults to merge; `--exact` opts into an unchanged baseline.
It checkpoints the retained ACK, including merged human contributions, even if
people continue editing afterward. This proposed contract does not add an SDK `revise`
method or execute unfinished model tool JSON.
