@giamme/forge 0.19.0 → 0.20.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.
@@ -0,0 +1,603 @@
1
+ """Triage: a read-only agent reviews a repository's open findings and proposes what to do (#161).
2
+
3
+ `start` checks that a triage may run, allocates `<triage home>/<n>/`, and writes `findings.json`,
4
+ `prompt.txt` and `state.json` there. `run_job` dispatches the agent, parses and validates its
5
+ reply strictly, retries once with a reminder that quotes the error, and writes `proposals.json`,
6
+ then the final `state.json`. `detach` runs the job in a session of its own and writes its exit
7
+ code to `done` when it ends. Nothing here changes a finding, a repository file, a memory or an
8
+ issue: `apply` (a later step) is the only writer.
9
+
10
+ Files of one triage dir: findings.json, prompt.txt, state.json, proposals.json, triage.out,
11
+ done, and the dispatch's own side.last / side.resolved.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import fcntl
16
+ import hashlib
17
+ import importlib.util
18
+ import json
19
+ import os
20
+ import re
21
+ import subprocess
22
+ import sys
23
+ import time
24
+ from pathlib import Path
25
+
26
+ SCRIPTS = Path(__file__).resolve().parent.parent
27
+ if str(SCRIPTS) not in sys.path:
28
+ sys.path.insert(0, str(SCRIPTS))
29
+
30
+ import forge_side # noqa: E402
31
+
32
+ DISPATCH = SCRIPTS / "forge-dispatch.sh"
33
+ PLANNER = SCRIPTS / "forge-planner.py"
34
+
35
+ DEFAULT_TIMEOUT = 3600
36
+ DEFAULT_MAX_FINDINGS = 400
37
+ MAX_FINDINGS_LIMIT = 2000
38
+ MAX_PROPOSALS = 200
39
+ MAX_TAGS = 8
40
+ MAX_TITLE = 200
41
+ MAX_BODY = 20000
42
+ MAX_WHY = 2000
43
+ MAX_PLAN_TASKS = 20
44
+ DOCTOR_TIMEOUT = 120
45
+
46
+ NO_BLOCK = "no-proposals-block"
47
+ SEVERITIES = ("P0", "P1", "P2", "P3")
48
+ TAG_RE = re.compile(r"[a-z][a-z0-9-]{0,23}\Z")
49
+ COMMIT_RE = re.compile(r"[0-9a-f]{7,40}\Z")
50
+ OPEN_RE = re.compile(r"^```forge-triage[ \t]*$")
51
+ CLOSE_RE = re.compile(r"^```[ \t]*$")
52
+ # Statuses that still need work: what a triage reads.
53
+ TRIAGE_STATUSES = ("open", "to-file")
54
+
55
+ KEYS = {
56
+ "duplicate": ("kind", "fp", "of", "why"),
57
+ "fixed": ("kind", "fp", "evidence", "commit"),
58
+ "tag": ("kind", "fps", "tags"),
59
+ "issue": ("kind", "fps", "title", "body"),
60
+ "plan": ("kind", "fps", "title", "request", "plan"),
61
+ }
62
+ # Not part of what the agent wrote: set by this module (id, hash, state) or by apply (decided).
63
+ STORED_KEYS = ("id", "hash", "state", "decided")
64
+
65
+ REMINDER = (
66
+ "Your last reply was not usable: %s.\n"
67
+ "Reply again, ending with exactly one ```forge-triage block holding the JSON object "
68
+ '{"proposals": [...]}, in exactly the format above.\n'
69
+ 'If there is nothing to propose, end with a block holding {"proposals": []}.\n')
70
+
71
+ PROMPT = """\
72
+ You are triaging the open review findings of one repository. You are read-only: never edit,
73
+ create or delete a file, and never run a command that changes the repository or anything else.
74
+ You may read the repository at {checkout} and run read-only commands there (`git log`,
75
+ `git show`, `git grep`, `git blame`, `ls`, `cat`). Nothing you do is applied automatically: a
76
+ person reads every proposal first, so propose few things and only what you are confident of.
77
+
78
+ The findings are in {findings} ({count} of them). Read that file first. It is JSON:
79
+ {{"findings": [...]}}, most severe and newest first. Each finding has an `fp` (its identifier;
80
+ use exactly that text wherever a proposal names a finding), a `severity`, a `file` and `line`,
81
+ a `summary` or `text`, its `status`, its `tags`, and its `record` (what was already done with it).
82
+
83
+ Look for:
84
+ - duplicates: two findings that describe the same defect;
85
+ - findings that are already fixed in the repository now (check the code, and `git log` for the commit);
86
+ - tags that would help to sort the findings, e.g. ui, backend, tests, docs, infra, enhancement, security;
87
+ - findings, or groups of related findings, worth filing as one issue;
88
+ - groups of findings that one planned change would fix together.
89
+
90
+ End your reply with exactly one fenced block whose info string is `forge-triage`, holding
91
+ one JSON object, and nothing after it:
92
+
93
+ ```forge-triage
94
+ {{"proposals": [
95
+ {{"kind": "duplicate", "fp": "<fp>", "of": "<fp of the finding it repeats>", "why": "..."}},
96
+ {{"kind": "fixed", "fp": "<fp>", "evidence": "what shows it is fixed", "commit": "<sha or null>"}},
97
+ {{"kind": "tag", "fps": ["<fp>"], "tags": ["ui"]}},
98
+ {{"kind": "issue", "fps": ["<fp>"], "title": "...", "body": "..."}},
99
+ {{"kind": "plan", "fps": ["<fp>"], "title": "...", "request": "...", "plan": {{"tasks": [...]}}}}
100
+ ]}}
101
+ ```
102
+
103
+ Rules for the block:
104
+ - At most {max_proposals} proposals. Few, and high-confidence. An empty list is a fine answer.
105
+ - Every `fp` and `of` is an `fp` from {findings}. A finding is never a duplicate of itself.
106
+ - `tags`: at most {max_tags} per proposal, each matching ^[a-z][a-z0-9-]{{0,23}}$.
107
+ - `title` at most {max_title} characters, `body` at most {max_body}, `why` and `evidence` at most
108
+ {max_why}. None of them is empty.
109
+ - `commit` is the full or abbreviated hash (7 to 40 lowercase hex characters) of the commit that
110
+ fixed the finding, or null when you do not know it.
111
+ - A `plan` proposal's `plan` holds exactly what forge's planner accepts inside a `forge-plan`
112
+ block: {{"tasks": [...]}} with 1 to {max_tasks} tasks, each with `id` (lowercase letters, digits
113
+ and dashes), `deps` (ids of earlier tasks), `difficulty` (low, medium or high), optionally
114
+ `risk` (low, medium or high), `files`, `title`, `approach` and `prompt`. Every task `prompt` ends
115
+ with a `## Acceptance criteria` section. `request` is the change in plain words.
116
+ Example of a plan:
117
+
118
+ {example}
119
+ """
120
+
121
+
122
+ class Refused(Exception):
123
+ """The triage may not start (exit 3). Nothing was written, or nothing is left running."""
124
+
125
+
126
+ class Failed(Exception):
127
+ """The triage could not be started (exit 1)."""
128
+
129
+
130
+ class Invalid(Exception):
131
+ """A reply that breaks the contract. Carries the first reason."""
132
+
133
+
134
+ # --- small files --------------------------------------------------------------------------------
135
+
136
+ def now() -> str:
137
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
138
+
139
+
140
+ def write_atomic(path, text: str) -> None:
141
+ path = Path(path)
142
+ tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
143
+ tmp.write_text(text, encoding="utf-8")
144
+ os.replace(tmp, path)
145
+
146
+
147
+ def write_json(path, data) -> None:
148
+ write_atomic(path, json.dumps(data, indent=2, ensure_ascii=False) + "\n")
149
+
150
+
151
+ def read_json(path):
152
+ try:
153
+ return json.loads(Path(path).read_text(encoding="utf-8"))
154
+ except (OSError, ValueError):
155
+ return None
156
+
157
+
158
+ def alive(pid) -> bool:
159
+ if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
160
+ return False
161
+ try:
162
+ os.kill(pid, 0)
163
+ except ProcessLookupError:
164
+ return False
165
+ except PermissionError:
166
+ return True
167
+ except OSError:
168
+ return False
169
+ return True
170
+
171
+
172
+ class _Lock:
173
+ """An flock on one file of the triage dir, for the read-modify-write of state.json."""
174
+
175
+ def __init__(self, path):
176
+ self.path = Path(path)
177
+ self.handle = None
178
+
179
+ def __enter__(self):
180
+ self.handle = open(self.path, "a+")
181
+ fcntl.flock(self.handle, fcntl.LOCK_EX)
182
+ return self
183
+
184
+ def __exit__(self, *_exc):
185
+ try:
186
+ fcntl.flock(self.handle, fcntl.LOCK_UN)
187
+ finally:
188
+ self.handle.close()
189
+
190
+
191
+ # --- the hash ---------------------------------------------------------------------------------
192
+
193
+ def proposal_hash(proposal) -> str:
194
+ """The first 12 hex of the sha256 of the proposal's canonical JSON, without id, hash, state and decided."""
195
+ body = {key: value for key, value in proposal.items() if key not in STORED_KEYS}
196
+ text = json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
197
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()[:12]
198
+
199
+
200
+ # --- the triage dirs --------------------------------------------------------------------------
201
+
202
+ def numbered(key) -> list:
203
+ """`[(n, dir)]` of the triage dirs of one repository key, ascending."""
204
+ home = forge_side.triage_home(key)
205
+ found = []
206
+ try:
207
+ entries = list(home.iterdir())
208
+ except OSError:
209
+ return found
210
+ for entry in entries:
211
+ if entry.name.isdigit() and entry.is_dir() and not entry.is_symlink():
212
+ found.append((int(entry.name), entry))
213
+ return sorted(found)
214
+
215
+
216
+ def triage_dir(key, n=None):
217
+ """The dir of triage `n`, or of the newest one. None when there is none."""
218
+ found = numbered(key)
219
+ if n is None:
220
+ return found[-1] if found else None
221
+ for number, path in found:
222
+ if number == n:
223
+ return number, path
224
+ return None
225
+
226
+
227
+ def read_state(dest) -> dict | None:
228
+ """The state of one triage dir. `running` with no live process, or with `done` written, reads `failed: lost`."""
229
+ dest = Path(dest)
230
+ state = read_json(dest / "state.json")
231
+ if state is None:
232
+ return None
233
+ if not isinstance(state, dict):
234
+ return {"state": "failed", "reason": "lost"}
235
+ if state.get("state") == "running" and ((dest / "done").exists() or not alive(state.get("pid"))):
236
+ lost = dict(state)
237
+ lost["state"] = "failed"
238
+ lost["reason"] = "lost"
239
+ return lost
240
+ return state
241
+
242
+
243
+ # --- the findings and the prompt -------------------------------------------------------------------
244
+
245
+ def _rank(value) -> int:
246
+ return SEVERITIES.index(value) if value in SEVERITIES else len(SEVERITIES)
247
+
248
+
249
+ def _age(row) -> float:
250
+ plan_dir = row.get("plan_dir")
251
+ if isinstance(plan_dir, str) and plan_dir:
252
+ try:
253
+ return os.stat(plan_dir).st_mtime
254
+ except OSError:
255
+ return 0.0
256
+ return 0.0
257
+
258
+
259
+ def select_findings(rows, cap) -> list:
260
+ """The rows a triage reads: open or to-file, highest severity first, newest first, at most `cap`."""
261
+ keep = [row for row in rows
262
+ if isinstance(row, dict) and row.get("status") in TRIAGE_STATUSES and isinstance(row.get("fp"), str)
263
+ and row["fp"]]
264
+ keep.sort(key=lambda row: (_rank(row.get("severity")), -_age(row)))
265
+ return keep[:cap]
266
+
267
+
268
+ def build_prompt(findings_path, checkout, count) -> str:
269
+ planner = _planner()
270
+ return PROMPT.format(
271
+ checkout=checkout, findings=findings_path, count=count, max_proposals=MAX_PROPOSALS,
272
+ max_tags=MAX_TAGS, max_title=MAX_TITLE, max_body=MAX_BODY, max_why=MAX_WHY,
273
+ max_tasks=MAX_PLAN_TASKS, example=planner.EXAMPLE)
274
+
275
+
276
+ # --- the reply -------------------------------------------------------------------------------
277
+
278
+ _planner_module = None
279
+
280
+
281
+ def _planner():
282
+ """forge-planner.py, loaded by path: its file name is not importable."""
283
+ global _planner_module
284
+ if _planner_module is None:
285
+ spec = importlib.util.spec_from_file_location("forge_planner", PLANNER)
286
+ module = importlib.util.module_from_spec(spec)
287
+ spec.loader.exec_module(module)
288
+ _planner_module = module
289
+ return _planner_module
290
+
291
+
292
+ def _no_duplicate_keys(pairs):
293
+ keys = [key for key, _ in pairs]
294
+ for key in keys:
295
+ if keys.count(key) > 1:
296
+ raise Invalid(f"duplicate key {key!r} in the JSON")
297
+ return dict(pairs)
298
+
299
+
300
+ def extract_block(reply) -> str:
301
+ """The text of the one `forge-triage` block. Raises Invalid(NO_BLOCK) when there is none."""
302
+ if not isinstance(reply, str):
303
+ raise Invalid(NO_BLOCK)
304
+ # Split on \\n only: U+2028 is legal inside a JSON string. A trailing \\r is ignored.
305
+ lines = reply.split("\n")
306
+ openings = [i for i, line in enumerate(lines) if OPEN_RE.match(line.rstrip("\r"))]
307
+ if not openings:
308
+ raise Invalid(NO_BLOCK)
309
+ if len(openings) > 1:
310
+ raise Invalid(f"{len(openings)} forge-triage blocks in the reply; exactly one is allowed")
311
+ for j in range(openings[0] + 1, len(lines)):
312
+ if CLOSE_RE.match(lines[j].rstrip("\r")):
313
+ return "\n".join(lines[openings[0] + 1:j])
314
+ raise Invalid("the forge-triage block is never closed")
315
+
316
+
317
+ def _text(value, where, name, limit):
318
+ if not isinstance(value, str) or not value.strip():
319
+ raise Invalid(f"{where}: {name} must be a non-empty string")
320
+ if len(value) > limit:
321
+ raise Invalid(f"{where}: {name} is longer than {limit} characters")
322
+ try: # a lone surrogate (JSON "\\ud800") parses but cannot be stored as UTF-8
323
+ value.encode("utf-8")
324
+ except UnicodeError:
325
+ raise Invalid(f"{where}: {name} has characters that cannot be stored")
326
+ return value
327
+
328
+
329
+ def _fp(value, where, name, known):
330
+ if not isinstance(value, str) or value not in known:
331
+ shown = value if isinstance(value, str) and len(value) <= 80 else "(not a fingerprint)"
332
+ raise Invalid(f"{where}: {name} {shown!r} is not an fp of findings.json")
333
+ return value
334
+
335
+
336
+ def _fps(value, where, known):
337
+ if not isinstance(value, list) or not value:
338
+ raise Invalid(f"{where}: fps must be a non-empty list")
339
+ found = []
340
+ for item in value:
341
+ fp = _fp(item, where, "fps entry", known)
342
+ if fp not in found:
343
+ found.append(fp)
344
+ return found
345
+
346
+
347
+ def _tags(value, where):
348
+ if not isinstance(value, list) or not value:
349
+ raise Invalid(f"{where}: tags must be a non-empty list")
350
+ found = []
351
+ for item in value:
352
+ if not isinstance(item, str) or TAG_RE.match(item) is None:
353
+ raise Invalid(f"{where}: tag {item!r} must match ^[a-z][a-z0-9-]{{0,23}}$")
354
+ if item not in found:
355
+ found.append(item)
356
+ if len(found) > MAX_TAGS:
357
+ raise Invalid(f"{where}: at most {MAX_TAGS} tags")
358
+ return found
359
+
360
+
361
+ def _check_plan(plan, where):
362
+ """The plan must pass forge-planner's parse of a `forge-plan` block, with 1 to 20 tasks."""
363
+ if not isinstance(plan, dict):
364
+ raise Invalid(f"{where}: plan must be an object holding tasks")
365
+ module = _planner()
366
+ try:
367
+ body = json.dumps(plan, ensure_ascii=False)
368
+ tasks, _groups = module.parse_reply("```forge-plan\n" + body + "\n```")
369
+ except module.Refusal as error:
370
+ raise Invalid(f"{where}: plan refused by the planner: {error}")
371
+ except (ValueError, RecursionError, UnicodeError) as error:
372
+ raise Invalid(f"{where}: plan could not be read ({type(error).__name__})")
373
+ if not 1 <= len(tasks) <= MAX_PLAN_TASKS:
374
+ raise Invalid(f"{where}: plan must have 1 to {MAX_PLAN_TASKS} tasks")
375
+ return plan
376
+
377
+
378
+ def _check_proposal(item, index, known):
379
+ where = f"proposal {index}"
380
+ if not isinstance(item, dict):
381
+ raise Invalid(f"{where} is not an object")
382
+ kind = item.get("kind")
383
+ if not isinstance(kind, str) or kind not in KEYS:
384
+ raise Invalid(f"{where}: kind must be one of {', '.join(KEYS)}")
385
+ expected = KEYS[kind]
386
+ missing = [key for key in expected if key not in item]
387
+ extra = [key for key in item if key not in expected]
388
+ if missing or extra:
389
+ parts = []
390
+ if missing:
391
+ parts.append("missing " + ", ".join(missing))
392
+ if extra:
393
+ parts.append("unexpected " + ", ".join(str(key) for key in extra))
394
+ raise Invalid(f"{where} ({kind}) must have exactly the keys {', '.join(expected)} ({'; '.join(parts)})")
395
+ out = {"kind": kind}
396
+ if kind == "duplicate":
397
+ out["fp"] = _fp(item["fp"], where, "fp", known)
398
+ out["of"] = _fp(item["of"], where, "of", known)
399
+ if out["fp"] == out["of"]:
400
+ raise Invalid(f"{where}: a finding cannot be a duplicate of itself")
401
+ out["why"] = _text(item["why"], where, "why", MAX_WHY)
402
+ elif kind == "fixed":
403
+ out["fp"] = _fp(item["fp"], where, "fp", known)
404
+ out["evidence"] = _text(item["evidence"], where, "evidence", MAX_WHY)
405
+ commit = item["commit"]
406
+ out["commit"] = commit if isinstance(commit, str) and COMMIT_RE.match(commit) else None
407
+ elif kind == "tag":
408
+ out["fps"] = _fps(item["fps"], where, known)
409
+ out["tags"] = _tags(item["tags"], where)
410
+ elif kind == "issue":
411
+ out["fps"] = _fps(item["fps"], where, known)
412
+ out["title"] = _text(item["title"], where, "title", MAX_TITLE)
413
+ out["body"] = _text(item["body"], where, "body", MAX_BODY)
414
+ else:
415
+ out["fps"] = _fps(item["fps"], where, known)
416
+ out["title"] = _text(item["title"], where, "title", MAX_TITLE)
417
+ out["request"] = _text(item["request"], where, "request", MAX_BODY)
418
+ out["plan"] = _check_plan(item["plan"], where)
419
+ return out
420
+
421
+
422
+ def parse_proposals(reply, fps):
423
+ """`(proposals, None)` for a usable reply, else `(None, error)`; error is NO_BLOCK when there is no block.
424
+
425
+ `fps` is every fp findings.json holds. Each proposal comes back with only the keys of its kind
426
+ (a commit that is not 7 to 40 lowercase hex characters becomes None). Never raises.
427
+ """
428
+ known = set(fps)
429
+ try:
430
+ body = extract_block(reply)
431
+ try:
432
+ data = json.loads(body, object_pairs_hook=_no_duplicate_keys)
433
+ except (ValueError, RecursionError) as error:
434
+ raise Invalid(f"the forge-triage body is not valid JSON: {type(error).__name__}: {str(error)[:200]}")
435
+ if not isinstance(data, dict) or list(data) != ["proposals"] or not isinstance(data["proposals"], list):
436
+ raise Invalid('the forge-triage body must be exactly {"proposals": [...]}')
437
+ items = data["proposals"]
438
+ if len(items) > MAX_PROPOSALS:
439
+ raise Invalid(f"at most {MAX_PROPOSALS} proposals ({len(items)})")
440
+ return [_check_proposal(item, index, known) for index, item in enumerate(items, 1)], None
441
+ except Invalid as error:
442
+ return None, " ".join(str(error).split())
443
+ except Exception as error: # noqa: BLE001 -- a broken reply must not end the job
444
+ return None, f"reply could not be read ({type(error).__name__})"
445
+
446
+
447
+ def reason_of(error) -> str:
448
+ """The `reason` a failed state carries for a parse error."""
449
+ return NO_BLOCK if error == NO_BLOCK else f"invalid: {error}"
450
+
451
+
452
+ # --- start ----------------------------------------------------------------------------------------
453
+
454
+ def preflight(spec) -> None:
455
+ """`forge-dispatch.sh doctor --spec S --role side`. Raises Refused with its message."""
456
+ argv = ["/bin/bash", str(DISPATCH), "doctor", "--spec", str(spec), "--role", "side"]
457
+ try:
458
+ result = subprocess.run(argv, capture_output=True, text=True, stdin=subprocess.DEVNULL,
459
+ timeout=DOCTOR_TIMEOUT)
460
+ except (OSError, subprocess.SubprocessError) as error:
461
+ raise Refused(f"doctor could not run: {error}")
462
+ if result.returncode == 0:
463
+ return
464
+ lines = [line.strip() for line in (result.stderr + "\n" + result.stdout).splitlines() if line.strip()]
465
+ raise Refused(lines[-1] if lines else f"doctor refused {spec} (exit {result.returncode})")
466
+
467
+
468
+ def start(ident, rows, spec, checkout, max_findings=DEFAULT_MAX_FINDINGS, actor="cli"):
469
+ """Preflight, allocate and write the triage dir. Returns `(n, dest)`; the state is `running`.
470
+
471
+ Raises Refused (doctor, `triage_allowed`, a triage already running, the cap, no checkout).
472
+ """
473
+ if not isinstance(max_findings, int) or isinstance(max_findings, bool) \
474
+ or not 1 <= max_findings <= MAX_FINDINGS_LIMIT:
475
+ raise Refused(f"--max-findings must be 1 to {MAX_FINDINGS_LIMIT}")
476
+ if not isinstance(spec, str) or not spec.strip():
477
+ raise Refused("a triage needs a model: --spec")
478
+ if not isinstance(checkout, str) or not os.path.isdir(checkout):
479
+ raise Refused("this repository has no checkout on this machine to read")
480
+ preflight(spec)
481
+ ok, reason = forge_side.triage_allowed(checkout, spec)
482
+ if not ok:
483
+ raise Refused(f"triage not allowed: {reason}")
484
+ key = ident["key"]
485
+ home = forge_side.triage_home(key)
486
+ try:
487
+ home.mkdir(parents=True, exist_ok=True)
488
+ gate = _Lock(home / ".start.lock")
489
+ gate.__enter__()
490
+ except OSError as error:
491
+ raise Failed(f"cannot use {home}: {error.strerror or error}")
492
+ try:
493
+ newest = triage_dir(key)
494
+ if newest is not None:
495
+ state = read_state(newest[1])
496
+ if state is not None and state.get("state") == "running":
497
+ raise Refused(f"a triage is running: {newest[0]}")
498
+ try:
499
+ dest = forge_side.allocate_triage(key)
500
+ except forge_side.TriageCapped as error:
501
+ raise Refused(str(error))
502
+ except (OSError, ValueError) as error:
503
+ raise Failed(f"cannot allocate a triage dir: {error}")
504
+ n = int(dest.name)
505
+ chosen = select_findings(rows, max_findings)
506
+ findings_path = dest / "findings.json"
507
+ write_json(findings_path, {"triage": n, "findings": chosen})
508
+ write_atomic(dest / "prompt.txt", build_prompt(findings_path, checkout, len(chosen)))
509
+ write_json(dest / "state.json", {
510
+ "state": "running", "spec": spec, "started": now(), "pid": os.getpid(),
511
+ "findings": len(chosen), "actor": actor})
512
+ finally:
513
+ gate.__exit__(None, None, None)
514
+ return n, dest
515
+
516
+
517
+ def detach(dest, argv):
518
+ """Run `argv` (the hidden job) in a session of its own. Its output goes to triage.out and its exit
519
+ code, written atomically, to `done`. Records the job's pid in state.json while it is running."""
520
+ dest = Path(dest)
521
+ done = dest / "done"
522
+ wrapper = '"${@:2}"; rc=$?; printf "%s\\n" "$rc" > "$1.tmp" && mv -f "$1.tmp" "$1"; exit "$rc"'
523
+ with open(dest / "triage.out", "ab") as out:
524
+ process = subprocess.Popen(["/bin/bash", "-c", wrapper, "forge-triage", str(done), *argv],
525
+ stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT,
526
+ start_new_session=True, close_fds=True)
527
+ with _Lock(dest / "state.lock"):
528
+ state = read_json(dest / "state.json")
529
+ if isinstance(state, dict) and state.get("state") == "running":
530
+ state["pid"] = process.pid
531
+ write_json(dest / "state.json", state)
532
+ return process.pid
533
+
534
+
535
+ def write_done(dest, code) -> None:
536
+ write_atomic(Path(dest) / "done", f"{int(code)}\n")
537
+
538
+
539
+ # --- the job ------------------------------------------------------------------------------------
540
+
541
+ def _finish(dest, current, **fields):
542
+ """The final state.json, under the lock that detach() takes for the pid."""
543
+ with _Lock(Path(dest) / "state.lock"):
544
+ final = dict(current)
545
+ final.update(fields)
546
+ final["finished"] = now()
547
+ write_json(Path(dest) / "state.json", final)
548
+ return final
549
+
550
+
551
+ def run_job(dest, checkout, n, timeout=DEFAULT_TIMEOUT):
552
+ """The job: dispatch, validate, retry once, store. Returns the final state. Never raises.
553
+
554
+ A triage dir whose state is not `running` is left alone.
555
+ """
556
+ dest = Path(dest)
557
+ state = read_json(dest / "state.json")
558
+ if not isinstance(state, dict) or state.get("state") != "running":
559
+ return state if isinstance(state, dict) else {"state": "failed", "reason": "lost"}
560
+ try:
561
+ return _job(dest, state, checkout, n, timeout)
562
+ except Exception as error: # noqa: BLE001 -- the state must say it failed
563
+ try:
564
+ return _finish(dest, state, state="failed", reason=f"error: {type(error).__name__}")
565
+ except Exception: # noqa: BLE001
566
+ return {"state": "failed", "reason": "error"}
567
+
568
+
569
+ def _job(dest, state, checkout, n, timeout):
570
+ data = read_json(dest / "findings.json")
571
+ findings = data.get("findings") if isinstance(data, dict) else None
572
+ if not isinstance(findings, list):
573
+ return _finish(dest, state, state="failed", reason="error: findings.json")
574
+ fps = [row["fp"] for row in findings if isinstance(row, dict) and isinstance(row.get("fp"), str)]
575
+ prompt = (dest / "prompt.txt").read_text(encoding="utf-8")
576
+ spec = state.get("spec")
577
+ reminder = ""
578
+ proposals, error = None, NO_BLOCK
579
+ for attempt in (1, 2):
580
+ result = forge_side.run_triage(dest, checkout, prompt + reminder, spec, timeout=timeout)
581
+ if not result.get("ok"):
582
+ return _finish(dest, state, state="failed", reason=result.get("reason") or "error")
583
+ last = result.get("last")
584
+ if attempt == 1 and isinstance(last, str):
585
+ try:
586
+ write_atomic(dest / "reply.1.txt", last)
587
+ except (OSError, UnicodeError):
588
+ pass
589
+ proposals, error = parse_proposals(last, fps)
590
+ if proposals is not None:
591
+ break
592
+ reminder = "\n\n" + REMINDER % error
593
+ if proposals is None:
594
+ return _finish(dest, state, state="failed", reason=reason_of(error))
595
+ stored = []
596
+ for k, proposal in enumerate(proposals, 1):
597
+ entry = dict(proposal)
598
+ entry["id"] = f"p{k}"
599
+ entry["hash"] = proposal_hash(proposal)
600
+ entry["state"] = "pending"
601
+ stored.append(entry)
602
+ write_json(dest / "proposals.json", {"triage": n, "spec": spec, "at": now(), "proposals": stored})
603
+ return _finish(dest, state, state="done", proposals=len(stored))