benchside 0.4.1__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.
- benchside/__init__.py +1 -0
- benchside/_content/app/SKILL.md +155 -0
- benchside/_content/app/references/app-api.md +261 -0
- benchside/_content/app/references/generic-agents.md +69 -0
- benchside/_content/app/references/metascience.md +346 -0
- benchside/_content/app/references/native-memory.md +429 -0
- benchside/_content/app/references/onboarding.md +313 -0
- benchside/_content/app/references/sharing.md +159 -0
- benchside/_content/app/scripts/benchside_app.py +311 -0
- benchside/_content/app-requirements.txt +197 -0
- benchside/_content/claude/bench-init/SKILL.md +37 -0
- benchside/_content/claude/bench-share/SKILL.md +44 -0
- benchside/_content/fixtures/.gitkeep +0 -0
- benchside/_content/legacy-skill-digests.json +26 -0
- benchside/_content/personas/journal-club.yaml +45 -0
- benchside/_content/personas/methods-clinic.yaml +49 -0
- benchside/_content/personas/peer-review.yaml +45 -0
- benchside/_content/personas/pi-hypothesis.yaml +121 -0
- benchside/_content/personas/pi.yaml +87 -0
- benchside/_content/personas/repro-check.yaml +45 -0
- benchside/_content/personas/results-meeting.yaml +46 -0
- benchside/_content/personas/study-design.yaml +50 -0
- benchside/_content/templates/app-role.md.tmpl +31 -0
- benchside/_content/templates/blocks/capture-contract.md +40 -0
- benchside/_content/templates/blocks/sovereignty.md +36 -0
- benchside/_content/templates/skill.md.tmpl +54 -0
- benchside/application/__init__.py +0 -0
- benchside/application/app.py +458 -0
- benchside/application/bridge.py +55 -0
- benchside/application/contributions.py +39 -0
- benchside/application/di.py +35 -0
- benchside/application/metascience.py +671 -0
- benchside/application/native.py +1088 -0
- benchside/application/packaging.py +19 -0
- benchside/application/sharing.py +439 -0
- benchside/application/submission_failures.py +28 -0
- benchside/cli/__init__.py +0 -0
- benchside/cli/hooks.py +159 -0
- benchside/cli/install.py +276 -0
- benchside/cli/journal.py +232 -0
- benchside/cli/main.py +761 -0
- benchside/cli/runtime.py +245 -0
- benchside/cli/sharing.py +66 -0
- benchside/cli/ui/__init__.py +5 -0
- benchside/cli/ui/_glyphs.py +21 -0
- benchside/cli/ui/_model.py +66 -0
- benchside/cli/ui/_renderer.py +110 -0
- benchside/cli/ui/_rich.py +75 -0
- benchside/config.py +122 -0
- benchside/domain/__init__.py +0 -0
- benchside/domain/authoring/__init__.py +0 -0
- benchside/domain/authoring/command/__init__.py +0 -0
- benchside/domain/authoring/command/compile.py +28 -0
- benchside/domain/authoring/model/__init__.py +0 -0
- benchside/domain/authoring/model/flow.py +27 -0
- benchside/domain/authoring/model/persona.py +56 -0
- benchside/domain/authoring/model/skill.py +32 -0
- benchside/domain/authoring/model/value.py +42 -0
- benchside/domain/authoring/port/__init__.py +5 -0
- benchside/domain/authoring/port/renderer.py +17 -0
- benchside/domain/authoring/port/repository.py +28 -0
- benchside/domain/authoring/port/skill_writer.py +19 -0
- benchside/domain/authoring/query/__init__.py +0 -0
- benchside/domain/authoring/query/get_persona.py +30 -0
- benchside/domain/authoring/query/list_personas.py +21 -0
- benchside/domain/authoring/service/__init__.py +0 -0
- benchside/domain/authoring/service/authoring.py +99 -0
- benchside/domain/authoring/util/__init__.py +0 -0
- benchside/domain/authoring/util/di/__init__.py +3 -0
- benchside/domain/authoring/util/di/provider.py +15 -0
- benchside/domain/consultation/__init__.py +0 -0
- benchside/domain/consultation/command/__init__.py +0 -0
- benchside/domain/consultation/command/capture_gap.py +28 -0
- benchside/domain/consultation/command/close.py +29 -0
- benchside/domain/consultation/command/open.py +36 -0
- benchside/domain/consultation/command/raise_critique.py +30 -0
- benchside/domain/consultation/command/record_decision.py +30 -0
- benchside/domain/consultation/command/resolve_critique.py +32 -0
- benchside/domain/consultation/command/state_hypothesis.py +28 -0
- benchside/domain/consultation/event/__init__.py +22 -0
- benchside/domain/consultation/event/closed.py +13 -0
- benchside/domain/consultation/event/critique_raised.py +12 -0
- benchside/domain/consultation/event/critique_resolved.py +12 -0
- benchside/domain/consultation/event/decision_recorded.py +13 -0
- benchside/domain/consultation/event/gap_observed.py +16 -0
- benchside/domain/consultation/event/hypothesis_stated.py +12 -0
- benchside/domain/consultation/event/opened.py +23 -0
- benchside/domain/consultation/event/question.py +16 -0
- benchside/domain/consultation/event/research_recorded.py +9 -0
- benchside/domain/consultation/model/__init__.py +0 -0
- benchside/domain/consultation/model/consultation.py +60 -0
- benchside/domain/consultation/model/project.py +78 -0
- benchside/domain/consultation/model/value.py +150 -0
- benchside/domain/consultation/port/__init__.py +6 -0
- benchside/domain/consultation/port/repository.py +32 -0
- benchside/domain/consultation/query/__init__.py +0 -0
- benchside/domain/consultation/query/get_consultation.py +28 -0
- benchside/domain/consultation/query/recall_project.py +97 -0
- benchside/domain/consultation/service/__init__.py +0 -0
- benchside/domain/consultation/service/consultation.py +373 -0
- benchside/domain/consultation/util/__init__.py +0 -0
- benchside/domain/consultation/util/di/__init__.py +3 -0
- benchside/domain/consultation/util/di/provider.py +33 -0
- benchside/domain/export/__init__.py +0 -0
- benchside/domain/export/command/__init__.py +0 -0
- benchside/domain/export/command/export_observations.py +31 -0
- benchside/domain/export/command/grant_consent.py +26 -0
- benchside/domain/export/command/revoke_consent.py +20 -0
- benchside/domain/export/event/__init__.py +19 -0
- benchside/domain/export/event/consent_granted.py +9 -0
- benchside/domain/export/event/consent_revoked.py +8 -0
- benchside/domain/export/event/observations_exported.py +12 -0
- benchside/domain/export/event/reporting.py +24 -0
- benchside/domain/export/model/__init__.py +0 -0
- benchside/domain/export/model/ledger.py +40 -0
- benchside/domain/export/model/metascience.py +418 -0
- benchside/domain/export/model/reporting.py +193 -0
- benchside/domain/export/model/value.py +79 -0
- benchside/domain/export/model/wire.py +104 -0
- benchside/domain/export/port/__init__.py +5 -0
- benchside/domain/export/port/redactor.py +27 -0
- benchside/domain/export/port/repository.py +25 -0
- benchside/domain/export/port/sink.py +19 -0
- benchside/domain/export/query/__init__.py +0 -0
- benchside/domain/export/query/consent_status.py +30 -0
- benchside/domain/export/query/preview_export.py +37 -0
- benchside/domain/export/service/__init__.py +0 -0
- benchside/domain/export/service/consent.py +53 -0
- benchside/domain/export/service/export.py +171 -0
- benchside/domain/export/service/reporting.py +281 -0
- benchside/domain/export/util/__init__.py +0 -0
- benchside/domain/export/util/di/__init__.py +3 -0
- benchside/domain/export/util/di/provider.py +22 -0
- benchside/domain/shared/__init__.py +0 -0
- benchside/domain/shared/command.py +44 -0
- benchside/domain/shared/error.py +51 -0
- benchside/domain/shared/event.py +46 -0
- benchside/domain/shared/model/__init__.py +31 -0
- benchside/domain/shared/model/aggregate.py +9 -0
- benchside/domain/shared/model/capture.py +33 -0
- benchside/domain/shared/model/entity.py +5 -0
- benchside/domain/shared/model/gap.py +89 -0
- benchside/domain/shared/model/ids.py +64 -0
- benchside/domain/shared/model/provenance.py +16 -0
- benchside/domain/shared/model/value.py +17 -0
- benchside/domain/shared/port/__init__.py +4 -0
- benchside/domain/shared/port/base.py +9 -0
- benchside/domain/shared/port/journal.py +36 -0
- benchside/domain/shared/query.py +42 -0
- benchside/domain/shared/service.py +31 -0
- benchside/infrastructure/__init__.py +9 -0
- benchside/infrastructure/content/__init__.py +0 -0
- benchside/infrastructure/content/loader.py +108 -0
- benchside/infrastructure/content/renderer.py +129 -0
- benchside/infrastructure/content/writer.py +26 -0
- benchside/infrastructure/files.py +43 -0
- benchside/infrastructure/http_sink.py +128 -0
- benchside/infrastructure/journal/__init__.py +0 -0
- benchside/infrastructure/journal/di.py +85 -0
- benchside/infrastructure/journal/projection.py +244 -0
- benchside/infrastructure/journal/registry.py +24 -0
- benchside/infrastructure/journal/store.py +134 -0
- benchside/infrastructure/placeholders.py +28 -0
- benchside/infrastructure/readable_records.py +211 -0
- benchside/infrastructure/readable_refresh.py +58 -0
- benchside/infrastructure/redaction.py +44 -0
- benchside/infrastructure/session_context.py +225 -0
- benchside/infrastructure/storage_layout.py +104 -0
- benchside/reporting.py +333 -0
- benchside/util/__init__.py +0 -0
- benchside/util/di/__init__.py +4 -0
- benchside/util/di/base.py +16 -0
- benchside/util/di/scope.py +18 -0
- benchside-0.4.1.dist-info/METADATA +97 -0
- benchside-0.4.1.dist-info/RECORD +178 -0
- benchside-0.4.1.dist-info/WHEEL +4 -0
- benchside-0.4.1.dist-info/entry_points.txt +2 -0
- benchside-0.4.1.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
"""Private, rebuildable ODT/Markdown views of the complete saved project journal."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import io
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import zipfile
|
|
9
|
+
from datetime import UTC, datetime
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from xml.etree import ElementTree as ET
|
|
12
|
+
|
|
13
|
+
from benchside.domain.shared.error import ValidationError
|
|
14
|
+
from benchside.domain.shared.model.ids import user_project_id
|
|
15
|
+
from benchside.infrastructure.files import atomic_bytes, atomic_json
|
|
16
|
+
|
|
17
|
+
ODT_TYPE = "application/vnd.oasis.opendocument.text"
|
|
18
|
+
FORMATS = ("odt", "markdown", "both")
|
|
19
|
+
NS = {
|
|
20
|
+
"office": "urn:oasis:names:tc:opendocument:xmlns:office:1.0",
|
|
21
|
+
"text": "urn:oasis:names:tc:opendocument:xmlns:text:1.0",
|
|
22
|
+
"style": "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
|
|
23
|
+
"fo": "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
|
|
24
|
+
"manifest": "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0",
|
|
25
|
+
}
|
|
26
|
+
for prefix, uri in NS.items():
|
|
27
|
+
ET.register_namespace(prefix, uri)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def tag(prefix, name):
|
|
31
|
+
return f"{{{NS[prefix]}}}{name}"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def xml(node):
|
|
35
|
+
return ET.tostring(node, encoding="utf-8", xml_declaration=True)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _text(element, value):
|
|
39
|
+
# ODF requires explicit elements for repeated spaces, tabs and line breaks.
|
|
40
|
+
value = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff\ufffe\uffff]", "�", str(value))
|
|
41
|
+
tail = None
|
|
42
|
+
for part in re.split(r"( {2,}|\t|\n)", value):
|
|
43
|
+
if part == "\n":
|
|
44
|
+
tail = ET.SubElement(element, tag("text", "line-break"))
|
|
45
|
+
elif part == "\t":
|
|
46
|
+
tail = ET.SubElement(element, tag("text", "tab"))
|
|
47
|
+
elif len(part) > 1 and not part.strip():
|
|
48
|
+
tail = ET.SubElement(element, tag("text", "s"), {tag("text", "c"): str(len(part))})
|
|
49
|
+
elif tail is None:
|
|
50
|
+
element.text = (element.text or "") + part
|
|
51
|
+
else:
|
|
52
|
+
tail.tail = (tail.tail or "") + part
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def odt_bytes(blocks):
|
|
56
|
+
root = ET.Element(tag("office", "document-content"), {tag("office", "version"): "1.2"})
|
|
57
|
+
body = ET.SubElement(ET.SubElement(root, tag("office", "body")), tag("office", "text"))
|
|
58
|
+
for level, text in blocks:
|
|
59
|
+
attributes = {tag("text", "outline-level"): str(level)} if level else {}
|
|
60
|
+
_text(ET.SubElement(body, tag("text", "h" if level else "p"), attributes), text)
|
|
61
|
+
styles = ET.Element(tag("office", "document-styles"), {tag("office", "version"): "1.2"})
|
|
62
|
+
defaults = ET.SubElement(ET.SubElement(styles, tag("office", "styles")), tag("style", "default-style"), {tag("style", "family"): "paragraph"})
|
|
63
|
+
ET.SubElement(defaults, tag("style", "paragraph-properties"), {tag("fo", "margin-bottom"): "0.12in"})
|
|
64
|
+
ET.SubElement(defaults, tag("style", "text-properties"), {tag("fo", "font-size"): "11pt", tag("fo", "font-family"): "Liberation Sans"})
|
|
65
|
+
manifest = ET.Element(tag("manifest", "manifest"), {tag("manifest", "version"): "1.2"})
|
|
66
|
+
for path, media in [("/", ODT_TYPE), ("content.xml", "text/xml"), ("styles.xml", "text/xml")]:
|
|
67
|
+
ET.SubElement(manifest, tag("manifest", "file-entry"), {tag("manifest", "full-path"): path, tag("manifest", "media-type"): media})
|
|
68
|
+
output = io.BytesIO()
|
|
69
|
+
with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as archive:
|
|
70
|
+
archive.writestr("mimetype", ODT_TYPE, compress_type=zipfile.ZIP_STORED)
|
|
71
|
+
archive.writestr("content.xml", xml(root))
|
|
72
|
+
archive.writestr("styles.xml", xml(styles))
|
|
73
|
+
archive.writestr("META-INF/manifest.xml", xml(manifest))
|
|
74
|
+
return output.getvalue()
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _fields(value, prefix=""):
|
|
78
|
+
for key, item in value.items():
|
|
79
|
+
if item is None:
|
|
80
|
+
continue
|
|
81
|
+
label = (prefix + " / " if prefix else "") + key.replace("_", " ").capitalize()
|
|
82
|
+
if isinstance(item, dict):
|
|
83
|
+
yield from _fields(item, label)
|
|
84
|
+
elif isinstance(item, list):
|
|
85
|
+
for index, child in enumerate(item, 1):
|
|
86
|
+
if isinstance(child, dict):
|
|
87
|
+
yield from _fields(child, f"{label} {index}")
|
|
88
|
+
else:
|
|
89
|
+
yield f"{label}: {child}"
|
|
90
|
+
else:
|
|
91
|
+
yield f"{label}: {item}"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def preferences(paths):
|
|
95
|
+
if paths.store_root is None:
|
|
96
|
+
raise ValidationError("Document format preferences need durable local storage; cloud documents use the host's supported format")
|
|
97
|
+
path = paths.home / "records-preferences.json"
|
|
98
|
+
if not path.exists():
|
|
99
|
+
return {"format": "odt", "configured": False}
|
|
100
|
+
value = json.loads(path.read_text())
|
|
101
|
+
if not isinstance(value, dict) or set(value) != {"format"} or value["format"] not in FORMATS:
|
|
102
|
+
raise ValidationError("Invalid readable document preference; choose odt, markdown or both again")
|
|
103
|
+
return {**value, "configured": True}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def configure(paths, document_format):
|
|
107
|
+
if paths.store_root is None:
|
|
108
|
+
raise ValidationError("Document format preferences need durable local storage; cloud documents use the host's supported format")
|
|
109
|
+
if not isinstance(document_format, str) or document_format not in FORMATS:
|
|
110
|
+
raise ValidationError("Choose document format odt, markdown or both")
|
|
111
|
+
atomic_json(paths.home / "records-preferences.json", {"format": document_format})
|
|
112
|
+
return {"format": document_format, "configured": True}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def export_project(paths, journal, project_id):
|
|
116
|
+
project_id = user_project_id(project_id)
|
|
117
|
+
if paths.store_root is None:
|
|
118
|
+
raise ValidationError("Readable file export needs durable local storage; use the cloud host's document export instead")
|
|
119
|
+
document_format = preferences(paths)["format"]
|
|
120
|
+
from benchside.domain.consultation.query.recall_project import describe_target
|
|
121
|
+
from benchside.infrastructure.journal.projection import JournalProjectRepository
|
|
122
|
+
|
|
123
|
+
config = paths.home / "app-projects" / f"{project_id.root}.json"
|
|
124
|
+
project = JournalProjectRepository(journal).get(project_id)
|
|
125
|
+
if project is None and not config.exists():
|
|
126
|
+
raise ValidationError("Project not found")
|
|
127
|
+
title = json.loads(config.read_text()).get("title") if config.exists() else None
|
|
128
|
+
title = title or project_id.root
|
|
129
|
+
index_path = paths.home / "readable-index.json"
|
|
130
|
+
index = json.loads(index_path.read_text()) if index_path.exists() else {}
|
|
131
|
+
if not isinstance(index, dict):
|
|
132
|
+
raise ValidationError("Invalid readable project index; preserve the journal and rebuild this index")
|
|
133
|
+
label = re.sub(r'[^\w .()-]+', ' ', title, flags=re.UNICODE).strip(' .')[:80] or "Research project"
|
|
134
|
+
label = label.encode("utf-8")[:180].decode("utf-8", errors="ignore").rstrip(" .")
|
|
135
|
+
suffix = hashlib.sha256(project_id.root.encode()).hexdigest()[:10]
|
|
136
|
+
folder_name = f"{label} — {suffix}"
|
|
137
|
+
previous_name = index.get(project_id.root, folder_name)
|
|
138
|
+
if not isinstance(previous_name, str) or Path(previous_name).name != previous_name or previous_name in {".", ".."}:
|
|
139
|
+
raise ValidationError("Invalid readable project folder; rebuild the private readable index")
|
|
140
|
+
root = paths.store_root.resolve()
|
|
141
|
+
folder = root / "researcher" / "projects" / folder_name
|
|
142
|
+
previous = folder.parent / previous_name
|
|
143
|
+
if any((directory / ".git").exists() for destination in (folder, previous)
|
|
144
|
+
for directory in (destination, *destination.parents)):
|
|
145
|
+
raise ValidationError("Readable research records must also stay outside Git")
|
|
146
|
+
# Do not follow a human-created symlink into a public/other directory.
|
|
147
|
+
if any(p.is_symlink() for p in (root / "researcher", root / "researcher/projects", folder, previous)):
|
|
148
|
+
raise ValidationError("Readable record folders must not be symlinks")
|
|
149
|
+
if previous != folder and previous.exists():
|
|
150
|
+
if folder.exists():
|
|
151
|
+
raise ValidationError("Both old and new readable project folders exist; resolve the conflict before renaming")
|
|
152
|
+
previous.rename(folder)
|
|
153
|
+
index[project_id.root] = folder_name
|
|
154
|
+
atomic_json(index_path, index)
|
|
155
|
+
folder.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
156
|
+
for directory in (root / "researcher", root / "researcher/projects", folder):
|
|
157
|
+
os.chmod(directory, 0o700)
|
|
158
|
+
events = list(journal.read_envelopes(project_id))
|
|
159
|
+
blocks = [
|
|
160
|
+
(1, title),
|
|
161
|
+
(0, "Private Benchside research record"),
|
|
162
|
+
(0, f"Updated {datetime.now(UTC).isoformat(timespec='seconds')} · {len(events)} saved events"),
|
|
163
|
+
(0, "This is a generated reading copy of the complete saved project record. Edits here are not imported into Benchside. Ask your agent to record corrections; these files are refreshed from the private journal. Nothing is sent to Science Works by creating this copy."),
|
|
164
|
+
(1, "Where things stand"),
|
|
165
|
+
]
|
|
166
|
+
if project:
|
|
167
|
+
current = project.current_hypothesis
|
|
168
|
+
if current:
|
|
169
|
+
blocks.append((0, "Current hypothesis: " + current.statement))
|
|
170
|
+
blocks.append((2, "Unresolved research questions"))
|
|
171
|
+
questions = [q.question for q in project.questions if q.answer is None]
|
|
172
|
+
blocks.extend((0, q) for q in questions)
|
|
173
|
+
if not questions:
|
|
174
|
+
blocks.append((0, "None recorded."))
|
|
175
|
+
blocks.append((2, "Open critiques"))
|
|
176
|
+
critiques = [describe_target(c.target) for c in project.critiques if c.is_open]
|
|
177
|
+
blocks.extend((0, c) for c in critiques)
|
|
178
|
+
if not critiques:
|
|
179
|
+
blocks.append((0, "None recorded."))
|
|
180
|
+
blocks.append((2, "Current decisions"))
|
|
181
|
+
superseded = {d.supersedes for d in project.decisions if d.supersedes}
|
|
182
|
+
for decision in project.decisions:
|
|
183
|
+
if decision.id not in superseded:
|
|
184
|
+
blocks.extend([(0, decision.decision), (0, "Reason: " + decision.rationale)])
|
|
185
|
+
else:
|
|
186
|
+
blocks.append((0, "No scientific records yet."))
|
|
187
|
+
blocks.append((1, "Complete saved history"))
|
|
188
|
+
for number, event in enumerate(events, 1):
|
|
189
|
+
data = dict(event.get("data", {}))
|
|
190
|
+
recorded = data.pop("recorded_at", "Date not recorded")
|
|
191
|
+
kind = re.sub(r"(?<!^)(?=[A-Z])", " ", event.get("type", "Record"))
|
|
192
|
+
blocks.append((2, f"{number}. {kind} — {recorded}"))
|
|
193
|
+
blocks.extend((0, text) for text in _fields(data))
|
|
194
|
+
if not events:
|
|
195
|
+
blocks.append((0, "Nothing recorded yet."))
|
|
196
|
+
markdown = "\n\n".join(("#" * level + " " + text) if level else "\n".join("> " + line for line in str(text).splitlines()) for level, text in blocks) + "\n"
|
|
197
|
+
odt = folder / "Research record.odt"
|
|
198
|
+
md = folder / "Research record.md"
|
|
199
|
+
result = {"format": document_format, "events": len(events), "generated_view": True}
|
|
200
|
+
if document_format in {"odt", "both"}:
|
|
201
|
+
atomic_bytes(odt, odt_bytes(blocks))
|
|
202
|
+
result["odt"] = str(odt)
|
|
203
|
+
if document_format in {"markdown", "both"}:
|
|
204
|
+
atomic_bytes(md, markdown.encode())
|
|
205
|
+
result["markdown"] = str(md)
|
|
206
|
+
# Preserve earlier copies (and any reader edits) when the preference changes.
|
|
207
|
+
# Only return the files refreshed by this export.
|
|
208
|
+
retained = [str(path) for key, path in (("odt", odt), ("markdown", md)) if key not in result and path.exists()]
|
|
209
|
+
if retained:
|
|
210
|
+
result["previous_copies_not_refreshed"] = retained
|
|
211
|
+
return result
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Refresh derived reading copies once per changed project at a command boundary."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from contextlib import contextmanager
|
|
5
|
+
from contextvars import ContextVar
|
|
6
|
+
|
|
7
|
+
logger = logging.getLogger(__name__)
|
|
8
|
+
_active = ContextVar("benchside_readable_refresh", default=None)
|
|
9
|
+
WARNING = (
|
|
10
|
+
"The scientific record was saved, but its readable ODT/Markdown copy could not be "
|
|
11
|
+
"refreshed. Retry records.export; do not repeat the recording action."
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class RefreshBatch:
|
|
16
|
+
def __init__(self):
|
|
17
|
+
self.pending = {}
|
|
18
|
+
self.results = {}
|
|
19
|
+
self.warning = None
|
|
20
|
+
|
|
21
|
+
def mark(self, paths, journal, project_id):
|
|
22
|
+
if paths.store_root and project_id not in {"consent-ledger", "reporting-ledger"}:
|
|
23
|
+
self.pending[(paths.home.resolve(), project_id)] = (paths, journal)
|
|
24
|
+
|
|
25
|
+
def flush(self):
|
|
26
|
+
from benchside.infrastructure.readable_records import export_project
|
|
27
|
+
|
|
28
|
+
for key, (paths, journal) in self.pending.items():
|
|
29
|
+
try:
|
|
30
|
+
self.results[key] = export_project(paths, journal, key[1])
|
|
31
|
+
except Exception as error: # noqa: BLE001 - the authoritative save already succeeded
|
|
32
|
+
self.warning = journal.readable_records_warning = WARNING
|
|
33
|
+
logger.warning("Readable record refresh failed (%s)", type(error).__name__)
|
|
34
|
+
self.pending.clear()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def mark_readable(paths, journal, project_id):
|
|
38
|
+
batch = _active.get()
|
|
39
|
+
if batch is not None:
|
|
40
|
+
batch.mark(paths, journal, project_id)
|
|
41
|
+
else:
|
|
42
|
+
# Direct journal callers have no command boundary; retain their refresh.
|
|
43
|
+
batch = RefreshBatch()
|
|
44
|
+
batch.mark(paths, journal, project_id)
|
|
45
|
+
batch.flush()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@contextmanager
|
|
49
|
+
def readable_refresh():
|
|
50
|
+
batch = RefreshBatch()
|
|
51
|
+
token = _active.set(batch)
|
|
52
|
+
try:
|
|
53
|
+
yield batch
|
|
54
|
+
finally:
|
|
55
|
+
try:
|
|
56
|
+
batch.flush() # Refresh even if a later step fails after durable appends.
|
|
57
|
+
finally:
|
|
58
|
+
_active.reset(token)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Conservative identifier scrubbing; human review is still required for free text."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
from benchside.domain.export.port.redactor import Finding
|
|
7
|
+
|
|
8
|
+
_PATTERNS = (
|
|
9
|
+
("email", re.compile(r"\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b", re.IGNORECASE)),
|
|
10
|
+
("local-path", re.compile(r"(?:/(?:Users|home)/[^\s\"<>]+|[A-Z]:\\Users\\[^\s\"<>]+)")),
|
|
11
|
+
("credential", re.compile(r"\b(?:sk-|ghp_|github_pat_)[A-Za-z0-9_-]{12,}\b")),
|
|
12
|
+
("url", re.compile(r"https?://[^\s\"<>]+")),
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class TextRedactor:
|
|
17
|
+
def apply(self, payload: str) -> str:
|
|
18
|
+
data = json.loads(payload)
|
|
19
|
+
|
|
20
|
+
def scrub(value):
|
|
21
|
+
if isinstance(value, str):
|
|
22
|
+
for label, pattern in _PATTERNS:
|
|
23
|
+
value = pattern.sub(f"[removed {label}]", value)
|
|
24
|
+
elif isinstance(value, list):
|
|
25
|
+
value = [scrub(item) for item in value]
|
|
26
|
+
elif isinstance(value, dict):
|
|
27
|
+
value = {key: scrub(item) for key, item in value.items()}
|
|
28
|
+
return value
|
|
29
|
+
|
|
30
|
+
# Only research-workflow text and feedback text are scrubbed. IDs,
|
|
31
|
+
# schema names and controlled metadata must remain byte-for-byte values.
|
|
32
|
+
for observation in data.get("observations", []):
|
|
33
|
+
observation["gap"] = scrub(observation["gap"])
|
|
34
|
+
if "feedback" in data:
|
|
35
|
+
data["feedback"]["comment"] = scrub(data["feedback"]["comment"])
|
|
36
|
+
return json.dumps(data, ensure_ascii=False, indent=2)
|
|
37
|
+
|
|
38
|
+
def scan(self, payload: str) -> list[Finding]:
|
|
39
|
+
# Patterns cannot detect names, unpublished results, or indirect identity.
|
|
40
|
+
return [
|
|
41
|
+
Finding(tier="HIGH", category=label, field="shared text")
|
|
42
|
+
for label, pattern in _PATTERNS
|
|
43
|
+
if pattern.search(payload)
|
|
44
|
+
]
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"""Which Claude session is this?
|
|
2
|
+
|
|
3
|
+
Claude Code does not export the session id to Bash subprocesses, so `bench`
|
|
4
|
+
cannot see it directly. The SessionStart hook — which does receive it —
|
|
5
|
+
registers it in a per-project file; everything bench writes is stamped from
|
|
6
|
+
there. CLAUDE_SESSION_ID still wins when set (tests, scripted use).
|
|
7
|
+
|
|
8
|
+
The registered id is also what links a journal entry to its conversation:
|
|
9
|
+
the archived transcript is `transcripts/<stamp>-<session_id>.jsonl`, and the
|
|
10
|
+
same id names Claude Code's own record in ~/.claude/projects/.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import math
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
import shlex
|
|
18
|
+
import time
|
|
19
|
+
from contextlib import contextmanager
|
|
20
|
+
from contextvars import ContextVar
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
from benchside.config import Paths
|
|
24
|
+
from benchside.domain.shared.error import InvalidStateError
|
|
25
|
+
from benchside.domain.shared.model.ids import ProjectId
|
|
26
|
+
from benchside.domain.shared.model.provenance import AppProvenance
|
|
27
|
+
from benchside.infrastructure.files import atomic_json, file_lock
|
|
28
|
+
|
|
29
|
+
_recording_context: ContextVar[tuple[str | None, AppProvenance] | None] = ContextVar(
|
|
30
|
+
"benchside_recording_context", default=None
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
# Anonymous fallback expires after 24 hours without explicit activity.
|
|
34
|
+
# Explicit activity refreshes only a known registration, never an ended one.
|
|
35
|
+
_REGISTRATION_LIFETIME_SECONDS = 24 * 60 * 60
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@contextmanager
|
|
39
|
+
def recording_context(*, provenance: AppProvenance, session_id: str | None = None):
|
|
40
|
+
"""Bind one caller's context without changing another thread's environment."""
|
|
41
|
+
if session_id is not None:
|
|
42
|
+
validate_session_id(session_id)
|
|
43
|
+
token = _recording_context.set((session_id, provenance))
|
|
44
|
+
try:
|
|
45
|
+
yield
|
|
46
|
+
finally:
|
|
47
|
+
_recording_context.reset(token)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def current_provenance() -> AppProvenance | None:
|
|
51
|
+
context = _recording_context.get()
|
|
52
|
+
return context[1] if context else None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def validate_session_id(value: str) -> str:
|
|
56
|
+
if not isinstance(value, str) or not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}", value):
|
|
57
|
+
raise InvalidStateError("Invalid session identifier")
|
|
58
|
+
return value
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _session_file(paths: Paths, project_id: ProjectId):
|
|
62
|
+
return paths.home / "projects" / project_id.root / "current-session"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def register_session(paths: Paths, project_id: ProjectId, session_id: str) -> None:
|
|
66
|
+
validate_session_id(session_id)
|
|
67
|
+
# Each Claude session has its own environment file. This avoids the
|
|
68
|
+
# last-started-session race of a shared per-project current-session file.
|
|
69
|
+
env_file = os.environ.get("CLAUDE_ENV_FILE")
|
|
70
|
+
if env_file:
|
|
71
|
+
with Path(env_file).open("a", encoding="utf-8") as handle:
|
|
72
|
+
handle.write(f"\nexport CLAUDE_SESSION_ID={shlex.quote(session_id)}\n")
|
|
73
|
+
# The registry is only a fallback. A damaged registry must not prevent
|
|
74
|
+
# Claude from giving this conversation its explicit, authoritative ID.
|
|
75
|
+
path = _session_file(paths, project_id)
|
|
76
|
+
with file_lock(path.with_suffix(".lock")):
|
|
77
|
+
sessions = _registered(path)
|
|
78
|
+
sessions[session_id] = time.time()
|
|
79
|
+
_prune_expired(paths, project_id, sessions)
|
|
80
|
+
_save_registered(path, sessions)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def clear_session(paths: Paths, project_id: ProjectId, session_id: str) -> None:
|
|
84
|
+
"""Retire only this project's named conversation; preserve its journal."""
|
|
85
|
+
validate_session_id(session_id)
|
|
86
|
+
path = _session_file(paths, project_id)
|
|
87
|
+
with file_lock(path.with_suffix(".lock")):
|
|
88
|
+
sessions = _registered(path)
|
|
89
|
+
retire_session_pointer(paths, session_id, project_id=project_id)
|
|
90
|
+
sessions.pop(session_id, None)
|
|
91
|
+
_save_registered(path, sessions)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def clear_project_sessions(paths: Paths, project_id: ProjectId) -> None:
|
|
95
|
+
"""Remove fallback registrations, preserving explicitly addressed conversations."""
|
|
96
|
+
path = _session_file(paths, project_id)
|
|
97
|
+
with file_lock(path.with_suffix(".lock")):
|
|
98
|
+
path.unlink(missing_ok=True)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def retire_session_pointer(
|
|
102
|
+
paths: Paths, session_id: str, *, project_id: ProjectId | None = None
|
|
103
|
+
) -> dict | None:
|
|
104
|
+
"""Keep unfinished work available for explicit resumption, never adoption."""
|
|
105
|
+
validate_session_id(session_id)
|
|
106
|
+
path = paths.home / "sessions" / f"{session_id}.json"
|
|
107
|
+
with file_lock(path.with_suffix(".lock")):
|
|
108
|
+
if not path.is_file():
|
|
109
|
+
return None
|
|
110
|
+
try:
|
|
111
|
+
record = json.loads(path.read_text(encoding="utf-8"))
|
|
112
|
+
except json.JSONDecodeError:
|
|
113
|
+
record = {}
|
|
114
|
+
if not isinstance(record, dict):
|
|
115
|
+
record = {}
|
|
116
|
+
if project_id is not None and record.get("project_id") != project_id.root:
|
|
117
|
+
return None
|
|
118
|
+
path.replace(path.with_suffix(".ended"))
|
|
119
|
+
return record
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def current_session(paths: Paths, project_id: ProjectId) -> str | None:
|
|
123
|
+
context = _recording_context.get()
|
|
124
|
+
if context and context[0] is not None:
|
|
125
|
+
_refresh_registered(paths, project_id, context[0])
|
|
126
|
+
return context[0]
|
|
127
|
+
env = os.environ.get("BENCHSIDE_SESSION_ID") or os.environ.get("CLAUDE_SESSION_ID")
|
|
128
|
+
if env:
|
|
129
|
+
session_id = validate_session_id(env)
|
|
130
|
+
_refresh_registered(paths, project_id, session_id)
|
|
131
|
+
return session_id
|
|
132
|
+
path = _session_file(paths, project_id)
|
|
133
|
+
with file_lock(path.with_suffix(".lock")):
|
|
134
|
+
sessions = _registered(path)
|
|
135
|
+
if _prune_expired(paths, project_id, sessions):
|
|
136
|
+
_save_registered(path, sessions)
|
|
137
|
+
if len(sessions) > 1:
|
|
138
|
+
raise InvalidStateError(
|
|
139
|
+
"Several conversations are active; a session identifier is required to record safely",
|
|
140
|
+
hint=(
|
|
141
|
+
"Use this conversation's CLAUDE_SESSION_ID or BENCHSIDE_SESSION_ID. "
|
|
142
|
+
f"Registered IDs: {', '.join(sorted(sessions))}. If one has ended, ask your agent "
|
|
143
|
+
f"to run `bench session clear --project {shlex.quote(project_id.root)} "
|
|
144
|
+
"--session <ended-session-id>`. This preserves its research records."
|
|
145
|
+
),
|
|
146
|
+
)
|
|
147
|
+
return next(iter(sessions), None)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _refresh_registered(paths: Paths, project_id: ProjectId, session_id: str) -> None:
|
|
151
|
+
"""Keep explicit activity alive without enrolling another project/session."""
|
|
152
|
+
path = _session_file(paths, project_id)
|
|
153
|
+
if not path.is_file():
|
|
154
|
+
return
|
|
155
|
+
with file_lock(path.with_suffix(".lock")):
|
|
156
|
+
try:
|
|
157
|
+
sessions = _registered(path)
|
|
158
|
+
except InvalidStateError:
|
|
159
|
+
# Explicit identity still works while a damaged registry awaits
|
|
160
|
+
# repair. Never overwrite it or infer missing registrations.
|
|
161
|
+
return
|
|
162
|
+
if session_id in sessions:
|
|
163
|
+
sessions[session_id] = time.time()
|
|
164
|
+
_save_registered(path, sessions)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _registered(path: Path) -> dict[str, float]:
|
|
168
|
+
try:
|
|
169
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
170
|
+
if not isinstance(data, dict):
|
|
171
|
+
raise TypeError("expected a registration object")
|
|
172
|
+
names_raw = data.get("sessions", [])
|
|
173
|
+
if not isinstance(names_raw, list):
|
|
174
|
+
raise TypeError("sessions must be a list of conversation IDs")
|
|
175
|
+
# Older registrations had no timestamps. Their last file write is a
|
|
176
|
+
# bounded migration fallback, never renewed merely by reading them.
|
|
177
|
+
legacy_timestamp = path.stat().st_mtime
|
|
178
|
+
names = {validate_session_id(s) for s in names_raw} | (
|
|
179
|
+
{validate_session_id(data["session_id"])} if "session_id" in data else set()
|
|
180
|
+
)
|
|
181
|
+
timestamps = data.get("registered_at", {name: legacy_timestamp for name in names})
|
|
182
|
+
if not isinstance(timestamps, dict) or set(timestamps) != names:
|
|
183
|
+
raise ValueError("timestamps must match the registered conversation IDs")
|
|
184
|
+
result = {}
|
|
185
|
+
now = time.time()
|
|
186
|
+
for name in names:
|
|
187
|
+
timestamp = timestamps[name]
|
|
188
|
+
if (
|
|
189
|
+
isinstance(timestamp, bool)
|
|
190
|
+
or not isinstance(timestamp, (int, float))
|
|
191
|
+
or timestamp < 0
|
|
192
|
+
or timestamp > now + 300
|
|
193
|
+
or not math.isfinite(timestamp)
|
|
194
|
+
):
|
|
195
|
+
raise ValueError("timestamps must be finite Unix times with at most 5 minutes skew")
|
|
196
|
+
result[name] = min(float(timestamp), now)
|
|
197
|
+
return result
|
|
198
|
+
except FileNotFoundError:
|
|
199
|
+
return {}
|
|
200
|
+
except (TypeError, ValueError, InvalidStateError) as error:
|
|
201
|
+
raise InvalidStateError(
|
|
202
|
+
"Invalid Benchside conversation registrations; recording is paused",
|
|
203
|
+
hint=(
|
|
204
|
+
f"Ask your agent to inspect and repair {path}, preserving active conversation "
|
|
205
|
+
"IDs and their original timestamps. Do not delete scientific journals. "
|
|
206
|
+
"An explicit conversation ID can still identify the current conversation."
|
|
207
|
+
),
|
|
208
|
+
) from error
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _save_registered(path: Path, sessions: dict[str, float]) -> None:
|
|
212
|
+
if sessions:
|
|
213
|
+
atomic_json(path, {"sessions": sorted(sessions), "registered_at": sessions})
|
|
214
|
+
else:
|
|
215
|
+
path.unlink(missing_ok=True)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _prune_expired(paths: Paths, project_id: ProjectId, sessions: dict[str, float]) -> bool:
|
|
219
|
+
cutoff = time.time() - _REGISTRATION_LIFETIME_SECONDS
|
|
220
|
+
expired = [name for name, timestamp in sessions.items() if timestamp <= cutoff]
|
|
221
|
+
for name in expired:
|
|
222
|
+
# Expiry makes anonymous fallback unsafe; it does not mean the actual
|
|
223
|
+
# conversation ended. Its pointer remains accessible only by its ID.
|
|
224
|
+
del sessions[name]
|
|
225
|
+
return bool(expired)
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""An explicit local-store upgrade; native notebooks keep their existing format."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import shutil
|
|
7
|
+
import tempfile
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from benchside.domain.shared.error import ValidationError
|
|
11
|
+
from benchside.infrastructure.files import atomic_json, file_lock
|
|
12
|
+
|
|
13
|
+
MARKER = ".benchside-layout.json"
|
|
14
|
+
STATE_NAMES = ("projects", "sessions", "app-projects", "app-sessions", "reporting", "sharing", "metascience", "app-probe.json", "readable-index.json", "records-preferences.json")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _state_fingerprint(root):
|
|
18
|
+
"""Detect legacy/uncoordinated writers as well as cooperating lifecycle hooks."""
|
|
19
|
+
state = {}
|
|
20
|
+
for name in STATE_NAMES:
|
|
21
|
+
source = root / name
|
|
22
|
+
if not source.exists() and not source.is_symlink():
|
|
23
|
+
continue
|
|
24
|
+
for path in [source, *source.rglob("*")] if source.is_dir() else [source]:
|
|
25
|
+
if path.is_symlink():
|
|
26
|
+
raise ValidationError("Resolve symlinks in private state before organising storage")
|
|
27
|
+
state[str(path.relative_to(root))] = (
|
|
28
|
+
hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None
|
|
29
|
+
)
|
|
30
|
+
return state
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def organised(root):
|
|
34
|
+
marker = root / MARKER
|
|
35
|
+
if not marker.exists():
|
|
36
|
+
return False
|
|
37
|
+
if marker.is_symlink() or json.loads(marker.read_text()) != {"version": 1, "agent": "agent", "researcher": "researcher"}:
|
|
38
|
+
raise ValidationError("Invalid Benchside folder layout marker")
|
|
39
|
+
if (root / "agent").is_symlink():
|
|
40
|
+
raise ValidationError("Benchside agent storage must not be a symlink")
|
|
41
|
+
return True
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def initialise(root):
|
|
45
|
+
root = root.resolve()
|
|
46
|
+
if any((p / ".git").exists() for p in (root, *root.parents)):
|
|
47
|
+
raise ValidationError("Benchside storage must be outside Git")
|
|
48
|
+
if organised(root):
|
|
49
|
+
return
|
|
50
|
+
if (root / "agent").exists():
|
|
51
|
+
raise ValidationError("An agent folder already exists without a Benchside layout marker")
|
|
52
|
+
(root / "agent").mkdir(parents=True, mode=0o700)
|
|
53
|
+
atomic_json(root / MARKER, {"version": 1, "agent": "agent", "researcher": "researcher"})
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def organise(root, confirm_idle):
|
|
57
|
+
root = root.resolve()
|
|
58
|
+
if type(confirm_idle) is not bool or not confirm_idle:
|
|
59
|
+
raise ValidationError("Stop other agents using this store, then confirm_idle:true to organise it")
|
|
60
|
+
if any((p / ".git").exists() for p in (root, *root.parents)):
|
|
61
|
+
raise ValidationError("Benchside storage must be outside Git")
|
|
62
|
+
with file_lock(root / ".transaction.lock"), file_lock(root / ".layout.lock"):
|
|
63
|
+
if organised(root):
|
|
64
|
+
return {"agent": str(root / "agent"), "researcher": str(root / "researcher"), "migrated": False}
|
|
65
|
+
if (root / "agent").exists():
|
|
66
|
+
raise ValidationError("An agent folder already exists; preserve it and resolve the conflict before organising")
|
|
67
|
+
sources = [root / name for name in STATE_NAMES if (root / name).exists()]
|
|
68
|
+
original_state = _state_fingerprint(root)
|
|
69
|
+
for source in sources:
|
|
70
|
+
if source.is_symlink() or (source.is_dir() and any(p.is_symlink() for p in source.rglob("*"))):
|
|
71
|
+
raise ValidationError("Resolve symlinks in private state before organising storage")
|
|
72
|
+
# Copy and verify before switching paths. Originals remain as a private backup.
|
|
73
|
+
temporary = Path(tempfile.mkdtemp(prefix=".benchside-layout-", dir=root))
|
|
74
|
+
try:
|
|
75
|
+
for source in sources:
|
|
76
|
+
target = temporary / source.name
|
|
77
|
+
if source.is_dir():
|
|
78
|
+
shutil.copytree(source, target)
|
|
79
|
+
for file in source.rglob("*"):
|
|
80
|
+
if file.is_file() and file.read_bytes() != (target / file.relative_to(source)).read_bytes():
|
|
81
|
+
raise OSError("Storage copy verification failed")
|
|
82
|
+
else:
|
|
83
|
+
shutil.copy2(source, target)
|
|
84
|
+
if source.read_bytes() != target.read_bytes():
|
|
85
|
+
raise OSError("Storage copy verification failed")
|
|
86
|
+
if _state_fingerprint(root) != original_state:
|
|
87
|
+
raise ValidationError(
|
|
88
|
+
"Private state changed during folder organisation; originals are intact. "
|
|
89
|
+
"Stop other agents and retry."
|
|
90
|
+
)
|
|
91
|
+
os.rename(temporary, root / "agent")
|
|
92
|
+
try:
|
|
93
|
+
atomic_json(root / MARKER, {"version": 1, "agent": "agent", "researcher": "researcher"})
|
|
94
|
+
except OSError:
|
|
95
|
+
os.rename(root / "agent", temporary)
|
|
96
|
+
raise
|
|
97
|
+
backup = root / "agent" / "legacy-backup"
|
|
98
|
+
backup.mkdir(mode=0o700)
|
|
99
|
+
for source in sources:
|
|
100
|
+
os.rename(source, backup / source.name)
|
|
101
|
+
finally:
|
|
102
|
+
if temporary.exists():
|
|
103
|
+
shutil.rmtree(temporary)
|
|
104
|
+
return {"agent": str(root / "agent"), "researcher": str(root / "researcher"), "migrated": True, "backup": str(backup)}
|