auto-optimize 1.0.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 (67) hide show
  1. auto_optimize/__init__.py +3 -0
  2. auto_optimize/__main__.py +5 -0
  3. auto_optimize/cli.py +651 -0
  4. auto_optimize/skills/auto-optimize-code/LICENSE +21 -0
  5. auto_optimize/skills/auto-optimize-code/SKILL.md +251 -0
  6. auto_optimize/skills/auto-optimize-code/VERSION +1 -0
  7. auto_optimize/skills/auto-optimize-code/references/algorithm.md +182 -0
  8. auto_optimize/skills/auto-optimize-code/references/changes.md +146 -0
  9. auto_optimize/skills/auto-optimize-code/references/cli.md +206 -0
  10. auto_optimize/skills/auto-optimize-code/references/dashboard.md +203 -0
  11. auto_optimize/skills/auto-optimize-code/references/documents.md +55 -0
  12. auto_optimize/skills/auto-optimize-code/references/extending.md +87 -0
  13. auto_optimize/skills/auto-optimize-code/references/external-validation.md +98 -0
  14. auto_optimize/skills/auto-optimize-code/references/glossary.md +134 -0
  15. auto_optimize/skills/auto-optimize-code/references/idea-miner.md +108 -0
  16. auto_optimize/skills/auto-optimize-code/references/issue-bugs.md +182 -0
  17. auto_optimize/skills/auto-optimize-code/references/layout.md +300 -0
  18. auto_optimize/skills/auto-optimize-code/references/main-session.md +45 -0
  19. auto_optimize/skills/auto-optimize-code/references/measuring.md +208 -0
  20. auto_optimize/skills/auto-optimize-code/references/pr-optimization.md +127 -0
  21. auto_optimize/skills/auto-optimize-code/references/pr-tests.md +254 -0
  22. auto_optimize/skills/auto-optimize-code/references/promotion.md +133 -0
  23. auto_optimize/skills/auto-optimize-code/references/reading-a-search.md +65 -0
  24. auto_optimize/skills/auto-optimize-code/references/repo-mode.md +224 -0
  25. auto_optimize/skills/auto-optimize-code/references/resume.md +81 -0
  26. auto_optimize/skills/auto-optimize-code/references/shared-knowledge.md +114 -0
  27. auto_optimize/skills/auto-optimize-code/references/step0-interview.md +298 -0
  28. auto_optimize/skills/auto-optimize-code/references/step1-unit-tests.md +136 -0
  29. auto_optimize/skills/auto-optimize-code/references/step2-baseline.md +708 -0
  30. auto_optimize/skills/auto-optimize-code/references/step3-rounds.md +350 -0
  31. auto_optimize/skills/auto-optimize-code/references/step4-final.md +121 -0
  32. auto_optimize/skills/auto-optimize-code/references/step5-ship.md +220 -0
  33. auto_optimize/skills/auto-optimize-code/references/step6-finish.md +67 -0
  34. auto_optimize/skills/auto-optimize-code/references/subagent.md +467 -0
  35. auto_optimize/skills/auto-optimize-code/references/symptoms.md +67 -0
  36. auto_optimize/skills/auto-optimize-code/references/writing-briefs.md +117 -0
  37. auto_optimize/skills/auto-optimize-code/scripts/attribution.py +156 -0
  38. auto_optimize/skills/auto-optimize-code/scripts/autoopt.py +12863 -0
  39. auto_optimize/skills/auto-optimize-code/scripts/check_seeding.py +334 -0
  40. auto_optimize/skills/auto-optimize-code/scripts/cold.py +90 -0
  41. auto_optimize/skills/auto-optimize-code/scripts/dashboard/README.md +165 -0
  42. auto_optimize/skills/auto-optimize-code/scripts/dashboard/autoopt_monitor.py +850 -0
  43. auto_optimize/skills/auto-optimize-code/scripts/dashboard/gpu_scan.py +954 -0
  44. auto_optimize/skills/auto-optimize-code/scripts/dashboard/monitor_writer.py +684 -0
  45. auto_optimize/skills/auto-optimize-code/scripts/dashboard/scan.py +1030 -0
  46. auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/dashboard.css +775 -0
  47. auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/dashboard.js +3652 -0
  48. auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/index.html +191 -0
  49. auto_optimize/skills/auto-optimize-code/scripts/issue_body.py +2118 -0
  50. auto_optimize/skills/auto-optimize-code/scripts/lint_text.py +448 -0
  51. auto_optimize/skills/auto-optimize-code/scripts/opt_pr_body.py +894 -0
  52. auto_optimize/skills/auto-optimize-code/scripts/opt_pr_tables.py +367 -0
  53. auto_optimize/skills/auto-optimize-code/scripts/paired.py +188 -0
  54. auto_optimize/skills/auto-optimize-code/scripts/preflight.py +280 -0
  55. auto_optimize/skills/auto-optimize-code/scripts/probe_run.py +72 -0
  56. auto_optimize/skills/auto-optimize-code/scripts/publish.py +385 -0
  57. auto_optimize/skills/auto-optimize-code/scripts/run_iteration.py +1382 -0
  58. auto_optimize/skills/auto-optimize-code/scripts/ship.py +1193 -0
  59. auto_optimize/skills/auto-optimize-code/scripts/stages.py +651 -0
  60. auto_optimize/skills/auto-optimize-code/scripts/tests_pr_body.py +1267 -0
  61. auto_optimize/skills/auto-optimize-code/scripts/tests_pr_push.py +426 -0
  62. auto_optimize/skills/auto-optimize-code/scripts/tests_pr_tables.py +779 -0
  63. auto_optimize-1.0.0.dist-info/METADATA +610 -0
  64. auto_optimize-1.0.0.dist-info/RECORD +67 -0
  65. auto_optimize-1.0.0.dist-info/WHEEL +4 -0
  66. auto_optimize-1.0.0.dist-info/entry_points.txt +2 -0
  67. auto_optimize-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,651 @@
1
+ #!/usr/bin/env python3
2
+ """The stages of a search, read from the files it already writes.
3
+
4
+ python3 stages.py render WORK # write WORK/NOTES.md
5
+ python3 stages.py status WORK # print the same table
6
+ python3 stages.py next WORK # the one command (or question) that is next
7
+
8
+ Six stages, in order: interview, setup, search, final, ship, finish. Each is
9
+ `not started`, `running` or `complete`, derived from state files
10
+ (`state.json`, `ended.json`, `config.json`'s `after.ship`, `ship/`,
11
+ `finish/`); nothing is typed into NOTES.md by
12
+ hand, so a render of the same state is the same bytes. `autoopt.py end` calls
13
+ `render`; it is also safe to run at any time.
14
+
15
+ Standard library only, Python 3.9 or later.
16
+ """
17
+
18
+ import os
19
+ import re
20
+ import sys
21
+ import glob
22
+ import json
23
+ import argparse
24
+
25
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
26
+
27
+ import autoopt
28
+
29
+ NOT_STARTED, RUNNING, COMPLETE = 'not started', 'running', 'complete'
30
+ HERE = os.path.dirname(os.path.abspath(__file__))
31
+
32
+
33
+ def read(path, default=None):
34
+ try:
35
+ with open(path, encoding='utf-8') as handle:
36
+ return json.load(handle)
37
+ except (OSError, ValueError):
38
+ return default
39
+
40
+
41
+ def exists(*parts):
42
+ return os.path.exists(os.path.join(*parts))
43
+
44
+
45
+ def mtime(path):
46
+ """The date a file last changed, `YYYY-MM-DD`, or None."""
47
+
48
+ try:
49
+ import time
50
+ return time.strftime('%Y-%m-%d', time.localtime(os.path.getmtime(
51
+ path)))
52
+ except OSError:
53
+ return None
54
+
55
+
56
+ def number(value, digits=4):
57
+ return '{:.{}g}'.format(value, digits) if isinstance(value,
58
+ (int, float)) else '?'
59
+
60
+
61
+ def interview(work, root, state):
62
+ path = os.path.join(root, 'spec.md')
63
+
64
+ if not exists(root, 'config.json'):
65
+ return NOT_STARTED, '', {}
66
+
67
+ # The three lines step 2 answers do not hold the interview open.
68
+ problems = [p for p in autoopt.spec_problems(root) if not re.search(
69
+ r'Gate proof|Width measured|Benchmark', p)]
70
+
71
+ if problems:
72
+ return RUNNING, 'spec.md still has TODO lines', {}
73
+
74
+ return COMPLETE, mtime(path) or '', {'spec': path}
75
+
76
+
77
+ def setup(work, root, state):
78
+ record = state.get('setup') or {}
79
+ status = record.get('status')
80
+
81
+ if not status:
82
+ return NOT_STARTED, '', {}
83
+
84
+ zero = (read(os.path.join(root, 'iterations', '0', 'result.json'), {})
85
+ .get('objective') or {}).get('median')
86
+ text = 'A0 {}'.format(number(zero)) if zero is not None else ''
87
+
88
+ if status == 'waiting':
89
+ text = 'a question waits for the user: {}'.format(record.get(
90
+ 'question', '?'))
91
+
92
+ if status != 'done':
93
+ return RUNNING, text, {}
94
+
95
+ return COMPLETE, (record.get('finished') or '')[:10] + (
96
+ '; ' if text else '') + text, {'readme': os.path.join(root,
97
+ 'iterations', '0', 'README.md')}
98
+
99
+
100
+ def search(work, root, state):
101
+ if (state.get('setup') or {}).get('status') != 'done':
102
+ return NOT_STARTED, '', {}
103
+
104
+ ended = autoopt.load_ended(root)
105
+ results = glob.glob(os.path.join(root, 'iterations', '*', 'result.json'))
106
+ count = len([r for r in results if os.path.basename(os.path.dirname(r))
107
+ != '0'])
108
+ text = '{} iterations settled'.format(count)
109
+
110
+ if ended:
111
+ counts = ended.get('counts') or {}
112
+ return COMPLETE, '{}; {} rounds, {} iterations, {} winning'.format(
113
+ (ended.get('ended_at') or '')[:10], counts.get('rounds', '?'),
114
+ counts.get('iterations', '?'), counts.get('winning_iterations',
115
+ '?')), {'rounds': os.path.join(root, 'rounds')}
116
+
117
+ if not count and not (state.get('loop') or {}).get('open'):
118
+ return NOT_STARTED, 'waiting for the idea miner\'s S1' if (
119
+ state.get('mining') or {}).get('done') is None else '', {}
120
+
121
+ return RUNNING, text, {'rounds': os.path.join(root, 'rounds')}
122
+
123
+
124
+ def final(work, root, state):
125
+ ended = autoopt.load_ended(root)
126
+
127
+ if not ended:
128
+ return NOT_STARTED, '', {}
129
+
130
+ medians = ended.get('medians') or {}
131
+ paired = ended.get('paired') or {}
132
+ text = '{} {}: A0 {} -> {}'.format(medians.get('objective', ''),
133
+ medians.get('unit') or '', number(medians.get('A0')),
134
+ number(medians.get('winner')))
135
+
136
+ if isinstance(paired, dict) and paired.get('summary'):
137
+ text += '; paired ' + str(paired['summary'])[:60]
138
+
139
+ return COMPLETE, (ended.get('ended_at') or '')[:10] + '; ' + text, {
140
+ 'ended': os.path.join(root, 'ended.md')}
141
+
142
+
143
+ SHIPPED = {'none': 'not shipped, the user\'s choice',
144
+ 'apply': 'applied to the original files',
145
+ 'branch': 'a branch in the original repository'}
146
+ PENDING = {'apply': 'the change is not applied yet',
147
+ 'branch': 'the branch is not made yet'}
148
+
149
+
150
+ def unoffered(work, after):
151
+ """Why the user's answer is none step 5 offers this search (a route of
152
+ the other mode, a document without its source), or None."""
153
+
154
+ import ship
155
+
156
+ config = read(os.path.join(work, 'autooptimize', 'config.json'), {})
157
+
158
+ try:
159
+ found = ship.choices(work, config)
160
+ except (RuntimeError, OSError, ValueError, KeyError):
161
+ return None
162
+
163
+ if after.get('ship') not in found['routes']:
164
+ return 'after.ship is {}, which this search does not offer'.format(
165
+ after.get('ship'))
166
+
167
+ documents = after.get('ship_documents') or []
168
+ extra = [one for one in documents if one not in found['documents']]
169
+
170
+ if after.get('ship') == 'github' and (extra or not documents):
171
+ return 'after.ship_documents {}'.format('names {}, which this search '
172
+ 'does not offer'.format(', '.join(extra)) if extra else 'is empty')
173
+
174
+ return None
175
+
176
+
177
+ def ship(work, root, state):
178
+ """Step 5. `after.ship` is the user's answer; the step is complete when
179
+ what it asked for is done: `ship/applied.json` or `ship/branch.json` of
180
+ the winner `ended.json` names, or every chosen GitHub document posted. An
181
+ answer this search is not offered is no answer."""
182
+
183
+ ended = autoopt.load_ended(root)
184
+
185
+ if not ended:
186
+ return NOT_STARTED, '', {}
187
+
188
+ # A search that kept nothing ends on A0, and there is nothing to ship.
189
+ if (ended.get('winner') or {}).get('id') == 0:
190
+ return COMPLETE, 'nothing to ship: no change was kept', {}
191
+
192
+ after = after_of(work)
193
+ choice = after.get('ship')
194
+
195
+ if choice in (None, 'ask') or (choice in ('github', 'branch') and
196
+ after.get('branch_prefix') not in ('yes', 'no')):
197
+ return NOT_STARTED, 'ask the user how to ship', {}
198
+
199
+ wrong = unoffered(work, after)
200
+
201
+ if wrong:
202
+ return NOT_STARTED, 'ask the user how to ship: {}'.format(wrong), {}
203
+
204
+ if choice == 'none':
205
+ return COMPLETE, SHIPPED['none'], {}
206
+
207
+ if choice in ('apply', 'branch'):
208
+ record = autoopt.work_path(work, 'ship', '{}.json'.format('applied'
209
+ if choice == 'apply' else 'branch'))
210
+ shipped = read(record)
211
+ winner = (ended.get('winner') or {}).get('id')
212
+
213
+ if shipped and shipped.get('id', winner) != winner:
214
+ return RUNNING, '{} {}; the winner is now {}'.format(
215
+ 'the original files hold' if choice == 'apply' else 'the '
216
+ 'branch holds', shipped.get('label') or shipped.get('id'), (
217
+ ended.get('winner') or {}).get('label') or winner), {choice:
218
+ record}
219
+
220
+ if shipped is not None:
221
+ return COMPLETE, SHIPPED[choice], {choice: record}
222
+
223
+ return RUNNING, PENDING[choice], {}
224
+
225
+ documents = after.get('ship_documents') or []
226
+ posted = {name: autoopt.ship_posted(work, name) for name in documents}
227
+ done = [name for name in documents if posted[name]]
228
+ text = '{} of {} document(s) posted{}'.format(len(done), len(documents),
229
+ ': ' + ', '.join(posted[name]['url'] for name in done) if done else '')
230
+
231
+ if documents and len(done) == len(documents):
232
+ return COMPLETE, text, {}
233
+
234
+ return RUNNING, text, {}
235
+
236
+
237
+ def finish(work, root, state):
238
+ """Step 6: complete once the final report holds no `<<FILL` mark;
239
+ `archive` writes it with several."""
240
+
241
+ report = autoopt.work_path(work, 'finish', 'final-report.md')
242
+
243
+ try:
244
+ with open(report, encoding='utf-8') as handle:
245
+ marks = handle.read().count('<<FILL')
246
+ except OSError:
247
+ return NOT_STARTED, '', {}
248
+
249
+ if marks:
250
+ return RUNNING, 'final-report.md has {} <<FILL mark(s) left'.format(
251
+ marks), {'report': report}
252
+
253
+ return COMPLETE, mtime(report) or '', {'report': report}
254
+
255
+
256
+ STAGES = (('interview', interview), ('setup', setup), ('search', search),
257
+ ('final', final), ('ship', ship), ('finish', finish))
258
+
259
+
260
+ def load_state(root):
261
+ return read(os.path.join(root, 'state.json'), {})
262
+
263
+
264
+ def collect(work):
265
+ """`[(stage, status, text, links)]` for the six stages."""
266
+
267
+ root = os.path.join(work, 'autooptimize')
268
+ state = load_state(root)
269
+
270
+ return [(name,) + function(work, root, state) for name, function in STAGES]
271
+
272
+
273
+ def render_text(work, rows):
274
+ config = read(os.path.join(work, 'autooptimize', 'config.json'), {})
275
+ lines = ['# NOTES', '', '*Generated by `stages.py render`: the stages of '
276
+ 'this search, read from its state files. Do not edit.*', '',
277
+ '**Task.** ' + (config.get('task') or '(no config.json yet)'), '',
278
+ '| Stage | Status | Detail |', '|---|---|---|']
279
+
280
+ for name, status, text, links in rows:
281
+ lines.append('| {} | {} | {} |'.format(name, status, text.replace(
282
+ '|', '/')))
283
+
284
+ links = [(name, key, path) for name, _, _, found in rows
285
+ for key, path in sorted(found.items()) if os.path.exists(path)]
286
+
287
+ if links:
288
+ lines += ['', '## Files', ''] + ['- {} {}: `{}`'.format(name, key,
289
+ os.path.relpath(path, work)) for name, key, path in links]
290
+
291
+ lines += ['', '## Next', '', next_text(work, rows), '']
292
+
293
+ return '\n'.join(lines)
294
+
295
+
296
+ # The command or question that follows each stage once the one before is
297
+ # complete. `{w}` is the search directory.
298
+ NEXT = {
299
+ 'interview': 'finish the interview: fill in spec.md (references/'
300
+ 'step0-interview.md)',
301
+ 'setup': 'python3 {ao}/autoopt.py setup {w}; spawn the setup subagent, '
302
+ 'and the idea miner once it reports',
303
+ 'search': 'python3 {ao}/autoopt.py loop {w}; spawn the orchestrator',
304
+ 'final': 'python3 {ao}/autoopt.py end {w} --background; autoopt.py wait '
305
+ '<log>',
306
+ 'ship': 'references/step5-ship.md: python3 {ao}/ship.py plan {w}, then '
307
+ 'ask the user how to ship',
308
+ 'finish': 'references/step6-finish.md: python3 {ao}/autoopt.py archive {w} '
309
+ 'if it has not run, the final report (every <<FILL mark), then prune',
310
+ }
311
+
312
+ # Step 5 once the user has answered, by `after.ship`; `github` is
313
+ # `github_move`'s.
314
+ SHIP_NEXT = {
315
+ 'apply': 'python3 {ao}/ship.py apply {w}: show the user the preview, then '
316
+ '--yes on their word',
317
+ 'branch': 'python3 {ao}/ship.py branch {w}: show the user the preview, '
318
+ 'then --yes on their word',
319
+ }
320
+ REVIEW = '(`references/step5-ship.md`, *Review, then post all*)'
321
+
322
+
323
+ def github_move(work, after):
324
+ """The next move of the GitHub route, from `ship/rehearsal.json` and
325
+ what is posted: the document writer, a rehearsal, the user's review, or
326
+ the post (again, when one stopped part way)."""
327
+
328
+ import ship
329
+
330
+ documents = [one for one in autoopt.SHIP_DOCUMENTS if one in (after.get(
331
+ 'ship_documents') or [])]
332
+ posted = [one for one in documents if autoopt.ship_posted(work, one)]
333
+ record = read(autoopt.work_path(work, 'ship', 'rehearsal.json'))
334
+ command = 'python3 {}'.format(os.path.join(HERE, 'ship.py'))
335
+ current = record and record.get('ok') and record.get('documents') == \
336
+ documents and record.get('digest') == ship.inputs_digest(work,
337
+ documents, after, record.get('branches'))
338
+ post = '{} post {} all --approved --digest {}{}'.format(command, work,
339
+ (record or {}).get('digest'), ''.join(' --branch {}={}'.format(*item)
340
+ for item in sorted(((record or {}).get('branches') or {}).items())))
341
+
342
+ if posted and current:
343
+ return ('{} of {} document(s) posted and the post stopped: fix its '
344
+ 'cause, then the same command again, which skips what was posted '
345
+ '(add --other-owner if the user confirmed the repository): {} {}'
346
+ .format(len(posted), len(documents), post, REVIEW))
347
+
348
+ if current:
349
+ return ('show the user every document of the rehearsal together '
350
+ '(ship/<folder>/body.md and ship/rehearsal/<document>.txt; {} '
351
+ 'status {}), then, once they ask for posting: {} {}'.format(command,
352
+ work, post, REVIEW))
353
+
354
+ rendered = all(os.path.exists(os.path.join(ship.folder(work, one),
355
+ 'body.title')) for one in documents)
356
+
357
+ if not rendered and not record:
358
+ return ('{} brief {}: spawn the document writer from its prompt, unless '
359
+ 'one is at work; it reports once `ship.py rehearse` exits 0 '
360
+ '(`references/step5-ship.md`, *The document writer*)'.format(command,
361
+ work))
362
+
363
+ return ('{} rehearse {}: {}; fix what it lists, or send it to the document '
364
+ 'writer (spawn one from `ship.py brief` if none is at work), then show '
365
+ 'the user the new batch {}'.format(command, work, 'no rehearsal yet' if
366
+ not record else 'the last rehearsal had problems' if not record.get(
367
+ 'ok') else 'the inputs changed since the last rehearsal', REVIEW))
368
+
369
+
370
+ def after_of(work):
371
+ config = read(os.path.join(work, 'autooptimize', 'config.json'), {})
372
+ return dict(autoopt.AFTER_DEFAULTS, **(config.get('after') or {}))
373
+
374
+
375
+ def hours_since(stamp):
376
+ """Hours from a `YYYY-MM-DDTHH:MM:SS` stamp to now, or None."""
377
+
378
+ import time
379
+
380
+ try:
381
+ return (time.time() - time.mktime(time.strptime(str(stamp)[:19],
382
+ '%Y-%m-%dT%H:%M:%S'))) / 3600
383
+ except ValueError:
384
+ return None
385
+
386
+
387
+ def stop_word(root, config, state, after):
388
+ """The When-to-stop criterion that is reached, or None: `floor`,
389
+ `stalled` (the open round holds a phase's worth of settled iterations) or
390
+ `budget` (`after.budget_iterations` iterations have settled, every idea
391
+ from the `after.budget_stages` idea-miner stages is
392
+ tried or dropped, or the wall clock since step 2 began passes
393
+ `after.budget_hours`)."""
394
+
395
+ derived = autoopt.end_reason(root, config, state, None)['criterion']
396
+
397
+ if derived:
398
+ return derived
399
+
400
+ spent = hours_since((state.get('setup') or {}).get('started'))
401
+
402
+ if after['budget_hours'] and spent is not None and spent >= after[
403
+ 'budget_hours']:
404
+ return 'budget'
405
+
406
+ return None
407
+
408
+
409
+ def end_failure(path):
410
+ """The last lines of an `end.log` that finished with a non-zero exit,
411
+ or None: a failed `end` is shown, not started again."""
412
+
413
+ try:
414
+ with open(path) as handle:
415
+ lines = [line for line in handle.read().splitlines()
416
+ if line.strip()]
417
+ except OSError:
418
+ return None
419
+
420
+ if not lines or not lines[-1].startswith('exit ') or lines[-1] == 'exit 0':
421
+ return None
422
+
423
+ return '{}; {}'.format(lines[-1], ' / '.join(lines[-4:-1])[-400:] or
424
+ 'no output')
425
+
426
+
427
+ def log_running(path):
428
+ """A detached command's log that has no `exit N` line yet, while its
429
+ process lives: one that died without the line is not running."""
430
+
431
+ try:
432
+ with open(path) as handle:
433
+ lines = handle.read().splitlines()
434
+ except OSError:
435
+ return False
436
+
437
+ if lines and lines[-1].startswith('exit '):
438
+ return False
439
+
440
+ jobs = dict((log, what) for log, what, _ in autoopt.background_jobs(
441
+ os.path.dirname(path)))
442
+
443
+ return jobs.get(path) != 'died'
444
+
445
+
446
+ def search_action(work, root, state, config, after, rows):
447
+ """The next move before the search has ended."""
448
+
449
+ status = dict((name, st) for name, st, _, _ in rows)
450
+ ao = os.path.join(HERE, 'autoopt.py')
451
+
452
+ if status['interview'] != COMPLETE:
453
+ return 'agent', ('finish the interview: fill in spec.md (references/'
454
+ 'step0-interview.md), then python3 {} init if it has not run'
455
+ .format(ao))
456
+
457
+ setup = state.get('setup') or {}
458
+
459
+ if not setup:
460
+ return 'agent', ('python3 {0} setup {1}; spawn the setup subagent '
461
+ 'from that prompt. The idea miner starts after setup, when A0\'s '
462
+ 'profile exists'.format(ao, work))
463
+
464
+ if setup.get('status') == 'waiting':
465
+ return 'stop', ('the setup subagent asked the user: {}. Ask them in '
466
+ 'one call, then python3 {} setup {} --answer "<their words>" and '
467
+ 'send the message it prints to the setup subagent (SendMessage); '
468
+ 'if it is gone, spawn the prompt printed after the message'.format(
469
+ setup.get('question'), ao, work))
470
+
471
+ if setup.get('status') != 'done':
472
+ return 'agent', ('wait for the setup subagent (its notes: '
473
+ 'autooptimize/setup/notes.md); if it died, python3 {} setup {} '
474
+ '--force'.format(ao, work))
475
+
476
+ mining = state.get('mining') or {}
477
+
478
+ if not mining.get('done'):
479
+ if not mining.get('stage'):
480
+ return 'agent', ('python3 {0} mine {1}; spawn the idea miner for '
481
+ 'S1 from its prompt (A0\'s profile is written now)'
482
+ .format(ao, work))
483
+
484
+ return 'agent', ('wait for the idea miner\'s S1 (python3 {} status '
485
+ '{}); if it died, python3 {} mine {} --force'.format(ao, work,
486
+ ao, work))
487
+
488
+ if log_running(os.path.join(root, 'end.log')):
489
+ return 'agent', ('`end` is running: `python3 {} wait {}`, again '
490
+ 'until it prints `wait: finished`'.format(ao, os.path.join(root,
491
+ 'end.log')))
492
+
493
+ failed = end_failure(os.path.join(root, 'end.log'))
494
+
495
+ if failed:
496
+ return 'stop', ('`end` failed and the search has not ended: {}. Fix '
497
+ 'what it names (references/step4-final.md), or tell the user, then '
498
+ 'run `end` again'.format(failed))
499
+
500
+ if (state.get('loop') or {}).get('open'):
501
+ return 'agent', ('the orchestrator phase {} is open: wait for its '
502
+ 'report (it closes the phase itself) and show the round tables. '
503
+ 'If it died without one: python3 {} loop {} --force'.format((
504
+ state['loop'] or {}).get('phase', '?'), ao, work))
505
+
506
+ word = stop_word(root, config, state, after)
507
+
508
+ if word is None:
509
+ return 'agent', ('python3 {} loop {}; spawn the orchestrator from '
510
+ 'its prompt'.format(ao, work))
511
+
512
+ if after['stop'] == 'auto' and word != 'floor':
513
+ return 'run', 'python3 {} end {} --reason {} --background'.format(
514
+ ao, work, word)
515
+
516
+ if word == 'floor':
517
+ return 'stop', ('the root reached the floor the user set ({0}): this '
518
+ 'benchmark cannot resolve a gain. Ask the user: end here '
519
+ '(python3 {1} end {2} --reason floor --background), a new search '
520
+ 'on a larger input seeded from this root (references/changes.md), '
521
+ 'or go on here with a lower floor or none (python3 {1} config {2} '
522
+ '--set floor=<lower, or 0> --reason "<their words>", then '
523
+ '`stages.py next` again)'.format(config.get('floor'), ao, work))
524
+
525
+ return 'stop', ('the search reached `{}`: ask the user whether to end '
526
+ 'it (after.stop is ask), then python3 {} end {} --reason {} '
527
+ '--background'.format(word, ao, work, word))
528
+
529
+
530
+ def next_action(work, rows):
531
+ """`(stage, kind, text)`: `run` is a command `--run` may start, `agent`
532
+ is for the session to do, `wait` is a command still running, `stop` is a
533
+ decision the step 0 interview did not make."""
534
+
535
+ after = after_of(work)
536
+ root = os.path.join(work, 'autooptimize')
537
+ state = load_state(root)
538
+ config = read(os.path.join(root, 'config.json'), {})
539
+ ended = autoopt.load_ended(root)
540
+
541
+ if not ended:
542
+ kind, text = search_action(work, root, state, config, after, rows)
543
+ stage = 'search' if (state.get('setup') or {}).get('status') == \
544
+ 'done' else ('interview' if kind == 'agent' and text.startswith(
545
+ 'finish the') else 'setup')
546
+ return stage, kind, text
547
+
548
+ # `end` wrote ended.json and is still cleaning up.
549
+ if log_running(os.path.join(root, 'end.log')):
550
+ return 'final', 'wait', '`end` is finishing ({})'.format(os.path.join(
551
+ root, 'end.log'))
552
+
553
+ for name, status, text, _ in rows:
554
+ if status == COMPLETE:
555
+ continue
556
+
557
+ if name == 'ship' and status != NOT_STARTED and after.get('ship') in \
558
+ SHIP_NEXT:
559
+ return name, 'agent', SHIP_NEXT[after['ship']].format(ao=HERE,
560
+ w=work)
561
+
562
+ if name == 'ship' and status != NOT_STARTED and after.get('ship') == \
563
+ 'github':
564
+ return name, 'agent', github_move(work, after)
565
+
566
+ if name == 'finish' and not config.get('repo') and not exists(
567
+ autoopt.work_path(work, 'finish', 'archive', 'idea.patch')):
568
+ return name, 'run', 'python3 {} archive {}'.format(os.path.join(
569
+ HERE, 'autoopt.py'), work)
570
+
571
+ return name, 'agent', NEXT[name].format(ao=HERE, w=work)
572
+
573
+ return None, 'done', 'every stage is complete'
574
+
575
+
576
+ def next_text(work, rows):
577
+ name, kind, text = next_action(work, rows)
578
+
579
+ if name is None:
580
+ return text
581
+
582
+ return '**{}** ({}): `{}`'.format(name, kind, text) if kind != 'stop' \
583
+ else '**{}** stops: {}'.format(name, text)
584
+
585
+
586
+ def render(work):
587
+ rows = collect(work)
588
+ path = os.path.join(work, 'NOTES.md')
589
+
590
+ # Whole or not at all.
591
+ with open(path + '.tmp', 'w', encoding='utf-8', newline='\n') as out:
592
+ out.write(render_text(work, rows))
593
+
594
+ os.replace(path + '.tmp', path)
595
+
596
+ return rows
597
+
598
+
599
+ def main(argv=None):
600
+ parser = argparse.ArgumentParser(description=__doc__,
601
+ formatter_class=argparse.RawDescriptionHelpFormatter)
602
+ parser.add_argument('command', choices=('render', 'status', 'next'))
603
+ parser.add_argument('work')
604
+ parser.add_argument('--run', action='store_true', help='with `next`: '
605
+ 'run the command when the stage\'s command is mechanical and the '
606
+ 'step 0 answers allow it')
607
+ args = parser.parse_args(argv)
608
+ work = os.path.abspath(os.path.expanduser(args.work))
609
+
610
+ if os.path.basename(work) == 'autooptimize':
611
+ work = os.path.dirname(work)
612
+
613
+ if not os.path.isdir(os.path.join(work, 'autooptimize')):
614
+ sys.stderr.write('stages: {} has no autooptimize/\n'.format(work))
615
+ return 1
616
+
617
+ if args.command == 'render':
618
+ render(work)
619
+ print(os.path.join(work, 'NOTES.md'))
620
+ return 0
621
+
622
+ rows = collect(work)
623
+
624
+ if args.command in ('next', 'status'):
625
+ # `status` is read by anyone; only `next`, the main session's, marks
626
+ # the change as told.
627
+ notice = autoopt.skill_notice(os.path.join(work, 'autooptimize'),
628
+ mark=args.command == 'next')
629
+
630
+ if notice:
631
+ print(notice)
632
+
633
+ if args.command == 'next':
634
+ print(next_text(work, rows))
635
+ name, kind, text = next_action(work, rows)
636
+
637
+ if args.run and kind == 'run':
638
+ import shlex
639
+ import subprocess
640
+ code = subprocess.run(shlex.split(text)).returncode
641
+ render(work)
642
+ return code
643
+
644
+ return 0
645
+
646
+ print(render_text(work, rows))
647
+ return 0
648
+
649
+
650
+ if __name__ == '__main__':
651
+ sys.exit(main())