memoryking 0.1.0__py3-none-any.whl
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.
- memoryking/__init__.py +3 -0
- memoryking/__main__.py +1328 -0
- memoryking/adapters/__init__.py +1 -0
- memoryking/adapters/adapter_state.py +242 -0
- memoryking/adapters/anchor_schema.sql +7 -0
- memoryking/adapters/atlas.py +441 -0
- memoryking/adapters/browser_commands.py +125 -0
- memoryking/adapters/dashboard.py +510 -0
- memoryking/adapters/dense_search.py +86 -0
- memoryking/adapters/egress_policy.py +244 -0
- memoryking/adapters/egress_schema.sql +13 -0
- memoryking/adapters/embedding.schema.json +302 -0
- memoryking/adapters/embedding_store.py +469 -0
- memoryking/adapters/execution.py +369 -0
- memoryking/adapters/experience.py +423 -0
- memoryking/adapters/experience.schema.json +1508 -0
- memoryking/adapters/experience_records.py +239 -0
- memoryking/adapters/experience_schema.sql +23 -0
- memoryking/adapters/handoff.py +494 -0
- memoryking/adapters/handoff.schema.json +299 -0
- memoryking/adapters/handoff_schema.sql +17 -0
- memoryking/adapters/index_schema.sql +11 -0
- memoryking/adapters/inference.py +454 -0
- memoryking/adapters/inference.schema.json +541 -0
- memoryking/adapters/inspection.py +1128 -0
- memoryking/adapters/inspection.schema.json +568 -0
- memoryking/adapters/knowledge.schema.json +633 -0
- memoryking/adapters/knowledge_schema.sql +37 -0
- memoryking/adapters/knowledge_store.py +800 -0
- memoryking/adapters/legacy_snapshot.py +358 -0
- memoryking/adapters/legacy_tables.py +49 -0
- memoryking/adapters/local_contract.py +45 -0
- memoryking/adapters/local_embeddings.py +189 -0
- memoryking/adapters/local_files.py +242 -0
- memoryking/adapters/local_ipc.py +258 -0
- memoryking/adapters/local_schema.sql +44 -0
- memoryking/adapters/local_store.py +632 -0
- memoryking/adapters/local_wire.schema.json +7672 -0
- memoryking/adapters/models/minilm-l6-v2-onnx.json +57 -0
- memoryking/adapters/models/ms-marco-minilm-l6-v2-onnx.json +57 -0
- memoryking/adapters/optional_schema.sql +43 -0
- memoryking/adapters/plan_dashboard.py +51 -0
- memoryking/adapters/plans.py +253 -0
- memoryking/adapters/postgres_admin.py +300 -0
- memoryking/adapters/postgres_anchor_schema.sql +9 -0
- memoryking/adapters/postgres_counter.sql +14 -0
- memoryking/adapters/postgres_egress_schema.sql +15 -0
- memoryking/adapters/postgres_experience_schema.sql +39 -0
- memoryking/adapters/postgres_index_schema.sql +7 -0
- memoryking/adapters/postgres_optional_schema.sql +71 -0
- memoryking/adapters/postgres_pool.py +77 -0
- memoryking/adapters/postgres_recovery.py +525 -0
- memoryking/adapters/postgres_schema.sql +365 -0
- memoryking/adapters/postgres_sql.py +102 -0
- memoryking/adapters/postgres_store.py +428 -0
- memoryking/adapters/postgres_summary_schema.sql +12 -0
- memoryking/adapters/postgres_trust_schema.sql +20 -0
- memoryking/adapters/processing.schema.json +471 -0
- memoryking/adapters/processing_store.py +346 -0
- memoryking/adapters/projects.py +83 -0
- memoryking/adapters/proposals.py +238 -0
- memoryking/adapters/ranking.py +315 -0
- memoryking/adapters/repository.schema.json +664 -0
- memoryking/adapters/repository_git.py +264 -0
- memoryking/adapters/repository_schema.sql +25 -0
- memoryking/adapters/repository_store.py +960 -0
- memoryking/adapters/retrieval.py +1285 -0
- memoryking/adapters/retrieval.schema.json +553 -0
- memoryking/adapters/retrieval_schema.sql +10 -0
- memoryking/adapters/shared_control.py +40 -0
- memoryking/adapters/shared_dashboard.py +636 -0
- memoryking/adapters/shared_gateway.py +63 -0
- memoryking/adapters/shared_http.py +216 -0
- memoryking/adapters/shared_mcp.py +159 -0
- memoryking/adapters/shared_service.py +124 -0
- memoryking/adapters/stdio.py +193 -0
- memoryking/adapters/stdio.tools.json +6776 -0
- memoryking/adapters/summary_schema.sql +10 -0
- memoryking/adapters/team.py +253 -0
- memoryking/adapters/timeline.py +80 -0
- memoryking/adapters/token_count.py +55 -0
- memoryking/adapters/tokenizers/LICENSE +21 -0
- memoryking/adapters/tokenizers/cl100k_base.tiktoken +100256 -0
- memoryking/adapters/trust.py +123 -0
- memoryking/adapters/trust_schema.sql +13 -0
- memoryking/adapters/web/app.css +1251 -0
- memoryking/adapters/web/app.js +907 -0
- memoryking/adapters/web/brand.js +44 -0
- memoryking/adapters/web/crown-mono.svg +1 -0
- memoryking/adapters/web/crown.svg +8 -0
- memoryking/adapters/web/elephant.png +0 -0
- memoryking/adapters/web/favicon.svg +8 -0
- memoryking/adapters/web/graph-layout.js +52 -0
- memoryking/adapters/web/graph-worker.js +10 -0
- memoryking/adapters/web/graph.js +570 -0
- memoryking/adapters/web/index.html +208 -0
- memoryking/adapters/web/observatory.js +1208 -0
- memoryking/adapters/web/team.js +151 -0
- memoryking/adapters/web/wordmark.svg +1 -0
- memoryking/adapters/working.py +971 -0
- memoryking/adapters/working.schema.json +1717 -0
- memoryking/adapters/working_schema.sql +24 -0
- memoryking/application/__init__.py +1 -0
- memoryking/application/conformance.py +50 -0
- memoryking/application/legacy_import.py +337 -0
- memoryking/application/local_port.py +9 -0
- memoryking/application/storage.py +117 -0
- memoryking/application/store_core.py +1292 -0
- memoryking/backups.py +131 -0
- memoryking/contracts/__init__.py +6 -0
- memoryking/contracts/__main__.py +20 -0
- memoryking/contracts/canonical.py +88 -0
- memoryking/contracts/embedding.schema.json +302 -0
- memoryking/contracts/embedding_generated.py +65 -0
- memoryking/contracts/experience.schema.json +1508 -0
- memoryking/contracts/experience_generated.py +239 -0
- memoryking/contracts/generated.py +122 -0
- memoryking/contracts/handoff.schema.json +299 -0
- memoryking/contracts/handoff_generated.py +69 -0
- memoryking/contracts/inference.schema.json +541 -0
- memoryking/contracts/inference_generated.py +106 -0
- memoryking/contracts/processing.schema.json +471 -0
- memoryking/contracts/processing_generated.py +82 -0
- memoryking/contracts/py.typed +0 -0
- memoryking/contracts/repository.schema.json +664 -0
- memoryking/contracts/repository_generated.py +144 -0
- memoryking/contracts/retrieval.schema.json +553 -0
- memoryking/contracts/retrieval_generated.py +110 -0
- memoryking/contracts/schema.json +696 -0
- memoryking/contracts/validation.py +92 -0
- memoryking/contracts/working.schema.json +1717 -0
- memoryking/contracts/working_generated.py +291 -0
- memoryking/domain/__init__.py +1 -0
- memoryking/domain/anchors.py +97 -0
- memoryking/domain/briefing.py +108 -0
- memoryking/domain/briefing_text.py +222 -0
- memoryking/domain/checkpoint.py +118 -0
- memoryking/domain/compression.py +64 -0
- memoryking/domain/delta.py +129 -0
- memoryking/domain/embeddings.py +90 -0
- memoryking/domain/hints.py +465 -0
- memoryking/domain/http_status.py +45 -0
- memoryking/domain/learning.py +62 -0
- memoryking/domain/local.py +65 -0
- memoryking/domain/plans.py +140 -0
- memoryking/domain/repository.py +118 -0
- memoryking/domain/selectors.py +356 -0
- memoryking/domain/summary.py +88 -0
- memoryking/domain/usage.py +163 -0
- memoryking/embedding_loop.py +98 -0
- memoryking/embedding_worker.py +131 -0
- memoryking/harness.py +882 -0
- memoryking/harness_context.py +376 -0
- memoryking/hooks.py +171 -0
- memoryking/host_hooks.py +454 -0
- memoryking/lean.py +352 -0
- memoryking/memory_tool.py +776 -0
- memoryking/migration.py +194 -0
- memoryking/model_install.py +78 -0
- memoryking/observability.py +101 -0
- memoryking/observability_metrics.py +100 -0
- memoryking/profiles.py +150 -0
- memoryking/providers.py +330 -0
- memoryking/py.typed +0 -0
- memoryking/pytest_plugin.py +69 -0
- memoryking/reference_agent.py +152 -0
- memoryking/repository_worker.py +57 -0
- memoryking/resume_adapter.py +154 -0
- memoryking/sdk.py +302 -0
- memoryking/shared.py +301 -0
- memoryking/shared_sdk.py +101 -0
- memoryking/vault.py +176 -0
- memoryking-0.1.0.dist-info/METADATA +157 -0
- memoryking-0.1.0.dist-info/RECORD +179 -0
- memoryking-0.1.0.dist-info/WHEEL +5 -0
- memoryking-0.1.0.dist-info/entry_points.txt +7 -0
- memoryking-0.1.0.dist-info/licenses/LICENSE +202 -0
- memoryking-0.1.0.dist-info/licenses/NOTICE +12 -0
- memoryking-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,776 @@
|
|
|
1
|
+
"""Memory as files: Anthropic's memory tool and a Markdown vault over MemoryKing records.
|
|
2
|
+
|
|
3
|
+
The memory tool is a file interface with six commands (`view`, `create`, `str_replace`,
|
|
4
|
+
`insert`, `delete`, `rename`) under a `/memories` root. This adapter answers them from a
|
|
5
|
+
MemoryKing project, so a Claude API agent uses MemoryKing as its memory backend with no
|
|
6
|
+
prompt changes and every write is an ordinary receipted capture or proposal:
|
|
7
|
+
|
|
8
|
+
/memories/<project>/README.md what this memory is, generated
|
|
9
|
+
/memories/<project>/<source>/<name>.md one observation per file, newest version
|
|
10
|
+
/memories/<project>/claims/<key>.md one reviewed claim per family
|
|
11
|
+
|
|
12
|
+
A directory is a source; a file is the newest version of a note whose event id is its
|
|
13
|
+
name; its earlier versions remain evidence and are counted in the provenance block
|
|
14
|
+
that opens every file. Editing a file captures a new version, creating a file under
|
|
15
|
+
`claims/` proposes a claim that waits for review, viewing a file is a receipted fetch,
|
|
16
|
+
and deleting or renaming needs an administrator because memory is evidence. The same
|
|
17
|
+
file model is what `memoryking vault export` writes for hand editing and portability.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import hashlib
|
|
23
|
+
import re
|
|
24
|
+
import time
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
from datetime import datetime, timezone
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
from memoryking.domain.hints import hint
|
|
30
|
+
from memoryking.domain.local import LocalError
|
|
31
|
+
from memoryking.sdk import LocalClient
|
|
32
|
+
|
|
33
|
+
ROOT = "/memories"
|
|
34
|
+
README = "README.md"
|
|
35
|
+
CLAIMS = "claims"
|
|
36
|
+
SUFFIX = ".md"
|
|
37
|
+
NAME_LIMIT = 80 # leaves room for a `__v<n>` version suffix inside a 96-char identifier
|
|
38
|
+
TEXT_LIMIT = 65536 # the capture contract's text bound, in bytes
|
|
39
|
+
CLAIM_TEXT_LIMIT = 8192
|
|
40
|
+
FETCH_CHUNK = 16384 # the fetch contract's largest range
|
|
41
|
+
LISTING_LIMIT = 256 # directory entries shown before the listing says what it left out
|
|
42
|
+
PAGE = 512
|
|
43
|
+
DAY_MS = 86_400_000
|
|
44
|
+
VERSION = re.compile(r"^(.+?)__v([0-9]+)$")
|
|
45
|
+
IDENTIFIER = re.compile(r"^[A-Za-z0-9_-]{1,96}$")
|
|
46
|
+
DEFINITION = {"type": "memory_20250818", "name": "memory"}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class MemoryToolError(Exception):
|
|
50
|
+
"""A message for the model, returned as a tool result with `is_error`."""
|
|
51
|
+
|
|
52
|
+
def __init__(self, message: str):
|
|
53
|
+
self.message = message
|
|
54
|
+
super().__init__(message)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True)
|
|
58
|
+
class Location:
|
|
59
|
+
kind: str # root | project | readme | directory | file
|
|
60
|
+
source: str | None = None
|
|
61
|
+
name: str | None = None
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def claim(self) -> bool:
|
|
65
|
+
return self.source == CLAIMS
|
|
66
|
+
|
|
67
|
+
def path(self, project: str) -> str:
|
|
68
|
+
if self.kind == "root":
|
|
69
|
+
return ROOT
|
|
70
|
+
if self.kind == "project":
|
|
71
|
+
return f"{ROOT}/{project}"
|
|
72
|
+
if self.kind == "readme":
|
|
73
|
+
return f"{ROOT}/{project}/{README}"
|
|
74
|
+
if self.kind == "directory":
|
|
75
|
+
return f"{ROOT}/{project}/{self.source}"
|
|
76
|
+
return f"{ROOT}/{project}/{self.source}/{self.name}{SUFFIX}"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def sanitize(part: str) -> str:
|
|
80
|
+
"""A file or directory name as the identifier it maps to; deterministic, bounded."""
|
|
81
|
+
if part.endswith(SUFFIX):
|
|
82
|
+
part = part[: -len(SUFFIX)]
|
|
83
|
+
name = re.sub(r"[^A-Za-z0-9_-]+", "-", part).strip("-")[:NAME_LIMIT]
|
|
84
|
+
if not name:
|
|
85
|
+
raise MemoryToolError("Error: names need at least one letter, digit, `_` or `-`.")
|
|
86
|
+
if VERSION.match(name):
|
|
87
|
+
raise MemoryToolError("Error: the `__v<number>` suffix is reserved for versions.")
|
|
88
|
+
return name
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def locate(path: Any, project: str) -> Location:
|
|
92
|
+
"""Resolve a memory path, refusing anything outside the root or shaped like traversal."""
|
|
93
|
+
if not isinstance(path, str) or not (path == ROOT or path.startswith(ROOT + "/")):
|
|
94
|
+
raise MemoryToolError(f"Error: The path {path} is outside {ROOT}.")
|
|
95
|
+
parts = [p for p in path[len(ROOT) :].split("/") if p]
|
|
96
|
+
for part in parts:
|
|
97
|
+
if part in {".", ".."} or part.startswith(".") or "\\" in part or "%" in part:
|
|
98
|
+
raise MemoryToolError(f"Error: The path {path} is not a valid memory path.")
|
|
99
|
+
if not parts:
|
|
100
|
+
return Location("root")
|
|
101
|
+
if parts[0] != project:
|
|
102
|
+
raise MemoryToolError(f"The path {path} does not exist. Please provide a valid path.")
|
|
103
|
+
if len(parts) == 1:
|
|
104
|
+
return Location("project")
|
|
105
|
+
if len(parts) == 2:
|
|
106
|
+
if parts[1] == README:
|
|
107
|
+
return Location("readme")
|
|
108
|
+
return Location("directory", sanitize(parts[1]))
|
|
109
|
+
if len(parts) == 3:
|
|
110
|
+
return Location("file", sanitize(parts[1]), sanitize(parts[2]))
|
|
111
|
+
raise MemoryToolError(f"The path {path} does not exist. Please provide a valid path.")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def stamp(ms: int) -> str:
|
|
115
|
+
return datetime.fromtimestamp(ms / 1000, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def human(size: int) -> str:
|
|
119
|
+
if size >= 1048576:
|
|
120
|
+
return f"{size / 1048576:.1f}M"
|
|
121
|
+
return f"{max(size, 1) / 1024:.1f}K"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def render(entry: dict[str, Any], project: str) -> str:
|
|
125
|
+
"""A file: a provenance block, then the text exactly as stored."""
|
|
126
|
+
if entry["kind"] == "claim":
|
|
127
|
+
head = [
|
|
128
|
+
"memoryking: claim",
|
|
129
|
+
f"revision: {entry['revision']}",
|
|
130
|
+
f"family: {entry['family']}",
|
|
131
|
+
f"key: {entry['logical_key']}",
|
|
132
|
+
f"family_version: {entry['family_version']}",
|
|
133
|
+
f"state: {entry['state']}" + (" (quarantined)" if entry["quarantined"] else ""),
|
|
134
|
+
f"project: {project}",
|
|
135
|
+
f"issuer: {entry['issuer']}",
|
|
136
|
+
"evidence: [" + ", ".join(entry["evidence"]) + "]",
|
|
137
|
+
f"valid_start: {entry['valid_start']}",
|
|
138
|
+
f"valid_end: {entry['valid_end']}",
|
|
139
|
+
f"sha256: {entry['hash']}",
|
|
140
|
+
]
|
|
141
|
+
else:
|
|
142
|
+
newest = entry["versions"][0]
|
|
143
|
+
head = [
|
|
144
|
+
"memoryking: observation",
|
|
145
|
+
f"id: {newest['id']}",
|
|
146
|
+
f"project: {project}",
|
|
147
|
+
f"source: {entry['source']}",
|
|
148
|
+
f"name: {entry['name']}",
|
|
149
|
+
f"version: {len(entry['versions'])}",
|
|
150
|
+
f"captured_by: {newest['principal']}",
|
|
151
|
+
f"observed: {stamp(newest['observed_at_ms'])}",
|
|
152
|
+
f"recorded: {stamp(newest['recorded_ms'])}",
|
|
153
|
+
f"classification: {newest['classification']}",
|
|
154
|
+
f"sha256: {newest['hash']}",
|
|
155
|
+
]
|
|
156
|
+
body: str = entry["text"]
|
|
157
|
+
return "---\n" + "\n".join(head) + "\n---\n" + body
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def split(content: str) -> tuple[dict[str, Any], str]:
|
|
161
|
+
"""(provenance fields, body) of a file; a file without a leading block is all body."""
|
|
162
|
+
if not content.startswith("---\n"):
|
|
163
|
+
return {}, content
|
|
164
|
+
end = content.find("\n---", 4)
|
|
165
|
+
if end < 0:
|
|
166
|
+
return {}, content
|
|
167
|
+
fields: dict[str, Any] = {}
|
|
168
|
+
for line in content[4:end].split("\n"):
|
|
169
|
+
key, _, value = line.partition(":")
|
|
170
|
+
value = value.strip()
|
|
171
|
+
if value.startswith("[") and value.endswith("]"):
|
|
172
|
+
fields[key.strip()] = [v.strip() for v in value[1:-1].split(",") if v.strip()]
|
|
173
|
+
else:
|
|
174
|
+
fields[key.strip()] = value
|
|
175
|
+
rest = content[end + 4 :]
|
|
176
|
+
if rest.startswith("\n"):
|
|
177
|
+
rest = rest[1:]
|
|
178
|
+
return fields, rest
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def numbered(content: str, path: str, view_range: Any = None) -> str:
|
|
182
|
+
lines = content[:-1].split("\n") if content.endswith("\n") else content.split("\n")
|
|
183
|
+
if len(lines) > 999_999:
|
|
184
|
+
raise MemoryToolError(f"File {path} exceeds maximum line limit of 999,999 lines.")
|
|
185
|
+
start, end = 1, len(lines)
|
|
186
|
+
if view_range is not None:
|
|
187
|
+
if (
|
|
188
|
+
not isinstance(view_range, list)
|
|
189
|
+
or len(view_range) != 2
|
|
190
|
+
or not all(isinstance(v, int) and not isinstance(v, bool) for v in view_range)
|
|
191
|
+
or not 1 <= view_range[0] <= len(lines)
|
|
192
|
+
or (view_range[1] != -1 and view_range[1] < view_range[0])
|
|
193
|
+
):
|
|
194
|
+
raise MemoryToolError(
|
|
195
|
+
f"Error: Invalid `view_range` parameter: {view_range}. It should be [start, end] "
|
|
196
|
+
f"within the {len(lines)} lines of the file, or [start, -1]."
|
|
197
|
+
)
|
|
198
|
+
start = view_range[0]
|
|
199
|
+
end = len(lines) if view_range[1] == -1 else min(view_range[1], len(lines))
|
|
200
|
+
shown = "\n".join(f"{i:6d}\t{lines[i - 1]}" for i in range(start, end + 1))
|
|
201
|
+
return f"Here's the content of {path} with line numbers:\n{shown}"
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def field(command: Any, key: str, default: Any = None) -> Any:
|
|
205
|
+
"""A command field, from a dict (the wire shape) or an SDK command object."""
|
|
206
|
+
if isinstance(command, dict):
|
|
207
|
+
return command.get(key, default)
|
|
208
|
+
return getattr(command, key, default)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def same(a: str, b: str) -> bool:
|
|
212
|
+
return a.rstrip("\n") == b.rstrip("\n")
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
class Files:
|
|
216
|
+
"""The project's records as files, over a bound client: list, read, write, propose."""
|
|
217
|
+
|
|
218
|
+
def __init__(self, client: LocalClient):
|
|
219
|
+
self.client = client
|
|
220
|
+
self.project = client.project
|
|
221
|
+
self.principal = client.binding[2]
|
|
222
|
+
|
|
223
|
+
def _catalog(self, kind: str, **filters: Any) -> dict[str, Any]:
|
|
224
|
+
return self.client.inspection(
|
|
225
|
+
{
|
|
226
|
+
"version": 1,
|
|
227
|
+
"incarnation": self.client.binding[-1],
|
|
228
|
+
"action": "catalog",
|
|
229
|
+
"args": {"project": self.project, "kind": kind, **filters},
|
|
230
|
+
}
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
def pages(self, kind: str, *, text: bool, **filters: Any) -> list[dict[str, Any]]:
|
|
234
|
+
"""Every item of a catalog, page after page."""
|
|
235
|
+
items: list[dict[str, Any]] = []
|
|
236
|
+
after: int | None = None
|
|
237
|
+
while True:
|
|
238
|
+
page = self._catalog(
|
|
239
|
+
kind,
|
|
240
|
+
text=text,
|
|
241
|
+
limit=PAGE,
|
|
242
|
+
**({"after": after} if after is not None else {}),
|
|
243
|
+
**filters,
|
|
244
|
+
)
|
|
245
|
+
items.extend(page["items"])
|
|
246
|
+
after = page["next_after"]
|
|
247
|
+
if after is None or not page["items"]:
|
|
248
|
+
return items
|
|
249
|
+
|
|
250
|
+
@staticmethod
|
|
251
|
+
def group(items: list[dict[str, Any]]) -> dict[tuple[str, str], dict[str, Any]]:
|
|
252
|
+
"""Observations as files keyed (source, name); versions newest first."""
|
|
253
|
+
files: dict[tuple[str, str], dict[str, Any]] = {}
|
|
254
|
+
for item in items: # newest first already
|
|
255
|
+
match = VERSION.match(item["source_event"])
|
|
256
|
+
name = match.group(1) if match else item["source_event"]
|
|
257
|
+
entry = files.setdefault(
|
|
258
|
+
(item["source"], name),
|
|
259
|
+
{"kind": "observation", "source": item["source"], "name": name, "versions": []},
|
|
260
|
+
)
|
|
261
|
+
entry["versions"].append(item)
|
|
262
|
+
for entry in files.values():
|
|
263
|
+
entry["text"] = entry["versions"][0].get("text", "")
|
|
264
|
+
return files
|
|
265
|
+
|
|
266
|
+
def listing(self, source: str | None = None, *, text: bool = False) -> dict[str, Any]:
|
|
267
|
+
"""One page of files (the newest `PAGE` observations) plus the total."""
|
|
268
|
+
filters = {"source": source} if source else {}
|
|
269
|
+
page = self._catalog("observations", text=text, limit=PAGE, **filters)
|
|
270
|
+
return {"files": self.group(page["items"]), "total": page["total"]}
|
|
271
|
+
|
|
272
|
+
def observation(self, source: str, name: str, *, text: bool = True) -> dict[str, Any] | None:
|
|
273
|
+
page = self._catalog("observations", source=source, name=name, text=text, limit=PAGE)
|
|
274
|
+
files = self.group(page["items"])
|
|
275
|
+
return files.get((source, name))
|
|
276
|
+
|
|
277
|
+
def by_id(self, observation: str) -> dict[str, Any] | None:
|
|
278
|
+
page = self._catalog("observations", id=observation, text=False, limit=1)
|
|
279
|
+
return page["items"][0] if page["items"] else None
|
|
280
|
+
|
|
281
|
+
def claims(self, *, text: bool = False) -> dict[str, dict[str, Any]]:
|
|
282
|
+
page = self._catalog("claims", text=text, limit=PAGE)
|
|
283
|
+
return {item["logical_key"]: {**item, "kind": "claim"} for item in page["items"]}
|
|
284
|
+
|
|
285
|
+
def claim(self, key: str) -> dict[str, Any] | None:
|
|
286
|
+
page = self._catalog("claims", name=key, text=True, limit=1)
|
|
287
|
+
return {**page["items"][0], "kind": "claim"} if page["items"] else None
|
|
288
|
+
|
|
289
|
+
def fetch(self, kind: str, reference: str, size: int) -> str:
|
|
290
|
+
"""The record's text through receipted fetches, so a view counts as a delivery."""
|
|
291
|
+
pieces = []
|
|
292
|
+
for start in range(0, size, FETCH_CHUNK):
|
|
293
|
+
packet = self.client.tool(
|
|
294
|
+
"memory_fetch",
|
|
295
|
+
{
|
|
296
|
+
"action": "fetch",
|
|
297
|
+
"args": {
|
|
298
|
+
"kind": kind,
|
|
299
|
+
"reference": reference,
|
|
300
|
+
"start_byte": start,
|
|
301
|
+
"end_byte": min(start + FETCH_CHUNK, size),
|
|
302
|
+
"max_output_tokens": 65536,
|
|
303
|
+
},
|
|
304
|
+
},
|
|
305
|
+
)
|
|
306
|
+
if packet["status"] != "partial":
|
|
307
|
+
raise LocalError(packet.get("reason", "unavailable"))
|
|
308
|
+
pieces.append(packet["excerpt"])
|
|
309
|
+
return "".join(pieces)
|
|
310
|
+
|
|
311
|
+
def capture(
|
|
312
|
+
self, source: str, name: str, text: str, versions: list[dict[str, Any]]
|
|
313
|
+
) -> dict[str, Any]:
|
|
314
|
+
"""A new version of a file: a capture whose event id carries the version."""
|
|
315
|
+
if not IDENTIFIER.match(source) or source == CLAIMS:
|
|
316
|
+
raise MemoryToolError(f"Error: {source} is not a directory notes can be written to.")
|
|
317
|
+
if not text.strip():
|
|
318
|
+
raise MemoryToolError("Error: a memory file needs some text.")
|
|
319
|
+
if len(text.encode()) > TEXT_LIMIT:
|
|
320
|
+
raise MemoryToolError(
|
|
321
|
+
f"Error: files are limited to {TEXT_LIMIT} bytes; split this one."
|
|
322
|
+
)
|
|
323
|
+
mine = {v["source_event"] for v in versions if v["principal"] == self.principal}
|
|
324
|
+
number = len(versions) + 1
|
|
325
|
+
event = name if not versions else f"{name}__v{number}"
|
|
326
|
+
while event in mine:
|
|
327
|
+
number += 1
|
|
328
|
+
event = f"{name}__v{number}"
|
|
329
|
+
key = "mt-" + hashlib.sha256(f"{source}\n{event}\n{text}".encode()).hexdigest()[:40]
|
|
330
|
+
observed = int(time.time() * 1000) // DAY_MS * DAY_MS
|
|
331
|
+
result = self.client.capture(
|
|
332
|
+
key,
|
|
333
|
+
{
|
|
334
|
+
"version": 1,
|
|
335
|
+
"project": self.project,
|
|
336
|
+
"source": source,
|
|
337
|
+
"source_event": event,
|
|
338
|
+
"text": text,
|
|
339
|
+
"readers": None,
|
|
340
|
+
"classification": "internal",
|
|
341
|
+
"observed_at_ms": observed,
|
|
342
|
+
},
|
|
343
|
+
)
|
|
344
|
+
return {**result, "version": len(versions) + 1, "source_event": event}
|
|
345
|
+
|
|
346
|
+
def spans(self, evidence: list[str]) -> list[dict[str, Any]]:
|
|
347
|
+
"""Whole-record evidence spans for observation ids or memory paths (`source/name`)."""
|
|
348
|
+
spans = []
|
|
349
|
+
for item in evidence:
|
|
350
|
+
found = None
|
|
351
|
+
if item.startswith("obs_"):
|
|
352
|
+
found = self.by_id(item)
|
|
353
|
+
else:
|
|
354
|
+
parts = [
|
|
355
|
+
p for p in item.replace(ROOT + "/" + self.project + "/", "").split("/") if p
|
|
356
|
+
]
|
|
357
|
+
if len(parts) == 2:
|
|
358
|
+
entry = self.observation(sanitize(parts[0]), sanitize(parts[1]), text=False)
|
|
359
|
+
found = entry["versions"][0] if entry else None
|
|
360
|
+
if found is None:
|
|
361
|
+
raise MemoryToolError(
|
|
362
|
+
f"Error: evidence `{item}` is not an observation id or a memory file "
|
|
363
|
+
"(`<source>/<name>`) in this project."
|
|
364
|
+
)
|
|
365
|
+
spans.append(
|
|
366
|
+
{
|
|
367
|
+
"observation": found["id"],
|
|
368
|
+
"start_byte": 0,
|
|
369
|
+
"end_byte": found["bytes"],
|
|
370
|
+
"content_hash": found["hash"],
|
|
371
|
+
}
|
|
372
|
+
)
|
|
373
|
+
if not spans:
|
|
374
|
+
raise MemoryToolError(
|
|
375
|
+
"Error: a claim needs evidence. Start the file with a block such as\n"
|
|
376
|
+
"---\nevidence: [notes/decision, pytest/ev-123]\n---\n"
|
|
377
|
+
"naming the memory files or observation ids that support it."
|
|
378
|
+
)
|
|
379
|
+
return spans[:16]
|
|
380
|
+
|
|
381
|
+
def propose(
|
|
382
|
+
self, key: str, text: str, evidence: list[str], existing: dict[str, Any] | None
|
|
383
|
+
) -> dict[str, Any]:
|
|
384
|
+
"""A claim proposal from a file: it waits for review like any other."""
|
|
385
|
+
if not text.strip():
|
|
386
|
+
raise MemoryToolError("Error: a claim needs some text.")
|
|
387
|
+
if len(text.encode()) > CLAIM_TEXT_LIMIT:
|
|
388
|
+
raise MemoryToolError(f"Error: claims are limited to {CLAIM_TEXT_LIMIT} bytes.")
|
|
389
|
+
if not IDENTIFIER.match(key):
|
|
390
|
+
raise MemoryToolError(
|
|
391
|
+
"Error: a claim's name is an identifier of at most 96 characters."
|
|
392
|
+
)
|
|
393
|
+
version = existing["family_version"] if existing else 0
|
|
394
|
+
body = {
|
|
395
|
+
"text": text,
|
|
396
|
+
"kind": "knowledge",
|
|
397
|
+
"selector": {"selector_version": "1", "any_of": [{"all_of": [{"op": "any"}]}]},
|
|
398
|
+
"valid_start": None,
|
|
399
|
+
"valid_end": None,
|
|
400
|
+
"task": None,
|
|
401
|
+
"run": None,
|
|
402
|
+
"readers": None,
|
|
403
|
+
"evidence": self.spans(evidence),
|
|
404
|
+
"authority": None,
|
|
405
|
+
"rule_key": None,
|
|
406
|
+
"effect": None,
|
|
407
|
+
"rule_value": None,
|
|
408
|
+
"provenance": {
|
|
409
|
+
"method": "memory_file_v1",
|
|
410
|
+
"path": f"{CLAIMS}/{key}{SUFFIX}",
|
|
411
|
+
"proposed_by": self.principal,
|
|
412
|
+
},
|
|
413
|
+
}
|
|
414
|
+
return self.client.knowledge(
|
|
415
|
+
{
|
|
416
|
+
"version": 1,
|
|
417
|
+
"incarnation": self.client.binding[-1],
|
|
418
|
+
"action": "propose",
|
|
419
|
+
"key": "mt-"
|
|
420
|
+
+ hashlib.sha256(f"{key}\n{version}\n{text}".encode()).hexdigest()[:40],
|
|
421
|
+
"args": {
|
|
422
|
+
"project": self.project,
|
|
423
|
+
"logical_key": key,
|
|
424
|
+
"expected_version": version,
|
|
425
|
+
"body": body,
|
|
426
|
+
},
|
|
427
|
+
}
|
|
428
|
+
)
|
|
429
|
+
|
|
430
|
+
def readme(self, files: dict[tuple[str, str], dict[str, Any]], total: int, claims: int) -> str:
|
|
431
|
+
sources = sorted({source for source, _ in files})
|
|
432
|
+
return (
|
|
433
|
+
f"# Memory for project {self.project}\n\n"
|
|
434
|
+
"This is a MemoryKing project seen as files. Every directory is a source and every\n"
|
|
435
|
+
"file is one observation: the newest version of a note whose name is its event id.\n"
|
|
436
|
+
"Each file opens with a provenance block (who captured it, when, which version); the\n"
|
|
437
|
+
"text below the block is what was recorded. Editing or re-creating a file adds a\n"
|
|
438
|
+
"version and keeps the earlier ones as evidence; nothing is overwritten.\n\n"
|
|
439
|
+
f"`{CLAIMS}/` holds reviewed knowledge, one file per claim. A file created or edited\n"
|
|
440
|
+
"there is a proposal that waits for review; it needs an `evidence: [...]` line in a\n"
|
|
441
|
+
"leading `---` block naming the files or observation ids that support it. Deleting or\n"
|
|
442
|
+
"renaming needs an administrator credential, because memory is evidence.\n\n"
|
|
443
|
+
f"Sources: {', '.join(sources) if sources else 'none yet'}. Observations: {total}. "
|
|
444
|
+
f"Claims: {claims}.\n"
|
|
445
|
+
)
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
class MemoryTool:
|
|
449
|
+
"""The six memory-tool commands over a MemoryKing project.
|
|
450
|
+
|
|
451
|
+
`execute` takes the command as the API sends it (a dict, or an SDK command object
|
|
452
|
+
with the same attribute names) and returns the text for the tool result; it raises
|
|
453
|
+
`MemoryToolError` with the text to return with `is_error`. `tool_result` builds the
|
|
454
|
+
`tool_result` block directly. The definition to send in `tools` is `DEFINITION`.
|
|
455
|
+
"""
|
|
456
|
+
|
|
457
|
+
definition = DEFINITION
|
|
458
|
+
|
|
459
|
+
def __init__(self, client: LocalClient):
|
|
460
|
+
self.files = Files(client)
|
|
461
|
+
self.project = client.project
|
|
462
|
+
|
|
463
|
+
def execute(self, command: Any) -> str:
|
|
464
|
+
name = field(command, "command")
|
|
465
|
+
handler = {
|
|
466
|
+
"view": self.view,
|
|
467
|
+
"create": self.create,
|
|
468
|
+
"str_replace": self.str_replace,
|
|
469
|
+
"insert": self.insert,
|
|
470
|
+
"delete": self.delete,
|
|
471
|
+
"rename": self.rename,
|
|
472
|
+
}.get(name)
|
|
473
|
+
if handler is None:
|
|
474
|
+
raise MemoryToolError(f"Error: unknown command {name}")
|
|
475
|
+
try:
|
|
476
|
+
return handler(command)
|
|
477
|
+
except LocalError as exc:
|
|
478
|
+
raise MemoryToolError(f"Error: {exc.code}: {exc.hint or hint(exc.code)}") from exc
|
|
479
|
+
|
|
480
|
+
def tool_result(self, tool_use_id: str, command: Any) -> dict[str, Any]:
|
|
481
|
+
try:
|
|
482
|
+
return {
|
|
483
|
+
"type": "tool_result",
|
|
484
|
+
"tool_use_id": tool_use_id,
|
|
485
|
+
"content": self.execute(command),
|
|
486
|
+
}
|
|
487
|
+
except MemoryToolError as exc:
|
|
488
|
+
return {
|
|
489
|
+
"type": "tool_result",
|
|
490
|
+
"tool_use_id": tool_use_id,
|
|
491
|
+
"content": exc.message,
|
|
492
|
+
"is_error": True,
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
# Reading
|
|
496
|
+
|
|
497
|
+
def _entry(self, location: Location, *, text: bool) -> dict[str, Any]:
|
|
498
|
+
if location.claim:
|
|
499
|
+
entry = self.files.claim(location.name or "")
|
|
500
|
+
else:
|
|
501
|
+
entry = self.files.observation(location.source or "", location.name or "", text=text)
|
|
502
|
+
if entry is None:
|
|
503
|
+
raise MemoryToolError(
|
|
504
|
+
f"The path {location.path(self.project)} does not exist. Please provide a valid path."
|
|
505
|
+
)
|
|
506
|
+
return entry
|
|
507
|
+
|
|
508
|
+
def _content(self, location: Location) -> str:
|
|
509
|
+
"""The rendered file, its text read through receipted fetches."""
|
|
510
|
+
entry = self._entry(location, text=False)
|
|
511
|
+
if entry["kind"] == "claim":
|
|
512
|
+
entry["text"] = self.files.fetch("revision", entry["revision"], entry["bytes"])
|
|
513
|
+
else:
|
|
514
|
+
newest = entry["versions"][0]
|
|
515
|
+
entry["text"] = self.files.fetch("observation", newest["id"], newest["bytes"])
|
|
516
|
+
return render(entry, self.project)
|
|
517
|
+
|
|
518
|
+
def view(self, command: Any) -> str:
|
|
519
|
+
location = locate(field(command, "path"), self.project)
|
|
520
|
+
path = location.path(self.project)
|
|
521
|
+
if location.kind == "readme":
|
|
522
|
+
listing = self.files.listing()
|
|
523
|
+
return numbered(
|
|
524
|
+
self.files.readme(listing["files"], listing["total"], len(self.files.claims())),
|
|
525
|
+
path,
|
|
526
|
+
field(command, "view_range"),
|
|
527
|
+
)
|
|
528
|
+
if location.kind == "file":
|
|
529
|
+
return numbered(self._content(location), path, field(command, "view_range"))
|
|
530
|
+
return self._directory(location)
|
|
531
|
+
|
|
532
|
+
def _directory(self, location: Location) -> str:
|
|
533
|
+
project = f"{ROOT}/{self.project}"
|
|
534
|
+
lines: list[tuple[int, str]] = []
|
|
535
|
+
left = 0
|
|
536
|
+
if location.kind == "root":
|
|
537
|
+
lines.append((0, ROOT))
|
|
538
|
+
lines.append((0, project))
|
|
539
|
+
listing = self.files.listing()
|
|
540
|
+
lines.append(
|
|
541
|
+
(
|
|
542
|
+
len(self.files.readme(listing["files"], listing["total"], 0)),
|
|
543
|
+
f"{project}/{README}",
|
|
544
|
+
)
|
|
545
|
+
)
|
|
546
|
+
lines.append((0, f"{project}/{CLAIMS}"))
|
|
547
|
+
for source in sorted({s for s, _ in listing["files"]}):
|
|
548
|
+
lines.append((0, f"{project}/{source}"))
|
|
549
|
+
elif location.kind == "project":
|
|
550
|
+
lines.append((0, project))
|
|
551
|
+
listing = self.files.listing()
|
|
552
|
+
claims = self.files.claims()
|
|
553
|
+
readme = self.files.readme(listing["files"], listing["total"], len(claims))
|
|
554
|
+
lines.append((len(readme), f"{project}/{README}"))
|
|
555
|
+
lines.append((sum(c["bytes"] for c in claims.values()), f"{project}/{CLAIMS}"))
|
|
556
|
+
for key, claim in sorted(claims.items()):
|
|
557
|
+
lines.append((claim["bytes"], f"{project}/{CLAIMS}/{key}{SUFFIX}"))
|
|
558
|
+
by_source: dict[str, list[dict[str, Any]]] = {}
|
|
559
|
+
for (source, _), entry in listing["files"].items():
|
|
560
|
+
by_source.setdefault(source, []).append(entry)
|
|
561
|
+
for source in sorted(by_source):
|
|
562
|
+
entries = by_source[source]
|
|
563
|
+
lines.append(
|
|
564
|
+
(sum(e["versions"][0]["bytes"] for e in entries), f"{project}/{source}")
|
|
565
|
+
)
|
|
566
|
+
for entry in entries:
|
|
567
|
+
lines.append(
|
|
568
|
+
(
|
|
569
|
+
entry["versions"][0]["bytes"],
|
|
570
|
+
f"{project}/{source}/{entry['name']}{SUFFIX}",
|
|
571
|
+
)
|
|
572
|
+
)
|
|
573
|
+
left = listing["total"] - sum(len(e["versions"]) for e in listing["files"].values())
|
|
574
|
+
elif location.claim:
|
|
575
|
+
claims = self.files.claims()
|
|
576
|
+
lines.append((sum(c["bytes"] for c in claims.values()), f"{project}/{CLAIMS}"))
|
|
577
|
+
for key, claim in sorted(claims.items()):
|
|
578
|
+
lines.append((claim["bytes"], f"{project}/{CLAIMS}/{key}{SUFFIX}"))
|
|
579
|
+
else:
|
|
580
|
+
listing = self.files.listing(location.source)
|
|
581
|
+
if not listing["files"]:
|
|
582
|
+
raise MemoryToolError(
|
|
583
|
+
f"The path {location.path(self.project)} does not exist. Please provide a valid path."
|
|
584
|
+
)
|
|
585
|
+
entries = list(listing["files"].values())
|
|
586
|
+
lines.append(
|
|
587
|
+
(sum(e["versions"][0]["bytes"] for e in entries), f"{project}/{location.source}")
|
|
588
|
+
)
|
|
589
|
+
for entry in entries:
|
|
590
|
+
lines.append(
|
|
591
|
+
(
|
|
592
|
+
entry["versions"][0]["bytes"],
|
|
593
|
+
f"{project}/{location.source}/{entry['name']}{SUFFIX}",
|
|
594
|
+
)
|
|
595
|
+
)
|
|
596
|
+
left = listing["total"] - sum(len(e["versions"]) for e in entries)
|
|
597
|
+
shown = lines[:LISTING_LIMIT]
|
|
598
|
+
text = "\n".join(f"{human(size)}\t{path}" for size, path in shown)
|
|
599
|
+
notes = []
|
|
600
|
+
if len(lines) > len(shown):
|
|
601
|
+
notes.append(
|
|
602
|
+
f"{len(lines) - len(shown)} more entries not listed; view a directory to list it."
|
|
603
|
+
)
|
|
604
|
+
if left > 0:
|
|
605
|
+
notes.append(f"{left} older observations not listed; the newest {PAGE} are shown.")
|
|
606
|
+
header = (
|
|
607
|
+
f"Here're the files and directories up to 2 levels deep in {location.path(self.project)}, "
|
|
608
|
+
"excluding hidden items and node_modules:\n"
|
|
609
|
+
)
|
|
610
|
+
return header + text + ("".join("\n" + n for n in notes))
|
|
611
|
+
|
|
612
|
+
# Writing
|
|
613
|
+
|
|
614
|
+
def _writable(self, command: Any, key: str = "path") -> Location:
|
|
615
|
+
location = locate(field(command, key), self.project)
|
|
616
|
+
if location.kind != "file":
|
|
617
|
+
raise MemoryToolError(
|
|
618
|
+
f"Error: write to a file under {ROOT}/{self.project}/<directory>/<name>{SUFFIX}; "
|
|
619
|
+
f"{README} is generated and directories are sources."
|
|
620
|
+
)
|
|
621
|
+
return location
|
|
622
|
+
|
|
623
|
+
def _write(self, location: Location, text: str, entry: dict[str, Any] | None) -> str:
|
|
624
|
+
"""Store new content for a file; the note tells the model what was recorded."""
|
|
625
|
+
if location.claim:
|
|
626
|
+
fields, body = split(text)
|
|
627
|
+
evidence = (
|
|
628
|
+
fields.get("evidence", []) if isinstance(fields.get("evidence"), list) else []
|
|
629
|
+
)
|
|
630
|
+
if entry and not evidence:
|
|
631
|
+
evidence = entry["evidence"]
|
|
632
|
+
result = self.files.propose(location.name or "", body, evidence, entry)
|
|
633
|
+
return (
|
|
634
|
+
f" (proposed as revision {result['revision']} of claim {location.name}; "
|
|
635
|
+
"it waits for review and is not knowledge until accepted)"
|
|
636
|
+
)
|
|
637
|
+
versions = entry["versions"] if entry else []
|
|
638
|
+
result = self.files.capture(location.source or "", location.name or "", text, versions)
|
|
639
|
+
note = f" (version {result['version']}, observation {result['observation']}"
|
|
640
|
+
if result["version"] > 1:
|
|
641
|
+
note += "; earlier versions are kept as evidence"
|
|
642
|
+
if result.get("held"):
|
|
643
|
+
note += f"; held for review because source {location.source} is untrusted"
|
|
644
|
+
return note + ")"
|
|
645
|
+
|
|
646
|
+
def create(self, command: Any) -> str:
|
|
647
|
+
location = self._writable(command)
|
|
648
|
+
text = field(command, "file_text")
|
|
649
|
+
if not isinstance(text, str):
|
|
650
|
+
raise MemoryToolError("Error: `file_text` is required for create.")
|
|
651
|
+
if location.claim:
|
|
652
|
+
entry = self.files.claim(location.name or "")
|
|
653
|
+
else:
|
|
654
|
+
entry = self.files.observation(location.source or "", location.name or "")
|
|
655
|
+
path = location.path(self.project)
|
|
656
|
+
if entry is not None and same(split(text)[1] if location.claim else text, entry["text"]):
|
|
657
|
+
return f"File created successfully at: {path} (unchanged)"
|
|
658
|
+
return f"File created successfully at: {path}" + self._write(location, text, entry)
|
|
659
|
+
|
|
660
|
+
def _edit_target(self, command: Any) -> tuple[Location, dict[str, Any], str, int]:
|
|
661
|
+
"""(location, entry, body, provenance line count) of a file to edit."""
|
|
662
|
+
location = locate(field(command, "path"), self.project)
|
|
663
|
+
if location.kind != "file":
|
|
664
|
+
raise MemoryToolError(
|
|
665
|
+
f"Error: The path {location.path(self.project)} does not exist. Please provide a valid path."
|
|
666
|
+
)
|
|
667
|
+
entry = self._entry(location, text=True)
|
|
668
|
+
rendered = render(entry, self.project)
|
|
669
|
+
head = rendered[: len(rendered) - len(entry["text"])]
|
|
670
|
+
return location, entry, entry["text"], head.count("\n")
|
|
671
|
+
|
|
672
|
+
def str_replace(self, command: Any) -> str:
|
|
673
|
+
location, entry, body, head = self._edit_target(command)
|
|
674
|
+
path = location.path(self.project)
|
|
675
|
+
old = field(command, "old_str")
|
|
676
|
+
new = field(command, "new_str") or ""
|
|
677
|
+
if not isinstance(old, str) or not old:
|
|
678
|
+
raise MemoryToolError("Error: `old_str` is required for str_replace.")
|
|
679
|
+
count = body.count(old)
|
|
680
|
+
if count == 0:
|
|
681
|
+
rendered = render(entry, self.project)
|
|
682
|
+
if old in rendered[: len(rendered) - len(body)]:
|
|
683
|
+
raise MemoryToolError(
|
|
684
|
+
f"Error: lines 1-{head} of {path} are provenance and cannot be edited; "
|
|
685
|
+
"edit the text below them."
|
|
686
|
+
)
|
|
687
|
+
raise MemoryToolError(
|
|
688
|
+
f"No replacement was performed, old_str `{old}` did not appear verbatim in {path}."
|
|
689
|
+
)
|
|
690
|
+
if count > 1:
|
|
691
|
+
numbers = [
|
|
692
|
+
head + body[:index].count("\n") + 1
|
|
693
|
+
for index in range(len(body))
|
|
694
|
+
if body.startswith(old, index)
|
|
695
|
+
]
|
|
696
|
+
raise MemoryToolError(
|
|
697
|
+
f"No replacement was performed. Multiple occurrences of old_str `{old}` in lines: "
|
|
698
|
+
f"{', '.join(str(n) for n in numbers)}. Please ensure it is unique"
|
|
699
|
+
)
|
|
700
|
+
updated = body.replace(old, new, 1)
|
|
701
|
+
note = self._write(location, updated, entry)
|
|
702
|
+
line = head + body[: body.index(old)].count("\n") + 1
|
|
703
|
+
snippet = self._snippet(entry, updated, line, new.count("\n") + 1)
|
|
704
|
+
return f"The memory file has been edited.{note}\n{snippet}"
|
|
705
|
+
|
|
706
|
+
def _snippet(self, entry: dict[str, Any], text: str, line: int, span: int) -> str:
|
|
707
|
+
preview = render({**entry, "text": text}, self.project)
|
|
708
|
+
lines = preview[:-1].split("\n") if preview.endswith("\n") else preview.split("\n")
|
|
709
|
+
start, end = max(1, line - 3), min(len(lines), line + span + 2)
|
|
710
|
+
return "\n".join(f"{i:6d}\t{lines[i - 1]}" for i in range(start, end + 1))
|
|
711
|
+
|
|
712
|
+
def insert(self, command: Any) -> str:
|
|
713
|
+
location, entry, body, head = self._edit_target(command)
|
|
714
|
+
path = location.path(self.project)
|
|
715
|
+
at = field(command, "insert_line")
|
|
716
|
+
text = field(command, "insert_text")
|
|
717
|
+
if not isinstance(text, str):
|
|
718
|
+
raise MemoryToolError("Error: `insert_text` is required for insert.")
|
|
719
|
+
trailing = body.endswith("\n")
|
|
720
|
+
lines = (body[:-1] if trailing else body).split("\n")
|
|
721
|
+
total = head + len(lines)
|
|
722
|
+
if not isinstance(at, int) or isinstance(at, bool) or not head <= at <= total:
|
|
723
|
+
raise MemoryToolError(
|
|
724
|
+
f"Error: Invalid `insert_line` parameter: {at}. It should be within the range of "
|
|
725
|
+
f"lines of the file: [{head}, {total}] (lines 1-{head} are provenance)"
|
|
726
|
+
)
|
|
727
|
+
lines.insert(at - head, text[:-1] if text.endswith("\n") else text)
|
|
728
|
+
note = self._write(location, "\n".join(lines) + ("\n" if trailing else ""), entry)
|
|
729
|
+
return f"The file {path} has been edited.{note}"
|
|
730
|
+
|
|
731
|
+
# Removing
|
|
732
|
+
|
|
733
|
+
def delete(self, command: Any) -> str:
|
|
734
|
+
location = locate(field(command, "path"), self.project)
|
|
735
|
+
path = location.path(self.project)
|
|
736
|
+
if location.kind in {"root", "project", "readme"}:
|
|
737
|
+
raise MemoryToolError(f"Error: {path} cannot be deleted.")
|
|
738
|
+
if location.kind == "directory":
|
|
739
|
+
raise MemoryToolError(
|
|
740
|
+
f"Error: {path} is a directory of sources; delete its files one at a time."
|
|
741
|
+
)
|
|
742
|
+
if location.claim:
|
|
743
|
+
raise MemoryToolError(
|
|
744
|
+
"Error: claims retire through review, not deletion; edit the file to propose a correction."
|
|
745
|
+
)
|
|
746
|
+
entry = self._entry(location, text=False)
|
|
747
|
+
self._purge(entry)
|
|
748
|
+
return f"Successfully deleted {path} ({len(entry['versions'])} version(s) purged)"
|
|
749
|
+
|
|
750
|
+
def _administrator(self) -> None:
|
|
751
|
+
if "admin" not in self.files.client.context()["capabilities"]:
|
|
752
|
+
raise MemoryToolError(
|
|
753
|
+
"Error: memory is evidence; deleting or renaming it needs an administrator "
|
|
754
|
+
"credential. Replace the file's content instead; earlier versions stay on record."
|
|
755
|
+
)
|
|
756
|
+
|
|
757
|
+
def _purge(self, entry: dict[str, Any]) -> None:
|
|
758
|
+
self._administrator()
|
|
759
|
+
for version in entry["versions"]:
|
|
760
|
+
self.files.client.purge(version["id"])
|
|
761
|
+
|
|
762
|
+
def rename(self, command: Any) -> str:
|
|
763
|
+
source = locate(field(command, "old_path"), self.project)
|
|
764
|
+
target = locate(field(command, "new_path"), self.project)
|
|
765
|
+
old, new = source.path(self.project), target.path(self.project)
|
|
766
|
+
if source.kind != "file" or source.claim:
|
|
767
|
+
raise MemoryToolError(f"Error: {old} cannot be renamed; only notes can.")
|
|
768
|
+
if target.kind != "file" or target.claim:
|
|
769
|
+
raise MemoryToolError(f"Error: {new} is not a note path.")
|
|
770
|
+
entry = self._entry(source, text=True)
|
|
771
|
+
if self.files.observation(target.source or "", target.name or "", text=False) is not None:
|
|
772
|
+
raise MemoryToolError(f"Error: The destination {new} already exists")
|
|
773
|
+
self._administrator()
|
|
774
|
+
self.files.capture(target.source or "", target.name or "", entry["text"], [])
|
|
775
|
+
self._purge(entry)
|
|
776
|
+
return f"Successfully renamed {old} to {new}"
|