memory-cli 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.
- memory_cli/__init__.py +1 -0
- memory_cli/__main__.py +49 -0
- memory_cli/capture/__init__.py +7 -0
- memory_cli/capture/codex_rollout.py +164 -0
- memory_cli/capture/event_lines.py +66 -0
- memory_cli/capture/extract.py +458 -0
- memory_cli/capture/state.py +183 -0
- memory_cli/commands/__init__.py +21 -0
- memory_cli/commands/admin.py +363 -0
- memory_cli/commands/common.py +609 -0
- memory_cli/commands/curate.py +1189 -0
- memory_cli/commands/diagnostics.py +126 -0
- memory_cli/commands/edit.py +1282 -0
- memory_cli/commands/hooks.py +730 -0
- memory_cli/commands/import_recovery.py +45 -0
- memory_cli/commands/install.py +152 -0
- memory_cli/commands/integrate.py +480 -0
- memory_cli/commands/memory.py +2152 -0
- memory_cli/commands/read.py +1290 -0
- memory_cli/commands/sources.py +766 -0
- memory_cli/commands/split.py +97 -0
- memory_cli/commands/split_plan.py +196 -0
- memory_cli/commands/split_transaction.py +230 -0
- memory_cli/commands/synthesis.py +1122 -0
- memory_cli/core/__init__.py +16 -0
- memory_cli/core/auto_state.py +30 -0
- memory_cli/core/codex_pass.py +109 -0
- memory_cli/core/config.py +87 -0
- memory_cli/core/file_journal.py +163 -0
- memory_cli/core/headless.py +130 -0
- memory_cli/core/jobs.py +130 -0
- memory_cli/core/resources.py +57 -0
- memory_cli/core/runner.py +398 -0
- memory_cli/core/safe_io.py +155 -0
- memory_cli/core/store_git.py +407 -0
- memory_cli/core/yaml_load.py +14 -0
- memory_cli/corroborate/__init__.py +11 -0
- memory_cli/corroborate/cli.py +267 -0
- memory_cli/corroborate/decide.py +893 -0
- memory_cli/corroborate/digest.py +425 -0
- memory_cli/corroborate/fill.py +744 -0
- memory_cli/corroborate/job.py +15 -0
- memory_cli/corroborate/reword.py +446 -0
- memory_cli/corroborate/run.py +1142 -0
- memory_cli/corroborate/state.py +300 -0
- memory_cli/digest/__init__.py +4 -0
- memory_cli/digest/lessons.py +483 -0
- memory_cli/entry/__init__.py +12 -0
- memory_cli/entry/auto.py +660 -0
- memory_cli/entry/capture.py +1403 -0
- memory_cli/entry/corroborate.py +214 -0
- memory_cli/entry/integrate.py +684 -0
- memory_cli/entry/integrate_self_check.py +203 -0
- memory_cli/entry/research.py +9 -0
- memory_cli/entry/settle.py +614 -0
- memory_cli/entry/split_auto.py +460 -0
- memory_cli/entry/synthesize.py +22 -0
- memory_cli/integrate/__init__.py +9 -0
- memory_cli/integrate/answers.py +42 -0
- memory_cli/integrate/briefs/check-brief.md +16 -0
- memory_cli/integrate/briefs/place-brief.md +26 -0
- memory_cli/integrate/log.py +43 -0
- memory_cli/integrate/plan.py +125 -0
- memory_cli/integrate/rows.py +99 -0
- memory_cli/integrate/state.py +158 -0
- memory_cli/integrate/undo.py +143 -0
- memory_cli/mem.py +1180 -0
- memory_cli/memories/__init__.py +16 -0
- memory_cli/memories/fingerprints.py +51 -0
- memory_cli/memories/journal.py +93 -0
- memory_cli/memories/locations.py +282 -0
- memory_cli/memories/matching.py +451 -0
- memory_cli/memories/model.py +205 -0
- memory_cli/memories/parse.py +237 -0
- memory_cli/memories/records.py +266 -0
- memory_cli/memories/rules.py +291 -0
- memory_cli/memories/sightings.py +314 -0
- memory_cli/memories/terms.py +148 -0
- memory_cli/memories/write.py +358 -0
- memory_cli/notes/__init__.py +13 -0
- memory_cli/notes/check.py +806 -0
- memory_cli/notes/due.py +260 -0
- memory_cli/notes/fields.py +217 -0
- memory_cli/notes/index.py +230 -0
- memory_cli/notes/links.py +170 -0
- memory_cli/notes/note.py +222 -0
- memory_cli/notes/search.py +391 -0
- memory_cli/notes/split_candidates.py +72 -0
- memory_cli/research/__init__.py +5 -0
- memory_cli/research/checks.py +1065 -0
- memory_cli/research/pipeline.py +952 -0
- memory_cli/session/__init__.py +5 -0
- memory_cli/session/handoff.py +139 -0
- memory_cli/session/notices.py +111 -0
- memory_cli/settle/__init__.py +5 -0
- memory_cli/settle/state.py +111 -0
- memory_cli/settle/verdicts.py +693 -0
- memory_cli/split/briefs/checker-brief.md +5 -0
- memory_cli/split/briefs/editor-brief.md +20 -0
- memory_cli/syntheses/__init__.py +8 -0
- memory_cli/syntheses/document.py +400 -0
- memory_cli/syntheses/edit.py +581 -0
- memory_cli/syntheses/project.py +384 -0
- memory_cli/syntheses/split_conservation.py +50 -0
- memory_cli/syntheses/units.py +427 -0
- memory_cli/synthesize/__init__.py +9 -0
- memory_cli/synthesize/backfill.py +431 -0
- memory_cli/synthesize/briefs/backfill-brief.md +26 -0
- memory_cli/synthesize/briefs/checker-brief.md +13 -0
- memory_cli/synthesize/briefs/fixer-brief.md +19 -0
- memory_cli/synthesize/briefs/memory-brief.md +30 -0
- memory_cli/synthesize/briefs/settle-brief.md +32 -0
- memory_cli/synthesize/briefs/verdict-brief.md +50 -0
- memory_cli/synthesize/briefs/web-brief.md +33 -0
- memory_cli/synthesize/cli.py +311 -0
- memory_cli/synthesize/pipeline.py +764 -0
- memory_cli/synthesize/references.py +164 -0
- memory_cli/synthesize/run.py +150 -0
- memory_cli/synthesize/topics.py +528 -0
- memory_cli/templates/knowledge.md +23 -0
- memory_cli/templates/literature.md +25 -0
- memory_cli/templates/research.md +23 -0
- memory_cli/templates/synthesis.md +6 -0
- memory_cli-0.1.0.dist-info/METADATA +102 -0
- memory_cli-0.1.0.dist-info/RECORD +128 -0
- memory_cli-0.1.0.dist-info/WHEEL +4 -0
- memory_cli-0.1.0.dist-info/entry_points.txt +9 -0
- memory_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1142 @@
|
|
|
1
|
+
"""mem-corroborate: the model sessions, the briefs, the applier and `execute` (one run); what the three jobs share."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
import shutil
|
|
10
|
+
import subprocess
|
|
11
|
+
import tempfile
|
|
12
|
+
import time
|
|
13
|
+
from dataclasses import dataclass, field, replace
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import TYPE_CHECKING, NamedTuple
|
|
16
|
+
|
|
17
|
+
from memory_cli.capture import state as cs
|
|
18
|
+
from memory_cli.core import codex_pass, headless, jobs, resources
|
|
19
|
+
from memory_cli.core import runner as runners
|
|
20
|
+
from memory_cli.corroborate import decide as corroborate_decide
|
|
21
|
+
from memory_cli.corroborate import job as corroborate_job
|
|
22
|
+
from memory_cli.corroborate import state as corroborate_state
|
|
23
|
+
from memory_cli.memories import records
|
|
24
|
+
from memory_cli.synthesize import pipeline as sp
|
|
25
|
+
|
|
26
|
+
if TYPE_CHECKING:
|
|
27
|
+
from collections.abc import Callable
|
|
28
|
+
|
|
29
|
+
logger = logging.getLogger(__name__)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
PROPOSE_MODEL = VERIFY_MODEL = "haiku"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
CHECK_MODEL = "haiku" # the second session of the automatic fill; chosen by the gate of 2026-11-22 (the plan's Results)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
SESSION_TIMEOUT = 600
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
MAX_FILE_BYTES = 1_000_000
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
# the exit of `mem remember` and `mem confirm` for a claim or a case that is already there
|
|
45
|
+
ALREADY_THERE = 3
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
ROW_FIELDS = 2 # a `remember` row that says what happened: the handle, then "sighting" or the like
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
REMEMBER_BODY = (
|
|
52
|
+
"Written by the corroboration pass; its sightings are the sessions and projects in `sources`.\n"
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
MEM = resources.mem_command()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
MEM_TIMEOUT = 60
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
SETTLE_STATE = ".settle-state.json" # beside the global records; `settle.STATE_NAME`
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
SESSION_VARS = (
|
|
66
|
+
"CLAUDE_ENV_FILE",
|
|
67
|
+
"CLAUDE_PLUGIN_ROOT",
|
|
68
|
+
"CLAUDE_PLUGIN_DATA",
|
|
69
|
+
"CLAUDE_PROJECT_DIR",
|
|
70
|
+
"CLAUDE_PID",
|
|
71
|
+
"CLAUDE_CODE_SESSION_ID",
|
|
72
|
+
"CLAUDE_CODE_MESSAGING_SOCKET",
|
|
73
|
+
"CLAUDE_CODE_MESSAGING_TOKEN",
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# `settle.state.maybe_start` starts a run from these
|
|
78
|
+
SETTLE_VARS = ("MEM_SETTLE_AUTO", "MEM_SETTLE_MINUTES", "MEM_SETTLE_CLAUDE")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
ANSWERS = ("same", "faithful", "general")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
MAX_RETRIES = 2 # runs that end with a failed action or an unusable answer on the same lessons before the run gives up
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
# a `mem merge` refuses with any non-zero exit; any other exit is a failure
|
|
88
|
+
REFUSED_MEM_EXITS = {"remember": (4, 5)}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class StopError(Exception):
|
|
92
|
+
"""A run that cannot go on: `short` is the fixed reason the log line keeps, the message goes to the run's log.txt."""
|
|
93
|
+
|
|
94
|
+
def __init__(self, short: str, detail: str):
|
|
95
|
+
super().__init__(detail)
|
|
96
|
+
self.short = short
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
PROPOSE_BRIEF = """You compare short lessons that coding sessions wrote down, and say which of them state the same lesson.
|
|
100
|
+
|
|
101
|
+
Read {lessons}. Each line is: an id, a reach (general or project), the lesson, and when it applies, separated by tabs.
|
|
102
|
+
Ids starting with g: are lessons already kept for every project; ids starting with p1:, p2: ... belong to one project each.
|
|
103
|
+
An id is copied whole, exactly as written, with its g: or p1: start; a line number that your reading tool shows before a line is not an id.
|
|
104
|
+
|
|
105
|
+
Two lessons are the same when a reader who follows one would do what the other asks, in the same kind of situation,
|
|
106
|
+
even if the words, the example or the numbers differ. Lessons about the same topic that advise different things are
|
|
107
|
+
not the same. When you are not sure, leave them apart: a wrong group merges two lessons and loses one.
|
|
108
|
+
|
|
109
|
+
Write {out} as JSON: {{"groups": [{{"ids": ["..."], "claim": "...", "context": "..."}}]}}
|
|
110
|
+
- One group for each set of two or more lessons that are the same.
|
|
111
|
+
- Also one group for each general lesson with a p id that is in no other group and matches no g: lesson: a group of one.
|
|
112
|
+
- Never a group of one for a g: lesson or a project lesson.
|
|
113
|
+
- An id appears in at most one group.
|
|
114
|
+
- claim: the lesson in one to three sentences, as a suggestion or a recommendation that says what was seen and what
|
|
115
|
+
is not known, never an order. It must hold in any project: name no project, company, client, person, repository,
|
|
116
|
+
file, path, product or internal system. Keep what a reader needs to act: the situation, the action, the reason.
|
|
117
|
+
- context: one sentence on when the lesson applies, under the same rule about names.
|
|
118
|
+
Write nothing else and use no other tool.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
VERIFY_BRIEF = """You check proposals to treat several short lessons as one. Another reader made the proposals; it is often wrong, and
|
|
123
|
+
a wrong "yes" merges two different lessons and loses one, so say yes only when you are sure.
|
|
124
|
+
|
|
125
|
+
Read {groups}. Each block starts with "group <n>", then one line per lesson (an id, the lesson, when it applies,
|
|
126
|
+
separated by tabs), then a line starting with "proposed": the single wording that would replace them for every project.
|
|
127
|
+
|
|
128
|
+
For each group, answer in this order:
|
|
129
|
+
- reason: one sentence saying what each lesson asks the reader to do and whether that is the same thing.
|
|
130
|
+
- same: true only if a reader who follows any one of the lessons would do what each of the others asks, in the same
|
|
131
|
+
kind of situation. The same topic with different advice is false. For a group of one lesson, write true.
|
|
132
|
+
- faithful: true only if the proposed wording keeps the situation, the action and the reason of the lessons, adds no
|
|
133
|
+
claim they do not make, turns no suggestion into an order, and names no project, company, client, person,
|
|
134
|
+
repository, file, path, product or internal system.
|
|
135
|
+
- general: true only if the lesson is about how to work (planning, delegating, verifying, using tools, reading what
|
|
136
|
+
was asked) and would hold in another project; false if it only makes sense inside one codebase or product.
|
|
137
|
+
|
|
138
|
+
Write {out} as JSON: {{"verdicts": [{{"group": 1, "reason": "...", "same": true, "faithful": true, "general": true}}]}}
|
|
139
|
+
One entry per group, in order. Write nothing else and use no other tool.
|
|
140
|
+
"""
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
FILL_BRIEF = """You write the short form and the topic of lessons that coding sessions wrote down.
|
|
144
|
+
Read {lessons}: one block per lesson, with an id, a claim and sometimes a context.
|
|
145
|
+
For each lesson write: short: one sentence of at most 120 characters (aim for 100) that says what may be worth doing and when, as a suggestion, never stronger than the claim. Name the action as a thing or an -ing form ("quoting the source line may catch errors"), not as a command to the reader ("quote the source line"), unless the claim itself is a command. Keep the claim's hedge (may, once, sometimes, untested, provisional); if it is too long, drop alternatives and detail first, never the hedge. It must stand on its own, say "the user" and never "the owner", name no project, person or company, and add nothing the claim does not say. Use the context only to see when it applies. topic: one or two lowercase words for the area (for example: testing, process, shell, review, docs). An id is copied whole.
|
|
146
|
+
Write {out} as JSON: {{"items": [{{"id": "g:example", "short": "...", "topic": "..."}}]}}
|
|
147
|
+
One item per lesson. Write nothing else and use no other tool.
|
|
148
|
+
"""
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
CHECK_BRIEF = """You check one-sentence short forms of lessons against the lessons they were drawn from. Another writer made them; it sometimes makes a short form stronger or wider than its lesson, and a short form is loaded into every later session, so say faithful only when you are sure.
|
|
152
|
+
Read {pairs}: one block per lesson, with an id, a claim, sometimes a context that says when the lesson applies, and a short.
|
|
153
|
+
For each block answer in this order:
|
|
154
|
+
- reason: one sentence comparing what the claim asks, and when, with what the short asks, and when.
|
|
155
|
+
- faithful: true only if the short asks for nothing the claim does not, in no wider a situation, with no more certainty (a "may" or "once" in the claim is still there in the short), as a suggestion and not an order unless the claim is an order (a command addressed to the reader, such as "remove the files" or "confirm it first", is an order even when a "may" stands elsewhere in the sentence), and names no project, person or company. A short that leaves out examples or alternatives is still faithful; one that leaves out the situation the claim is about is not.
|
|
156
|
+
Write {out} as JSON: {{"verdicts": [{{"id": "g:example", "reason": "...", "faithful": true}}]}}
|
|
157
|
+
One entry per block. Write nothing else and use no other tool.
|
|
158
|
+
"""
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
REWORD_BRIEF = """You rewrite the short form of lessons that coding sessions wrote down. Each short form below was loaded into later sessions and the thing the lesson warns about still happened, so the present wording did not reach its reader.
|
|
162
|
+
Read {lessons}: one block per lesson, with an id, a claim, sometimes a context, every wording tried so far with how often the lesson then worked and failed, and what kind of failure followed where it is recorded.
|
|
163
|
+
For each lesson write: short: one sentence of at most 120 characters (aim for 100), drawn from the claim and not from the earlier wordings, that differs from all of them. Start with the situation in which it applies, in words a reader in that situation would recognize, then name what may be worth doing as a thing or an -ing form ("quoting the source line may catch errors"), not as a command to the reader, unless the claim itself is a command. It is a suggestion and never stronger than the claim: keep the claim's hedge (may, once, sometimes, untested, provisional); if it is too long, drop alternatives and detail first, never the hedge. It must stand on its own, say "the user" and never "the owner", name no project, person or company, and add nothing the claim does not say. An id is copied whole.
|
|
164
|
+
Write {out} as JSON: {{"items": [{{"id": "g:example", "short": "..."}}]}}
|
|
165
|
+
One item per lesson. Write nothing else and use no other tool.
|
|
166
|
+
"""
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
DIGEST_BRIEF = """You write, for groups of lessons that coding sessions wrote down, the text that later sessions read at their start. The lessons of one topic are printed together under one heading, so the heading says once what they share and each lesson's line does not repeat it.
|
|
170
|
+
Read {topics}: one block per topic, with its name, its heading (marked keep and followed by its text, or the word write), and its lessons. Each lesson has an id, a claim, sometimes a context, its short form, and the word write or keep; a kept lesson shows the line it already has, for you to read and not to change.
|
|
171
|
+
For a topic whose heading says write, write: heading: at most 80 characters, the situation in which the topic's lessons apply, as a clause a line can follow ("when briefing or reading a subagent"), true of every lesson under it, holding no advice, ending without a period, and naming no project, person or company.
|
|
172
|
+
For each lesson that says write, write: line: one sentence of at most 120 characters (aim for 100) that reads on from the heading. It does not repeat the situation the heading names; it says what may be worth doing, and why when the claim says why, drawn from the claim and not from the short form. It is a suggestion and never stronger than the claim: keep the claim's hedge (may, once, sometimes, untested, provisional); if it is too long, drop alternatives and detail first, never the hedge. Name the action as a thing or an -ing form ("quoting the source line may catch errors"), not as a command to the reader, unless the claim itself is a command. If the claim applies in a narrower situation than the heading, say so in the line. Say "the user" and never "the owner", name no project, person or company, and add nothing the claim does not say. An id is copied whole.
|
|
173
|
+
Write {out} as JSON: {{"topics": [{{"topic": "example", "heading": "...", "lines": [{{"id": "g:example", "line": "..."}}]}}]}}
|
|
174
|
+
Leave "heading" out for a topic whose heading is kept, and write lines only for lessons that say write. Write nothing else and use no other tool.
|
|
175
|
+
"""
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
DIGEST_CHECK_BRIEF = """You check texts that are loaded into every later coding session. The lessons of one topic are printed under a heading that names a situation, each as a line that reads on from it. Another writer made the headings and lines; it sometimes makes a line stronger or wider than its lesson, so say true only when you are sure.
|
|
179
|
+
Read {pairs}: one block per lesson, with an id, a claim, sometimes a context that says when the lesson applies, the heading of its topic, and its line.
|
|
180
|
+
For each block answer in this order:
|
|
181
|
+
- reason: one sentence comparing what the claim asks, and when, with what the heading and the line ask together, and when.
|
|
182
|
+
- fits: true only if the situation the claim is about lies inside the situation the heading names.
|
|
183
|
+
- faithful: true only if the heading and the line, read together, ask for nothing the claim does not, in no wider a situation than the claim's (when the heading is wider, the line must narrow it), with no more certainty (a "may" or "once" in the claim is still there), as a suggestion and not an order unless the claim is an order, and name no project, person or company. A line that leaves out examples or alternatives is still faithful; one that adds a reason or a condition the claim does not state is not.
|
|
184
|
+
Write {out} as JSON: {{"verdicts": [{{"id": "g:example", "reason": "...", "fits": true, "faithful": true}}]}}
|
|
185
|
+
One entry per block. Write nothing else and use no other tool.
|
|
186
|
+
"""
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
class SessionLimits(NamedTuple):
|
|
190
|
+
"""The model name and the maximum budget in USD of one session."""
|
|
191
|
+
|
|
192
|
+
model: str
|
|
193
|
+
max_budget: float
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
@dataclass
|
|
197
|
+
class Spend:
|
|
198
|
+
"""The runner of one run, resolved once, and the tokens its Codex sessions have used (Codex reports no money)."""
|
|
199
|
+
|
|
200
|
+
runner: str = "claude"
|
|
201
|
+
tokens: int = 0
|
|
202
|
+
|
|
203
|
+
@property
|
|
204
|
+
def spent_up(self) -> bool:
|
|
205
|
+
return self.runner == "codex" and codex_pass.over_cap(self.tokens)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
class AskJob(NamedTuple):
|
|
209
|
+
"""What `_ask` runs: the brief template, the text for the session, the template's key for that text and the
|
|
210
|
+
output file name."""
|
|
211
|
+
|
|
212
|
+
template: str
|
|
213
|
+
text: str
|
|
214
|
+
text_key: str
|
|
215
|
+
out_name: str
|
|
216
|
+
spend: Spend | None = None
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def session_spec(
|
|
220
|
+
claude: str, work: Path, brief: str, settings: Path, limits: SessionLimits
|
|
221
|
+
) -> headless.Session:
|
|
222
|
+
model, max_budget = limits
|
|
223
|
+
return headless.Session(
|
|
224
|
+
claude=claude,
|
|
225
|
+
prompt=brief,
|
|
226
|
+
model=model,
|
|
227
|
+
effort="medium",
|
|
228
|
+
settings=settings,
|
|
229
|
+
tools=("Read", "Write"),
|
|
230
|
+
allowed=(f"Read(/{work}/**)", f"Write(/{work}/**)", f"Edit(/{work}/**)"),
|
|
231
|
+
disallowed=("Bash", "WebSearch", "WebFetch"),
|
|
232
|
+
max_budget=max_budget,
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def session_cmd(
|
|
237
|
+
claude: str, work: Path, brief: str, settings: Path, limits: SessionLimits
|
|
238
|
+
) -> list[str]:
|
|
239
|
+
"""One session. Only Read and Write exist (`--tools`, no MCP server) and the rules allow them inside `work`
|
|
240
|
+
only; no Bash, no web, hooks disabled by `settings`."""
|
|
241
|
+
return headless.command(session_spec(claude, work, brief, settings, limits))
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def run_session(cmd: list[str], work: Path) -> dict:
|
|
245
|
+
raw = headless.run_raw(
|
|
246
|
+
cmd, cwd=work, env=headless.session_env(), timeout=SESSION_TIMEOUT, errors="replace"
|
|
247
|
+
).stdout
|
|
248
|
+
return sp.parse(raw)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
CODEX_IO_ADDENDUM = (
|
|
252
|
+
"Codex: read the input file and write the output file named above in the current folder with your shell; "
|
|
253
|
+
"run no other command, and use no tool beyond that. Then end with the one-word final message `done`."
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def run_on(spend: Spend, work: Path, spec: headless.Session, out: Path | None = None) -> dict:
|
|
258
|
+
"""One session on the run's runner; the `sp.parse` dict, with `tokens` from Codex. Codex writes its output file
|
|
259
|
+
`out` in `work`, which is its whole sandbox; a Codex session that leaves no `out` has failed."""
|
|
260
|
+
if spend.runner == "codex":
|
|
261
|
+
spec = replace(spec, prompt=f"{spec.prompt}\n\n{CODEX_IO_ADDENDUM}")
|
|
262
|
+
done = codex_pass.ask(spec, work, writes=True, timeout=SESSION_TIMEOUT)
|
|
263
|
+
spend.tokens += done["tokens"]
|
|
264
|
+
if spend.tokens > codex_pass.token_cap():
|
|
265
|
+
done |= {
|
|
266
|
+
"has_result": False,
|
|
267
|
+
"error": True,
|
|
268
|
+
"failure": f"{spend.tokens} tokens exceeded the token cap {codex_pass.token_cap()}",
|
|
269
|
+
}
|
|
270
|
+
if out is not None and done["has_result"] and not out.is_file():
|
|
271
|
+
done |= {"has_result": False, "error": True, "failure": f"it wrote no {out.name}"}
|
|
272
|
+
return done
|
|
273
|
+
return run_session(headless.command(spec), work)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def because(done: dict) -> str:
|
|
277
|
+
"""`: <why>` for a session that failed with a reason (a Codex session that wrote no output file), else ''."""
|
|
278
|
+
return f": {done['failure']}" if done.get("failure") else ""
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def missing_codex(spend: Spend) -> str | None:
|
|
282
|
+
"""Why a Codex run cannot start a session, or None (also for a Claude run)."""
|
|
283
|
+
if spend.runner == "codex" and runners.find_codex() is None:
|
|
284
|
+
return codex_pass.NO_CODEX
|
|
285
|
+
return None
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def read_object(path: Path) -> object:
|
|
289
|
+
"""The JSON of `path`, or None when it is missing, too large or not JSON (the validators then say why)."""
|
|
290
|
+
try:
|
|
291
|
+
if not path.is_file() or path.stat().st_size > MAX_FILE_BYTES:
|
|
292
|
+
return None
|
|
293
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
294
|
+
except (OSError, ValueError):
|
|
295
|
+
return None
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _remember_args(a) -> list[str]:
|
|
299
|
+
"""The `mem remember --global` call that writes the record of a `write_global` action."""
|
|
300
|
+
args = ["remember", "--global", f"--kind={a.record_kind}", f"--claim={a.claim}"]
|
|
301
|
+
if a.context:
|
|
302
|
+
args.append(f"--context={a.context}")
|
|
303
|
+
args += ["--origin", "transcript", "--reach", "general", "--weight", a.weight]
|
|
304
|
+
return [*args, *(f"--source={e}" for e in a.entries), "--body-file", "-"]
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _first_row(done: subprocess.CompletedProcess[str]) -> list[str]:
|
|
308
|
+
"""The tab-separated fields of the first line `mem` printed (a handle, then what happened)."""
|
|
309
|
+
text = done.stdout.strip()
|
|
310
|
+
return text.splitlines()[0].split("\t") if text else []
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
class Applier:
|
|
314
|
+
"""Applies the kept groups through `bin/mem`; the counts of what happened are in `counts`.
|
|
315
|
+
|
|
316
|
+
A refusal (exit 4 or 5 of `remember`, a non-zero `merge`) is counted and marked so the group is not tried again.
|
|
317
|
+
Any other result of a `mem` call (an undocumented exit code, a timeout, no process) is a failure: it stops the
|
|
318
|
+
group, marks nothing and keeps the run from saving its fingerprint, so the next run tries again."""
|
|
319
|
+
|
|
320
|
+
def __init__(
|
|
321
|
+
self,
|
|
322
|
+
journal: corroborate_state.Journal,
|
|
323
|
+
lessons: dict,
|
|
324
|
+
gfolder: Path | None,
|
|
325
|
+
cwd: Path,
|
|
326
|
+
log: Callable[[str], None],
|
|
327
|
+
):
|
|
328
|
+
self.journal, self.lessons, self.gfolder, self.cwd, self.log = (
|
|
329
|
+
journal,
|
|
330
|
+
lessons,
|
|
331
|
+
gfolder,
|
|
332
|
+
cwd,
|
|
333
|
+
log,
|
|
334
|
+
)
|
|
335
|
+
self.counts = {
|
|
336
|
+
"written": 0,
|
|
337
|
+
"sightings": 0,
|
|
338
|
+
"links": 0,
|
|
339
|
+
"merges": 0,
|
|
340
|
+
"refused": 0,
|
|
341
|
+
"failed_actions": 0,
|
|
342
|
+
"cases": 0,
|
|
343
|
+
}
|
|
344
|
+
self.refused_ids: set[str] = set()
|
|
345
|
+
self.current: corroborate_decide.Group | None = None
|
|
346
|
+
self.written: str | None = (
|
|
347
|
+
None # the global record that this group's write_global made or found
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
def mem(
|
|
351
|
+
self,
|
|
352
|
+
args: list[str],
|
|
353
|
+
project: Path | None = None,
|
|
354
|
+
stdin: str | None = None,
|
|
355
|
+
drop_env: tuple = (),
|
|
356
|
+
) -> subprocess.CompletedProcess[str] | None:
|
|
357
|
+
env = {
|
|
358
|
+
k: v
|
|
359
|
+
for k, v in os.environ.items()
|
|
360
|
+
if k not in SESSION_VARS and k not in drop_env and k != "MEM_PROJECT"
|
|
361
|
+
}
|
|
362
|
+
if project is not None:
|
|
363
|
+
env["MEM_PROJECT"] = str(project)
|
|
364
|
+
try:
|
|
365
|
+
done = subprocess.run(
|
|
366
|
+
[*MEM, *args],
|
|
367
|
+
env=resources.child_env(env),
|
|
368
|
+
cwd=self.cwd,
|
|
369
|
+
input=stdin,
|
|
370
|
+
capture_output=True,
|
|
371
|
+
text=True,
|
|
372
|
+
errors="replace",
|
|
373
|
+
timeout=MEM_TIMEOUT,
|
|
374
|
+
check=False,
|
|
375
|
+
)
|
|
376
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
377
|
+
self.log(f"mem {args[0]}: could not run ({type(exc).__name__})")
|
|
378
|
+
return None
|
|
379
|
+
self.log(
|
|
380
|
+
f"mem {args[0]}: exit {done.returncode} {done.stdout.strip()[:120]!r} {done.stderr.strip()[:200]!r}"
|
|
381
|
+
)
|
|
382
|
+
return done
|
|
383
|
+
|
|
384
|
+
def handle(self, lesson_id: str) -> str:
|
|
385
|
+
return f"m:{self.lessons[lesson_id].memory.handle}"
|
|
386
|
+
|
|
387
|
+
def add_cases(self, target: str, entries: list[str], cases: list[str]) -> bool:
|
|
388
|
+
"""One `mem confirm` per case of the action, for the session's entry; exit 3 (the case is already there) is
|
|
389
|
+
fine, exit 0 counts a case written. False when a call failed."""
|
|
390
|
+
by_session = {records.session_key(e): e for e in reversed(entries)}
|
|
391
|
+
for raw in cases:
|
|
392
|
+
c = records.case(raw)
|
|
393
|
+
entry = by_session.get(c.session) if c else None
|
|
394
|
+
if c is None or entry is None:
|
|
395
|
+
continue
|
|
396
|
+
done = self.mem([
|
|
397
|
+
"confirm",
|
|
398
|
+
target,
|
|
399
|
+
"--global",
|
|
400
|
+
f"--source={entry}",
|
|
401
|
+
f"--outcome={c.outcome}",
|
|
402
|
+
f"--seen-on={c.on.isoformat()}",
|
|
403
|
+
])
|
|
404
|
+
if done is None or done.returncode not in {0, ALREADY_THERE}:
|
|
405
|
+
return False
|
|
406
|
+
self.counts["cases"] += done.returncode == 0
|
|
407
|
+
return True
|
|
408
|
+
|
|
409
|
+
def sight(self, target: str, entry: str, cases: list[str]):
|
|
410
|
+
"""The sighting of `entry`: its first case rides on the first call, so no `seen` entry is logged for it. The
|
|
411
|
+
result of that call, and whether the cases after it went well (None when the call itself did not work)."""
|
|
412
|
+
parsed = [c for c in map(records.case, cases) if c]
|
|
413
|
+
extra = (
|
|
414
|
+
[f"--outcome={parsed[0].outcome}", f"--seen-on={parsed[0].on.isoformat()}"]
|
|
415
|
+
if parsed
|
|
416
|
+
else []
|
|
417
|
+
)
|
|
418
|
+
done = self.mem(["confirm", target, "--global", f"--source={entry}", *extra])
|
|
419
|
+
if done is None or done.returncode not in {0, ALREADY_THERE}:
|
|
420
|
+
return done, None
|
|
421
|
+
if parsed and done.returncode == 0:
|
|
422
|
+
self.counts["cases"] += 1
|
|
423
|
+
return done, self.add_cases(target, [entry], cases[1:] if parsed else cases)
|
|
424
|
+
|
|
425
|
+
def path(self, lesson_id: str) -> Path:
|
|
426
|
+
return self.lessons[lesson_id].memory.path
|
|
427
|
+
|
|
428
|
+
def apply(self, group, acts) -> bool:
|
|
429
|
+
"""Every action of one group, in order; False when one was refused or failed and the rest was left."""
|
|
430
|
+
self.written = None
|
|
431
|
+
steps = {
|
|
432
|
+
"merge": self._merge,
|
|
433
|
+
"merge_global": self._merge,
|
|
434
|
+
"write_global": self._write_global,
|
|
435
|
+
"sighting": self._sighting,
|
|
436
|
+
"cases": self._cases,
|
|
437
|
+
"link": self._link,
|
|
438
|
+
}
|
|
439
|
+
for a in acts:
|
|
440
|
+
step = steps.get(a.kind)
|
|
441
|
+
if step is not None and not step(a):
|
|
442
|
+
return False
|
|
443
|
+
return True
|
|
444
|
+
|
|
445
|
+
def _merge(self, a) -> bool:
|
|
446
|
+
args = [
|
|
447
|
+
"merge",
|
|
448
|
+
*(["--global"] if a.kind == "merge_global" else []),
|
|
449
|
+
self.handle(a.keep),
|
|
450
|
+
self.handle(a.drop),
|
|
451
|
+
]
|
|
452
|
+
before = self.journal.watch([self.path(a.keep), self.path(a.drop)])
|
|
453
|
+
done = self.mem(args, a.project)
|
|
454
|
+
self.journal.commit(a.kind, before)
|
|
455
|
+
if done is None:
|
|
456
|
+
return self.fail()
|
|
457
|
+
if done.returncode:
|
|
458
|
+
return self.refuse() # left for curation, never forced
|
|
459
|
+
self.counts["merges"] += 1
|
|
460
|
+
return True
|
|
461
|
+
|
|
462
|
+
def _run_remember(self, a) -> tuple[subprocess.CompletedProcess[str] | None, list[str], bool]:
|
|
463
|
+
"""`mem remember` for a `write_global` action and the cases of its record: the result, its first row, whether
|
|
464
|
+
the case calls went well; what changed in the global folder is journaled."""
|
|
465
|
+
before = self.journal.watch_folder(self.gfolder) if self.gfolder else {}
|
|
466
|
+
# no counts in the body: the record is not rewritten when a sighting arrives, so a figure would go stale
|
|
467
|
+
done = self.mem(_remember_args(a), stdin=REMEMBER_BODY)
|
|
468
|
+
first = _first_row(done) if done else []
|
|
469
|
+
cases_ok = True
|
|
470
|
+
if (
|
|
471
|
+
done is not None
|
|
472
|
+
and done.returncode in {0, ALREADY_THERE}
|
|
473
|
+
and first
|
|
474
|
+
and first[0].startswith("m:")
|
|
475
|
+
):
|
|
476
|
+
cases_ok = self.add_cases(first[0], a.entries, a.cases)
|
|
477
|
+
self.journal.commit("write_global", before, self.gfolder)
|
|
478
|
+
return done, first, cases_ok
|
|
479
|
+
|
|
480
|
+
def _write_global(self, a) -> bool:
|
|
481
|
+
done, first, cases_ok = self._run_remember(a)
|
|
482
|
+
named = bool(first) and first[0].startswith("m:")
|
|
483
|
+
if done is not None and done.returncode == 0 and named:
|
|
484
|
+
self.counts["written"] += 1 # the record exists, though a case call may have failed
|
|
485
|
+
self.written = first[0]
|
|
486
|
+
if done is None or not cases_ok:
|
|
487
|
+
return self.fail()
|
|
488
|
+
if done.returncode == ALREADY_THERE and len(first) == ROW_FIELDS and named:
|
|
489
|
+
self.written = first[0] # the claim exists: its sightings were added by `remember`
|
|
490
|
+
self.counts["sightings"] += first[1] == "sighting"
|
|
491
|
+
return True
|
|
492
|
+
if done.returncode == 0 and named:
|
|
493
|
+
return True
|
|
494
|
+
if done.returncode in REFUSED_MEM_EXITS["remember"]:
|
|
495
|
+
return self.refuse()
|
|
496
|
+
return self.fail()
|
|
497
|
+
|
|
498
|
+
def _sighting(self, a) -> bool:
|
|
499
|
+
target = (a.target and f"m:{a.target}") or self.written
|
|
500
|
+
if not target or not self.gfolder:
|
|
501
|
+
return self.refuse()
|
|
502
|
+
before = self.journal.watch([self.gfolder / f"{target[2:]}.md"])
|
|
503
|
+
done, cases_ok = self.sight(target, a.entry, a.cases)
|
|
504
|
+
self.journal.commit("sighting", before)
|
|
505
|
+
if done is not None and done.returncode == 0:
|
|
506
|
+
self.counts["sightings"] += 1
|
|
507
|
+
if cases_ok is False or done is None or done.returncode not in {0, ALREADY_THERE}:
|
|
508
|
+
return self.fail()
|
|
509
|
+
return True
|
|
510
|
+
|
|
511
|
+
def _cases(self, a) -> bool:
|
|
512
|
+
if not a.target or not self.gfolder:
|
|
513
|
+
return self.refuse()
|
|
514
|
+
before = self.journal.watch([self.gfolder / f"{a.target}.md"])
|
|
515
|
+
cases_ok = self.add_cases(f"m:{a.target}", [a.entry], a.cases)
|
|
516
|
+
self.journal.commit("cases", before)
|
|
517
|
+
return cases_ok or self.fail()
|
|
518
|
+
|
|
519
|
+
def _link(self, a) -> bool:
|
|
520
|
+
target = (a.target and f"m:{a.target}") or self.written
|
|
521
|
+
if not target:
|
|
522
|
+
return self.refuse()
|
|
523
|
+
before = self.journal.watch([self.path(a.member)])
|
|
524
|
+
done = self.mem(["promote", "--done", self.handle(a.member), "--to", target], a.project)
|
|
525
|
+
self.journal.commit("link", before)
|
|
526
|
+
if done is not None and done.returncode == 0:
|
|
527
|
+
self.counts["links"] += 1
|
|
528
|
+
return True
|
|
529
|
+
return self.fail()
|
|
530
|
+
|
|
531
|
+
def refuse(self) -> bool:
|
|
532
|
+
self.counts["refused"] += 1
|
|
533
|
+
if self.current is None: # only `apply` reaches here, with the group set by `_apply_groups`
|
|
534
|
+
raise AttributeError("refuse() needs the group being applied")
|
|
535
|
+
self.refused_ids.update(self.current.ids)
|
|
536
|
+
return False
|
|
537
|
+
|
|
538
|
+
def fail(self) -> bool:
|
|
539
|
+
self.counts["failed_actions"] += 1
|
|
540
|
+
return False
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def stable_key(lesson) -> str:
|
|
544
|
+
"""The name of a lesson that does not change between runs (the ids of a lessons file depend on the registry)."""
|
|
545
|
+
return corroborate_decide.fill_key(lesson.project, lesson.memory.handle)
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def planned(acts) -> list[dict]:
|
|
549
|
+
out = []
|
|
550
|
+
for a in acts:
|
|
551
|
+
row = {k: v for k, v in vars(a).items() if v not in (None, [], "")}
|
|
552
|
+
if "project" in row:
|
|
553
|
+
row["project"] = records.project_key(a.project)
|
|
554
|
+
out.append(row)
|
|
555
|
+
return out
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def refused_by_verdict(verdict_data: object, n: int) -> bool:
|
|
559
|
+
"""True when exactly one verdict names group `n` and its `same` or `general` is present and not `true` (so "yes"
|
|
560
|
+
or `null` counts as a refusal): a verdict that is missing, repeated or lacks both is not. A group refused only
|
|
561
|
+
because its rewording is not `faithful` is not a refusal to remember: the next run rewords it again."""
|
|
562
|
+
items = verdict_data.get("verdicts") if isinstance(verdict_data, dict) else None
|
|
563
|
+
if not isinstance(items, list):
|
|
564
|
+
return False
|
|
565
|
+
found = [
|
|
566
|
+
v
|
|
567
|
+
for v in items
|
|
568
|
+
if isinstance(v, dict) and v.get("group") == n and not isinstance(v.get("group"), bool)
|
|
569
|
+
]
|
|
570
|
+
return len(found) == 1 and any(
|
|
571
|
+
k in found[0] and found[0][k] is not True for k in ("same", "general")
|
|
572
|
+
)
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def has_verdict(verdict_data: object, n: int) -> bool:
|
|
576
|
+
items = verdict_data.get("verdicts") if isinstance(verdict_data, dict) else None
|
|
577
|
+
return isinstance(items, list) and any(
|
|
578
|
+
isinstance(v, dict) and v.get("group") == n and not isinstance(v.get("group"), bool)
|
|
579
|
+
for v in items
|
|
580
|
+
)
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def _blank_line() -> dict:
|
|
584
|
+
return {
|
|
585
|
+
"t": datetime.datetime.now(datetime.UTC).isoformat(timespec="seconds"),
|
|
586
|
+
"lessons": 0,
|
|
587
|
+
"groups": 0,
|
|
588
|
+
"proposed": 0,
|
|
589
|
+
"verified": 0,
|
|
590
|
+
"dropped": 0,
|
|
591
|
+
"written": 0,
|
|
592
|
+
"sightings": 0,
|
|
593
|
+
"links": 0,
|
|
594
|
+
"merges": 0,
|
|
595
|
+
"refused": 0,
|
|
596
|
+
"failed_actions": 0,
|
|
597
|
+
"cases": 0,
|
|
598
|
+
"skipped": None,
|
|
599
|
+
"cost": 0.0,
|
|
600
|
+
"tokens": 0,
|
|
601
|
+
"runner": "claude",
|
|
602
|
+
"failed": None,
|
|
603
|
+
"ms": 0,
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
@dataclass
|
|
608
|
+
class _Run:
|
|
609
|
+
"""What the phases of one `execute` share: its inputs, the log line it builds and the run folder it logs to."""
|
|
610
|
+
|
|
611
|
+
claude: str # "" when there is none
|
|
612
|
+
budget: float
|
|
613
|
+
groups_file: str | None
|
|
614
|
+
dry_run: bool
|
|
615
|
+
out_file: str | None
|
|
616
|
+
data: Path
|
|
617
|
+
cdir: Path
|
|
618
|
+
scratch: Path | None # a dry run's folder, in place of a run folder
|
|
619
|
+
line: dict = field(default_factory=_blank_line)
|
|
620
|
+
spend: Spend = field(default_factory=Spend)
|
|
621
|
+
start: float = field(default_factory=time.time)
|
|
622
|
+
run: Path | None = None
|
|
623
|
+
logged: bool = False
|
|
624
|
+
|
|
625
|
+
def finish_log(self) -> None:
|
|
626
|
+
if self.dry_run:
|
|
627
|
+
return
|
|
628
|
+
self.line["ms"] = int((time.time() - self.start) * 1000)
|
|
629
|
+
corroborate_state.append_log(self.cdir, self.line)
|
|
630
|
+
self.logged = True
|
|
631
|
+
|
|
632
|
+
def log(self, text: str) -> None:
|
|
633
|
+
if self.run is None:
|
|
634
|
+
return
|
|
635
|
+
fd = os.open(self.run / "log.txt", os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
|
|
636
|
+
with os.fdopen(fd, "a", encoding="utf-8", errors="replace") as f:
|
|
637
|
+
f.write(f"{time.strftime('%H:%M:%S')} {text}\n")
|
|
638
|
+
|
|
639
|
+
|
|
640
|
+
@dataclass
|
|
641
|
+
class _World:
|
|
642
|
+
"""Where the lessons come from."""
|
|
643
|
+
|
|
644
|
+
registry: dict
|
|
645
|
+
gfolder: Path | None
|
|
646
|
+
today: datetime.date
|
|
647
|
+
|
|
648
|
+
def collect(self) -> list:
|
|
649
|
+
return corroborate_decide.collect(
|
|
650
|
+
corroborate_decide.counted_projects(self.registry), self.gfolder, self.today
|
|
651
|
+
)
|
|
652
|
+
|
|
653
|
+
|
|
654
|
+
@dataclass
|
|
655
|
+
class _Judged:
|
|
656
|
+
"""What the sessions (or a reviewed groups file) decided about the lessons."""
|
|
657
|
+
|
|
658
|
+
proposal: object
|
|
659
|
+
proposed: list
|
|
660
|
+
reasons: list[str]
|
|
661
|
+
kept: list
|
|
662
|
+
vreasons: list[str]
|
|
663
|
+
verdict_data: object = None
|
|
664
|
+
incomplete: bool = (
|
|
665
|
+
False # a session left no usable file: nothing is saved, so the next run asks again
|
|
666
|
+
)
|
|
667
|
+
refused: set[str] = field(
|
|
668
|
+
default_factory=set
|
|
669
|
+
) # ids of the groups the verifying session refused
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def _make_run_folder(cdir: Path) -> Path:
|
|
673
|
+
run = cdir / "runs" / f"{time.strftime('%Y%m%d-%H%M%S')}-{os.getpid()}"
|
|
674
|
+
jobs.private_dir(run)
|
|
675
|
+
return run
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
def _read_world(data: Path) -> _World:
|
|
679
|
+
try:
|
|
680
|
+
registry = records.read_registry(data)
|
|
681
|
+
except ValueError as exc:
|
|
682
|
+
raise StopError("registry unreadable", f"registry: {exc}") from exc
|
|
683
|
+
return _World(registry, records.global_memories_root(os.environ), datetime.date.today())
|
|
684
|
+
|
|
685
|
+
|
|
686
|
+
def _skip_reason(ctx: _Run, seen: dict, lessons: list, before: str) -> str | None:
|
|
687
|
+
if not lessons:
|
|
688
|
+
return "no lessons"
|
|
689
|
+
if not (ctx.groups_file or ctx.dry_run) and seen.get("fingerprint") == before:
|
|
690
|
+
return "nothing new"
|
|
691
|
+
return None
|
|
692
|
+
|
|
693
|
+
|
|
694
|
+
def _start_run(ctx: _Run) -> Path:
|
|
695
|
+
"""The folder this run writes to: a dry run's scratch folder, else a new run folder (and a `running` status)."""
|
|
696
|
+
if ctx.scratch is not None:
|
|
697
|
+
return ctx.scratch
|
|
698
|
+
ctx.run = _make_run_folder(ctx.cdir)
|
|
699
|
+
corroborate_state.save_status(
|
|
700
|
+
ctx.cdir, state="running", started=time.time(), finished=None, log=str(ctx.run)
|
|
701
|
+
)
|
|
702
|
+
return ctx.run
|
|
703
|
+
|
|
704
|
+
|
|
705
|
+
def _run_checked(ctx: _Run, work: Path, brief: str, model: str, stage: str) -> None:
|
|
706
|
+
"""One session of a stage ("propose" or "verify"): its cost goes to the line, a failed one stops the run."""
|
|
707
|
+
doing, out_name = {
|
|
708
|
+
"propose": ("proposing", "groups.json"),
|
|
709
|
+
"verify": ("verifying", "verdicts.json"),
|
|
710
|
+
}[stage]
|
|
711
|
+
if ctx.spend.spent_up:
|
|
712
|
+
raise StopError(
|
|
713
|
+
"token cap",
|
|
714
|
+
f"the {doing} session did not start: {ctx.spend.tokens} tokens reached the cap",
|
|
715
|
+
)
|
|
716
|
+
limits = SessionLimits(model, ctx.budget)
|
|
717
|
+
done = run_on(
|
|
718
|
+
ctx.spend,
|
|
719
|
+
work,
|
|
720
|
+
session_spec(ctx.claude, work, brief, work.parent / "settings.json", limits),
|
|
721
|
+
work / out_name,
|
|
722
|
+
)
|
|
723
|
+
ctx.line["cost"] += done["cost"] if done["has_result"] else 0.0
|
|
724
|
+
ctx.line["tokens"] = ctx.spend.tokens
|
|
725
|
+
spent = (
|
|
726
|
+
f"tokens={done['tokens']}" if ctx.spend.runner == "codex" else f"cost={done['cost']:.3f}"
|
|
727
|
+
)
|
|
728
|
+
ctx.log(f"{stage}: has_result={done['has_result']} error={done['error']} {spent}")
|
|
729
|
+
if not done["has_result"] or done["error"]:
|
|
730
|
+
no_result = (
|
|
731
|
+
"ended without a result"
|
|
732
|
+
if ctx.spend.runner == "codex"
|
|
733
|
+
else "ended without a cost report"
|
|
734
|
+
)
|
|
735
|
+
raise StopError(
|
|
736
|
+
"session error",
|
|
737
|
+
(
|
|
738
|
+
f"the {doing} session {no_result}"
|
|
739
|
+
if not done["has_result"]
|
|
740
|
+
else f"the {doing} session failed"
|
|
741
|
+
)
|
|
742
|
+
+ codex_pass.reason(done),
|
|
743
|
+
)
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
def _propose(ctx: _Run, root: Path) -> object:
|
|
747
|
+
work = root / "propose"
|
|
748
|
+
work.mkdir(mode=0o700)
|
|
749
|
+
corroborate_state.write_private(
|
|
750
|
+
work / "lessons.txt", (root / "lessons.txt").read_text(encoding="utf-8")
|
|
751
|
+
)
|
|
752
|
+
out = work / "groups.json"
|
|
753
|
+
brief = PROPOSE_BRIEF.format(lessons=work / "lessons.txt", out=out)
|
|
754
|
+
_run_checked(ctx, work, brief, PROPOSE_MODEL, "propose")
|
|
755
|
+
return read_object(out)
|
|
756
|
+
|
|
757
|
+
|
|
758
|
+
def _verify(ctx: _Run, root: Path, judged: _Judged, by_id: dict) -> None:
|
|
759
|
+
"""The verifying session over the proposed groups: sets what was kept and why the rest was not."""
|
|
760
|
+
work = root / "verify"
|
|
761
|
+
work.mkdir(mode=0o700)
|
|
762
|
+
lines = corroborate_decide.verification_lines(judged.proposed, by_id)
|
|
763
|
+
corroborate_state.write_private(work / "groups.txt", "".join(f"{ln}\n" for ln in lines))
|
|
764
|
+
out = work / "verdicts.json"
|
|
765
|
+
brief = VERIFY_BRIEF.format(groups=work / "groups.txt", out=out)
|
|
766
|
+
_run_checked(ctx, work, brief, VERIFY_MODEL, "verify")
|
|
767
|
+
data = read_object(out)
|
|
768
|
+
judged.verdict_data = data
|
|
769
|
+
judged.incomplete = judged.incomplete or not (
|
|
770
|
+
isinstance(data, dict) and isinstance(data.get("verdicts"), list)
|
|
771
|
+
)
|
|
772
|
+
judged.kept, judged.vreasons = corroborate_decide.validate_verdicts(data, judged.proposed)
|
|
773
|
+
|
|
774
|
+
|
|
775
|
+
def _judge_file(groups_file: str, lessons: list) -> _Judged:
|
|
776
|
+
"""A reviewed groups file: no sessions, every valid group is kept."""
|
|
777
|
+
proposal = read_object(Path(groups_file).expanduser())
|
|
778
|
+
proposed, reasons = corroborate_decide.validate_groups(proposal, lessons)
|
|
779
|
+
return _Judged(proposal, proposed, reasons, list(proposed), [])
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
def _judge_sessions(
|
|
783
|
+
ctx: _Run, root: Path, lessons: list, by_id: dict, refused_seen: dict
|
|
784
|
+
) -> _Judged:
|
|
785
|
+
if ctx.spend.runner == "claude" and not ctx.claude:
|
|
786
|
+
raise StopError("no claude", "no claude binary (--claude, CLAUDE_CODE_EXECPATH or PATH)")
|
|
787
|
+
if missing := missing_codex(ctx.spend):
|
|
788
|
+
raise StopError("no codex", missing)
|
|
789
|
+
corroborate_state.write_private(root / "settings.json", json.dumps({"disableAllHooks": True}))
|
|
790
|
+
proposal = _propose(ctx, root)
|
|
791
|
+
incomplete = not (isinstance(proposal, dict) and isinstance(proposal.get("groups"), list))
|
|
792
|
+
proposed, reasons = corroborate_decide.validate_groups(proposal, lessons)
|
|
793
|
+
# a refused group waits until one of its lessons changes (a sighting, a new wording): all marks must still hold
|
|
794
|
+
proposed = [
|
|
795
|
+
g
|
|
796
|
+
for g in proposed
|
|
797
|
+
if not all(
|
|
798
|
+
refused_seen.get(stable_key(by_id[i]))
|
|
799
|
+
== corroborate_decide.lesson_fingerprint(by_id[i])
|
|
800
|
+
for i in g.ids
|
|
801
|
+
)
|
|
802
|
+
]
|
|
803
|
+
judged = _Judged(proposal, proposed, reasons, [], [], None, incomplete)
|
|
804
|
+
if proposed:
|
|
805
|
+
_verify(ctx, root, judged, by_id)
|
|
806
|
+
return judged
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
def _count_judgement(ctx: _Run, judged: _Judged) -> None:
|
|
810
|
+
"""Put the counts of the sessions on the line, log what was not applied and note what the verifier refused."""
|
|
811
|
+
proposed, kept = judged.proposed, judged.kept
|
|
812
|
+
raw_groups = judged.proposal.get("groups") if isinstance(judged.proposal, dict) else None
|
|
813
|
+
ctx.line["groups"] = len(raw_groups) if isinstance(raw_groups, list) else 0
|
|
814
|
+
ctx.line["proposed"], ctx.line["verified"], ctx.line["dropped"] = (
|
|
815
|
+
len(proposed),
|
|
816
|
+
len(kept),
|
|
817
|
+
len(judged.reasons),
|
|
818
|
+
)
|
|
819
|
+
# a proposed group the verifying session did not answer is neither applied nor marked: ask again
|
|
820
|
+
judged.incomplete = judged.incomplete or any(
|
|
821
|
+
g not in kept and not has_verdict(judged.verdict_data, n)
|
|
822
|
+
for n, g in enumerate(proposed, start=1)
|
|
823
|
+
if not ctx.groups_file
|
|
824
|
+
)
|
|
825
|
+
if judged.incomplete: # no usable answer from a session counts as dropped, even where the validator says it per group
|
|
826
|
+
ctx.line["dropped"] += len(judged.vreasons)
|
|
827
|
+
for why in [*judged.reasons, *judged.vreasons]:
|
|
828
|
+
ctx.log(f"not applied: {why}")
|
|
829
|
+
judged.refused = {
|
|
830
|
+
i
|
|
831
|
+
for n, g in enumerate(proposed, start=1)
|
|
832
|
+
if g not in kept and refused_by_verdict(judged.verdict_data, n)
|
|
833
|
+
for i in g.ids
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
|
|
837
|
+
def _write_plan(ctx: _Run, judged: _Judged, by_id: dict) -> None:
|
|
838
|
+
"""A dry run's only output: the proposal, the verdicts and the planned actions."""
|
|
839
|
+
if ctx.out_file is None:
|
|
840
|
+
raise TypeError("a dry run needs an output file")
|
|
841
|
+
plan = [
|
|
842
|
+
{"ids": g.ids, "claim": g.claim, "actions": planned(corroborate_decide.actions(g, by_id))}
|
|
843
|
+
for g in judged.kept
|
|
844
|
+
]
|
|
845
|
+
report = {
|
|
846
|
+
"proposal": judged.proposal,
|
|
847
|
+
"dropped": judged.reasons,
|
|
848
|
+
"verdicts": judged.verdict_data,
|
|
849
|
+
"not_verified": judged.vreasons,
|
|
850
|
+
"plan": plan,
|
|
851
|
+
}
|
|
852
|
+
corroborate_state.write_private(
|
|
853
|
+
Path(ctx.out_file), json.dumps(report, ensure_ascii=False, indent=1) + "\n"
|
|
854
|
+
)
|
|
855
|
+
|
|
856
|
+
|
|
857
|
+
def _apply_groups(ctx: _Run, judged: _Judged, by_id: dict, root: Path, world: _World) -> set[str]:
|
|
858
|
+
"""Apply the kept groups, one at a time; a group that raises counts as a failed action. The counts go to the
|
|
859
|
+
line. The ids to mark as refused: the verifier's and the applier's, less those of a group that failed."""
|
|
860
|
+
applier = Applier(corroborate_state.Journal(root), by_id, world.gfolder, root, ctx.log)
|
|
861
|
+
failed_ids: set[str] = set()
|
|
862
|
+
for g in judged.kept:
|
|
863
|
+
applier.current = g
|
|
864
|
+
failed_before = applier.counts["failed_actions"]
|
|
865
|
+
try:
|
|
866
|
+
applier.apply(g, corroborate_decide.actions(g, by_id))
|
|
867
|
+
except Exception as exc: # one odd group never stops the others
|
|
868
|
+
logger.debug("a group failed", exc_info=True)
|
|
869
|
+
ctx.log(f"group failed: {type(exc).__name__}: {exc}")
|
|
870
|
+
applier.fail()
|
|
871
|
+
if applier.counts["failed_actions"] > failed_before:
|
|
872
|
+
failed_ids.update(g.ids)
|
|
873
|
+
for key in ("written", "sightings", "links", "merges", "refused", "failed_actions", "cases"):
|
|
874
|
+
ctx.line[key] = applier.counts[key]
|
|
875
|
+
return (judged.refused | applier.refused_ids) - failed_ids
|
|
876
|
+
|
|
877
|
+
|
|
878
|
+
def _refusal_marks(
|
|
879
|
+
world: _World, by_id: dict, refused_seen: dict, ids: set[str]
|
|
880
|
+
) -> tuple[dict, set[str]]:
|
|
881
|
+
"""The marks the next run keeps: the fingerprints the lessons have now, after this run's own writes (a merge
|
|
882
|
+
changes the kept record); the marks this run added."""
|
|
883
|
+
after = {stable_key(x): corroborate_decide.lesson_fingerprint(x) for x in world.collect()}
|
|
884
|
+
marked = {stable_key(by_id[i]) for i in ids}
|
|
885
|
+
marks = {k: v for k, v in refused_seen.items() if isinstance(v, str) and k in after}
|
|
886
|
+
marks.update({k: after[k] for k in marked if k in after})
|
|
887
|
+
return marks, marked
|
|
888
|
+
|
|
889
|
+
|
|
890
|
+
def _retries_so_far(seen: dict, before: str) -> int:
|
|
891
|
+
old = seen.get("retry")
|
|
892
|
+
if (
|
|
893
|
+
isinstance(old, dict)
|
|
894
|
+
and old.get("fingerprint") == before
|
|
895
|
+
and isinstance(old.get("count"), int)
|
|
896
|
+
):
|
|
897
|
+
return old["count"]
|
|
898
|
+
return 0
|
|
899
|
+
|
|
900
|
+
|
|
901
|
+
def _retry_entry(world: _World, seen: dict, before: str) -> tuple[dict, bool]:
|
|
902
|
+
"""A run with a failed action or an unusable answer saves no fingerprint, so the next run tries again, but only
|
|
903
|
+
MAX_RETRIES times on the same lessons; then it gives up (the fingerprint is saved) and says so."""
|
|
904
|
+
count = _retries_so_far(seen, before) + 1
|
|
905
|
+
now = corroborate_decide.fingerprint(
|
|
906
|
+
world.collect()
|
|
907
|
+
) # after this run's writes: what the next run starts from
|
|
908
|
+
if count >= MAX_RETRIES:
|
|
909
|
+
return {"fingerprint": now}, True
|
|
910
|
+
return {"retry": {"fingerprint": now, "count": count}}, False
|
|
911
|
+
|
|
912
|
+
|
|
913
|
+
def _next_state(
|
|
914
|
+
ctx: _Run, world: _World, seen: dict, before: str, incomplete: bool
|
|
915
|
+
) -> tuple[dict, bool]:
|
|
916
|
+
"""The fingerprint or retry entry for `seen.json`, and whether the run gives up on these lessons."""
|
|
917
|
+
failing = ctx.line["failed_actions"] or incomplete
|
|
918
|
+
if failing and not ctx.groups_file:
|
|
919
|
+
return _retry_entry(world, seen, before)
|
|
920
|
+
state: dict = {}
|
|
921
|
+
if failing:
|
|
922
|
+
if isinstance(
|
|
923
|
+
seen.get("retry"), dict
|
|
924
|
+
): # a reviewed file starts no session and leaves the bound alone
|
|
925
|
+
state["retry"] = seen["retry"]
|
|
926
|
+
elif (
|
|
927
|
+
not ctx.groups_file
|
|
928
|
+
): # a reviewed file never tells the model's pass that the lessons were seen
|
|
929
|
+
state["fingerprint"] = corroborate_decide.fingerprint(world.collect())
|
|
930
|
+
elif "fingerprint" in seen:
|
|
931
|
+
state["fingerprint"] = seen["fingerprint"]
|
|
932
|
+
return state, False
|
|
933
|
+
|
|
934
|
+
|
|
935
|
+
def _resolve_runner(ctx: _Run) -> None:
|
|
936
|
+
"""After the lock (the run folder of a failure needs it); a malformed setting fails the run naming its source."""
|
|
937
|
+
try:
|
|
938
|
+
ctx.spend.runner = ctx.line["runner"] = runners.resolve_runner(None)
|
|
939
|
+
except ValueError as exc:
|
|
940
|
+
raise StopError("runner setting", str(exc)) from exc
|
|
941
|
+
|
|
942
|
+
|
|
943
|
+
def _run_pass(ctx: _Run) -> dict:
|
|
944
|
+
_resolve_runner(ctx) # once per run, before any early stop
|
|
945
|
+
seen = jobs.read_json(ctx.cdir / "seen.json")
|
|
946
|
+
refused_seen = seen["refused"] if isinstance(seen.get("refused"), dict) else {}
|
|
947
|
+
world = _read_world(ctx.data)
|
|
948
|
+
lessons = world.collect()
|
|
949
|
+
before = corroborate_decide.fingerprint(
|
|
950
|
+
lessons
|
|
951
|
+
) # compared with the retry a failed run stored (its lessons after its writes)
|
|
952
|
+
ctx.line["lessons"] = len(lessons)
|
|
953
|
+
ctx.line["skipped"] = _skip_reason(ctx, seen, lessons, before)
|
|
954
|
+
if ctx.line["skipped"]:
|
|
955
|
+
ctx.finish_log()
|
|
956
|
+
return ctx.line
|
|
957
|
+
root = _start_run(ctx) # only a run that works gets a folder and a status
|
|
958
|
+
by_id = {x.id: x for x in lessons}
|
|
959
|
+
corroborate_state.write_private(
|
|
960
|
+
root / "lessons.txt", "".join(f"{ln}\n" for ln in corroborate_decide.lesson_lines(lessons))
|
|
961
|
+
)
|
|
962
|
+
judged = (
|
|
963
|
+
_judge_file(ctx.groups_file, lessons)
|
|
964
|
+
if ctx.groups_file
|
|
965
|
+
else _judge_sessions(ctx, root, lessons, by_id, refused_seen)
|
|
966
|
+
)
|
|
967
|
+
_count_judgement(ctx, judged)
|
|
968
|
+
if ctx.dry_run:
|
|
969
|
+
_write_plan(ctx, judged, by_id)
|
|
970
|
+
return ctx.line
|
|
971
|
+
refused_ids = _apply_groups(ctx, judged, by_id, root, world)
|
|
972
|
+
marks, marked = _refusal_marks(world, by_id, refused_seen, refused_ids)
|
|
973
|
+
state, gave_up = _next_state(ctx, world, seen, before, judged.incomplete)
|
|
974
|
+
corroborate_state.write_private(
|
|
975
|
+
root / "seen-added.json", json.dumps({"marked": sorted(marked)})
|
|
976
|
+
)
|
|
977
|
+
jobs.write_json(ctx.cdir / "seen.json", {"refused": marks, **state})
|
|
978
|
+
if gave_up:
|
|
979
|
+
raise StopError(
|
|
980
|
+
"gave up after repeated failures",
|
|
981
|
+
f"gave up: {MAX_RETRIES} runs in a row on these lessons ended "
|
|
982
|
+
"with a failed action or an unusable answer; the run folders hold the details",
|
|
983
|
+
)
|
|
984
|
+
save_done(ctx.cdir, ctx.line, None, ctx.dry_run)
|
|
985
|
+
ctx.finish_log()
|
|
986
|
+
return ctx.line
|
|
987
|
+
|
|
988
|
+
|
|
989
|
+
def _record_failure(ctx: _Run, reason: str, locked: bool) -> None:
|
|
990
|
+
"""The details of a failure go to the run folder (made now when the failure came first) and the status."""
|
|
991
|
+
if ctx.run is None and locked: # the details of a failure need a private place
|
|
992
|
+
ctx.run = _make_run_folder(ctx.cdir)
|
|
993
|
+
ctx.log(f"failed: {reason}")
|
|
994
|
+
save_done(
|
|
995
|
+
ctx.cdir, ctx.line, ctx.line["failed"], ctx.dry_run, log=str(ctx.run) if ctx.run else ""
|
|
996
|
+
)
|
|
997
|
+
if not ctx.logged:
|
|
998
|
+
ctx.finish_log()
|
|
999
|
+
|
|
1000
|
+
|
|
1001
|
+
def _report_failure(ctx: _Run, exc: Exception, locked: bool) -> None:
|
|
1002
|
+
"""A background process reports and ends: the reason goes to the line (a dry run) or to the run's files."""
|
|
1003
|
+
reason = str(exc) if isinstance(exc, StopError) else f"{type(exc).__name__}: {exc}"
|
|
1004
|
+
ctx.line["failed"] = exc.short if isinstance(exc, StopError) else type(exc).__name__
|
|
1005
|
+
if ctx.dry_run:
|
|
1006
|
+
ctx.line["failed_reason"] = reason
|
|
1007
|
+
return
|
|
1008
|
+
try:
|
|
1009
|
+
_record_failure(ctx, reason, locked)
|
|
1010
|
+
except Exception: # the failure itself is already on the line
|
|
1011
|
+
logger.debug("could not record the failure", exc_info=True)
|
|
1012
|
+
|
|
1013
|
+
|
|
1014
|
+
def _release(ctx: _Run, lock: int | None) -> None:
|
|
1015
|
+
"""Prune the old run folders, release the run lock and drop a dry run's scratch folder."""
|
|
1016
|
+
if lock is not None and (
|
|
1017
|
+
ctx.run is not None or (ctx.cdir / "runs").is_dir()
|
|
1018
|
+
): # a skipped run prunes too
|
|
1019
|
+
try:
|
|
1020
|
+
cs.prune_runs(ctx.cdir / "runs", cs.KEEP_RUNS, cs.KEEP_RUN_DAYS, time.time())
|
|
1021
|
+
except Exception: # pruning is housekeeping
|
|
1022
|
+
logger.debug("could not prune the run folders", exc_info=True)
|
|
1023
|
+
if lock is not None:
|
|
1024
|
+
os.close(lock)
|
|
1025
|
+
if ctx.scratch is not None:
|
|
1026
|
+
shutil.rmtree(ctx.scratch, ignore_errors=True)
|
|
1027
|
+
|
|
1028
|
+
|
|
1029
|
+
def execute(
|
|
1030
|
+
claude: str | None,
|
|
1031
|
+
budget: float,
|
|
1032
|
+
groups_file: str | None = None,
|
|
1033
|
+
dry_run: bool = False,
|
|
1034
|
+
out_file: str | None = None,
|
|
1035
|
+
) -> dict:
|
|
1036
|
+
"""One run. The log line (counts only); a dry run writes nothing but `out_file`. The runner is the configured
|
|
1037
|
+
one (`runner.resolve_runner`)."""
|
|
1038
|
+
data = corroborate_state.data_dir()
|
|
1039
|
+
scratch = Path(tempfile.mkdtemp(prefix="mem-corroborate-")) if dry_run else None
|
|
1040
|
+
ctx = _Run(
|
|
1041
|
+
claude or "",
|
|
1042
|
+
budget,
|
|
1043
|
+
groups_file,
|
|
1044
|
+
dry_run,
|
|
1045
|
+
out_file,
|
|
1046
|
+
data,
|
|
1047
|
+
corroborate_state.corroborate_dir(data),
|
|
1048
|
+
scratch,
|
|
1049
|
+
)
|
|
1050
|
+
lock = None
|
|
1051
|
+
try:
|
|
1052
|
+
if not dry_run:
|
|
1053
|
+
lock = jobs.take_run_lock(ctx.cdir)
|
|
1054
|
+
if lock is None:
|
|
1055
|
+
ctx.line["skipped"] = "another run holds the lock"
|
|
1056
|
+
ctx.finish_log()
|
|
1057
|
+
return ctx.line
|
|
1058
|
+
return _run_pass(ctx)
|
|
1059
|
+
except Exception as exc: # a background process reports and ends
|
|
1060
|
+
logger.debug("the run failed", exc_info=True)
|
|
1061
|
+
_report_failure(ctx, exc, lock is not None)
|
|
1062
|
+
return ctx.line
|
|
1063
|
+
finally:
|
|
1064
|
+
_release(ctx, lock)
|
|
1065
|
+
|
|
1066
|
+
|
|
1067
|
+
def save_done(cdir: Path, line: dict, failure: str | None, dry_run: bool, log: str = "") -> None:
|
|
1068
|
+
"""A failure line stays in the status until `ack`: a later successful run does not clear it."""
|
|
1069
|
+
if dry_run:
|
|
1070
|
+
return
|
|
1071
|
+
now = time.time()
|
|
1072
|
+
end: dict = {
|
|
1073
|
+
"state": "failed" if failure else "ok",
|
|
1074
|
+
"finished": now,
|
|
1075
|
+
"cost": line["cost"],
|
|
1076
|
+
"tokens": line["tokens"],
|
|
1077
|
+
"runner": line["runner"],
|
|
1078
|
+
}
|
|
1079
|
+
if log:
|
|
1080
|
+
end["log"] = log
|
|
1081
|
+
if failure:
|
|
1082
|
+
end["failure"] = {"at": now, "reason": failure[:300], "log": log}
|
|
1083
|
+
corroborate_state.save_status(cdir, **end)
|
|
1084
|
+
|
|
1085
|
+
|
|
1086
|
+
def repo_above(folder: Path) -> Path | None:
|
|
1087
|
+
"""The nearest folder, `folder` or an ancestor, that holds an entry named `.git` (as `mem-capture run --out`)."""
|
|
1088
|
+
for p in (folder, *folder.parents):
|
|
1089
|
+
if os.path.lexists(p / ".git"):
|
|
1090
|
+
return p
|
|
1091
|
+
return None
|
|
1092
|
+
|
|
1093
|
+
|
|
1094
|
+
def _fill_world():
|
|
1095
|
+
"""(data folder, registry, counted projects, global folder, project name of each path)."""
|
|
1096
|
+
data = corroborate_state.data_dir()
|
|
1097
|
+
registry = records.read_registry(data)
|
|
1098
|
+
projects = corroborate_decide.counted_projects(registry)
|
|
1099
|
+
names: dict[Path, str] = {}
|
|
1100
|
+
for name in sorted(registry):
|
|
1101
|
+
entry = registry[name]
|
|
1102
|
+
if isinstance(entry, dict) and isinstance(entry.get("path"), str):
|
|
1103
|
+
names.setdefault(Path(entry["path"]), name)
|
|
1104
|
+
return data, projects, records.global_memories_root(os.environ), names
|
|
1105
|
+
|
|
1106
|
+
|
|
1107
|
+
_cell = corroborate_job.cell
|
|
1108
|
+
|
|
1109
|
+
|
|
1110
|
+
def _ask(
|
|
1111
|
+
claude: str,
|
|
1112
|
+
scratch: Path,
|
|
1113
|
+
name: str,
|
|
1114
|
+
limits: SessionLimits,
|
|
1115
|
+
job: AskJob,
|
|
1116
|
+
) -> tuple[object, float, bool, str]:
|
|
1117
|
+
"""One session in its own folder: (the JSON it wrote or None, its cost, whether it ended with a result and no error,
|
|
1118
|
+
why it failed: ': <reason>' or '' when it gave none).
|
|
1119
|
+
Callers pass `claude`, `scratch` and `name` positionally (`name` stays third: a test wraps the call). `job.spend`:
|
|
1120
|
+
the run's runner and Codex tokens (the configured runner when None); a session that would start past the token
|
|
1121
|
+
cap does not start and counts as failed."""
|
|
1122
|
+
template, text, text_key, out_name, spend = job
|
|
1123
|
+
spend = spend or Spend(runners.resolve_runner(None))
|
|
1124
|
+
if spend.spent_up:
|
|
1125
|
+
return None, 0.0, False, f": {spend.tokens} tokens reached the token cap"
|
|
1126
|
+
work = scratch / name
|
|
1127
|
+
work.mkdir(mode=0o700)
|
|
1128
|
+
corroborate_state.write_private(work / "input.txt", text)
|
|
1129
|
+
out = work / out_name
|
|
1130
|
+
brief = template.format(**{text_key: work / "input.txt"}, out=out)
|
|
1131
|
+
try:
|
|
1132
|
+
done = run_on(
|
|
1133
|
+
spend,
|
|
1134
|
+
work,
|
|
1135
|
+
session_spec(claude, work, brief, scratch / "settings.json", limits),
|
|
1136
|
+
out,
|
|
1137
|
+
)
|
|
1138
|
+
except OSError as exc: # a binary that is missing or cannot run is a failed session
|
|
1139
|
+
return None, 0.0, False, f": {codex_pass.NO_CODEX if spend.runner == 'codex' else exc}"
|
|
1140
|
+
cost = done["cost"] if done["has_result"] else 0.0
|
|
1141
|
+
ok = done["has_result"] and not done["error"]
|
|
1142
|
+
return (read_object(out) if ok else None), cost, ok, because(done)
|