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