@giamme/forge 0.15.0 → 0.17.0

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 (80) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/VERSION +1 -1
  3. package/docs/artifacts.md +1 -1
  4. package/docs/commands.md +14 -3
  5. package/docs/dataset.md +8 -0
  6. package/docs/forge-ui.md +14 -0
  7. package/docs/memory.md +22 -0
  8. package/docs/reviews.md +22 -1
  9. package/forge +11 -0
  10. package/package.json +1 -1
  11. package/references/dataset.md +129 -7
  12. package/references/decision-models.md +15 -2
  13. package/references/decompose.md +95 -13
  14. package/references/harnesses.md +4 -1
  15. package/references/planning.md +3 -2
  16. package/references/solo.md +5 -1
  17. package/references/ui.md +10 -1
  18. package/scripts/forge-artifact.sh +53 -0
  19. package/scripts/forge-contract.py +107 -9
  20. package/scripts/forge-control.py +0 -2
  21. package/scripts/forge-dispatch.sh +28 -12
  22. package/scripts/forge-fail-first.py +3 -1
  23. package/scripts/forge-guard.py +247 -8
  24. package/scripts/forge-issues.py +16 -3
  25. package/scripts/forge-ledger.py +3 -1
  26. package/scripts/forge-lib-adopt.sh +266 -0
  27. package/scripts/forge-lib-attribute.sh +10 -2
  28. package/scripts/forge-lib-plans.sh +16 -4
  29. package/scripts/forge-lib-review.sh +8 -2
  30. package/scripts/forge-lib-task.sh +19 -5
  31. package/scripts/forge-memory.sh +41 -4
  32. package/scripts/forge-metrics.sh +29 -0
  33. package/scripts/forge-parallel.sh +99 -14
  34. package/scripts/forge-plan-check.py +25 -2
  35. package/scripts/forge-planner.py +20 -6
  36. package/scripts/forge-route.py +16 -2
  37. package/scripts/forge-runs-rm.py +23 -7
  38. package/scripts/forge-runtime.py +25 -2
  39. package/scripts/forge-schedule.py +5 -2
  40. package/scripts/forge-shadow.py +30 -9
  41. package/scripts/forge-solo.sh +6 -0
  42. package/scripts/forge-sweep.py +25 -10
  43. package/scripts/forge_dataset/cli.py +99 -0
  44. package/scripts/forge_dataset/export.py +1 -0
  45. package/scripts/forge_dataset/facts.py +278 -0
  46. package/scripts/forge_dataset/harvest.py +27 -3
  47. package/scripts/forge_dataset/history.py +126 -0
  48. package/scripts/forge_dataset/outcomes.py +206 -58
  49. package/scripts/forge_dataset/pairs.py +174 -0
  50. package/scripts/forge_dataset/risk.py +108 -0
  51. package/scripts/forge_dataset/tiers.py +427 -0
  52. package/scripts/forge_dataset/worktrees.py +95 -0
  53. package/scripts/forge_decide/cli.py +23 -2
  54. package/scripts/forge_decide/labels.py +30 -6
  55. package/scripts/forge_decide/replay.py +10 -4
  56. package/scripts/forge_memory_list.py +153 -0
  57. package/scripts/forge_worktrees.py +88 -0
  58. package/ui/README.md +31 -0
  59. package/ui/docs/api.md +92 -6
  60. package/ui/forge_ui/__init__.py +14 -1
  61. package/ui/forge_ui/__main__.py +1 -1
  62. package/ui/forge_ui/control.py +77 -0
  63. package/ui/forge_ui/export.py +9 -2
  64. package/ui/forge_ui/findings.py +11 -2
  65. package/ui/forge_ui/projects.py +571 -0
  66. package/ui/forge_ui/reader.py +96 -9
  67. package/ui/forge_ui/server.py +8 -0
  68. package/ui/forge_ui/static/app.js +105 -22
  69. package/ui/forge_ui/static/cloudui.js +6 -2
  70. package/ui/forge_ui/static/convo.js +1 -1
  71. package/ui/forge_ui/static/diffview.js +9 -5
  72. package/ui/forge_ui/static/files.js +1 -1
  73. package/ui/forge_ui/static/index.html +5 -1
  74. package/ui/forge_ui/static/panel.js +69 -2
  75. package/ui/forge_ui/static/projectsview.js +372 -0
  76. package/ui/forge_ui/static/settings.js +136 -4
  77. package/ui/forge_ui/static/style.css +94 -3
  78. package/ui/forge_ui/static/uikit.js +94 -1
  79. package/ui/forge_ui/static/worktreesview.js +250 -0
  80. package/ui/forge_ui/worktrees.py +570 -0
@@ -170,16 +170,34 @@ def findings(message: str | None) -> list:
170
170
  return parse_review(message)[0]
171
171
 
172
172
 
173
+ def review_tests(message: str | None) -> dict | None:
174
+ """What a QA reply says about its tests; None when it does not, or the contract cannot load."""
175
+ try:
176
+ return contract().tests_report(message) if message else None
177
+ except Exception:
178
+ return None
179
+
180
+
173
181
  def parse_review(message: str | None) -> tuple[list, bool]:
174
182
  """(findings, parsed): parsed is False when the contract's parser raised."""
175
183
  if not message:
176
184
  return [], True
177
185
  try:
178
- parsed = contract().parse_findings(message)
186
+ module = contract()
187
+ parsed = module.parse_findings(message)
179
188
  except Exception:
180
189
  return [], False
181
- return [dict(status=f.status, severity=f.severity, located=f.located, line=f.line,
182
- head=f.text.splitlines()[0][:300] if f.text else '') for f in parsed], True
190
+ out = []
191
+ for f in parsed:
192
+ head = f.text.splitlines()[0] if f.text else ''
193
+ item = dict(status=f.status, severity=f.severity, located=f.located, line=f.line,
194
+ head=module.split_facts(head)[0][:300])
195
+ # #119: the facts suffix is kept apart, so a head reads as it did before it existed.
196
+ found = module.facts(f.text)
197
+ if found is not None:
198
+ item['facts'] = found
199
+ out.append(item)
200
+ return out, True
183
201
 
184
202
 
185
203
  def review_completeness(verdict: str | None, found: list, parsed: bool = True) -> str | None:
@@ -305,6 +323,8 @@ def locate(root: str | Path, role: str | None = None) -> dict:
305
323
  plan, ctx['scope'] = p.parent.parent, 'final_review'
306
324
  elif p.name.startswith('integrate-') and (p.parent / 'tasks.tsv').exists():
307
325
  plan, ctx['scope'] = p.parent, 'integrate'
326
+ elif p.name.startswith('adopt-') and (p.parent / 'tasks.tsv').exists():
327
+ plan, ctx['scope'] = p.parent, 'adopt'
308
328
  elif (p / 'tasks.tsv').exists() or (p / 'run_id').exists():
309
329
  plan, ctx['scope'] = p, 'plan'
310
330
  if plan is not None:
@@ -438,6 +458,7 @@ def dispatch_event(attempt: Path, root: Path, role: str, harness: str, rc, prov:
438
458
  prompt_bytes=metrics.get('prompt_bytes'), final_source=final_source,
439
459
  verdict=verdict, findings=found, learnings=learnings(message),
440
460
  findings_parse=review_completeness(verdict, found, parsed) if role == 'qa' else None,
461
+ tests=review_tests(message) if role == 'qa' else None,
441
462
  session_id=session_id, session_continue=session_continue,
442
463
  root=str(root), scope=prov.get('scope'), trigger=prov.get('trigger'),
443
464
  **({'shadow': shadow} if shadow else {}),
@@ -700,7 +721,10 @@ def plan_event(plan: Path, prov: dict, src: str = 'live', inventory: bool = True
700
721
  source = 'planner'
701
722
  else:
702
723
  source = 'orchestrator'
724
+ risk = (text(tdir / 'risk') or '').split()
703
725
  per_task[tid] = dict(row, declared_difficulty=declared_tier, difficulty_source=source,
726
+ # #122: the task's risk, recorded in shadow beside its difficulty (None: not rated)
727
+ risk=risk[0] if risk and risk[0] in ('low', 'medium', 'high') else None,
704
728
  routing=routing, prompt=put_file(tdir / 'prompt.md', 'prompt'),
705
729
  approach=put_file(tdir / 'approach.md', 'prompt'))
706
730
  decisions = jsonl(tdir / 'route.jsonl')
@@ -0,0 +1,126 @@
1
+ """`forge dataset history`: the reviews' findings and the learnings the dataset keeps, for runs whose dir is gone (#126).
2
+
3
+ forge-ui's Projects screen reads run dirs first; this is what it adds for the runs and checkouts that no longer
4
+ exist. Each run is one record with its repository and base commit, so the screen can tell which project it
5
+ belongs to (the same base-commit rule forge-ui's repos.py uses for a run whose checkout is gone):
6
+
7
+ runs {run (dataset uid), run_id, mode, repo_path, base, first, last}
8
+ findings one per review dispatch (qa, qa_shadow) that listed findings: {run, run_id, task, attempt, role,
9
+ scope, reviewer, verdict, ts, findings: [{head, severity (0-3 or null), status, line}]}, as the
10
+ capture parsed them with forge-contract.py (no second parser)
11
+ learnings one per FORGE_LEARNING line a dispatch emitted: {run, run_id, task, role, model, ts, category, text}
12
+ ledger the ledger rows `forge dataset import --ledger` stored: {repo_path, ts, run_id, task, role, model,
13
+ category, key, text, injectable}
14
+
15
+ Read-only: it never creates a store. With the dataset off everything is empty and `enabled` is false.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import json
20
+
21
+ from . import connect, dataset_dir, enabled
22
+
23
+ _HEAD_MAX = 400
24
+ _TEXT_MAX = 2000
25
+
26
+
27
+ def _empty(on):
28
+ return dict(enabled=on, runs=[], findings=[], learnings=[], ledger=[])
29
+
30
+
31
+ def load() -> dict:
32
+ if not enabled():
33
+ return _empty(False)
34
+ if not (dataset_dir() / 'dataset.sqlite').exists():
35
+ return _empty(True)
36
+ db = connect()
37
+ try:
38
+ paths = dict(db.execute('SELECT repo, path FROM repos'))
39
+ out = _empty(True)
40
+ runs = {}
41
+
42
+ def note(run, run_id, mode, repo, ts):
43
+ if not run:
44
+ return None
45
+ r = runs.setdefault(run, dict(run=run, run_id=run_id, mode=mode, repo_path=paths.get(repo), base=None,
46
+ first=ts, last=ts))
47
+ r['first'], r['last'] = min(r['first'], ts), max(r['last'], ts)
48
+ r['run_id'] = r['run_id'] or run_id
49
+ r['repo_path'] = r['repo_path'] or paths.get(repo)
50
+ return r
51
+
52
+ attempt_task = {}
53
+ for rid, run, run_id, mode, repo, task, attempt, ts, data in db.execute(
54
+ "SELECT rid, run, run_id, mode, repo, task, attempt, ts, data FROM events WHERE kind = 'attempt' ORDER BY ts"):
55
+ r = note(run, run_id, mode, repo, ts)
56
+ attempt_task[rid] = (task, attempt)
57
+ if r is not None and r['base'] is None:
58
+ try:
59
+ base = json.loads(data).get('base_ref')
60
+ except ValueError:
61
+ base = None
62
+ if isinstance(base, str) and len(base) in (40, 64):
63
+ r['base'] = base.lower()
64
+ for run, run_id, mode, repo, task, attempt, parent, ts, data in db.execute(
65
+ "SELECT run, run_id, mode, repo, task, attempt, parent, ts, data FROM events WHERE kind = 'dispatch' ORDER BY ts"):
66
+ try:
67
+ d = json.loads(data)
68
+ except ValueError:
69
+ continue
70
+ note(run, run_id, mode, repo, ts)
71
+ if task is None and parent in attempt_task:
72
+ task, attempt = task or attempt_task[parent][0], attempt or attempt_task[parent][1]
73
+ role = d.get('role')
74
+ spec = d.get('alias') or d.get('model')
75
+ if d.get('effort') and spec and ':' not in str(spec):
76
+ spec = '%s:%s' % (spec, d['effort'])
77
+ found = d.get('findings')
78
+ if role in ('qa', 'qa_shadow') and isinstance(found, list) and found:
79
+ items = []
80
+ for f in found:
81
+ if not isinstance(f, dict) or not isinstance(f.get('head'), str):
82
+ continue
83
+ sev = f.get('severity')
84
+ items.append(dict(head=f['head'][:_HEAD_MAX], severity=sev if type(sev) is int and 0 <= sev <= 3 else None,
85
+ status=f.get('status') if f.get('status') in ('CONFIRMED', 'PLAUSIBLE', 'UNSTATED') else None,
86
+ line=f.get('line') if type(f.get('line')) is int else None))
87
+ if items:
88
+ out['findings'].append(dict(run=run, run_id=run_id, task=task, attempt=attempt, role=role,
89
+ scope=d.get('scope'), reviewer=spec, verdict=d.get('verdict'), ts=ts,
90
+ findings=items))
91
+ for line in d.get('learnings') or []:
92
+ if not isinstance(line, str):
93
+ continue
94
+ category, sep, text = line.partition('|')
95
+ if not sep:
96
+ continue
97
+ out['learnings'].append(dict(run=run, run_id=run_id, task=task, role=role, model=spec, ts=ts,
98
+ category=category.strip().lower(), text=text.strip()[:_TEXT_MAX]))
99
+ for repo, data in db.execute("SELECT repo, data FROM events WHERE kind = 'ledger' ORDER BY ts"):
100
+ try:
101
+ d = json.loads(data)
102
+ except ValueError:
103
+ continue
104
+ if not isinstance(d.get('text'), str) or d.get('category') in (None, '-'):
105
+ continue
106
+ out['ledger'].append(dict(repo_path=paths.get(repo), ts=d.get('ts'), run_id=d.get('run_id'), task=d.get('task'),
107
+ role=d.get('role'), model=d.get('model'), category=d.get('category'),
108
+ key=d.get('key'), text=d['text'][:_TEXT_MAX], injectable=d.get('injectable') != '0'))
109
+ out['runs'] = sorted(runs.values(), key=lambda r: r['first'])
110
+ return out
111
+ finally:
112
+ db.close()
113
+
114
+
115
+ def main(args) -> int:
116
+ rep = load()
117
+ if args.json:
118
+ print(json.dumps(rep, sort_keys=True))
119
+ return 0
120
+ if not rep['enabled']:
121
+ print('the dataset is off (FORGE_DATASET=off)')
122
+ return 0
123
+ print('runs: %d, reviews with findings: %d, learnings: %d, ledger rows: %d' % (
124
+ len(rep['runs']), len(rep['findings']), len(rep['learnings']), len(rep['ledger'])))
125
+ print("forge-ui's Projects screen (#/projects) shows them by repository.")
126
+ return 0
@@ -14,6 +14,19 @@ default) after the integration, and whether any later commit reverted it.
14
14
  Survival describes the artifact that landed (with every retry it took), not the first
15
15
  model that was routed to the task: the exporter attaches it to the review of that diff.
16
16
 
17
+ Integrations are followed where they went (#120). One whose branch was deleted, or whose
18
+ candidate is no longer on that branch's first-parent chain, is looked for in every other
19
+ branch (local, then remote; never forge's own): the commit where it entered a branch's
20
+ first-parent chain, a merge or itself, is where the horizon is walked from. A run nobody
21
+ ran `integrate` for, its integration branch merged by hand, is followed the same way from
22
+ its last integration commit, with the horizon counted from when it landed. A squash or a
23
+ rebase leaves no ancestry to follow: an `integrate` that went that way is `lost`, and a
24
+ hand-merged run that did is `not_landed`, retried at every harvest and never written.
25
+
26
+ `--deadline S` stops starting new work after S seconds and records what it has; the run's
27
+ automatic harvest (end of `run` and `integrate`, FORGE_OUTCOMES=off to skip) uses it. Every
28
+ harvest that writes leaves `outcomes.last` in the dataset dir for `forge dataset status`.
29
+
17
30
  Read-only by construction: the store is opened read-only (connect() would migrate it),
18
31
  and git runs only object-store queries (rev-parse, rev-list, log, diff between commits,
19
32
  blame at a commit, cat-file) with GIT_OPTIONAL_LOCKS=0, so nothing touches a working
@@ -37,6 +50,7 @@ from . import dataset_dir, record, sha256
37
50
 
38
51
  HORIZON_DAYS = 14
39
52
  GIT_TIMEOUT_S = 120
53
+ _FORGE_REF = re.compile(r'^refs/(?:heads|remotes/[^/]+)/forge/')
40
54
  _REVERTS = re.compile(r'This reverts commit ([0-9a-f]{7,40})')
41
55
  _HUNK = re.compile(rb'^([0-9a-f]{40}) \d+ \d+ (\d+)$')
42
56
 
@@ -104,7 +118,7 @@ def read_store():
104
118
  have = {rid for (rid,) in db.execute("SELECT rid FROM events WHERE kind = 'outcome'")}
105
119
  finally:
106
120
  db.close()
107
- integrations, merges, bases = [], {}, {}
121
+ integrations, merges, bases, landed_by_hand = [], {}, {}, defaultdict(list)
108
122
  for kind, run, task, repo, ts, data in rows:
109
123
  d = json.loads(data)
110
124
  if kind == 'attempt':
@@ -118,41 +132,89 @@ def read_store():
118
132
  if commit:
119
133
  # The last MERGED event for a commit wins; split/combine copies keep their run.
120
134
  merges[(repo, commit)] = dict(run=run, task=task, commit=commit, integration=d.get('integration'))
135
+ if d.get('integration'):
136
+ landed_by_hand[(repo, run)].append((ts, d['integration']))
137
+ integrated = {(i['repo'], i['run']) for i in integrations}
138
+ runs = [dict(repo=repo, run=run, commits=[c for _, c in sorted(found)]) for (repo, run), found in landed_by_hand.items()
139
+ if (repo, run) not in integrated]
121
140
  return dict(integrations=sorted(integrations, key=lambda i: i['ts']), merges=merges, bases=bases,
122
- repos=repos, have=have)
141
+ repos=repos, have=have, runs=sorted(runs, key=lambda r: (r['repo'] or '', r['run'] or '')))
123
142
 
124
143
 
125
144
  def outcome_rid(candidate: str, reviewed: str, horizon_days: int) -> str:
126
145
  return 'outcome:survival:' + sha256(('%s:%s:%d' % (candidate, reviewed, horizon_days)).encode())[:24]
127
146
 
128
147
 
148
+ def landing(git: Git, tip: str, candidate: str):
149
+ """The commit where `candidate` entered `tip`'s first-parent chain: `candidate` itself when it is on
150
+ that chain, else the oldest chain commit that contains it (the merge that brought it in); None when
151
+ `tip` does not contain it."""
152
+ if tip == candidate:
153
+ return candidate
154
+ if git.out('merge-base', '--is-ancestor', candidate, tip, ok=(0, 1))[0]:
155
+ return None
156
+ chain = [line.split() for line in git.text('log', '--first-parent', '--format=%H %P', '%s..%s' % (candidate, tip)
157
+ ).splitlines()] # newest first
158
+ if chain and chain[-1][1:2] == [candidate]:
159
+ return candidate
160
+ descendants = set(git.text('rev-list', '--ancestry-path', '%s..%s' % (candidate, tip)).split())
161
+ return next((row[0] for row in reversed(chain) if row[0] in descendants), None)
162
+
163
+
164
+ def walk(git: Git, tip: str, start: str, cutoff: float, now: float):
165
+ """('ok', rev, ts) | ('pending', None, None): the last commit of `tip`'s first-parent chain from `start`
166
+ on that was there at `cutoff`. By position along the chain, so out-of-order commit dates cannot jump
167
+ past a commit that came later; `start` itself when it came after the cutoff."""
168
+ chain = []
169
+ for line in git.text('log', '--first-parent', '--format=%H %ct', '%s..%s' % (start, tip)).splitlines():
170
+ sha, ct = line.split()[:2]
171
+ chain.append((sha, int(ct)))
172
+ rev, rev_ts = start, int(git.text('log', '-1', '--format=%ct', start).strip())
173
+ for sha, ct in reversed(chain):
174
+ if ct > cutoff:
175
+ return 'ok', rev, rev_ts
176
+ rev, rev_ts = sha, ct
177
+ if now < cutoff:
178
+ return 'pending', None, None # more commits may still land before the horizon
179
+ return 'ok', rev, rev_ts
180
+
181
+
129
182
  def horizon_rev(git: Git, branch: str, candidate: str, cutoff: float, now: float):
130
- """('ok', rev, ts) | ('lost', None, None) | ('pending', None, None).
183
+ """('ok', rev, ts) | ('lost', None, None) | ('pending', None, None) on the branch `integrate` advanced.
131
184
 
132
185
  The branch is resolved once to an immutable tip. The candidate must sit on its
133
- first-parent chain (a rebase, squash or reset loses it: unobservable, not failure).
134
- The horizon is found by position along that chain, so out-of-order commit dates
135
- cannot jump past a commit that came later.
186
+ first-parent chain; when it does not (the branch was deleted, rebased, squashed or reset),
187
+ harvest() looks for it elsewhere with follow().
136
188
  """
137
189
  if not branch or git.out('rev-parse', '--verify', '-q', branch + '^{commit}', ok=(0, 1))[0]:
138
190
  return 'lost', None, None
139
191
  tip = git.text('rev-parse', branch + '^{commit}').strip()
140
- chain = [] # first-parent commits after the candidate, newest first
141
- for line in git.text('log', '--first-parent', '--format=%H %ct %P', '%s..%s' % (candidate, tip)).splitlines():
142
- sha, ct, *parents = line.split()
143
- chain.append((sha, int(ct), parents))
144
- if tip != candidate and (not chain or chain[-1][2][:1] != [candidate]):
192
+ if landing(git, tip, candidate) != candidate:
145
193
  return 'lost', None, None # the walk never passed through the candidate
146
- chain = [(sha, ct) for sha, ct, _ in reversed(chain)]
147
- candidate_ct = int(git.text('log', '-1', '--format=%ct', candidate).strip())
148
- rev, rev_ts = candidate, candidate_ct
149
- for sha, ct in chain:
150
- if ct > cutoff:
151
- return 'ok', rev, rev_ts
152
- rev, rev_ts = sha, ct
153
- if now < cutoff:
154
- return 'pending', None, None # more commits may still land before the horizon
155
- return 'ok', rev, rev_ts
194
+ return walk(git, tip, candidate, cutoff, now)
195
+
196
+
197
+ def follow(git: Git, candidate: str):
198
+ """(branch, tip, landing, landing time) of the branch where `candidate` landed first, or None. Every
199
+ branch that contains it (local and remote, never forge's own) is a candidate; the earliest landing
200
+ wins, a local branch before a remote one at the same time, then by name."""
201
+ best = None
202
+ refs = git.text('for-each-ref', '--contains', candidate, '--format=%(refname)', 'refs/heads', 'refs/remotes').split()
203
+ for ref in refs:
204
+ if _FORGE_REF.match(ref) or ref.endswith('/HEAD'):
205
+ continue
206
+ tip = git.text('rev-parse', ref + '^{commit}').strip()
207
+ landed = landing(git, tip, candidate)
208
+ if landed is None:
209
+ continue
210
+ at = int(git.text('log', '-1', '--format=%ct', landed).strip())
211
+ key = (at, ref.startswith('refs/remotes/'), ref)
212
+ if best is None or key < best[0]:
213
+ best = (key, ref, tip, landed, at)
214
+ if best is None:
215
+ return None
216
+ _, ref, tip, landed, at = best
217
+ return ref.split('/', 2)[2], tip, landed, at
156
218
 
157
219
 
158
220
  def survival(git: Git, base: str, reviewed: str, rev: str) -> dict:
@@ -185,77 +247,151 @@ def reverts(git: Git, candidate: str, rev: str, shas: set) -> list:
185
247
 
186
248
 
187
249
  def harvest(*, horizon_days: int = HORIZON_DAYS, repo: str | None = None, include_temp: bool = False,
188
- now: float | None = None) -> tuple[list, Counter]:
250
+ now: float | None = None, deadline: float | None = None) -> tuple[list, Counter]:
251
+ """(events to record, counts). `deadline` (seconds) stops starting new integrations once passed; what
252
+ was left is counted as `deferred` and found again by the next harvest."""
189
253
  from .importer import is_temp
190
254
  state = read_store()
191
255
  counts = Counter()
192
256
  if state is None:
193
257
  return [], counts
194
258
  now = time.time() if now is None else now
259
+ stop = time.monotonic() + deadline if deadline is not None else None
195
260
  wanted = str(Path(repo).resolve()) if repo else None
196
261
  by_repo = defaultdict(list)
197
- for integration in state['integrations']:
198
- path = state['repos'].get(integration['repo'])
199
- if not path or (wanted and str(Path(path).resolve()) != wanted):
200
- continue
201
- if is_temp(path) and not include_temp:
202
- counts['skipped_temp'] += 1
203
- continue
204
- if not Path(path).is_dir():
205
- counts['repo_missing'] += 1
206
- continue
207
- by_repo[path].append(integration)
262
+ for kind, items in (('integrate', state['integrations']), ('merged', state['runs'])):
263
+ for item in items:
264
+ path = state['repos'].get(item['repo'])
265
+ if not path or (wanted and str(Path(path).resolve()) != wanted):
266
+ continue
267
+ if is_temp(path) and not include_temp:
268
+ counts['skipped_temp'] += 1
269
+ continue
270
+ if not Path(path).is_dir():
271
+ counts['repo_missing'] += 1
272
+ continue
273
+ by_repo[path].append((kind, item))
208
274
  out = []
209
- for path, integrations in by_repo.items():
275
+ for path, items in by_repo.items():
210
276
  git = Git(path)
211
- for integration in integrations:
212
- candidate, parent = integration['candidate'], integration['parent']
277
+ for kind, item in items:
278
+ if stop is not None and time.monotonic() > stop:
279
+ counts['deferred'] += 1
280
+ continue
213
281
  try:
214
- if not git.exists(candidate + '^{commit}'):
215
- counts['candidate_missing'] += 1
216
- continue
217
- landed = set(git.text('rev-list', candidate, '^' + parent).split())
218
- tasks = [m for (r, c), m in state['merges'].items() if r == integration['repo'] and c in landed]
219
- todo = [m for m in tasks if outcome_rid(candidate, m['commit'], horizon_days) not in state['have']]
220
- counts['already'] += len(tasks) - len(todo)
221
- if not todo:
222
- continue
223
- cutoff = integration['ts'] + horizon_days * 86400
224
- status, rev, rev_ts = horizon_rev(git, integration['branch'], candidate, cutoff, now)
282
+ found = _locate(git, kind, item, state, horizon_days, now, counts)
225
283
  except GitError:
226
284
  counts['git_error'] += 1
227
285
  continue
228
- if status == 'pending':
229
- counts['pending'] += len(todo)
286
+ if found is None:
230
287
  continue
288
+ candidate, todo, status, rev, rev_ts, where = found
231
289
  for merge in todo:
232
290
  base = state['bases'].get(merge['commit'])
233
291
  if not base:
234
292
  counts['no_base'] += 1
235
293
  continue
236
294
  data = dict(name='survival', candidate=candidate, reviewed=merge['commit'], base_ref=base,
237
- branch=integration['branch'], horizon_days=horizon_days, integrated_ts=integration['ts'],
238
- horizon_rev=rev, horizon_ts=rev_ts, integrate_run=integration['run'])
295
+ horizon_days=horizon_days, horizon_rev=rev, horizon_ts=rev_ts, **where)
239
296
  try:
240
297
  if status == 'ok':
241
- found = survival(git, base, merge['commit'], rev)
242
- task_shas = set(found.pop('commits')) | {s for s in (merge.get('integration'), candidate) if s}
243
- data.update(found, reverted_by=reverts(git, candidate, rev, task_shas),
244
- status='ok' if found['added'] else 'no_additions')
298
+ measured = survival(git, base, merge['commit'], rev)
299
+ task_shas = set(measured.pop('commits')) | {s for s in (merge.get('integration'), candidate) if s}
300
+ data.update(measured, reverted_by=reverts(git, where.get('landed') or candidate, rev, task_shas),
301
+ status='ok' if measured['added'] else 'no_additions')
245
302
  else:
246
303
  data.update(status='lost')
247
304
  except GitError:
248
305
  counts['git_error'] += 1
249
306
  continue
250
307
  counts[data['status']] += 1
308
+ if where.get('followed'):
309
+ counts['followed'] += 1
251
310
  out.append((path, dict(rid=outcome_rid(candidate, merge['commit'], horizon_days), kind='outcome',
252
311
  src='harvest', ts=now, run=merge['run'], task=merge['task'],
253
312
  mode='parallel', data=data)))
254
313
  return out, counts
255
314
 
256
315
 
316
+ def _locate(git, kind, item, state, horizon_days, now, counts):
317
+ """(candidate, merges to record, status, horizon rev, its time, how it was found) for one integration,
318
+ or None when there is nothing to record now (counted)."""
319
+ if kind == 'integrate':
320
+ candidate, parent, run = item['candidate'], item['parent'], item['run']
321
+ else:
322
+ commits = [c for c in item['commits'] if git.exists(c + '^{commit}')]
323
+ if not commits:
324
+ counts['integration_gone'] += 1
325
+ return None
326
+ candidate, run = commits[-1], item['run']
327
+ parent = git.text('rev-parse', commits[0] + '^1').strip() if git.exists(commits[0] + '^1') else None
328
+ if not git.exists(candidate + '^{commit}'):
329
+ counts['candidate_missing'] += 1
330
+ return None
331
+ landed = set(git.text('rev-list', candidate, *(['^' + parent] if parent else [])).split())
332
+ tasks = [m for (r, c), m in state['merges'].items() if r == item['repo'] and c in landed
333
+ and (kind == 'integrate' or m['run'] == run)]
334
+ todo = [m for m in tasks if outcome_rid(candidate, m['commit'], horizon_days) not in state['have']]
335
+ counts['already'] += len(tasks) - len(todo)
336
+ if not todo:
337
+ return None
338
+ if kind == 'integrate':
339
+ cutoff = item['ts'] + horizon_days * 86400
340
+ where = dict(branch=item['branch'], integrated_ts=item['ts'], integrate_run=run)
341
+ status, rev, rev_ts = horizon_rev(git, item['branch'], candidate, cutoff, now)
342
+ if status == 'lost':
343
+ seen = follow(git, candidate)
344
+ if seen is not None:
345
+ branch, tip, landing_commit, _at = seen
346
+ status, rev, rev_ts = walk(git, tip, landing_commit, cutoff, now)
347
+ where.update(followed=branch, landed=landing_commit)
348
+ else:
349
+ gone = not item['branch'] or git.out('rev-parse', '--verify', '-q', item['branch'] + '^{commit}',
350
+ ok=(0, 1))[0] != 0
351
+ where.update(lost_cause='branch_gone' if gone else 'off_branch')
352
+ else:
353
+ seen = follow(git, candidate)
354
+ if seen is None:
355
+ counts['not_landed'] += len(todo) # not merged yet, or squashed: nothing to follow
356
+ return None
357
+ branch, tip, landing_commit, at = seen
358
+ cutoff = at + horizon_days * 86400
359
+ status, rev, rev_ts = walk(git, tip, landing_commit, cutoff, now)
360
+ where = dict(branch=None, integrated_ts=at, integrate_run=None, followed=branch, landed=landing_commit,
361
+ merged_by_hand=True)
362
+ if status == 'pending':
363
+ counts['pending'] += len(todo)
364
+ return None
365
+ return candidate, todo, status, rev, rev_ts, where
366
+
367
+
368
+ LAST = 'outcomes.last'
369
+
370
+
371
+ def last_harvest():
372
+ """What the last harvest that wrote did ({at, repo, recorded, counts}), or None."""
373
+ try:
374
+ data = json.loads((dataset_dir() / LAST).read_text())
375
+ except (OSError, ValueError):
376
+ return None
377
+ return data if isinstance(data, dict) else None
378
+
379
+
257
380
  def main(args) -> int:
258
- events, counts = harvest(horizon_days=args.horizon_days, repo=args.repo, include_temp=args.include_temp)
381
+ if getattr(args, 'quiet', False):
382
+ # the automatic harvest at the end of a run: whatever goes wrong is logged, never raised
383
+ try:
384
+ return _main(args)
385
+ except Exception as error: # noqa: BLE001 - a harvest must never fail the run that called it
386
+ from . import log_error
387
+ log_error('outcomes', error)
388
+ return 0
389
+ return _main(args)
390
+
391
+
392
+ def _main(args) -> int:
393
+ events, counts = harvest(horizon_days=args.horizon_days, repo=args.repo, include_temp=args.include_temp,
394
+ deadline=getattr(args, 'deadline', None))
259
395
  written = 0
260
396
  if not args.dry_run:
261
397
  by_repo = defaultdict(list)
@@ -263,11 +399,23 @@ def main(args) -> int:
263
399
  by_repo[path].append(event)
264
400
  for path, batch in by_repo.items():
265
401
  written += record(batch, repo=path, where='outcomes')
402
+ stamp = dict(at=time.time(), repo=str(Path(args.repo).resolve()) if args.repo else None, recorded=written,
403
+ counts=dict(counts))
404
+ try:
405
+ target = dataset_dir() / LAST
406
+ target.parent.mkdir(parents=True, exist_ok=True)
407
+ tmp = target.with_suffix('.tmp')
408
+ tmp.write_text(json.dumps(stamp, sort_keys=True) + '\n')
409
+ os.replace(tmp, target)
410
+ except OSError:
411
+ pass
412
+ if getattr(args, 'quiet', False):
413
+ return 0
266
414
  label = 'would record' if args.dry_run else 'recorded'
267
415
  print('%s %d survival outcome(s) at %d days' % (label, len(events) if args.dry_run else written,
268
416
  args.horizon_days))
269
- for key in ('ok', 'no_additions', 'lost', 'pending', 'already', 'no_base', 'candidate_missing',
270
- 'repo_missing', 'skipped_temp', 'git_error'):
417
+ for key in ('ok', 'no_additions', 'lost', 'followed', 'pending', 'not_landed', 'already', 'no_base',
418
+ 'candidate_missing', 'integration_gone', 'repo_missing', 'skipped_temp', 'deferred', 'git_error'):
271
419
  if counts.get(key):
272
420
  print(' %-17s %d' % (key, counts[key]))
273
421
  if not args.dry_run and written < len(events):