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