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.
Files changed (128) hide show
  1. memory_cli/__init__.py +1 -0
  2. memory_cli/__main__.py +49 -0
  3. memory_cli/capture/__init__.py +7 -0
  4. memory_cli/capture/codex_rollout.py +164 -0
  5. memory_cli/capture/event_lines.py +66 -0
  6. memory_cli/capture/extract.py +458 -0
  7. memory_cli/capture/state.py +183 -0
  8. memory_cli/commands/__init__.py +21 -0
  9. memory_cli/commands/admin.py +363 -0
  10. memory_cli/commands/common.py +609 -0
  11. memory_cli/commands/curate.py +1189 -0
  12. memory_cli/commands/diagnostics.py +126 -0
  13. memory_cli/commands/edit.py +1282 -0
  14. memory_cli/commands/hooks.py +730 -0
  15. memory_cli/commands/import_recovery.py +45 -0
  16. memory_cli/commands/install.py +152 -0
  17. memory_cli/commands/integrate.py +480 -0
  18. memory_cli/commands/memory.py +2152 -0
  19. memory_cli/commands/read.py +1290 -0
  20. memory_cli/commands/sources.py +766 -0
  21. memory_cli/commands/split.py +97 -0
  22. memory_cli/commands/split_plan.py +196 -0
  23. memory_cli/commands/split_transaction.py +230 -0
  24. memory_cli/commands/synthesis.py +1122 -0
  25. memory_cli/core/__init__.py +16 -0
  26. memory_cli/core/auto_state.py +30 -0
  27. memory_cli/core/codex_pass.py +109 -0
  28. memory_cli/core/config.py +87 -0
  29. memory_cli/core/file_journal.py +163 -0
  30. memory_cli/core/headless.py +130 -0
  31. memory_cli/core/jobs.py +130 -0
  32. memory_cli/core/resources.py +57 -0
  33. memory_cli/core/runner.py +398 -0
  34. memory_cli/core/safe_io.py +155 -0
  35. memory_cli/core/store_git.py +407 -0
  36. memory_cli/core/yaml_load.py +14 -0
  37. memory_cli/corroborate/__init__.py +11 -0
  38. memory_cli/corroborate/cli.py +267 -0
  39. memory_cli/corroborate/decide.py +893 -0
  40. memory_cli/corroborate/digest.py +425 -0
  41. memory_cli/corroborate/fill.py +744 -0
  42. memory_cli/corroborate/job.py +15 -0
  43. memory_cli/corroborate/reword.py +446 -0
  44. memory_cli/corroborate/run.py +1142 -0
  45. memory_cli/corroborate/state.py +300 -0
  46. memory_cli/digest/__init__.py +4 -0
  47. memory_cli/digest/lessons.py +483 -0
  48. memory_cli/entry/__init__.py +12 -0
  49. memory_cli/entry/auto.py +660 -0
  50. memory_cli/entry/capture.py +1403 -0
  51. memory_cli/entry/corroborate.py +214 -0
  52. memory_cli/entry/integrate.py +684 -0
  53. memory_cli/entry/integrate_self_check.py +203 -0
  54. memory_cli/entry/research.py +9 -0
  55. memory_cli/entry/settle.py +614 -0
  56. memory_cli/entry/split_auto.py +460 -0
  57. memory_cli/entry/synthesize.py +22 -0
  58. memory_cli/integrate/__init__.py +9 -0
  59. memory_cli/integrate/answers.py +42 -0
  60. memory_cli/integrate/briefs/check-brief.md +16 -0
  61. memory_cli/integrate/briefs/place-brief.md +26 -0
  62. memory_cli/integrate/log.py +43 -0
  63. memory_cli/integrate/plan.py +125 -0
  64. memory_cli/integrate/rows.py +99 -0
  65. memory_cli/integrate/state.py +158 -0
  66. memory_cli/integrate/undo.py +143 -0
  67. memory_cli/mem.py +1180 -0
  68. memory_cli/memories/__init__.py +16 -0
  69. memory_cli/memories/fingerprints.py +51 -0
  70. memory_cli/memories/journal.py +93 -0
  71. memory_cli/memories/locations.py +282 -0
  72. memory_cli/memories/matching.py +451 -0
  73. memory_cli/memories/model.py +205 -0
  74. memory_cli/memories/parse.py +237 -0
  75. memory_cli/memories/records.py +266 -0
  76. memory_cli/memories/rules.py +291 -0
  77. memory_cli/memories/sightings.py +314 -0
  78. memory_cli/memories/terms.py +148 -0
  79. memory_cli/memories/write.py +358 -0
  80. memory_cli/notes/__init__.py +13 -0
  81. memory_cli/notes/check.py +806 -0
  82. memory_cli/notes/due.py +260 -0
  83. memory_cli/notes/fields.py +217 -0
  84. memory_cli/notes/index.py +230 -0
  85. memory_cli/notes/links.py +170 -0
  86. memory_cli/notes/note.py +222 -0
  87. memory_cli/notes/search.py +391 -0
  88. memory_cli/notes/split_candidates.py +72 -0
  89. memory_cli/research/__init__.py +5 -0
  90. memory_cli/research/checks.py +1065 -0
  91. memory_cli/research/pipeline.py +952 -0
  92. memory_cli/session/__init__.py +5 -0
  93. memory_cli/session/handoff.py +139 -0
  94. memory_cli/session/notices.py +111 -0
  95. memory_cli/settle/__init__.py +5 -0
  96. memory_cli/settle/state.py +111 -0
  97. memory_cli/settle/verdicts.py +693 -0
  98. memory_cli/split/briefs/checker-brief.md +5 -0
  99. memory_cli/split/briefs/editor-brief.md +20 -0
  100. memory_cli/syntheses/__init__.py +8 -0
  101. memory_cli/syntheses/document.py +400 -0
  102. memory_cli/syntheses/edit.py +581 -0
  103. memory_cli/syntheses/project.py +384 -0
  104. memory_cli/syntheses/split_conservation.py +50 -0
  105. memory_cli/syntheses/units.py +427 -0
  106. memory_cli/synthesize/__init__.py +9 -0
  107. memory_cli/synthesize/backfill.py +431 -0
  108. memory_cli/synthesize/briefs/backfill-brief.md +26 -0
  109. memory_cli/synthesize/briefs/checker-brief.md +13 -0
  110. memory_cli/synthesize/briefs/fixer-brief.md +19 -0
  111. memory_cli/synthesize/briefs/memory-brief.md +30 -0
  112. memory_cli/synthesize/briefs/settle-brief.md +32 -0
  113. memory_cli/synthesize/briefs/verdict-brief.md +50 -0
  114. memory_cli/synthesize/briefs/web-brief.md +33 -0
  115. memory_cli/synthesize/cli.py +311 -0
  116. memory_cli/synthesize/pipeline.py +764 -0
  117. memory_cli/synthesize/references.py +164 -0
  118. memory_cli/synthesize/run.py +150 -0
  119. memory_cli/synthesize/topics.py +528 -0
  120. memory_cli/templates/knowledge.md +23 -0
  121. memory_cli/templates/literature.md +25 -0
  122. memory_cli/templates/research.md +23 -0
  123. memory_cli/templates/synthesis.md +6 -0
  124. memory_cli-0.1.0.dist-info/METADATA +102 -0
  125. memory_cli-0.1.0.dist-info/RECORD +128 -0
  126. memory_cli-0.1.0.dist-info/WHEEL +4 -0
  127. memory_cli-0.1.0.dist-info/entry_points.txt +9 -0
  128. memory_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,15 @@
1
+ """Small helpers shared by the corroboration background jobs."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ def finish(result: dict, **changes) -> dict:
7
+ """Apply final result fields and normalize accumulated model cost."""
8
+ result.update(changes)
9
+ result["cost"] = round(result["cost"], 6)
10
+ return result
11
+
12
+
13
+ def cell(text: object) -> str:
14
+ """Format one value for a Markdown table cell."""
15
+ return " ".join(str(text or "").split()).replace("|", "\\|")
@@ -0,0 +1,446 @@
1
+ """mem-corroborate: `reword`, a new short form for loaded lessons that got worse."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+ import hashlib
7
+ import json
8
+ import logging
9
+ import os
10
+ import shutil
11
+ import tempfile
12
+ import time
13
+ from pathlib import Path
14
+ from typing import NamedTuple, TypedDict, Unpack
15
+
16
+ from memory_cli.core import jobs
17
+ from memory_cli.core import runner as runners
18
+ from memory_cli.corroborate import decide as corroborate_decide
19
+ from memory_cli.corroborate import job as corroborate_job
20
+ from memory_cli.corroborate import run as corroborate_run
21
+ from memory_cli.corroborate import state as corroborate_state
22
+ from memory_cli.memories import records
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ REWORD_ATTEMPTS_NAME = "reword-attempts.json"
27
+
28
+
29
+ REWORD_WRITER_OUT = "reword.json"
30
+
31
+
32
+ REWORD_CHECK_OUT = "reword-check.json"
33
+
34
+
35
+ def _reword_state(cdir: Path) -> dict:
36
+ """The step's memory, read defensively: a missing or broken file is an empty state."""
37
+ data = jobs.read_json(cdir / REWORD_ATTEMPTS_NAME)
38
+ lessons = data.get("lessons")
39
+ failures = data.get("failures")
40
+ lessons = (
41
+ {k: v for k, v in lessons.items() if isinstance(v, dict)}
42
+ if isinstance(lessons, dict)
43
+ else {}
44
+ )
45
+ failures = failures if isinstance(failures, dict) else {}
46
+ count = failures.get("count")
47
+ return {
48
+ "lessons": lessons,
49
+ "failures": {
50
+ "count": count if isinstance(count, int) and count > 0 else 0,
51
+ "fingerprint": failures.get("fingerprint"),
52
+ },
53
+ }
54
+
55
+
56
+ def _reword_run_folder(cdir: Path) -> Path:
57
+ base = f"{time.strftime('%Y%m%d-%H%M%S')}-{os.getpid()}"
58
+ run, n = cdir / "runs" / f"{base}-reword", 1
59
+ while run.exists():
60
+ n += 1
61
+ run = cdir / "runs" / f"{base}-{n}-reword"
62
+ return run
63
+
64
+
65
+ # Only exit 4 of `mem memory edit` (a secret, a forbidden term) refuses the text. Exit 2 is also a usage error, "not found"
66
+ # or "not active": counting it as a refusal would make every lesson give up if the command line were ever wrong, and the
67
+ # step has run the same code check itself before the edit.
68
+ REWORD_REFUSED_EXITS = (4,)
69
+
70
+
71
+ def _reword_edit(applier: corroborate_run.Applier, project: Path | None, m, *flags: str) -> str:
72
+ """One `mem memory edit` of the step, journaled: "ok", "refused" (exit 4: the command refused the text) or "failed"
73
+ (it could not run, timed out or exited otherwise: nothing says the text is bad, so no attempt is spent)."""
74
+ watched = (
75
+ [m.path] if project is not None else [m.path, m.path.parent / corroborate_run.SETTLE_STATE]
76
+ ) # a global edit may update it
77
+ before = applier.journal.watch(watched)
78
+ done = applier.mem(
79
+ ["memory", "edit", f"m:{m.handle}", *(["--global"] if project is None else []), *flags],
80
+ project,
81
+ drop_env=corroborate_run.SETTLE_VARS,
82
+ )
83
+ applier.journal.commit("reword", before)
84
+ if done is not None and done.returncode == 0:
85
+ return "ok"
86
+ return "refused" if done is not None and done.returncode in REWORD_REFUSED_EXITS else "failed"
87
+
88
+
89
+ def _reword_sheet(path: Path, rows: list[tuple]) -> None:
90
+ lines = [
91
+ "| id | claim | present short form | proposed short form | outcome | checker's reason |",
92
+ "|---|---|---|---|---|---|",
93
+ ]
94
+ lines += ["| " + " | ".join(corroborate_job.cell(x) for x in row) + " |" for row in rows]
95
+ corroborate_state.write_private(path, "\n".join(lines) + "\n")
96
+
97
+
98
+ class RewordOptions(TypedDict, total=False):
99
+ """The keyword options of `reword_auto` (defaults: `every` False, `apply` True, `sheet` None, `limit` 30)."""
100
+
101
+ every: bool
102
+ apply: bool
103
+ sheet: Path | None
104
+ limit: int
105
+
106
+
107
+ class _Params(NamedTuple):
108
+ claude: str | None
109
+ budget: float
110
+ every: bool
111
+ apply: bool
112
+ sheet: Path | None
113
+ limit: int
114
+
115
+
116
+ class _World(NamedTuple):
117
+ projects: list[Path]
118
+ gfolder: Path | None
119
+ candidates: list
120
+
121
+
122
+ class _Sessions(NamedTuple):
123
+ """What the writer and checker sessions gave: the proposals, the ids the checker accepted and its reasons, or
124
+ `failure` (why a session gave no usable answer)."""
125
+
126
+ proposed: dict
127
+ accepted: set[str]
128
+ reasons: dict[str, str]
129
+ failure: str | None = None
130
+
131
+
132
+ _finish = corroborate_job.finish
133
+
134
+
135
+ def reword_auto(claude: str | None, budget: float, **options: Unpack[RewordOptions]) -> dict:
136
+ """Rewrites the short form of loaded lessons that got worse, with nobody reading it first: a writer session, the
137
+ code check, a second session that checks the survivors against their claims, then one `mem memory edit
138
+ --reworded` each. Follows `fill_auto`: every doubt ends in not writing; a session with no usable answer is a
139
+ failed session that charges no lesson. With `apply` false it writes no record and saves no state (the sessions
140
+ still run, and cost). Never raises: a failure is a counted result with `stopped` set."""
141
+ result = {
142
+ "asked": 0,
143
+ "written": 0,
144
+ "refused_code": 0,
145
+ "refused_check": 0,
146
+ "same_text": 0,
147
+ "no_proposal": 0,
148
+ "gave_up": 0,
149
+ "changed": 0,
150
+ "failed_edits": 0,
151
+ "cost": 0.0,
152
+ "stopped": None,
153
+ }
154
+ params = _Params(
155
+ claude,
156
+ budget,
157
+ options.get("every", False),
158
+ options.get("apply", True),
159
+ options.get("sheet"),
160
+ options.get("limit", 30),
161
+ )
162
+ try:
163
+ return _reword_guarded(params, result)
164
+ except Exception:
165
+ logger.debug("reword step failed", exc_info=True)
166
+ return _finish(result, stopped="the step failed")
167
+
168
+
169
+ def _reword_guarded(params: _Params, result: dict) -> dict:
170
+ cdir = corroborate_state.corroborate_dir(corroborate_state.data_dir())
171
+ lock = jobs.take_run_lock(cdir)
172
+ if lock is None:
173
+ return {**result, "stopped": "a run is going"}
174
+ try:
175
+ return _reword_locked(params, cdir, result)
176
+ finally:
177
+ os.close(lock)
178
+
179
+
180
+ def _reword_applier(cdir: Path, gfolder: Path | None) -> corroborate_run.Applier:
181
+ run = _reword_run_folder(cdir)
182
+ jobs.private_dir(run)
183
+ corroborate_state.write_private(
184
+ run / "fill", ""
185
+ ) # marks the run: its undo leaves the pass's `seen.json` alone
186
+ return corroborate_run.Applier(
187
+ corroborate_state.Journal(run), {}, gfolder, run, lambda _text: None
188
+ )
189
+
190
+
191
+ def _retry_give_ups(cdir: Path, state: dict, projects, gfolder: Path | None) -> int:
192
+ """The `--reword-failed` edit of a give-up that did not run: every lesson the state counts REWORD_ATTEMPTS or more
193
+ for its present version and whose record lacks the mark gets it again. Returns the marks written."""
194
+ applier, done, seen = None, 0, set()
195
+ for _i, p, m in corroborate_decide.fill_records(projects, gfolder):
196
+ key, versions = corroborate_decide.reword_key(p, m.handle), records.version_list(m)
197
+ if key in seen or not versions or m.reword_failed == versions[-1][0]:
198
+ continue
199
+ seen.add(key)
200
+ if (
201
+ corroborate_decide._count(corroborate_decide._entry(state, key), versions[-1][0])
202
+ >= corroborate_decide.REWORD_ATTEMPTS
203
+ ):
204
+ applier = applier or _reword_applier(cdir, gfolder)
205
+ if _reword_edit(applier, p, m, "--reword-failed") == "ok":
206
+ done += 1
207
+ return done
208
+
209
+
210
+ def _reword_candidates(params: _Params, state: dict, projects, gfolder: Path | None) -> list:
211
+ candidates = corroborate_decide.reword_candidates(
212
+ projects, gfolder, datetime.date.today(), state, every=params.every
213
+ )
214
+ return candidates[: max(params.limit, 0)] if params.every else candidates
215
+
216
+
217
+ def _reword_locked(params: _Params, cdir: Path, result: dict) -> dict:
218
+ try:
219
+ _data, projects, gfolder, _names = corroborate_run._fill_world()
220
+ except ValueError:
221
+ return _finish(result, stopped="the registry is unreadable")
222
+ state = _reword_state(cdir)
223
+ if params.apply:
224
+ result["gave_up"] += _retry_give_ups(cdir, state, projects, gfolder)
225
+ candidates = _reword_candidates(params, state, projects, gfolder)
226
+ result["asked"] = len(candidates)
227
+ if not candidates:
228
+ return _finish(result)
229
+ return _RewordPass(params, cdir, result, state, _World(projects, gfolder, candidates)).run()
230
+
231
+
232
+ def _still_open(seen, m) -> bool:
233
+ """False when the owner edited, kept or reworded the lesson meanwhile: that must not be overwritten."""
234
+ return (
235
+ seen is not None
236
+ and (seen.claim, seen.short) == (m.claim, m.short)
237
+ and seen.status == "active"
238
+ and corroborate_decide.reword_open(seen, records.version_list(seen)[-1][0])
239
+ )
240
+
241
+
242
+ def _check_reasons(payload: object) -> dict[str, str]:
243
+ verdicts = payload.get("verdicts") if isinstance(payload, dict) else None
244
+ return {
245
+ v["id"]: v["reason"]
246
+ for v in verdicts or []
247
+ if isinstance(v, dict) and isinstance(v.get("id"), str) and isinstance(v.get("reason"), str)
248
+ }
249
+
250
+
251
+ class _RewordPass:
252
+ """One run of the step past the lock: the candidates, the sessions, the edits, the state and the sheet."""
253
+
254
+ writer_why = "" # why the writer session failed (`_ask`), for the stop text
255
+
256
+ def __init__(
257
+ self, params: _Params, cdir: Path, result: dict, state: dict, world: _World
258
+ ) -> None:
259
+ self.params, self.cdir, self.result, self.state = params, cdir, result, state
260
+ self.projects, self.gfolder, self.candidates = world
261
+ self.where = {
262
+ i: p for i, p, _m in corroborate_decide.fill_records(self.projects, self.gfolder)
263
+ }
264
+ self.by_id = dict(self.candidates)
265
+ keys = {
266
+ i: corroborate_decide.reword_key(self.where[i], m.handle) for i, m in self.candidates
267
+ }
268
+ self.fingerprint = hashlib.sha256(
269
+ json.dumps(
270
+ sorted(
271
+ (keys[i], records.version_list(m)[-1][0].isoformat())
272
+ for i, m in self.candidates
273
+ )
274
+ ).encode()
275
+ ).hexdigest()
276
+ self.failures = state["failures"]
277
+ if self.failures["fingerprint"] != self.fingerprint:
278
+ self.failures["count"] = 0
279
+ self.applier: corroborate_run.Applier | None = None
280
+ self.spend = corroborate_run.Spend(runners.resolve_runner(None)) # one cap for all sessions
281
+
282
+ def run(self) -> dict:
283
+ claude = self.params.claude
284
+ if self.failures["count"] >= corroborate_decide.FILL_FAILURES:
285
+ return _finish(self.result, stopped="waiting for the lessons to change", asked=0)
286
+ if not claude:
287
+ return _finish(self.result, stopped="no claude binary")
288
+ sessions = self._sessions(claude)
289
+ if sessions.failure is not None:
290
+ return self._failed_session(sessions.failure)
291
+ outcome = corroborate_decide.reword_outcome(
292
+ self.candidates, sessions.proposed, sessions.accepted
293
+ )
294
+ if self.params.apply:
295
+ self._apply(sessions.proposed, outcome)
296
+ self._tally(outcome)
297
+ if self.params.sheet is not None and not self._write_sheet(
298
+ self.params.sheet, sessions, outcome
299
+ ):
300
+ return _finish(
301
+ self.result, stopped=self.result["stopped"] or "the sheet could not be written"
302
+ )
303
+ return _finish(self.result)
304
+
305
+ def _save_state(self) -> None:
306
+ if self.params.apply:
307
+ jobs.write_json(self.cdir / REWORD_ATTEMPTS_NAME, self.state)
308
+
309
+ def _count_failure(self) -> None:
310
+ self.failures["count"] += 1
311
+ self.failures["fingerprint"] = self.fingerprint
312
+
313
+ def _failed_session(self, why: str) -> dict:
314
+ self._count_failure()
315
+ self._save_state()
316
+ return _finish(self.result, stopped=why)
317
+
318
+ def _get_applier(self) -> corroborate_run.Applier:
319
+ self.applier = self.applier or _reword_applier(self.cdir, self.gfolder)
320
+ return self.applier
321
+
322
+ def _sessions(self, claude: str) -> _Sessions:
323
+ scratch = Path(tempfile.mkdtemp(prefix="mem-corroborate-reword-"))
324
+ try:
325
+ return self._run_sessions(claude, scratch)
326
+ finally:
327
+ shutil.rmtree(scratch, ignore_errors=True)
328
+
329
+ def _run_sessions(self, claude: str, scratch: Path) -> _Sessions:
330
+ corroborate_state.write_private(
331
+ scratch / "settings.json", json.dumps({"disableAllHooks": True})
332
+ )
333
+ proposed = self._ask_writer(claude, scratch)
334
+ if proposed is None:
335
+ return _Sessions(
336
+ {}, set(), {}, f"the writer session gave no usable answer{self.writer_why}"
337
+ )
338
+ kept, _refused = corroborate_decide.reword_survivors(proposed, self.candidates)
339
+ if not kept:
340
+ return _Sessions(proposed, set(), {})
341
+ return self._ask_checker(claude, scratch, proposed, kept)
342
+
343
+ def _ask_writer(self, claude: str, scratch: Path) -> dict | None:
344
+ limits = corroborate_run.SessionLimits(corroborate_run.PROPOSE_MODEL, self.params.budget)
345
+ job = corroborate_run.AskJob(
346
+ corroborate_run.REWORD_BRIEF,
347
+ corroborate_decide.reword_blocks(self.candidates),
348
+ "lessons",
349
+ REWORD_WRITER_OUT,
350
+ self.spend,
351
+ )
352
+ payload, cost, ok, why = corroborate_run._ask(claude, scratch, "write", limits, job)
353
+ self.writer_why = why
354
+ self.result["cost"] += cost
355
+ try:
356
+ return corroborate_decide.validate_reword(payload, self.candidates) if ok else None
357
+ except ValueError:
358
+ return None
359
+
360
+ def _ask_checker(self, claude: str, scratch: Path, proposed: dict, kept: list) -> _Sessions:
361
+ text = corroborate_decide.check_lines([
362
+ (i, m.claim, m.context, short) for i, m, short in kept
363
+ ])
364
+ limits = corroborate_run.SessionLimits(corroborate_run.CHECK_MODEL, self.params.budget)
365
+ job = corroborate_run.AskJob(
366
+ corroborate_run.CHECK_BRIEF, text, "pairs", REWORD_CHECK_OUT, self.spend
367
+ )
368
+ payload, cost, ok, why = corroborate_run._ask(claude, scratch, "check", limits, job)
369
+ self.result["cost"] += cost
370
+ checked = (
371
+ corroborate_decide.validate_check(payload, [i for i, _m, _s in kept]) if ok else None
372
+ )
373
+ if checked is None:
374
+ return _Sessions({}, set(), {}, f"the checker session gave no usable answer{why}")
375
+ accepted = {i for i, faithful in checked.items() if faithful}
376
+ return _Sessions(proposed, accepted, _check_reasons(payload))
377
+
378
+ def _edit_written(self, proposed: dict, outcome: dict[str, str]) -> None:
379
+ now = {
380
+ i: m for i, _p, m in corroborate_decide.fill_records(self.projects, self.gfolder)
381
+ } # the owner may have edited meanwhile
382
+ for i, m in self.candidates:
383
+ if outcome[i] != "written":
384
+ continue
385
+ if not _still_open(now.get(i), m):
386
+ outcome[i] = "changed"
387
+ continue
388
+ edit = _reword_edit(
389
+ self._get_applier(),
390
+ self.where[i],
391
+ m,
392
+ f"--short={proposed[i]['short']}",
393
+ "--reworded",
394
+ )
395
+ outcome[i] = {"refused": "refused_code", "failed": "failed_edit"}.get(edit, outcome[i])
396
+
397
+ def _apply(self, proposed: dict, outcome: dict[str, str]) -> None:
398
+ self._edit_written(proposed, outcome)
399
+ new_state, giveup = corroborate_decide.reword_state_after(
400
+ self.state, self.candidates, outcome, datetime.date.today()
401
+ )
402
+ self.state["lessons"] = new_state["lessons"]
403
+ if (
404
+ "failed_edit" in outcome.values()
405
+ ): # as a failed session: repeated failures end in the wait
406
+ self._count_failure()
407
+ else:
408
+ self.failures["count"], self.failures["fingerprint"] = 0, None
409
+ self._save_state()
410
+ for i in giveup:
411
+ if (
412
+ _reword_edit(self._get_applier(), self.where[i], self.by_id[i], "--reword-failed")
413
+ == "ok"
414
+ ):
415
+ self.result["gave_up"] += 1
416
+
417
+ def _tally(self, outcome: dict[str, str]) -> None:
418
+ for word in ("refused_code", "refused_check", "same_text", "no_proposal", "changed"):
419
+ self.result[word] = sum(1 for v in outcome.values() if v == word)
420
+ self.result["failed_edits"] = sum(1 for v in outcome.values() if v == "failed_edit")
421
+ self.result["written"] = (
422
+ sum(1 for v in outcome.values() if v == "written") if self.params.apply else 0
423
+ )
424
+
425
+ def _write_sheet(self, sheet: Path, sessions: _Sessions, outcome: dict[str, str]) -> bool:
426
+ """False when the sheet could not be written: the run is done, so that must not turn it into a failed step."""
427
+ proposed, apply = sessions.proposed, self.params.apply
428
+ try:
429
+ _reword_sheet(
430
+ sheet,
431
+ [
432
+ (
433
+ i,
434
+ m.claim,
435
+ m.short,
436
+ proposed.get(i, {}).get("short"),
437
+ "would be written" if outcome[i] == "written" and not apply else outcome[i],
438
+ sessions.reasons.get(i),
439
+ )
440
+ for i, m in self.candidates
441
+ ],
442
+ )
443
+ except Exception:
444
+ logger.debug("reword sheet not written", exc_info=True)
445
+ return False
446
+ return True