math-research-ledger 1.5.2__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.
Files changed (103) hide show
  1. math_research/__init__.py +3 -0
  2. math_research/cli/__init__.py +1 -0
  3. math_research/cli/__main__.py +3 -0
  4. math_research/cli/main.py +337 -0
  5. math_research/core/__init__.py +1 -0
  6. math_research/core/atomicio.py +184 -0
  7. math_research/core/config.py +60 -0
  8. math_research/core/errors.py +59 -0
  9. math_research/core/hashing.py +18 -0
  10. math_research/core/integrity.py +24 -0
  11. math_research/core/jsonl.py +156 -0
  12. math_research/core/limits.py +3 -0
  13. math_research/core/migration.py +102 -0
  14. math_research/core/paths.py +132 -0
  15. math_research/core/process.py +211 -0
  16. math_research/core/redaction.py +11 -0
  17. math_research/core/refs.py +25 -0
  18. math_research/core/research_agents.md +42 -0
  19. math_research/core/textnorm.py +89 -0
  20. math_research/core/workspace.py +42 -0
  21. math_research/ledger/__init__.py +1 -0
  22. math_research/ledger/archive.py +257 -0
  23. math_research/ledger/assets.py +539 -0
  24. math_research/ledger/bindings.py +152 -0
  25. math_research/ledger/checkpoint.py +275 -0
  26. math_research/ledger/continuation.py +232 -0
  27. math_research/ledger/decomposition.py +227 -0
  28. math_research/ledger/dependencies.py +39 -0
  29. math_research/ledger/episodes.py +1221 -0
  30. math_research/ledger/epistemics.py +52 -0
  31. math_research/ledger/handoff.py +291 -0
  32. math_research/ledger/history.py +55 -0
  33. math_research/ledger/identity.py +190 -0
  34. math_research/ledger/manifest.py +650 -0
  35. math_research/ledger/persistence.py +52 -0
  36. math_research/ledger/premises.py +158 -0
  37. math_research/ledger/preview.py +350 -0
  38. math_research/ledger/projection.py +90 -0
  39. math_research/ledger/provisional.py +141 -0
  40. math_research/ledger/publication.py +69 -0
  41. math_research/ledger/readers.py +43 -0
  42. math_research/ledger/records/__init__.py +1 -0
  43. math_research/ledger/records/claims.py +621 -0
  44. math_research/ledger/records/counterexamples.py +100 -0
  45. math_research/ledger/records/evidence_content.py +150 -0
  46. math_research/ledger/records/experiments.py +55 -0
  47. math_research/ledger/records/models.py +423 -0
  48. math_research/ledger/records/store.py +668 -0
  49. math_research/ledger/records/validation.py +99 -0
  50. math_research/ledger/records/write_boundary.py +69 -0
  51. math_research/ledger/relations/__init__.py +1 -0
  52. math_research/ledger/relations/content.py +61 -0
  53. math_research/ledger/relations/edges.py +204 -0
  54. math_research/ledger/relations/ledger.py +574 -0
  55. math_research/ledger/relations/models.py +148 -0
  56. math_research/ledger/relations/policy.py +71 -0
  57. math_research/ledger/source_reader.py +300 -0
  58. math_research/ledger/source_records.py +134 -0
  59. math_research/ledger/source_review.py +52 -0
  60. math_research/ledger/sources.py +159 -0
  61. math_research/ledger/state.py +535 -0
  62. math_research/ledger/target.py +67 -0
  63. math_research/ledger/verification/__init__.py +1 -0
  64. math_research/ledger/verification/proofs.py +88 -0
  65. math_research/mcp/__init__.py +1 -0
  66. math_research/mcp/adapter.py +471 -0
  67. math_research/mcp/server.py +255 -0
  68. math_research/retrieval/__init__.py +1 -0
  69. math_research/retrieval/context.py +1012 -0
  70. math_research/retrieval/continuation_selection.py +101 -0
  71. math_research/retrieval/embeddings.py +19 -0
  72. math_research/retrieval/index.py +515 -0
  73. math_research/retrieval/memory_policy.py +43 -0
  74. math_research/retrieval/packet.py +389 -0
  75. math_research/retrieval/policy.py +372 -0
  76. math_research/retrieval/recall.py +737 -0
  77. math_research/retrieval/related_research.py +269 -0
  78. math_research/retrieval/research_map.py +251 -0
  79. math_research/retrieval/selection.py +861 -0
  80. math_research/services/__init__.py +1 -0
  81. math_research/services/acceptance.py +138 -0
  82. math_research/services/ingest.py +172 -0
  83. math_research/services/problems.py +225 -0
  84. math_research/services/research.py +155 -0
  85. math_research/services/retrieval.py +150 -0
  86. math_research/services/review.py +91 -0
  87. math_research/services/stale.py +65 -0
  88. math_research/services/verification.py +252 -0
  89. math_research/verification/__init__.py +1 -0
  90. math_research/verification/authority.py +40 -0
  91. math_research/verification/formal/__init__.py +17 -0
  92. math_research/verification/formal/checker.py +296 -0
  93. math_research/verification/formal/freeze.py +126 -0
  94. math_research/verification/formal/models.py +95 -0
  95. math_research/verification/freshness.py +148 -0
  96. math_research/verification/models.py +87 -0
  97. math_research/verification/review.py +39 -0
  98. math_research_ledger-1.5.2.dist-info/METADATA +239 -0
  99. math_research_ledger-1.5.2.dist-info/RECORD +103 -0
  100. math_research_ledger-1.5.2.dist-info/WHEEL +5 -0
  101. math_research_ledger-1.5.2.dist-info/entry_points.txt +6 -0
  102. math_research_ledger-1.5.2.dist-info/licenses/LICENSE +201 -0
  103. math_research_ledger-1.5.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,3 @@
1
+ """Structured memory and retrieval for long-horizon mathematical research."""
2
+
3
+ __version__ = "1.5.2"
@@ -0,0 +1 @@
1
+ """Thin human/debug command interface."""
@@ -0,0 +1,3 @@
1
+ from math_research.cli.main import run
2
+
3
+ run()
@@ -0,0 +1,337 @@
1
+ """CLI adapters only; domain decisions and writes live in deterministic services."""
2
+
3
+ import json
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ import typer
8
+ from pydantic import BaseModel
9
+
10
+ from math_research.core.config import workspace_config
11
+ from math_research.core.errors import ResearchError
12
+ from math_research.core.paths import (
13
+ STATE_DIRNAMES,
14
+ WORKSPACE_DIRNAME,
15
+ find_workspace_root,
16
+ state_at,
17
+ )
18
+ from math_research.core.refs import ObjectRef
19
+ from math_research.ledger.dependencies import DependencyRole
20
+ from math_research.ledger.records.models import Definition
21
+ from math_research.services import (
22
+ acceptance,
23
+ ingest,
24
+ research,
25
+ retrieval,
26
+ review,
27
+ stale,
28
+ verification,
29
+ )
30
+
31
+ app = typer.Typer(
32
+ help="MathResearch Ledger: persistent research state, context and verification. "
33
+ "Legacy compatibility aliases: smr, math-research."
34
+ )
35
+ ledger_app = typer.Typer(help="Typed objects and qualified references.")
36
+ context_app = typer.Typer()
37
+ ingest_app = typer.Typer()
38
+ verify_app = typer.Typer()
39
+ formal_app = typer.Typer()
40
+ acceptance_app = typer.Typer()
41
+ stale_app = typer.Typer()
42
+ review_app = typer.Typer()
43
+ for name, child in [
44
+ ("ledger", ledger_app),
45
+ ("context", context_app),
46
+ ("ingest", ingest_app),
47
+ ("verify", verify_app),
48
+ ("formal", formal_app),
49
+ ("acceptance", acceptance_app),
50
+ ("stale", stale_app),
51
+ ("review", review_app),
52
+ ]:
53
+ app.add_typer(child, name=name)
54
+
55
+
56
+ def emit(value):
57
+ from math_research.retrieval.packet import ContextPacket
58
+
59
+ if isinstance(value, ContextPacket):
60
+ typer.echo(value.model_dump_json())
61
+ return
62
+ if isinstance(value, BaseModel):
63
+ value = value.model_dump(mode="json")
64
+ typer.echo(
65
+ json.dumps(value, ensure_ascii=False, indent=2, default=lambda v: v.model_dump(mode="json"))
66
+ )
67
+
68
+
69
+ @app.callback()
70
+ def main(ctx: typer.Context, workspace: Path = typer.Option(Path("."), "--workspace", "-w")):
71
+ root = workspace.resolve()
72
+ if root.name in STATE_DIRNAMES:
73
+ root = root.parent
74
+ if ctx.invoked_subcommand not in {"init", "migrate"}:
75
+ root = find_workspace_root(root) or root
76
+ ctx.obj = (
77
+ root / WORKSPACE_DIRNAME
78
+ if ctx.invoked_subcommand == "migrate"
79
+ else state_at(root) or root / WORKSPACE_DIRNAME
80
+ )
81
+ workspace_config(ctx.obj.parent)
82
+
83
+
84
+ def state(ctx):
85
+ return ctx.obj
86
+
87
+
88
+ def ref(value):
89
+ try:
90
+ return ObjectRef.parse(value)
91
+ except ValueError as exc:
92
+ raise typer.BadParameter("Use problem_id:kind:object_id (or _global:kind:id).") from exc
93
+
94
+
95
+ @app.command()
96
+ def init(ctx: typer.Context):
97
+ emit(research.initialize(state(ctx)))
98
+
99
+
100
+ @app.command()
101
+ def migrate(ctx: typer.Context, from_workspace: Path | None = None, rollback: bool = False):
102
+ """Explicit offline state-directory migration; preserves corpus bytes and provenance."""
103
+ from math_research.core.migration import migrate_workspace, rollback_migration
104
+
105
+ root = state(ctx).parent
106
+ emit(rollback_migration(root) if rollback else migrate_workspace(from_workspace or root, root))
107
+
108
+
109
+ @app.command()
110
+ def status(ctx: typer.Context):
111
+ emit(research.status(state(ctx)))
112
+
113
+
114
+ @ingest_app.command("recover")
115
+ def recover_ingest(ctx: typer.Context):
116
+ """Roll back interrupted checkpoint metadata; retain original raw source bytes."""
117
+ from math_research.ledger.checkpoint import recover_checkpoint
118
+
119
+ emit(recover_checkpoint(state(ctx)))
120
+
121
+
122
+ @ledger_app.command("list")
123
+ def ledger_list(ctx: typer.Context, problem: str | None = None):
124
+ emit(research.list_objects(state(ctx), problem))
125
+
126
+
127
+ @ledger_app.command("show")
128
+ def ledger_show(ctx: typer.Context, reference: str):
129
+ emit(research.get_object(state(ctx), ref(reference)))
130
+
131
+
132
+ @ledger_app.command("create-problem")
133
+ def create_problem(ctx: typer.Context, title: str, statement: str):
134
+ emit(research.create_problem(state(ctx), title, statement))
135
+
136
+
137
+ @ledger_app.command("update-problem")
138
+ def update_problem(
139
+ ctx: typer.Context,
140
+ problem: str,
141
+ primary_claim_id: str,
142
+ dry_run: bool = False,
143
+ expected_version: str | None = None,
144
+ ):
145
+ """Bind an exact primary Claim using an explicit semantic revision."""
146
+ from math_research.services.problems import update_problem as update
147
+
148
+ emit(
149
+ update(
150
+ state(ctx),
151
+ problem_id=problem,
152
+ primary_claim_id=primary_claim_id,
153
+ revision_kind="semantic",
154
+ dry_run=dry_run,
155
+ expected_version=expected_version,
156
+ )
157
+ )
158
+
159
+
160
+ @ledger_app.command("history")
161
+ def object_history(ctx: typer.Context, reference: str):
162
+ emit(research.history(state(ctx), ref(reference)))
163
+
164
+
165
+ @ledger_app.command("add-claim")
166
+ def add_claim(ctx: typer.Context, problem: str, statement: str):
167
+ emit(research.add_claim(state(ctx), problem, statement))
168
+
169
+
170
+ @ledger_app.command("add-definition")
171
+ def add_definition(ctx: typer.Context, problem: str, term: str, definition: str):
172
+ emit(research.add_definition(state(ctx), problem, term, definition))
173
+
174
+
175
+ @ledger_app.command("revise-definition")
176
+ def revise_definition(ctx: typer.Context, reference: str, definition: str):
177
+ target = ref(reference)
178
+ old = research.get_object(state(ctx), target)
179
+ if target.kind != "definition":
180
+ raise typer.BadParameter("Expected definition reference.")
181
+ value = Definition.model_validate(old.object.record).model_copy(
182
+ update={"definition": definition}
183
+ )
184
+ emit(research.update_definition(state(ctx), target.problem_id, value))
185
+
186
+
187
+ @ledger_app.command("link")
188
+ def link(ctx: typer.Context, dependent: str, target: str, role: DependencyRole):
189
+ emit(research.link_dependency(state(ctx), ref(dependent), ref(target), role))
190
+
191
+
192
+ @app.command("search")
193
+ def search(
194
+ ctx: typer.Context,
195
+ query: str,
196
+ problem: str | None = None,
197
+ kind: str | None = None,
198
+ limit: int = 20,
199
+ ):
200
+ emit(retrieval.search_research(state(ctx), query, problem_id=problem, kind=kind, limit=limit))
201
+
202
+
203
+ @context_app.command("export")
204
+ def export_context(
205
+ ctx: typer.Context,
206
+ reference: str,
207
+ budget: int = 8000,
208
+ query: str = "",
209
+ purpose: str = "CONTINUE_RESEARCH",
210
+ ):
211
+ emit(
212
+ retrieval.export_context_packet(
213
+ state(ctx), ref(reference), token_budget=budget, query=query, purpose=purpose
214
+ )
215
+ )
216
+
217
+
218
+ @ingest_app.command("episode")
219
+ def ingest_episode(
220
+ ctx: typer.Context,
221
+ problem: str,
222
+ file: Path,
223
+ provenance: str = typer.Option(...),
224
+ preview: bool = False,
225
+ ):
226
+ emit(ingest.ingest_file(state(ctx), problem, file, provenance=provenance, preview=preview))
227
+
228
+
229
+ @ingest_app.command("review")
230
+ def review_candidate(
231
+ ctx: typer.Context, problem: str, candidate_id: str, decision: str, edits: Path | None = None
232
+ ):
233
+ emit(ingest.review_from_file(state(ctx), problem, candidate_id, decision, edits))
234
+
235
+
236
+ @ingest_app.command("source")
237
+ def ingest_source(ctx: typer.Context, problem: str, file: Path):
238
+ emit(ingest.ingest_source_file(state(ctx), problem, file))
239
+
240
+
241
+ @verify_app.command("show")
242
+ def show_verification(ctx: typer.Context, verification_id: str):
243
+ emit(verification.get_receipt(state(ctx), verification_id))
244
+
245
+
246
+ @formal_app.command("freeze")
247
+ def formal_freeze(
248
+ ctx: typer.Context,
249
+ reference: str,
250
+ ident: str,
251
+ repo: Path,
252
+ statement: str,
253
+ module: str,
254
+ declaration: str,
255
+ expected_type: str,
256
+ local_definition: list[str] = typer.Option([]),
257
+ version: int = 1,
258
+ reason: str | None = None,
259
+ ):
260
+ emit(
261
+ verification.freeze_statement(
262
+ state(ctx),
263
+ ref(reference),
264
+ ident=ident,
265
+ repo=repo,
266
+ statement=statement,
267
+ module=module,
268
+ declaration=declaration,
269
+ expected_type=expected_type,
270
+ local_definitions=tuple(local_definition),
271
+ version=version,
272
+ reason=reason,
273
+ )
274
+ )
275
+
276
+
277
+ @formal_app.command("check")
278
+ def formal_check(
279
+ ctx: typer.Context,
280
+ reference: str,
281
+ lake: Path = typer.Option(...),
282
+ elan_home: Path = typer.Option(...),
283
+ ):
284
+ emit(verification.run_formal_check(state(ctx), ref(reference), lake=lake, elan_home=elan_home))
285
+
286
+
287
+ @acceptance_app.command("request")
288
+ def request_acceptance(ctx: typer.Context, reference: str, verification_id: str):
289
+ emit(acceptance.request_acceptance(state(ctx), ref(reference), verification_id))
290
+
291
+
292
+ @acceptance_app.command("pending")
293
+ def pending(ctx: typer.Context):
294
+ emit(acceptance.pending_acceptances(state(ctx)))
295
+
296
+
297
+ @acceptance_app.command("accept")
298
+ def human_accept(
299
+ ctx: typer.Context,
300
+ request_id: str,
301
+ actor: str = typer.Option(...),
302
+ rationale: str = typer.Option(...),
303
+ correspondence: str | None = None,
304
+ ):
305
+ """Trusted human operator only; not exposed by MCP. Automated scope is refused."""
306
+ emit(
307
+ acceptance.accept(
308
+ state(ctx), request_id, actor=actor, rationale=rationale, correspondence=correspondence
309
+ )
310
+ )
311
+
312
+
313
+ @stale_app.command("report")
314
+ def stale_report(ctx: typer.Context, problem: str | None = None):
315
+ emit(stale.stale_report(state(ctx), problem))
316
+
317
+
318
+ @review_app.command("packet")
319
+ def review_packet(ctx: typer.Context, reference: str):
320
+ emit(review.prepare_review(state(ctx), ref(reference)))
321
+
322
+
323
+ @review_app.command("record")
324
+ def review_record(ctx: typer.Context, file: Path):
325
+ emit(review.ingest_report_file(state(ctx), file))
326
+
327
+
328
+ def run():
329
+ for stream in (sys.stdout, sys.stderr):
330
+ configure = getattr(stream, "reconfigure", None)
331
+ if configure is not None:
332
+ configure(encoding="utf-8")
333
+ try:
334
+ app()
335
+ except (ResearchError, ValueError, OSError) as exc:
336
+ typer.echo(str(exc), err=True)
337
+ raise SystemExit(2) from None
@@ -0,0 +1 @@
1
+ """Structured mathematical research."""
@@ -0,0 +1,184 @@
1
+ """Atomic file writes for the artifact store.
2
+
3
+ A crash, full disk, or Ctrl-C during a plain ``write_text`` (or a truncate-then-
4
+ write ``rewrite``) can leave a half-written, corrupt file. Authoritative JSONL
5
+ readers fail closed on corruption; preventing damage remains essential. Routing the
6
+ store's whole-file writes through :func:`atomic_write_text` makes them durable:
7
+ write to a temp file in the same directory, fsync, then ``os.replace`` — an atomic
8
+ rename that either fully succeeds or leaves the prior file intact.
9
+
10
+ Atomicity of a single write is not enough for a *mutable* ledger, though. Those are
11
+ updated read-modify-write — read every record, add or change one, replace the file
12
+ — and two processes doing that concurrently both succeed while one of them silently
13
+ loses its record, because the second rename overwrites the first writer's file.
14
+ Worse, each derives the next artifact id from what it just read, so both mint the
15
+ same id. Measured: four processes appending fifteen claims each to one workspace
16
+ reported sixty successes and left sixteen records behind, with ids handed out four
17
+ times over. :func:`file_lock` closes that window — hold it across the read *and*
18
+ the write, not just the write.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import errno
24
+ import math
25
+ import os
26
+ import tempfile
27
+ import time
28
+ from collections.abc import Iterator
29
+ from contextlib import contextmanager
30
+ from pathlib import Path
31
+
32
+ from math_research.core.errors import ResearchError
33
+
34
+ _LOCK_POLL_SECONDS = 0.02
35
+ _LOCK_TIMEOUT_SECONDS = 15.0
36
+ # A holder that died leaves its lock file behind. Reclaim one that is older than any
37
+ # plausible read-modify-write rather than blocking every later run forever.
38
+ _LOCK_STALE_SECONDS = 120.0
39
+ _WINDOWS = os.name == "nt"
40
+ # Windows delete-pending/sharing errors can briefly masquerade as access denial.
41
+ # Never turn a persistent ACL denial into an ordinary, indefinitely held lock.
42
+ _WINDOWS_ACCESS_RETRIES = 3
43
+
44
+
45
+ @contextmanager
46
+ def file_lock(
47
+ path: Path,
48
+ *,
49
+ timeout: float = _LOCK_TIMEOUT_SECONDS,
50
+ stale_after: float = _LOCK_STALE_SECONDS,
51
+ ) -> Iterator[None]:
52
+ """Serialize a read-modify-write of ``path`` across processes.
53
+
54
+ Uses an ``O_EXCL`` sibling lock file rather than ``fcntl``: the same code then
55
+ works on Windows, and the lock is visible in a directory listing when something
56
+ goes wrong. A lock file older than ``stale_after`` is assumed to belong to a
57
+ process that died and is reclaimed, so a crash cannot wedge the workspace.
58
+
59
+ Every retry checks the monotonic deadline and sleeps. Only EEXIST establishes
60
+ contention; unreadable state and cleanup errors fail diagnostically. Known
61
+ Windows sharing/delete-pending access errors receive a short bounded retry.
62
+ A caller that cannot take the lock must never fall through and write anyway.
63
+ """
64
+ lock = path.with_name(path.name + ".lock")
65
+ if not math.isfinite(timeout) or timeout < 0:
66
+ raise ValueError("Lock timeout must be finite and nonnegative.")
67
+ if not math.isfinite(stale_after) or stale_after < 0:
68
+ raise ValueError("Lock stale_after must be finite and nonnegative.")
69
+
70
+ def failure(operation: str, exc: OSError) -> ResearchError:
71
+ return ResearchError(f"Cannot {operation} lock {lock}: {type(exc).__name__}: {exc}")
72
+
73
+ def release() -> None:
74
+ try:
75
+ lock.unlink()
76
+ except OSError as exc:
77
+ raise failure("remove owned", exc) from exc
78
+
79
+ try:
80
+ lock.parent.mkdir(parents=True, exist_ok=True)
81
+ except OSError as exc:
82
+ raise failure("prepare directory for", exc) from exc
83
+ deadline = time.monotonic() + timeout
84
+ access_retries = 0
85
+ last_error: OSError | None = None
86
+
87
+ def timed_out() -> ResearchError:
88
+ detail = f" Last error: {type(last_error).__name__}: {last_error}." if last_error else ""
89
+ return ResearchError(
90
+ f"Timed out after {timeout:g}s waiting for lock {lock}.{detail} "
91
+ "Inspect the lock holder and workspace access; no write was performed."
92
+ )
93
+
94
+ first_attempt = True
95
+ while True:
96
+ if not first_attempt and time.monotonic() >= deadline:
97
+ raise timed_out() from last_error
98
+ first_attempt = False
99
+ try:
100
+ fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
101
+ except FileExistsError as exc:
102
+ last_error = exc
103
+ try:
104
+ age = time.time() - lock.stat().st_mtime
105
+ except FileNotFoundError:
106
+ pass # released during inspection; still use the bounded retry below
107
+ except OSError as exc:
108
+ raise failure("inspect existing", exc) from exc
109
+ else:
110
+ if age > stale_after:
111
+ try:
112
+ lock.unlink()
113
+ except FileNotFoundError:
114
+ pass # another contender already reclaimed it
115
+ except OSError as exc:
116
+ raise failure("remove stale", exc) from exc
117
+ except PermissionError as exc:
118
+ last_error = exc
119
+ # The Windows CRT can return EACCES without preserving winerror
120
+ # for a delete-pending lock. This is a transient access retry,
121
+ # never evidence that another holder exists or permission to write.
122
+ transient_access = getattr(exc, "winerror", None) in {5, 32, 303} or (
123
+ getattr(exc, "winerror", None) is None and exc.errno == errno.EACCES
124
+ )
125
+ if not _WINDOWS or not transient_access or access_retries >= _WINDOWS_ACCESS_RETRIES:
126
+ raise failure("create (access denied)", exc) from exc
127
+ access_retries += 1
128
+ except OSError as exc:
129
+ raise failure("create", exc) from exc
130
+ else:
131
+ break
132
+ remaining = deadline - time.monotonic()
133
+ if remaining <= 0:
134
+ raise timed_out() from last_error
135
+ time.sleep(min(_LOCK_POLL_SECONDS, remaining))
136
+
137
+ try:
138
+ try:
139
+ os.write(fd, f"{os.getpid()}\n".encode())
140
+ finally:
141
+ os.close(fd)
142
+ except OSError as exc:
143
+ try:
144
+ release()
145
+ except ResearchError as cleanup:
146
+ raise cleanup from exc
147
+ raise failure("initialize", exc) from exc
148
+ try:
149
+ yield
150
+ finally:
151
+ release()
152
+
153
+
154
+ def atomic_write_text(path: Path, data: str, *, encoding: str = "utf-8") -> None:
155
+ """Write ``data`` to ``path`` atomically (temp file + fsync + rename)."""
156
+ path.parent.mkdir(parents=True, exist_ok=True)
157
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
158
+ try:
159
+ with os.fdopen(fd, "w", encoding=encoding, newline="") as fh:
160
+ fh.write(data)
161
+ fh.flush()
162
+ os.fsync(fh.fileno())
163
+ # Windows read handles can briefly deny rename with ERROR_ACCESS_DENIED
164
+ # or sharing/lock violations. Optimistic readers do not hold the writer
165
+ # lock; allow their handles to close without weakening atomic publication.
166
+ for attempt in range(_WINDOWS_ACCESS_RETRIES + 1):
167
+ try:
168
+ os.replace(tmp, path)
169
+ break
170
+ except PermissionError as exc:
171
+ if (
172
+ not _WINDOWS
173
+ or getattr(exc, "winerror", None) not in {5, 32, 33}
174
+ or attempt == _WINDOWS_ACCESS_RETRIES
175
+ ):
176
+ raise
177
+ time.sleep(_LOCK_POLL_SECONDS)
178
+ except BaseException:
179
+ # Never leave the temp file behind on failure; the original is untouched.
180
+ try:
181
+ os.unlink(tmp)
182
+ except OSError:
183
+ pass
184
+ raise
@@ -0,0 +1,60 @@
1
+ """Versioned research workspace metadata, independent of tool/runtime settings.
2
+
3
+ Legacy .math-research/config.yaml is preserved as historical data and is never
4
+ used for Agent/provider configuration. Existing ledgers need no write to read.
5
+ """
6
+
7
+ from datetime import UTC, datetime
8
+ from pathlib import Path
9
+ from typing import Literal
10
+
11
+ import yaml
12
+ from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, ValidationError
13
+
14
+ from math_research.core.atomicio import atomic_write_text, file_lock
15
+ from math_research.core.errors import ResearchError
16
+
17
+ CONFIG_FILENAME = "workspace.yaml"
18
+
19
+
20
+ class Config(BaseModel):
21
+ model_config = ConfigDict(extra="forbid", frozen=True)
22
+
23
+ workspace_version: Literal[1, 2]
24
+ name: str = Field(min_length=1, max_length=255)
25
+ created_at: AwareDatetime
26
+
27
+
28
+ def default_config(name: str = "research-workspace") -> Config:
29
+ return Config(workspace_version=2, name=name, created_at=datetime.now(UTC))
30
+
31
+
32
+ def load_config(path: Path) -> Config:
33
+ try:
34
+ return Config.model_validate(yaml.safe_load(path.read_text("utf-8-sig")))
35
+ except (ValidationError, yaml.YAMLError, UnicodeError) as exc:
36
+ raise ResearchError(
37
+ "Invalid workspace.yaml: expected workspace_version: 1 or 2, name and "
38
+ "timezone-aware created_at. Preserve history and migrate metadata explicitly."
39
+ ) from exc
40
+
41
+
42
+ def default_config_yaml(name: str = "research-workspace") -> str:
43
+ return yaml.safe_dump(default_config(name).model_dump(mode="json"), sort_keys=False)
44
+
45
+
46
+ def write_default_config(path: Path, *, name: str = "research-workspace") -> None:
47
+ with file_lock(path):
48
+ if not path.exists():
49
+ atomic_write_text(path, default_config_yaml(name))
50
+
51
+
52
+ def write_config(path: Path, config: Config) -> None:
53
+ with file_lock(path):
54
+ atomic_write_text(path, yaml.safe_dump(config.model_dump(mode="json"), sort_keys=False))
55
+
56
+
57
+ def workspace_config(root: Path) -> Config | None:
58
+ """None means a legacy/unversioned workspace; reading never migrates it."""
59
+ path = root / CONFIG_FILENAME
60
+ return load_config(path) if path.is_file() else None
@@ -0,0 +1,59 @@
1
+ """MathResearch Ledger exception hierarchy.
2
+
3
+ All recoverable, user-facing failures inherit from :class:`ResearchError` so the
4
+ CLI can render them as helpful, actionable messages instead of raw tracebacks.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+
10
+ class ResearchError(Exception):
11
+ """Base class for all MathResearch Ledger errors."""
12
+
13
+
14
+ class IntegrityError(ResearchError):
15
+ """An authoritative source cannot be read or no longer matches its identity."""
16
+
17
+ def __init__(self, message: str):
18
+ super().__init__("INTEGRITY_ERROR: " + message)
19
+
20
+
21
+ class RecoverableToolError(ResearchError):
22
+ """An ordinary tool outcome the Agent can repair, not a broken runtime."""
23
+
24
+ def __init__(self, message: str, **metadata: object):
25
+ super().__init__(message)
26
+ self.metadata = metadata
27
+
28
+
29
+ class PathTraversalError(ResearchError):
30
+ """Raised when a path would escape the workspace root."""
31
+
32
+
33
+ class WorkspaceError(ResearchError):
34
+ """Raised for workspace initialization or discovery problems."""
35
+
36
+
37
+ class ConfigError(ResearchError):
38
+ """Raised when configuration cannot be loaded or is invalid."""
39
+
40
+
41
+ class PermissionDeniedError(ResearchError):
42
+ """Raised when an action is denied by the permission policy."""
43
+
44
+
45
+ class ProviderError(ResearchError):
46
+ """Raised when a model provider is misconfigured or unavailable."""
47
+
48
+
49
+ def is_recoverable_tool_parse_error(exc: Exception) -> bool:
50
+ """True when the provider failed because model tool-call JSON was invalid."""
51
+ msg = str(exc).lower()
52
+ needles = (
53
+ "error parsing tool call",
54
+ "failed to parse json",
55
+ "unexpected end of json input",
56
+ "parse tool call",
57
+ "invalid character",
58
+ )
59
+ return isinstance(exc, ProviderError) and any(n in msg for n in needles)
@@ -0,0 +1,18 @@
1
+ """Exact byte hashes and deterministic content identities; never primary IDs."""
2
+
3
+ import hashlib
4
+ import json
5
+
6
+
7
+ def sha256(raw: bytes) -> str:
8
+ return hashlib.sha256(raw).hexdigest()
9
+
10
+
11
+ def canonical_json(value: object) -> bytes:
12
+ return json.dumps(
13
+ value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False
14
+ ).encode("utf-8")
15
+
16
+
17
+ def content_hash(value: object) -> str:
18
+ return sha256(canonical_json(value))
@@ -0,0 +1,24 @@
1
+ """Exact immutable-source reads. Hash the bytes returned, never repair metadata."""
2
+
3
+ import hashlib
4
+ from pathlib import Path
5
+
6
+ from math_research.core.errors import IntegrityError
7
+
8
+
9
+ def verified_bytes(path: Path, expected_sha256: str, *, label: str) -> bytes:
10
+ try:
11
+ raw = path.read_bytes()
12
+ except OSError as exc:
13
+ raise IntegrityError(f"Unreadable source {label}: {type(exc).__name__}") from exc
14
+ if hashlib.sha256(raw).hexdigest() != expected_sha256:
15
+ raise IntegrityError(f"Source SHA-256 mismatch: {label}")
16
+ return raw
17
+
18
+
19
+ def verified_text(path: Path, expected_sha256: str, *, label: str) -> str:
20
+ raw = verified_bytes(path, expected_sha256, label=label)
21
+ try:
22
+ return raw.decode("utf-8-sig")
23
+ except UnicodeError as exc:
24
+ raise IntegrityError(f"Source is not UTF-8: {label}") from exc