datasette-agent-edit 0.1a0__tar.gz

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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: datasette-agent-edit
3
+ Version: 0.1a0
4
+ Summary: Storage-agnostic file-editing tools (view / str_replace / insert) for Datasette Agent plugins
5
+ Author: Simon Willison
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/datasette/datasette-agent-edit
8
+ Project-URL: Issues, https://github.com/datasette/datasette-agent-edit/issues
9
+ Classifier: Framework :: Datasette
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: datasette>=1.0a31
14
+ Requires-Dist: python-ulid
15
+ Requires-Dist: typing_extensions
16
+ Dynamic: license-file
17
+
18
+ # datasette-agent-edit
19
+
20
+ Storage-agnostic file-editing tools (`view` / `str_replace` / `insert` / batch
21
+ `edit`) for Datasette Agent plugins. The same tool behaviour can sit on top of
22
+ any storage layer — SQLite, the local filesystem, S3, the GitHub contents API,
23
+
24
+
25
+ ## The three layers
26
+
27
+ 1. **`operations`** — pure, synchronous string surgery (`view_lines`,
28
+ `str_replace`, `insert`, `apply_edits`). No I/O, no `await`, no Datasette.
29
+ 2. **`EditStore`** — the storage seam. The defining method is
30
+ `edit(ref, transform)`: the backend reads the current content, runs your
31
+ *pure* transform inside whatever critical section it needs, and persists the
32
+ result atomically. A failing transform persists nothing.
33
+ - `SqliteVersionedStore` runs the transform inside Datasette's write thread
34
+ (`execute_write_fn`) and keeps full version history.
35
+ - `DiskStore` uses a lock + atomic `os.replace`.
36
+ - S3 (`If-Match`) and GitHub (`sha`) backends fit the same shape with a
37
+ compare-and-set retry loop.
38
+ 3. **`EditToolset`** — turns any `EditStore` into Datasette Agent tools with one
39
+ consistent JSON envelope. Two hooks absorb the plugin-specific parts:
40
+ - `id_codec` maps internal refs to the ids the model sees (e.g. an
41
+ `artifact-` prefix).
42
+ - `render` optionally injects presentation (e.g. an `_html` iframe preview);
43
+ omit it and no `*_render` tool is registered.
44
+
45
+ ## Why `transform` is synchronous
46
+
47
+ The transform sits *between* a backend's awaits, never inside them — the SQLite
48
+ backend literally cannot `await` on its write thread, and the S3/GitHub backends
49
+ must not re-run network calls on every compare-and-set retry. If an edit
50
+ decision needs async work, resolve it first and close over the result:
51
+
52
+ ```python
53
+ resolved = await registry.lookup(name)
54
+ await store.edit(ref, lambda c: rewrite(c, resolved))
55
+ ```
56
+
57
+ A rare backend that genuinely needs in-transaction async can implement the
58
+ optional `AsyncTransformStore.aedit` capability; the toolset never requires it.
59
+
60
+ ## Example
61
+
62
+ ```python
63
+ from datasette_agent_edit import EditToolset, SqliteVersionedStore, PrefixCodec
64
+
65
+ store = SqliteVersionedStore(datasette.get_internal_database())
66
+ toolset = EditToolset(
67
+ store,
68
+ name_prefix="artifact",
69
+ id_field="artifact_id",
70
+ id_codec=PrefixCodec("artifact-"),
71
+ render=lambda editable: {"_html": build_iframe(editable.content, editable.metadata)},
72
+ )
73
+ agent_tools = toolset.tools() # list of AgentTool, ready to register
74
+ ```
75
+
76
+ ## Development
77
+
78
+ ```bash
79
+ uv run pytest
80
+ ```
@@ -0,0 +1,63 @@
1
+ # datasette-agent-edit
2
+
3
+ Storage-agnostic file-editing tools (`view` / `str_replace` / `insert` / batch
4
+ `edit`) for Datasette Agent plugins. The same tool behaviour can sit on top of
5
+ any storage layer — SQLite, the local filesystem, S3, the GitHub contents API,
6
+
7
+
8
+ ## The three layers
9
+
10
+ 1. **`operations`** — pure, synchronous string surgery (`view_lines`,
11
+ `str_replace`, `insert`, `apply_edits`). No I/O, no `await`, no Datasette.
12
+ 2. **`EditStore`** — the storage seam. The defining method is
13
+ `edit(ref, transform)`: the backend reads the current content, runs your
14
+ *pure* transform inside whatever critical section it needs, and persists the
15
+ result atomically. A failing transform persists nothing.
16
+ - `SqliteVersionedStore` runs the transform inside Datasette's write thread
17
+ (`execute_write_fn`) and keeps full version history.
18
+ - `DiskStore` uses a lock + atomic `os.replace`.
19
+ - S3 (`If-Match`) and GitHub (`sha`) backends fit the same shape with a
20
+ compare-and-set retry loop.
21
+ 3. **`EditToolset`** — turns any `EditStore` into Datasette Agent tools with one
22
+ consistent JSON envelope. Two hooks absorb the plugin-specific parts:
23
+ - `id_codec` maps internal refs to the ids the model sees (e.g. an
24
+ `artifact-` prefix).
25
+ - `render` optionally injects presentation (e.g. an `_html` iframe preview);
26
+ omit it and no `*_render` tool is registered.
27
+
28
+ ## Why `transform` is synchronous
29
+
30
+ The transform sits *between* a backend's awaits, never inside them — the SQLite
31
+ backend literally cannot `await` on its write thread, and the S3/GitHub backends
32
+ must not re-run network calls on every compare-and-set retry. If an edit
33
+ decision needs async work, resolve it first and close over the result:
34
+
35
+ ```python
36
+ resolved = await registry.lookup(name)
37
+ await store.edit(ref, lambda c: rewrite(c, resolved))
38
+ ```
39
+
40
+ A rare backend that genuinely needs in-transaction async can implement the
41
+ optional `AsyncTransformStore.aedit` capability; the toolset never requires it.
42
+
43
+ ## Example
44
+
45
+ ```python
46
+ from datasette_agent_edit import EditToolset, SqliteVersionedStore, PrefixCodec
47
+
48
+ store = SqliteVersionedStore(datasette.get_internal_database())
49
+ toolset = EditToolset(
50
+ store,
51
+ name_prefix="artifact",
52
+ id_field="artifact_id",
53
+ id_codec=PrefixCodec("artifact-"),
54
+ render=lambda editable: {"_html": build_iframe(editable.content, editable.metadata)},
55
+ )
56
+ agent_tools = toolset.tools() # list of AgentTool, ready to register
57
+ ```
58
+
59
+ ## Development
60
+
61
+ ```bash
62
+ uv run pytest
63
+ ```
@@ -0,0 +1,57 @@
1
+ """Storage-agnostic file-editing tools for Datasette Agent plugins.
2
+
3
+ Three layers:
4
+
5
+ 1. :mod:`datasette_agent_edit.operations` -- pure string-editing primitives.
6
+ 2. :mod:`datasette_agent_edit.store` -- the :class:`EditStore` backend seam,
7
+ plus ready-made :class:`SqliteVersionedStore` / :class:`DiskStore` backends.
8
+ 3. :class:`EditToolset` -- builds Datasette Agent tools over any backend with
9
+ a single consistent JSON envelope and optional presentation hook.
10
+ """
11
+
12
+ from .operations import (
13
+ EditApplyError,
14
+ EditError,
15
+ apply_edit,
16
+ apply_edits,
17
+ insert,
18
+ str_replace,
19
+ view_lines,
20
+ )
21
+ from .store import (
22
+ AsyncTransformStore,
23
+ Conflict,
24
+ Editable,
25
+ EditStore,
26
+ IdCodec,
27
+ NotFound,
28
+ PrefixCodec,
29
+ Transform,
30
+ )
31
+ from .stores import DiskStore, SqliteVersionedStore
32
+ from .toolset import EditToolset
33
+
34
+ __all__ = [
35
+ # operations
36
+ "view_lines",
37
+ "str_replace",
38
+ "insert",
39
+ "apply_edit",
40
+ "apply_edits",
41
+ "EditError",
42
+ "EditApplyError",
43
+ # store
44
+ "Editable",
45
+ "EditStore",
46
+ "AsyncTransformStore",
47
+ "Transform",
48
+ "IdCodec",
49
+ "PrefixCodec",
50
+ "NotFound",
51
+ "Conflict",
52
+ # backends
53
+ "SqliteVersionedStore",
54
+ "DiskStore",
55
+ # toolset
56
+ "EditToolset",
57
+ ]
@@ -0,0 +1,120 @@
1
+ """Pure, storage-agnostic text-editing primitives.
2
+
3
+ These functions operate on plain strings and never touch a storage backend,
4
+ an event loop, or a Datasette instance. They are the in-memory "surgery" that
5
+ a backend's atomic ``edit()`` critical section applies to content. Keeping
6
+ them pure is what lets the same editing behaviour run unchanged inside a
7
+ SQLite write thread, a disk file lock, or an S3/GitHub compare-and-set loop.
8
+ """
9
+
10
+
11
+ class EditError(ValueError):
12
+ """Raised when an edit cannot be applied to the given content.
13
+
14
+ Subclasses ``ValueError`` so existing ``except ValueError`` handlers (and
15
+ the test-suite's ``pytest.raises(ValueError, ...)`` expectations) keep
16
+ working.
17
+ """
18
+
19
+
20
+ class EditApplyError(EditError):
21
+ """Raised by :func:`apply_edits` when one edit in a batch fails.
22
+
23
+ Carries the list of human-readable descriptions of the edits that did
24
+ succeed before the failure, plus the zero-based index of the edit that
25
+ failed, so callers can report partial progress without re-deriving it.
26
+ """
27
+
28
+ def __init__(self, message, applied, index):
29
+ super().__init__(message)
30
+ self.applied = applied
31
+ self.index = index
32
+
33
+
34
+ def view_lines(content, view_range=""):
35
+ """Format ``content`` as numbered lines, optionally sliced to a range.
36
+
37
+ ``view_range`` is a string ``"start,end"`` (1-indexed, inclusive). An end
38
+ of ``-1`` means end-of-file. An empty string returns every line.
39
+ """
40
+ all_lines = content.splitlines(True)
41
+ total_lines = len(all_lines)
42
+
43
+ if view_range:
44
+ parts = view_range.split(",")
45
+ start = int(parts[0])
46
+ end = int(parts[1])
47
+ if end == -1:
48
+ end = total_lines
49
+ lines = all_lines[start - 1 : end]
50
+ start_num = start
51
+ else:
52
+ lines = all_lines
53
+ start_num = 1
54
+
55
+ numbered = []
56
+ for i, line in enumerate(lines, start=start_num):
57
+ numbered.append(f"{i}:\t{line.rstrip()}")
58
+ return "\n".join(numbered)
59
+
60
+
61
+ def str_replace(content, old_str, new_str):
62
+ """Replace exactly one occurrence of ``old_str`` in ``content``.
63
+
64
+ Raises :class:`EditError` if ``old_str`` is absent or appears more than
65
+ once (the caller should add surrounding context to disambiguate).
66
+ """
67
+ count = content.count(old_str)
68
+ if count == 0:
69
+ raise EditError("old_str not found in content")
70
+ if count > 1:
71
+ raise EditError(f"old_str appears {count} times in content; must be unique")
72
+ return content.replace(old_str, new_str, 1)
73
+
74
+
75
+ def insert(content, insert_line, insert_text):
76
+ """Insert ``insert_text`` after line number ``insert_line``.
77
+
78
+ ``insert_line=0`` inserts at the very beginning of the content.
79
+ """
80
+ lines = content.splitlines(True)
81
+ insert_pieces = insert_text.splitlines(True)
82
+ new_lines = lines[:insert_line] + insert_pieces + lines[insert_line:]
83
+ return "".join(new_lines)
84
+
85
+
86
+ def apply_edit(content, edit):
87
+ """Apply a single ``{"operation": ..., ...}`` edit dict to ``content``.
88
+
89
+ Supported operations:
90
+
91
+ - ``str_replace``: keys ``old_str``, ``new_str``
92
+ - ``insert``: keys ``insert_line``, ``insert_text``
93
+ """
94
+ op = edit.get("operation")
95
+ if op == "str_replace":
96
+ return str_replace(content, edit["old_str"], edit["new_str"])
97
+ if op == "insert":
98
+ return insert(content, edit["insert_line"], edit["insert_text"])
99
+ raise EditError(
100
+ f"unknown operation {op!r}. Use 'str_replace' or 'insert'."
101
+ )
102
+
103
+
104
+ def apply_edits(content, edits):
105
+ """Apply a sequence of edit dicts, returning ``(new_content, applied)``.
106
+
107
+ Edits are applied in order, so each edit sees the result of the previous
108
+ one. If any edit fails, an :class:`EditApplyError` is raised before any
109
+ result is returned, so callers can treat the batch as all-or-nothing.
110
+ ``applied`` is a list of strings like ``"str_replace #1: OK"``.
111
+ """
112
+ applied = []
113
+ for i, edit in enumerate(edits):
114
+ op = edit.get("operation")
115
+ try:
116
+ content = apply_edit(content, edit)
117
+ except EditError as e:
118
+ raise EditApplyError(str(e), applied=applied, index=i) from e
119
+ applied.append(f"{op} #{i + 1}: OK")
120
+ return content, applied
@@ -0,0 +1,139 @@
1
+ """The storage seam: :class:`EditStore` and its supporting types.
2
+
3
+ A backend is anything that can create, read and atomically transform a piece
4
+ of text content addressed by a ``ref``. The defining method is
5
+ :meth:`EditStore.edit`, which takes a *synchronous, pure* ``transform``
6
+ callable and is responsible for running it inside whatever critical section
7
+ the backend needs (a SQLite write transaction, a file lock, an S3/GitHub
8
+ compare-and-set retry loop). Because the transform contains no I/O and no
9
+ awaits, the same editing logic is safe inside any of those contexts.
10
+ """
11
+
12
+ from dataclasses import dataclass, field
13
+ from typing import Any, Awaitable, Callable, Optional
14
+
15
+ try:
16
+ from typing import Protocol, runtime_checkable
17
+ except ImportError: # pragma: no cover - py<3.8 fallback
18
+ from typing_extensions import Protocol, runtime_checkable
19
+
20
+
21
+ #: A pure, synchronous content transform: old content in, new content out.
22
+ #: It must not perform I/O or await; raise :class:`~.operations.EditError`
23
+ #: (a ``ValueError``) to abort the edit before anything is persisted.
24
+ Transform = Callable[[str], str]
25
+
26
+ #: An async transform, for the optional :class:`AsyncTransformStore` capability.
27
+ AsyncTransform = Callable[[str], Awaitable[str]]
28
+
29
+
30
+ class NotFound(Exception):
31
+ """Raised by a store when ``ref`` does not identify existing content."""
32
+
33
+
34
+ class Conflict(Exception):
35
+ """Raised when an atomic edit could not be committed due to contention.
36
+
37
+ Backends that implement optimistic concurrency (S3 ``If-Match``, the
38
+ GitHub contents API ``sha``) raise this after exhausting their retries.
39
+ """
40
+
41
+
42
+ @dataclass
43
+ class Editable:
44
+ """A snapshot of stored content plus its addressing and bookkeeping.
45
+
46
+ ``version`` is an opaque token whose meaning is backend-defined: an
47
+ incrementing integer for a versioned SQLite store, an mtime for a disk
48
+ file, an ETag or git blob SHA for object stores. The toolset only echoes
49
+ it back to the model and (optionally) uses it for display; it never
50
+ interprets it.
51
+ """
52
+
53
+ ref: str
54
+ content: str
55
+ metadata: dict = field(default_factory=dict)
56
+ version: Any = None
57
+
58
+
59
+ @runtime_checkable
60
+ class EditStore(Protocol):
61
+ """The interface every storage backend implements."""
62
+
63
+ async def create(
64
+ self, content: str, *, ref: Optional[str] = None, metadata: Optional[dict] = None
65
+ ) -> Editable:
66
+ """Create new content and return its :class:`Editable`.
67
+
68
+ ``ref`` may be supplied for path-addressed backends (disk, S3,
69
+ GitHub); id-generating backends (SQLite) generate one when it is
70
+ ``None``.
71
+ """
72
+ ...
73
+
74
+ async def read(self, ref: str) -> Editable:
75
+ """Return the current :class:`Editable` for ``ref``.
76
+
77
+ Raises :class:`NotFound` if it does not exist.
78
+ """
79
+ ...
80
+
81
+ async def edit(self, ref: str, transform: Transform) -> Editable:
82
+ """Atomically apply ``transform`` to the content at ``ref``.
83
+
84
+ The backend reads the current content, applies ``transform`` inside
85
+ its critical section, persists the result and returns the new
86
+ :class:`Editable`. If ``transform`` raises, nothing is persisted.
87
+ Raises :class:`NotFound` if ``ref`` does not exist and
88
+ :class:`Conflict` if the write could not be committed.
89
+ """
90
+ ...
91
+
92
+ async def delete(self, ref: str) -> None:
93
+ """Delete the content at ``ref`` (raising :class:`NotFound` if absent)."""
94
+ ...
95
+
96
+
97
+ @runtime_checkable
98
+ class AsyncTransformStore(Protocol):
99
+ """Opt-in capability for the rare backend that can await mid-edit.
100
+
101
+ Most backends cannot (a SQLite write transform runs on a non-async write
102
+ thread), so this is deliberately separate from :class:`EditStore`. The
103
+ :class:`~.toolset.EditToolset` never calls it; it exists for specialised
104
+ callers whose edit decision must consult something asynchronously and who
105
+ cannot pre-resolve that work before calling :meth:`EditStore.edit`.
106
+ """
107
+
108
+ async def aedit(self, ref: str, transform: AsyncTransform) -> Editable:
109
+ ...
110
+
111
+
112
+ class IdCodec:
113
+ """Translates between the internal ``ref`` and the id the model sees.
114
+
115
+ The default is an identity mapping. Subclass (or use :class:`PrefixCodec`)
116
+ to expose, for example, ``artifact-01J...`` externally while storing the
117
+ bare ULID internally.
118
+ """
119
+
120
+ def to_external(self, ref: str) -> str:
121
+ return ref
122
+
123
+ def to_internal(self, external_id: str) -> str:
124
+ return external_id
125
+
126
+
127
+ class PrefixCodec(IdCodec):
128
+ """An :class:`IdCodec` that adds/strips a fixed prefix."""
129
+
130
+ def __init__(self, prefix: str):
131
+ self.prefix = prefix
132
+
133
+ def to_external(self, ref: str) -> str:
134
+ return self.prefix + ref
135
+
136
+ def to_internal(self, external_id: str) -> str:
137
+ if external_id.startswith(self.prefix):
138
+ return external_id[len(self.prefix) :]
139
+ return external_id
@@ -0,0 +1,4 @@
1
+ from .disk import DiskStore
2
+ from .sqlite import SqliteVersionedStore
3
+
4
+ __all__ = ["DiskStore", "SqliteVersionedStore"]