@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.
- package/CHANGELOG.md +32 -0
- package/README.md +7 -0
- package/SKILL.md +3 -0
- package/VERSION +1 -1
- package/docs/README.md +1 -0
- package/docs/commands.md +137 -5
- package/docs/development.md +1 -1
- package/docs/forge-ui.md +70 -19
- package/forge +8 -2
- package/package.json +1 -1
- package/references/decompose.md +20 -8
- package/references/memory.md +30 -5
- package/scripts/forge-config.py +10 -9
- package/scripts/forge-control.py +51 -35
- package/scripts/forge-findings.py +675 -0
- package/scripts/forge-group.py +2 -1
- package/scripts/forge-guard.py +71 -33
- package/scripts/forge-handoff.py +14 -17
- package/scripts/forge-issues.py +233 -99
- package/scripts/forge-memory.sh +471 -19
- package/scripts/forge-parallel.sh +24 -14
- package/scripts/forge-planner.py +28 -2
- package/scripts/forge-pre-review.py +11 -4
- package/scripts/forge-ripwire.py +68 -22
- package/scripts/forge-route.py +10 -3
- package/scripts/forge-runs-compact.py +3 -2
- package/scripts/forge-runs-rm.py +14 -14
- package/scripts/forge-runtime.py +36 -19
- package/scripts/forge-schedule.py +135 -62
- package/scripts/forge-shadow.py +16 -9
- package/scripts/forge-summarize.py +7 -3
- package/scripts/forge-sweep.py +206 -46
- package/scripts/forge-ui.py +8 -13
- package/scripts/forge-verify.py +29 -23
- package/scripts/forge_brief/__init__.py +1 -1
- package/scripts/forge_brief/proposals.py +7 -2
- package/scripts/forge_decide/budget.py +6 -1
- package/scripts/forge_decide/replay.py +6 -1
- package/scripts/forge_findings/__init__.py +17 -0
- package/scripts/forge_findings/apply.py +442 -0
- package/scripts/forge_findings/status.py +43 -0
- package/scripts/forge_findings/store.py +595 -0
- package/scripts/forge_findings/tags.py +53 -0
- package/scripts/forge_findings/triage.py +594 -0
- package/scripts/forge_flock.py +87 -0
- package/scripts/forge_fractal/__init__.py +7 -3
- package/scripts/forge_fractal/cli.py +7 -2
- package/scripts/forge_fractal/execution.py +14 -14
- package/scripts/forge_fractal/invocation.py +3 -2
- package/scripts/forge_fractal/pipeline.py +2 -1
- package/scripts/forge_fractal/selection.py +2 -1
- package/scripts/forge_identity.py +328 -0
- package/scripts/forge_locations.py +14 -4
- package/scripts/forge_memory_list.py +7 -3
- package/scripts/forge_posix.py +108 -0
- package/scripts/forge_proc.py +399 -0
- package/scripts/forge_registry.py +15 -6
- package/scripts/forge_retro/__init__.py +8 -2
- package/scripts/forge_retro/issues.py +2 -1
- package/scripts/forge_side/__init__.py +232 -38
- package/scripts/forge_storage.py +11 -1
- package/ui/docs/api.md +130 -12
- package/ui/forge_ui/control.py +693 -17
- package/ui/forge_ui/export.py +1 -1
- package/ui/forge_ui/projects.py +209 -22
- package/ui/forge_ui/reader.py +18 -17
- package/ui/forge_ui/server.py +10 -1
- package/ui/forge_ui/static/findingsactions.js +201 -0
- package/ui/forge_ui/static/index.html +2 -0
- package/ui/forge_ui/static/projectsview.js +600 -45
- package/ui/forge_ui/static/style.css +59 -0
- package/ui/forge_ui/static/triageview.js +423 -0
|
@@ -0,0 +1,595 @@
|
|
|
1
|
+
"""The finding record store: one JSON file per repository, keyed by repository identity.
|
|
2
|
+
|
|
3
|
+
`${XDG_STATE_HOME:-~/.local/state}/forge/findings/<identity key>.record.json` holds, per finding
|
|
4
|
+
fingerprint, the status the user or a forge command gave it, its tags, note, edit and issue draft. The
|
|
5
|
+
old per-checkout dismissals (`<checkout key>.json`, written by `forge issues`) are merged in on read as
|
|
6
|
+
`dismissed` and never touched. Every change is appended to `<key>.record.log.jsonl` and recorded as one
|
|
7
|
+
`finding_record` dataset point event (fail-open).
|
|
8
|
+
|
|
9
|
+
The store follows `forge issues`' rules without importing it: a real directory and regular files (no
|
|
10
|
+
symlinks), writes by temp file + fsync + rename, an empty or relative XDG_STATE_HOME counts as unset,
|
|
11
|
+
and `<key>.lock` (flock, O_NOFOLLOW, 10 s wait) is the same lock `forge issues --apply` takes.
|
|
12
|
+
|
|
13
|
+
Errors: `Invalid` (the input is refused, nothing was written), `Busy` (the lock was not free in time),
|
|
14
|
+
`Corrupt` (the store cannot be used: unreadable record, symlink, no home directory, no write access).
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import contextlib
|
|
19
|
+
import errno
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import re
|
|
23
|
+
import stat
|
|
24
|
+
import sys
|
|
25
|
+
import tempfile
|
|
26
|
+
import time
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
|
|
29
|
+
_SCRIPTS = str(Path(__file__).resolve().parents[1])
|
|
30
|
+
if _SCRIPTS not in sys.path:
|
|
31
|
+
sys.path.insert(0, _SCRIPTS)
|
|
32
|
+
import forge_flock as fcntl # noqa: E402
|
|
33
|
+
import forge_identity # noqa: E402
|
|
34
|
+
import forge_posix # noqa: E402
|
|
35
|
+
import forge_registry # noqa: E402
|
|
36
|
+
|
|
37
|
+
STATUSES = ("open", "to-file", "filed", "fixed", "dismissed", "duplicate")
|
|
38
|
+
ACTORS = ("cli", "ui", "triage", "sweep", "issues")
|
|
39
|
+
SEVERITIES = ("P0", "P1", "P2", "P3")
|
|
40
|
+
|
|
41
|
+
FP_RE = re.compile(r"[0-9a-f]{12}")
|
|
42
|
+
TAG_RE = re.compile(r"[a-z][a-z0-9-]{0,23}")
|
|
43
|
+
COMMIT_RE = re.compile(r"[0-9a-f]{7,40}")
|
|
44
|
+
_KEY_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*")
|
|
45
|
+
|
|
46
|
+
MAX_TAGS = 8
|
|
47
|
+
MAX_NOTE = 2000
|
|
48
|
+
MAX_EDIT_TEXT = 4000
|
|
49
|
+
MAX_TITLE = 200
|
|
50
|
+
MAX_BODY = 20000
|
|
51
|
+
MAX_REASON = 500
|
|
52
|
+
MAX_ISSUE = 500
|
|
53
|
+
LOCK_WAIT = 10.0 # seconds a busy lock is retried before Busy
|
|
54
|
+
LOCK_POLL = 0.1
|
|
55
|
+
FILE_MAX = 16 << 20 # a record or an old dismissal store is a few hundred bytes per finding
|
|
56
|
+
|
|
57
|
+
CHANGE_KEYS = ("status", "reason", "commit", "issue", "duplicate_of", "note", "edit", "draft",
|
|
58
|
+
"add_tags", "remove_tags")
|
|
59
|
+
_STATUS_FIELDS = ("reason", "commit", "issue", "duplicate_of")
|
|
60
|
+
_LOG_OPS = (("status", "status"), ("reason", "status"), ("commit", "status"), ("issue", "status"),
|
|
61
|
+
("duplicate_of", "status"), ("tags", "tags"), ("note", "note"), ("edit", "edit"),
|
|
62
|
+
("draft", "draft"))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class Busy(Exception):
|
|
66
|
+
"""Another process holds the repository lock past the wait."""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Invalid(ValueError):
|
|
70
|
+
"""The input is refused. Nothing was written."""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class Corrupt(Exception):
|
|
74
|
+
"""The store cannot be used: an unreadable or malformed record, a symlink, or no usable location."""
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# ------------------------------------------------------------------------------------------ location
|
|
78
|
+
|
|
79
|
+
def findings_dir() -> Path:
|
|
80
|
+
"""`${XDG_STATE_HOME:-~/.local/state}/forge/findings`; an empty or relative XDG_STATE_HOME counts as unset."""
|
|
81
|
+
for candidate in (os.environ.get("XDG_STATE_HOME") or "", "~/.local/state"):
|
|
82
|
+
try:
|
|
83
|
+
base = Path(candidate).expanduser() if candidate else None
|
|
84
|
+
except RuntimeError: # no home directory to expand "~" against
|
|
85
|
+
base = None
|
|
86
|
+
if base is not None and base.is_absolute():
|
|
87
|
+
return base / "forge" / "findings"
|
|
88
|
+
raise Corrupt("cannot place the finding record: no home directory and no absolute XDG_STATE_HOME")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _store_dir(create: bool):
|
|
92
|
+
"""The findings directory after an lstat check that it is a real directory; None when absent."""
|
|
93
|
+
path = findings_dir()
|
|
94
|
+
if create:
|
|
95
|
+
try:
|
|
96
|
+
path.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
97
|
+
except OSError as exc:
|
|
98
|
+
raise Corrupt(f"{path}: cannot create the finding record directory: {exc.strerror or exc}")
|
|
99
|
+
try:
|
|
100
|
+
mode = os.lstat(path).st_mode
|
|
101
|
+
except FileNotFoundError:
|
|
102
|
+
if create:
|
|
103
|
+
raise Corrupt(f"{path}: the finding record directory vanished")
|
|
104
|
+
return None
|
|
105
|
+
except OSError as exc:
|
|
106
|
+
raise Corrupt(f"{path}: cannot use the finding record directory: {exc.strerror}")
|
|
107
|
+
if not stat.S_ISDIR(mode):
|
|
108
|
+
raise Corrupt(f"{path}: the finding record directory must be a real directory, not a symlink")
|
|
109
|
+
return path
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _key(ident) -> str:
|
|
113
|
+
key = ident.get("key") if isinstance(ident, dict) else None
|
|
114
|
+
if not isinstance(key, str) or not _KEY_RE.fullmatch(key):
|
|
115
|
+
raise Invalid("identity has no usable key")
|
|
116
|
+
return key
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def record_path(ident) -> Path:
|
|
120
|
+
"""Where the repository's record file is (it may not exist yet)."""
|
|
121
|
+
return findings_dir() / f"{_key(ident)}.record.json"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
# --------------------------------------------------------------------------------------------- lock
|
|
125
|
+
|
|
126
|
+
@contextlib.contextmanager
|
|
127
|
+
def lock(ident):
|
|
128
|
+
"""Hold `<key>.lock` (flock) for the repository; busy for LOCK_WAIT seconds raises `Busy`.
|
|
129
|
+
|
|
130
|
+
The lock is its own file, opened in place and never replaced, because the record is replaced on every save.
|
|
131
|
+
"""
|
|
132
|
+
key = _key(ident)
|
|
133
|
+
path = _store_dir(create=True) / f"{key}.lock"
|
|
134
|
+
try:
|
|
135
|
+
fd = forge_posix.open_nofollow(
|
|
136
|
+
path,
|
|
137
|
+
os.O_RDWR | os.O_CREAT | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK,
|
|
138
|
+
0o600,
|
|
139
|
+
)
|
|
140
|
+
except OSError as exc:
|
|
141
|
+
raise Corrupt(f"{path}: cannot open the repository lock ({exc.strerror}); it must not be a symlink")
|
|
142
|
+
try:
|
|
143
|
+
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
|
144
|
+
raise Corrupt(f"{path}: the repository lock must be a regular file")
|
|
145
|
+
deadline = time.monotonic() + LOCK_WAIT
|
|
146
|
+
while True:
|
|
147
|
+
try:
|
|
148
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
149
|
+
break
|
|
150
|
+
except OSError as exc:
|
|
151
|
+
if exc.errno not in (errno.EWOULDBLOCK, errno.EAGAIN, errno.EACCES):
|
|
152
|
+
raise Corrupt(f"{path}: cannot lock the repository: {exc.strerror}")
|
|
153
|
+
if time.monotonic() >= deadline:
|
|
154
|
+
raise Busy("busy: another change to this repository's findings is in progress")
|
|
155
|
+
time.sleep(LOCK_POLL)
|
|
156
|
+
yield
|
|
157
|
+
finally:
|
|
158
|
+
os.close(fd) # closing the descriptor releases the flock
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
# --------------------------------------------------------------------------------------- read, write
|
|
162
|
+
|
|
163
|
+
def _read_json(path: Path, noun: str):
|
|
164
|
+
"""The parsed JSON of a regular file, None when it does not exist. Raises Corrupt otherwise."""
|
|
165
|
+
not_regular = f"{path}: the {noun} must be a regular file, not a symlink or special file"
|
|
166
|
+
try:
|
|
167
|
+
if not stat.S_ISREG(os.lstat(path).st_mode):
|
|
168
|
+
raise Corrupt(not_regular)
|
|
169
|
+
# NOFOLLOW again for a swap after the lstat; NONBLOCK so a FIFO cannot hold the open
|
|
170
|
+
with os.fdopen(
|
|
171
|
+
forge_posix.open_nofollow(path, os.O_RDONLY | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK),
|
|
172
|
+
"rb",
|
|
173
|
+
) as fh:
|
|
174
|
+
if not stat.S_ISREG(os.fstat(fh.fileno()).st_mode):
|
|
175
|
+
raise Corrupt(not_regular)
|
|
176
|
+
raw = fh.read(FILE_MAX + 1)
|
|
177
|
+
except FileNotFoundError:
|
|
178
|
+
return None
|
|
179
|
+
except OSError as exc:
|
|
180
|
+
raise Corrupt(f"{path}: cannot read the {noun}: {exc.strerror}")
|
|
181
|
+
try:
|
|
182
|
+
if len(raw) > FILE_MAX:
|
|
183
|
+
raise ValueError("too large")
|
|
184
|
+
return json.loads(raw.decode("utf-8"))
|
|
185
|
+
except ValueError:
|
|
186
|
+
raise Corrupt(f"{path}: not a {noun} (invalid JSON); fix or remove it")
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _is_num(value) -> bool:
|
|
190
|
+
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _shape_problem(entry):
|
|
194
|
+
"""Why a stored entry is not well formed (types, vocabularies and limits), None when it is."""
|
|
195
|
+
if not isinstance(entry, dict):
|
|
196
|
+
return "not an object"
|
|
197
|
+
# no status = nothing recorded about its state (only tags, a note, an edit or a draft)
|
|
198
|
+
if "status" in entry and entry["status"] not in STATUSES:
|
|
199
|
+
return "unknown status"
|
|
200
|
+
if not _is_num(entry.get("at")):
|
|
201
|
+
return "no time"
|
|
202
|
+
if "actor" in entry and entry["actor"] not in ACTORS:
|
|
203
|
+
return "unknown actor"
|
|
204
|
+
for field, limit in (("reason", MAX_REASON), ("note", MAX_NOTE), ("issue", MAX_ISSUE)):
|
|
205
|
+
if field in entry and not (isinstance(entry[field], str) and len(entry[field]) <= limit):
|
|
206
|
+
return f"bad {field}"
|
|
207
|
+
if "commit" in entry and not (isinstance(entry["commit"], str) and COMMIT_RE.fullmatch(entry["commit"])):
|
|
208
|
+
return "bad commit"
|
|
209
|
+
if "duplicate_of" in entry and not (isinstance(entry["duplicate_of"], str)
|
|
210
|
+
and FP_RE.fullmatch(entry["duplicate_of"])):
|
|
211
|
+
return "bad duplicate_of"
|
|
212
|
+
if "tags" in entry:
|
|
213
|
+
tags = entry["tags"]
|
|
214
|
+
if not (isinstance(tags, list) and len(tags) <= MAX_TAGS
|
|
215
|
+
and all(isinstance(t, str) and TAG_RE.fullmatch(t) for t in tags)):
|
|
216
|
+
return "bad tags"
|
|
217
|
+
if "edit" in entry:
|
|
218
|
+
edit = entry["edit"]
|
|
219
|
+
if not (isinstance(edit, dict) and set(edit) <= {"severity", "text"}
|
|
220
|
+
and edit.get("severity", "P0") in SEVERITIES
|
|
221
|
+
and isinstance(edit.get("text", ""), str) and len(edit.get("text", "")) <= MAX_EDIT_TEXT):
|
|
222
|
+
return "bad edit"
|
|
223
|
+
if "draft" in entry:
|
|
224
|
+
draft = entry["draft"]
|
|
225
|
+
if not (isinstance(draft, dict) and set(draft) <= {"title", "body"}
|
|
226
|
+
and isinstance(draft.get("title", ""), str) and len(draft.get("title", "")) <= MAX_TITLE
|
|
227
|
+
and isinstance(draft.get("body", ""), str) and len(draft.get("body", "")) <= MAX_BODY):
|
|
228
|
+
return "bad draft"
|
|
229
|
+
return None
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _read_record(ident) -> dict:
|
|
233
|
+
"""The record file's own entries, `{}` when none yet. Corrupt when it is not a record."""
|
|
234
|
+
base = _store_dir(create=False)
|
|
235
|
+
if base is None:
|
|
236
|
+
return {}
|
|
237
|
+
path = base / f"{_key(ident)}.record.json"
|
|
238
|
+
data = _read_json(path, "finding record")
|
|
239
|
+
if data is None:
|
|
240
|
+
return {}
|
|
241
|
+
findings = data.get("findings") if isinstance(data, dict) else None
|
|
242
|
+
if not (isinstance(data, dict) and data.get("version") == 1 and isinstance(findings, dict)):
|
|
243
|
+
raise Corrupt(f"{path}: not a finding record ({{version: 1, findings: {{fingerprint: entry}}}}); fix or remove it")
|
|
244
|
+
for fp, entry in findings.items():
|
|
245
|
+
problem = _shape_problem(entry) if FP_RE.fullmatch(fp) else "not a fingerprint"
|
|
246
|
+
if problem:
|
|
247
|
+
raise Corrupt(f"{path}: finding {fp}: {problem}; fix or remove the file")
|
|
248
|
+
return findings
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _old_dismissals(ident) -> dict:
|
|
252
|
+
"""The dismissals `forge issues` kept per checkout, as record entries. Read only; unreadable files are skipped."""
|
|
253
|
+
base = _store_dir(create=False)
|
|
254
|
+
if base is None:
|
|
255
|
+
return {}
|
|
256
|
+
keys = []
|
|
257
|
+
candidates = []
|
|
258
|
+
with contextlib.suppress(Exception):
|
|
259
|
+
candidates.extend(forge_identity.checkouts(ident))
|
|
260
|
+
for checkout in candidates:
|
|
261
|
+
with contextlib.suppress(Exception):
|
|
262
|
+
keys.append(forge_registry.repo_key(checkout))
|
|
263
|
+
keys.append(_key(ident))
|
|
264
|
+
found: dict = {}
|
|
265
|
+
for key in dict.fromkeys(keys):
|
|
266
|
+
if not _KEY_RE.fullmatch(key):
|
|
267
|
+
continue
|
|
268
|
+
try:
|
|
269
|
+
data = _read_json(base / f"{key}.json", "dismissal store")
|
|
270
|
+
except Corrupt:
|
|
271
|
+
continue
|
|
272
|
+
if not isinstance(data, dict):
|
|
273
|
+
continue
|
|
274
|
+
for fp, value in data.items():
|
|
275
|
+
if not (isinstance(fp, str) and FP_RE.fullmatch(fp) and isinstance(value, dict)
|
|
276
|
+
and isinstance(value.get("reason"), str) and _is_num(value.get("at"))):
|
|
277
|
+
continue
|
|
278
|
+
entry = {"status": "dismissed", "at": value["at"], "actor": "issues", "reason": value["reason"][:MAX_REASON]}
|
|
279
|
+
if fp not in found or entry["at"] > found[fp]["at"]:
|
|
280
|
+
found[fp] = entry
|
|
281
|
+
return found
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _view(ident, own: dict) -> dict:
|
|
285
|
+
"""The record's entries with the old dismissals merged in for fingerprints the record does not have."""
|
|
286
|
+
merged = {fp: dict(entry) for fp, entry in _old_dismissals(ident).items() if fp not in own}
|
|
287
|
+
merged.update(own)
|
|
288
|
+
return merged
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _write_record(ident, own: dict) -> None:
|
|
292
|
+
"""Replace the record atomically: a temp file in the same directory, fsynced, then renamed over it."""
|
|
293
|
+
base = _store_dir(create=True)
|
|
294
|
+
name = f"{_key(ident)}.record.json"
|
|
295
|
+
path = base / name
|
|
296
|
+
try:
|
|
297
|
+
if not stat.S_ISREG(os.lstat(path).st_mode):
|
|
298
|
+
raise Corrupt(f"{path}: the finding record must be a regular file, not a symlink or special file")
|
|
299
|
+
except FileNotFoundError:
|
|
300
|
+
pass
|
|
301
|
+
except OSError as exc:
|
|
302
|
+
raise Corrupt(f"{path}: cannot write the finding record: {exc.strerror}")
|
|
303
|
+
try:
|
|
304
|
+
fd, tmp = tempfile.mkstemp(prefix=f".{name.removesuffix('.json')}.", suffix=".tmp", dir=base)
|
|
305
|
+
try:
|
|
306
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
307
|
+
json.dump({"version": 1, "findings": own}, fh, indent=2, sort_keys=True, ensure_ascii=False)
|
|
308
|
+
fh.write("\n")
|
|
309
|
+
fh.flush()
|
|
310
|
+
os.fsync(fh.fileno())
|
|
311
|
+
os.replace(tmp, path)
|
|
312
|
+
except BaseException:
|
|
313
|
+
with contextlib.suppress(OSError):
|
|
314
|
+
os.unlink(tmp)
|
|
315
|
+
raise
|
|
316
|
+
except OSError as exc:
|
|
317
|
+
raise Corrupt(f"{path}: cannot write the finding record: {exc.strerror}")
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _append_log(ident, lines: list) -> None:
|
|
321
|
+
"""Append the change lines to `<key>.record.log.jsonl`. The record is the truth; a log failure is not."""
|
|
322
|
+
try:
|
|
323
|
+
base = _store_dir(create=True)
|
|
324
|
+
path = base / f"{_key(ident)}.record.log.jsonl"
|
|
325
|
+
fd = forge_posix.open_nofollow(
|
|
326
|
+
path,
|
|
327
|
+
os.O_WRONLY | os.O_APPEND | os.O_CREAT | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK,
|
|
328
|
+
0o600,
|
|
329
|
+
)
|
|
330
|
+
try:
|
|
331
|
+
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
|
332
|
+
return
|
|
333
|
+
payload = "".join(json.dumps(line, sort_keys=True, ensure_ascii=False) + "\n" for line in lines)
|
|
334
|
+
os.write(fd, payload.encode("utf-8"))
|
|
335
|
+
finally:
|
|
336
|
+
os.close(fd)
|
|
337
|
+
except (OSError, Corrupt):
|
|
338
|
+
pass
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _emit(ident, lines: list) -> None:
|
|
342
|
+
"""One `finding_record` dataset point event per change. Fail-open, like every capture."""
|
|
343
|
+
try:
|
|
344
|
+
from forge_dataset.capture import point
|
|
345
|
+
for line in lines:
|
|
346
|
+
after = line["after"] or {}
|
|
347
|
+
point("finding_record", None, None,
|
|
348
|
+
{"fp": line["fp"], "op": line["op"], "status": after.get("status"), "actor": line["actor"]},
|
|
349
|
+
repo=ident.get("root"))
|
|
350
|
+
except Exception:
|
|
351
|
+
pass
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
# ------------------------------------------------------------------------------------------------ API
|
|
355
|
+
|
|
356
|
+
def load(ident) -> dict:
|
|
357
|
+
"""`{fp: entry}`: the record plus the old dismissals for fingerprints it does not have."""
|
|
358
|
+
_key(ident)
|
|
359
|
+
return _view(ident, _read_record(ident))
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def get(ident, fp):
|
|
363
|
+
"""One finding's entry, None when the store has nothing for it."""
|
|
364
|
+
return load(ident).get(fp)
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _text(value, name: str, limit: int, allow_empty: bool = True) -> str:
|
|
368
|
+
if not isinstance(value, str) or len(value) > limit or (not allow_empty and not value):
|
|
369
|
+
raise Invalid(f"{name} must be {'a non-empty ' if not allow_empty else ''}string of at most {limit} characters")
|
|
370
|
+
return value
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _check_changes(actor, changes: dict) -> None:
|
|
374
|
+
if actor not in ACTORS:
|
|
375
|
+
raise Invalid(f"actor must be one of {', '.join(ACTORS)}")
|
|
376
|
+
unknown = sorted(set(changes) - set(CHANGE_KEYS))
|
|
377
|
+
if unknown:
|
|
378
|
+
raise Invalid(f"unknown change: {', '.join(unknown)}")
|
|
379
|
+
if "status" in changes and changes["status"] not in STATUSES:
|
|
380
|
+
raise Invalid(f"status must be one of {', '.join(STATUSES)}")
|
|
381
|
+
if changes.get("reason") is not None:
|
|
382
|
+
_text(changes["reason"], "reason", MAX_REASON)
|
|
383
|
+
if changes.get("issue") is not None:
|
|
384
|
+
_text(changes["issue"], "issue", MAX_ISSUE, allow_empty=False)
|
|
385
|
+
if changes.get("commit") is not None and not (isinstance(changes["commit"], str)
|
|
386
|
+
and COMMIT_RE.fullmatch(changes["commit"])):
|
|
387
|
+
raise Invalid("commit must be 7 to 40 lowercase hex characters")
|
|
388
|
+
if changes.get("duplicate_of") is not None and not (isinstance(changes["duplicate_of"], str)
|
|
389
|
+
and FP_RE.fullmatch(changes["duplicate_of"])):
|
|
390
|
+
raise Invalid("duplicate_of must be a 12-character fingerprint")
|
|
391
|
+
if changes.get("note") is not None:
|
|
392
|
+
_text(changes["note"], "note", MAX_NOTE)
|
|
393
|
+
for name in ("add_tags", "remove_tags"):
|
|
394
|
+
tags = changes.get(name)
|
|
395
|
+
if tags is None:
|
|
396
|
+
continue
|
|
397
|
+
if not isinstance(tags, (list, tuple, set, frozenset)) or not all(isinstance(t, str) for t in tags):
|
|
398
|
+
raise Invalid(f"{name} must be a list of tags")
|
|
399
|
+
if name == "add_tags":
|
|
400
|
+
for tag in tags:
|
|
401
|
+
if not TAG_RE.fullmatch(tag):
|
|
402
|
+
raise Invalid(f"tag {tag!r}: lowercase letters, digits and dashes, starting with a letter, at most 24")
|
|
403
|
+
edit = changes.get("edit")
|
|
404
|
+
if edit:
|
|
405
|
+
if not isinstance(edit, dict) or not set(edit) <= {"severity", "text"}:
|
|
406
|
+
raise Invalid("edit must be {severity, text}")
|
|
407
|
+
if edit.get("severity") not in (None, "", *SEVERITIES):
|
|
408
|
+
raise Invalid("severity must be one of P0, P1, P2, P3")
|
|
409
|
+
if edit.get("text") is not None:
|
|
410
|
+
_text(edit["text"], "edit text", MAX_EDIT_TEXT)
|
|
411
|
+
draft = changes.get("draft")
|
|
412
|
+
if draft:
|
|
413
|
+
if not isinstance(draft, dict) or not set(draft) <= {"title", "body"}:
|
|
414
|
+
raise Invalid("draft must be {title, body}")
|
|
415
|
+
_text(draft.get("title", ""), "draft title", MAX_TITLE)
|
|
416
|
+
_text(draft.get("body", ""), "draft body", MAX_BODY)
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _apply(fp: str, before, actor: str, now: float, changes: dict) -> dict:
|
|
420
|
+
"""The entry `before` becomes under `changes`. Raises Invalid; touches nothing."""
|
|
421
|
+
# A finding with no entry that only gets tags, a note, an edit or a draft records no status: a stored
|
|
422
|
+
# `open` means "reopened" to status.effective, which would hide what forge issues knows (swept, filed).
|
|
423
|
+
entry = dict(before) if before else {}
|
|
424
|
+
if "status" in changes:
|
|
425
|
+
# a new status starts its own fields: the old issue or commit does not follow a reopen or a dismissal
|
|
426
|
+
for field in _STATUS_FIELDS:
|
|
427
|
+
entry.pop(field, None)
|
|
428
|
+
entry["status"] = changes["status"]
|
|
429
|
+
for field in _STATUS_FIELDS:
|
|
430
|
+
value = changes.get(field)
|
|
431
|
+
if value is not None:
|
|
432
|
+
entry[field] = value
|
|
433
|
+
if "note" in changes:
|
|
434
|
+
if changes["note"]:
|
|
435
|
+
entry["note"] = changes["note"]
|
|
436
|
+
else:
|
|
437
|
+
entry.pop("note", None)
|
|
438
|
+
for name in ("edit", "draft"):
|
|
439
|
+
if name in changes:
|
|
440
|
+
value = changes[name]
|
|
441
|
+
if not value:
|
|
442
|
+
entry.pop(name, None)
|
|
443
|
+
elif name == "edit":
|
|
444
|
+
edit = {k: v for k, v in value.items() if v}
|
|
445
|
+
if edit:
|
|
446
|
+
entry["edit"] = edit
|
|
447
|
+
else:
|
|
448
|
+
entry.pop("edit", None)
|
|
449
|
+
else:
|
|
450
|
+
entry["draft"] = {"title": value.get("title", ""), "body": value.get("body", "")}
|
|
451
|
+
if "add_tags" in changes or "remove_tags" in changes:
|
|
452
|
+
tags = list(entry.get("tags", []))
|
|
453
|
+
for tag in changes.get("add_tags") or ():
|
|
454
|
+
if tag not in tags:
|
|
455
|
+
tags.append(tag)
|
|
456
|
+
gone = set(changes.get("remove_tags") or ())
|
|
457
|
+
tags = [tag for tag in tags if tag not in gone]
|
|
458
|
+
if len(tags) > MAX_TAGS:
|
|
459
|
+
raise Invalid(f"{fp}: at most {MAX_TAGS} tags")
|
|
460
|
+
if tags:
|
|
461
|
+
entry["tags"] = tags
|
|
462
|
+
else:
|
|
463
|
+
entry.pop("tags", None)
|
|
464
|
+
if any(key in changes for key in ("status", *_STATUS_FIELDS)):
|
|
465
|
+
_require(fp, entry)
|
|
466
|
+
return entry
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def _require(fp: str, entry: dict) -> None:
|
|
470
|
+
status = entry.get("status")
|
|
471
|
+
if status is None:
|
|
472
|
+
raise Invalid(f"{fp}: a reason, commit, issue or duplicate needs a status")
|
|
473
|
+
if status == "filed" and not entry.get("issue"):
|
|
474
|
+
raise Invalid(f"{fp}: filed needs the issue URL")
|
|
475
|
+
if status == "fixed" and not (entry.get("commit") or entry.get("reason")):
|
|
476
|
+
raise Invalid(f"{fp}: fixed needs a commit and/or a reason")
|
|
477
|
+
if status == "dismissed" and not entry.get("reason"):
|
|
478
|
+
raise Invalid(f"{fp}: dismissed needs a reason")
|
|
479
|
+
if status == "duplicate":
|
|
480
|
+
if not entry.get("duplicate_of"):
|
|
481
|
+
raise Invalid(f"{fp}: duplicate needs duplicate_of")
|
|
482
|
+
if entry["duplicate_of"] == fp:
|
|
483
|
+
raise Invalid(f"{fp}: a finding cannot be a duplicate of itself")
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _op(before, after, changes) -> str:
|
|
487
|
+
"""What a change touched, for the log: status, tags, note, edit, draft, joined by "+"."""
|
|
488
|
+
before = before or {}
|
|
489
|
+
names = []
|
|
490
|
+
for field, op in _LOG_OPS:
|
|
491
|
+
old, new = before.get(field), after.get(field)
|
|
492
|
+
# a tag or a note on a finding the store has not seen creates it open: that is no status change
|
|
493
|
+
if op == "status" and "status" not in changes and field == "status":
|
|
494
|
+
continue
|
|
495
|
+
if old != new and op not in names:
|
|
496
|
+
names.append(op)
|
|
497
|
+
return "+".join(names) or "update"
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def _comparable(entry):
|
|
501
|
+
return None if entry is None else {k: v for k, v in entry.items() if k not in ("at", "actor")}
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
@contextlib.contextmanager
|
|
505
|
+
def _held(ident, locked: bool):
|
|
506
|
+
if locked:
|
|
507
|
+
yield
|
|
508
|
+
else:
|
|
509
|
+
with lock(ident):
|
|
510
|
+
yield
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def update(ident, fps, actor, locked=False, **changes):
|
|
514
|
+
"""Change every finding in `fps` the same way, in one lock and one write; a log line per changed finding.
|
|
515
|
+
|
|
516
|
+
`changes`: status, reason, commit, issue, duplicate_of, note ("" clears), edit ({severity, text}; None or
|
|
517
|
+
{} clears), draft ({title, body}; None clears), add_tags, remove_tags. Giving `status` starts the entry's
|
|
518
|
+
reason, commit, issue and duplicate_of afresh. An entry the change leaves as it was is not written or logged.
|
|
519
|
+
`locked=True` means the caller holds `lock(ident)`. Returns `[(fp, before, after)]` for the changed findings.
|
|
520
|
+
Raises Invalid before anything is written when any finding or change is refused.
|
|
521
|
+
"""
|
|
522
|
+
_key(ident)
|
|
523
|
+
if isinstance(fps, str):
|
|
524
|
+
raise Invalid("fps must be a list of fingerprints")
|
|
525
|
+
fps = list(dict.fromkeys(fps))
|
|
526
|
+
for fp in fps:
|
|
527
|
+
if not (isinstance(fp, str) and FP_RE.fullmatch(fp)):
|
|
528
|
+
raise Invalid(f"{fp!r} is not a 12-character fingerprint")
|
|
529
|
+
_check_changes(actor, changes)
|
|
530
|
+
with _held(ident, locked):
|
|
531
|
+
own = _read_record(ident)
|
|
532
|
+
view = _view(ident, own)
|
|
533
|
+
now = time.time()
|
|
534
|
+
results = []
|
|
535
|
+
pending = {}
|
|
536
|
+
for fp in fps:
|
|
537
|
+
before = view.get(fp)
|
|
538
|
+
after = _apply(fp, before, actor, now, changes)
|
|
539
|
+
if before is not None and _comparable(before) == _comparable(after):
|
|
540
|
+
continue
|
|
541
|
+
if before is None and "status" not in changes and not after:
|
|
542
|
+
# a change that adds nothing (clearing an absent note or tag) creates no entry at all
|
|
543
|
+
continue
|
|
544
|
+
after["at"] = now
|
|
545
|
+
after["actor"] = actor
|
|
546
|
+
pending[fp] = after
|
|
547
|
+
results.append((fp, before, after))
|
|
548
|
+
if not results:
|
|
549
|
+
return []
|
|
550
|
+
own.update(pending)
|
|
551
|
+
_write_record(ident, own)
|
|
552
|
+
lines = [{"at": now, "actor": actor, "fp": fp, "op": _op(before, after, changes), "before": before, "after": after}
|
|
553
|
+
for fp, before, after in results]
|
|
554
|
+
_append_log(ident, lines)
|
|
555
|
+
_emit(ident, lines)
|
|
556
|
+
return results
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
def set_status(ident, fps, status, actor, **fields):
|
|
560
|
+
"""`update` with a status and its fields (reason, commit, issue, duplicate_of)."""
|
|
561
|
+
return update(ident, fps, actor, status=status, **fields)
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def add_tags(ident, fps, tags, actor):
|
|
565
|
+
return update(ident, fps, actor, add_tags=list(tags))
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def remove_tags(ident, fps, tags, actor):
|
|
569
|
+
return update(ident, fps, actor, remove_tags=list(tags))
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
def set_note(ident, fp, text, actor):
|
|
573
|
+
"""Set the finding's note; empty text clears it."""
|
|
574
|
+
return update(ident, [fp], actor, note=text)
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
def set_edit(ident, fp, actor, severity=None, text=None):
|
|
578
|
+
"""Change the finding's edited severity and/or text; an empty string clears that field, None leaves it."""
|
|
579
|
+
if severity is None and text is None:
|
|
580
|
+
return []
|
|
581
|
+
if not (isinstance(fp, str) and FP_RE.fullmatch(fp)):
|
|
582
|
+
raise Invalid(f"{fp!r} is not a 12-character fingerprint")
|
|
583
|
+
_check_changes(actor, {"edit": {"severity": severity, "text": text}})
|
|
584
|
+
with lock(ident):
|
|
585
|
+
current = dict((get(ident, fp) or {}).get("edit") or {})
|
|
586
|
+
if severity is not None:
|
|
587
|
+
current["severity"] = severity
|
|
588
|
+
if text is not None:
|
|
589
|
+
current["text"] = text
|
|
590
|
+
return update(ident, [fp], actor, locked=True, edit=current)
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def mark_duplicate(ident, fp, of, actor):
|
|
594
|
+
"""Mark `fp` a duplicate of the finding `of` (never itself)."""
|
|
595
|
+
return update(ident, [fp], actor, status="duplicate", duplicate_of=of)
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Default tags of a finding, derived from its file path and never stored."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import fnmatch
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
_TESTS_DIR = re.compile(r"(^|/)tests?/")
|
|
8
|
+
_TEST_NAMES = ("test_*", "*_test.*", "*.test.*")
|
|
9
|
+
_DOCS_PREFIXES = ("docs/", "site/")
|
|
10
|
+
_INFRA_PREFIXES = (".github/", "ci/", "scripts/forge-install")
|
|
11
|
+
_INFRA_ROOT_NAMES = ("*.yml", "*.yaml")
|
|
12
|
+
_UI_PREFIXES = ("ui/", "web/", "frontend/", "static/")
|
|
13
|
+
_UI_NAMES = ("*.js", "*.ts", "*.tsx", "*.css", "*.html")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _any(name: str, patterns) -> bool:
|
|
17
|
+
return any(fnmatch.fnmatchcase(name, pattern) for pattern in patterns)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def default_tags(path) -> list[str]:
|
|
21
|
+
"""The tag a finding gets from its file: the first matching rule wins; no path gives `[]`.
|
|
22
|
+
|
|
23
|
+
tests (a tests/ directory, test_*, *_test.*, *.test.*), docs (docs/, site/, *.md),
|
|
24
|
+
infra (.github/, ci/, Dockerfile, root *.yml/*.yaml, install*, scripts/forge-install*),
|
|
25
|
+
ui (ui/, web/, frontend/, static/, *.js *.ts *.tsx *.css *.html), else backend.
|
|
26
|
+
"""
|
|
27
|
+
if not isinstance(path, str) or not path.strip():
|
|
28
|
+
return []
|
|
29
|
+
text = path.strip().replace("\\", "/")
|
|
30
|
+
while text.startswith("./"):
|
|
31
|
+
text = text[2:]
|
|
32
|
+
text = text.lstrip("/")
|
|
33
|
+
if not text:
|
|
34
|
+
return []
|
|
35
|
+
name = text.rsplit("/", 1)[-1]
|
|
36
|
+
if _TESTS_DIR.search(text) or _any(name, _TEST_NAMES):
|
|
37
|
+
return ["tests"]
|
|
38
|
+
if text.startswith(_DOCS_PREFIXES) or name.endswith(".md"):
|
|
39
|
+
return ["docs"]
|
|
40
|
+
if (text.startswith(_INFRA_PREFIXES) or name == "Dockerfile"
|
|
41
|
+
or ("/" not in text and _any(name, _INFRA_ROOT_NAMES)) or name.startswith("install")):
|
|
42
|
+
return ["infra"]
|
|
43
|
+
if text.startswith(_UI_PREFIXES) or _any(name, _UI_NAMES):
|
|
44
|
+
return ["ui"]
|
|
45
|
+
return ["backend"]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def tags_for(entry, path) -> list[str]:
|
|
49
|
+
"""The tags a record entry stores, else the defaults for the finding's file."""
|
|
50
|
+
stored = entry.get("tags") if isinstance(entry, dict) else None
|
|
51
|
+
if isinstance(stored, list) and stored:
|
|
52
|
+
return [tag for tag in stored if isinstance(tag, str)]
|
|
53
|
+
return default_tags(path)
|