-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathworkspace_store.py
More file actions
3130 lines (2868 loc) · 114 KB
/
Copy pathworkspace_store.py
File metadata and controls
3130 lines (2868 loc) · 114 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Local workspace persistence for SLR Assistant.
Phase 1 deliberately keeps this module small and standard-library only:
folder lifecycle, SQLite schema/migrations, reference-import metadata, PDF
metadata, and workspace audit events.
"""
from __future__ import annotations
import hashlib
import json
import re
import shutil
import sqlite3
import uuid
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path, PurePosixPath
from typing import Any, Iterable, Iterator
try:
from version import VERSION
except Exception: # pragma: no cover - defensive for standalone use
VERSION = "unknown"
SCHEMA_VERSION = 4
DATABASE_NAME = "workspace.sqlite3"
WORKSPACE_JSON = "workspace.json"
WORKSPACE_SUBDIRS = ("imports", "pdfs", "exports", "cache", "audit")
WORKSPACE_PDF_TOKEN = "workspace:pdfs"
AUTOMATION_RUN_STATUS_RUNNING = "running"
AUTOMATION_RUN_STATUS_INTERRUPTED = "interrupted"
# Default on-disk location for workspaces created through the guided flow.
# Researchers should not have to paste an absolute path to start a project.
DEFAULT_WORKSPACES_DIR_NAME = "SLR Assistant Workspaces"
REVIEW_TYPE_SYSTEMATIC = "systematic_review"
REVIEW_TYPE_SCOPING = "scoping_review"
REVIEW_TYPE_OTHER = "other"
REVIEW_TYPES = (REVIEW_TYPE_SYSTEMATIC, REVIEW_TYPE_SCOPING, REVIEW_TYPE_OTHER)
# Optional review metadata stored in workspace.json (not a database schema
# change). These describe the project for display only; they do not alter
# screening, deduplication, or export count definitions.
REVIEW_METADATA_KEYS = ("review_title", "review_type", "review_question", "reviewer_name")
DEDUP_STATUS_UNIQUE = "unique"
DEDUP_STATUS_DUPLICATE = "duplicate"
DEDUP_METHOD_DOI = "doi"
DEDUP_METHOD_FUZZY_TITLE = "fuzzy_title"
DEDUP_METHOD_OTHER = "other"
DEFAULT_REVIEWER_ID = "default-local-reviewer"
DEFAULT_EXCLUSION_REASONS = (
("wrong_population", "Wrong population", "Population does not match the review criteria."),
("wrong_intervention", "Wrong intervention or exposure", "Intervention or exposure is outside scope."),
("wrong_comparator", "Wrong comparator", "Comparator does not match the review criteria."),
("wrong_outcome", "Wrong outcome", "Outcomes do not match the review criteria."),
("wrong_study_design", "Wrong study design", "Study design or publication type is outside scope."),
("not_empirical", "Not empirical research", "Record is not an empirical research study."),
("outside_scope", "Outside date, language, or topic scope", "Record is outside declared review limits."),
("full_text_unavailable", "Full text unavailable", "Full text could not be obtained."),
("duplicate", "Duplicate record", "Record duplicates another imported record."),
)
SECRET_KEY_PARTS = (
"api_key",
"apikey",
"secret",
"token",
"password",
"credential",
"prompt",
"full_text",
"paper_text",
"document_text",
"extracted_text",
)
SAFE_HASH_KEY_SUFFIXES = ("_hash",)
SAFE_METADATA_KEYS = {"cache_key"}
REVIEW_STAGE_TITLE_ABSTRACT = "title_abstract"
REVIEW_STAGE_FULL_TEXT = "full_text"
REVIEW_STAGES = {REVIEW_STAGE_TITLE_ABSTRACT, REVIEW_STAGE_FULL_TEXT}
REVIEW_STATUS_PENDING = "pending"
REVIEW_STATUS_SUGGESTED = "suggested"
REVIEW_STATUS_INCLUDED = "included"
REVIEW_STATUS_EXCLUDED = "excluded"
REVIEW_STATUS_MAYBE = "maybe"
REVIEW_STATUS_FAILED = "failed"
REVIEW_STATUSES = {
REVIEW_STATUS_PENDING,
REVIEW_STATUS_SUGGESTED,
REVIEW_STATUS_INCLUDED,
REVIEW_STATUS_EXCLUDED,
REVIEW_STATUS_MAYBE,
REVIEW_STATUS_FAILED,
}
DECISION_INCLUDE = "include"
DECISION_EXCLUDE = "exclude"
DECISION_MAYBE = "maybe"
DECISION_FLAG = "flag"
DECISION_FAILED = "failed"
DECISIONS = {
DECISION_INCLUDE,
DECISION_EXCLUDE,
DECISION_MAYBE,
DECISION_FLAG,
DECISION_FAILED,
}
ACTOR_AI = "ai"
ACTOR_HUMAN = "human"
ACTOR_SYSTEM = "system"
ACTOR_TYPES = {ACTOR_AI, ACTOR_HUMAN, ACTOR_SYSTEM}
RECORD_ORIGIN_IMPORTED_REFERENCE = "imported_reference"
RECORD_ORIGIN_PDF_ONLY = "pdf_only"
RECORD_ORIGIN_MANUAL = "manual"
RECORD_ORIGINS = {
RECORD_ORIGIN_IMPORTED_REFERENCE,
RECORD_ORIGIN_PDF_ONLY,
RECORD_ORIGIN_MANUAL,
}
class WorkspaceError(ValueError):
"""Base class for workspace validation and persistence errors."""
class UnsafeWorkspacePath(WorkspaceError):
"""Raised when a workspace path is unsafe."""
class WorkspaceNotFound(WorkspaceError):
"""Raised when a path is not an existing workspace."""
@dataclass(frozen=True)
class WorkspaceHandle:
root: Path
workspace_id: str
name: str
schema_version: int
review_title: str = ""
review_type: str = ""
review_question: str = ""
reviewer_name: str = ""
@property
def db_path(self) -> Path:
return self.root / DATABASE_NAME
def public_summary(self) -> dict[str, Any]:
summary = get_workspace_summary(self.root)
summary.update({
"workspace_id": self.workspace_id,
"name": self.name,
"schema_version": self.schema_version,
"pdf_folder": WORKSPACE_PDF_TOKEN,
"review_title": self.review_title or summary.get("review_title", ""),
"review_type": self.review_type or summary.get("review_type", ""),
"review_question": self.review_question or summary.get("review_question", ""),
"reviewer_name": self.reviewer_name or summary.get("reviewer_name", ""),
})
return summary
def utc_now() -> str:
return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
def create_workspace(
root: str | Path | None = None,
name: str | None = None,
*,
review_title: str | None = None,
review_type: str | None = None,
review_question: str | None = None,
reviewer_name: str | None = None,
) -> WorkspaceHandle:
review_title_text = _bounded_text(review_title)
review_type_value = _normalize_review_type(review_type)
review_question_text = _bounded_text(review_question)
reviewer_name_text = _bounded_text(reviewer_name)
if not root or str(root).strip() == "":
root = default_workspace_path(review_title=review_title_text, name=name)
workspace_root = validate_workspace_root(root)
if workspace_root.exists():
_reject_unrelated_existing_contents(workspace_root)
workspace_root.mkdir(parents=True, exist_ok=True)
_ensure_subfolders(workspace_root)
metadata_path = workspace_root / WORKSPACE_JSON
if metadata_path.exists():
metadata = _load_workspace_json(workspace_root)
if name:
metadata["name"] = name
else:
now = utc_now()
metadata = {
"workspace_id": uuid.uuid4().hex,
"name": name or workspace_root.name,
"schema_version": SCHEMA_VERSION,
"app_version": VERSION,
"created_at": now,
"updated_at": now,
"database": DATABASE_NAME,
"folders": {folder: folder for folder in WORKSPACE_SUBDIRS},
}
if review_title_text:
metadata["review_title"] = review_title_text
if review_type_value:
metadata["review_type"] = review_type_value
if review_question_text:
metadata["review_question"] = review_question_text
if reviewer_name_text:
metadata["reviewer_name"] = reviewer_name_text
_write_workspace_json(workspace_root, metadata)
migrate(workspace_root)
return open_workspace(workspace_root)
def open_workspace(root: str | Path) -> WorkspaceHandle:
workspace_root = validate_workspace_root(root)
if not workspace_root.exists() or not workspace_root.is_dir():
raise WorkspaceNotFound("Workspace folder not found")
if not (workspace_root / WORKSPACE_JSON).is_file():
raise WorkspaceNotFound("workspace.json not found")
if not (workspace_root / DATABASE_NAME).is_file():
raise WorkspaceNotFound("workspace.sqlite3 not found")
migrate(workspace_root)
metadata = _load_workspace_json(workspace_root)
_ensure_subfolders(workspace_root)
workspace_id = str(metadata.get("workspace_id") or get_meta(workspace_root, "workspace_id") or "")
name = str(metadata.get("name") or get_meta(workspace_root, "name") or workspace_root.name)
schema_version = int(metadata.get("schema_version") or SCHEMA_VERSION)
review_title = str(metadata.get("review_title") or "")
review_type = _normalize_review_type(metadata.get("review_type"))
review_question = str(metadata.get("review_question") or "")
reviewer_name = str(metadata.get("reviewer_name") or "")
if not workspace_id:
raise WorkspaceError("Workspace metadata is missing workspace_id")
return WorkspaceHandle(
workspace_root,
workspace_id,
name,
schema_version,
review_title=review_title,
review_type=review_type,
review_question=review_question,
reviewer_name=reviewer_name,
)
def migrate(root: str | Path) -> None:
workspace_root = validate_workspace_root(root)
workspace_root.mkdir(parents=True, exist_ok=True)
_ensure_subfolders(workspace_root)
metadata = _load_workspace_json(workspace_root) if (workspace_root / WORKSPACE_JSON).exists() else {}
if not metadata:
now = utc_now()
metadata = {
"workspace_id": uuid.uuid4().hex,
"name": workspace_root.name,
"schema_version": SCHEMA_VERSION,
"app_version": VERSION,
"created_at": now,
"updated_at": now,
"database": DATABASE_NAME,
"folders": {folder: folder for folder in WORKSPACE_SUBDIRS},
}
_write_workspace_json(workspace_root, metadata)
with workspace_connection(workspace_root) as conn:
conn.execute("PRAGMA foreign_keys = ON")
for statement in _schema_statements():
conn.execute(statement)
_apply_record_origin_migration(conn)
_apply_dedup_migration(conn)
_apply_review_queue_migrations(conn)
_seed_workspace_meta(conn, metadata)
_seed_default_reviewer(conn)
_seed_default_exclusion_reasons(conn)
conn.execute(
"""
INSERT OR IGNORE INTO schema_migrations(version, name, applied_at)
VALUES (?, ?, ?)
""",
(1, "phase_1_workspace_schema", utc_now()),
)
conn.execute(
"""
INSERT OR IGNORE INTO schema_migrations(version, name, applied_at)
VALUES (?, ?, ?)
""",
(2, "phase_2_review_queue_schema", utc_now()),
)
conn.execute(
"""
INSERT OR IGNORE INTO schema_migrations(version, name, applied_at)
VALUES (?, ?, ?)
""",
(3, "phase_3_record_origin_schema", utc_now()),
)
conn.execute(
"""
INSERT OR IGNORE INTO schema_migrations(version, name, applied_at)
VALUES (?, ?, ?)
""",
(4, "phase_4_dedup_state_schema", utc_now()),
)
metadata["schema_version"] = SCHEMA_VERSION
metadata["updated_at"] = utc_now()
_write_workspace_json(workspace_root, metadata)
def connect(root: str | Path) -> sqlite3.Connection:
workspace_root = validate_workspace_root(root)
conn = sqlite3.connect(workspace_root / DATABASE_NAME)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
return conn
@contextmanager
def workspace_connection(root: str | Path) -> Iterator[sqlite3.Connection]:
conn = connect(root)
try:
with conn:
yield conn
finally:
conn.close()
def default_workspaces_root() -> Path:
"""Return the safe default directory used to store guided-flow workspaces."""
return Path.home() / DEFAULT_WORKSPACES_DIR_NAME
def default_workspace_path(*, review_title: str | None = None, name: str | None = None) -> Path:
"""Build a safe, non-colliding workspace folder under the default location.
The researcher supplies a review title and the app picks a folder name. They
never have to type an absolute path in the normal flow.
"""
raw = _bounded_text(review_title) or _bounded_text(name) or ""
if not raw:
raise WorkspaceError(
"A review title is required to create a workspace in the default location"
)
slug = _slugify(raw) or "workspace"
base = default_workspaces_root()
candidate = base / slug
counter = 2
while candidate.exists():
if not candidate.is_dir():
raise WorkspaceError(
"Default workspace location already contains a file with this name"
)
candidate = base / f"{slug}-{counter}"
counter += 1
if counter > 9999:
raise WorkspaceError("Could not find a free default workspace folder name")
return candidate
def _normalize_review_type(value: Any) -> str:
text = _bounded_text(value)
if not text:
return ""
lowered = text.lower()
if lowered in REVIEW_TYPES:
return lowered
return ""
def _slugify(value: str) -> str:
text = re.sub(r"[^A-Za-z0-9._ -]+", "_", value or "").strip()
text = re.sub(r"[ ]+", "-", text)
text = re.sub(r"[_]+", "_", text).strip("-_")
if not text:
return ""
return text[:80]
def validate_workspace_root(root: str | Path) -> Path:
if root is None or str(root).strip() == "":
raise UnsafeWorkspacePath("Workspace path is required")
workspace_root = Path(root).expanduser().resolve()
if workspace_root == workspace_root.parent:
raise UnsafeWorkspacePath("Filesystem root cannot be used as a workspace")
if workspace_root.anchor:
try:
if workspace_root == Path(workspace_root.anchor).resolve():
raise UnsafeWorkspacePath("Drive root cannot be used as a workspace")
except OSError:
raise UnsafeWorkspacePath("Drive root cannot be used as a workspace")
try:
if workspace_root == Path.home().resolve():
raise UnsafeWorkspacePath("Home directory cannot be used as a workspace")
except OSError:
pass
if workspace_root.exists() and not workspace_root.is_dir():
raise UnsafeWorkspacePath("Workspace path must be a folder")
return workspace_root
def resolve_workspace_relative_path(
root: str | Path,
relative_path: str,
*,
subdir: str | None = None,
must_exist: bool = False,
require_file: bool = False,
) -> Path:
workspace_root = validate_workspace_root(root)
clean_relative = _validate_relative_path(relative_path)
target = (workspace_root / clean_relative).resolve()
base = (workspace_root / subdir).resolve() if subdir else workspace_root.resolve()
try:
target.relative_to(base)
except ValueError as exc:
raise UnsafeWorkspacePath("Path is outside the workspace") from exc
if must_exist and not target.exists():
raise FileNotFoundError("Workspace path not found")
if require_file and target.exists() and not target.is_file():
raise UnsafeWorkspacePath("Workspace path is not a file")
return target
def persist_reference_import(
root: str | Path,
source_path: str | Path,
records: list[dict[str, Any]],
*,
original_filename: str | None = None,
) -> dict[str, Any]:
workspace_root = validate_workspace_root(root)
source = Path(source_path).resolve()
if not source.is_file():
raise FileNotFoundError("Import file not found")
copied = copy_file_into_workspace(
workspace_root,
source,
"imports",
original_filename=original_filename,
)
source_id = uuid.uuid4().hex
imported_at = utc_now()
try:
with workspace_connection(workspace_root) as conn:
conn.execute(
"""
INSERT INTO sources(
source_id, source_type, original_filename, stored_filename,
relative_path, file_size, sha256, record_count, imported_at,
metadata_json
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
source_id,
"reference_import",
copied["original_filename"],
copied["stored_filename"],
copied["relative_path"],
copied["size"],
copied["sha256"],
len(records),
imported_at,
"{}",
),
)
for index, record in enumerate(records):
record_id = _record_id(record)
conn.execute(
"""
INSERT OR IGNORE INTO records(
record_id, title, abstract, authors, year, journal, doi,
keywords, source_file, record_origin, created_at, updated_at, metadata_json
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
record_id,
_text(record.get("title")),
_text(record.get("abstract")),
_text(record.get("authors")),
_text(record.get("year")),
_text(record.get("journal")),
_text(record.get("doi")),
_text(record.get("keywords")),
copied["original_filename"],
RECORD_ORIGIN_IMPORTED_REFERENCE,
imported_at,
imported_at,
"{}",
),
)
conn.execute(
"""
INSERT OR IGNORE INTO record_sources(
record_id, source_id, source_record_index,
source_record_id, created_at, raw_json
)
VALUES (?, ?, ?, ?, ?, ?)
""",
(
record_id,
source_id,
index,
_text(record.get("record_id")),
imported_at,
json_dumps(_sanitize_metadata(record)),
),
)
_create_review_item_row(
conn,
record_id=record_id,
stage=REVIEW_STAGE_TITLE_ABSTRACT,
pdf_id=None,
created_at=imported_at,
)
_insert_audit_event(
conn,
event_type="reference_imported",
entity_type="source",
entity_id=source_id,
summary=f"Imported {len(records)} reference records",
metadata={"record_count": len(records), "source_sha256": copied["sha256"]},
)
except Exception:
copied_path = resolve_workspace_relative_path(workspace_root, copied["relative_path"])
copied_path.unlink(missing_ok=True)
raise
return {
"source_id": source_id,
"record_count": len(records),
"relative_path": copied["relative_path"],
"original_filename": copied["original_filename"],
"sha256": copied["sha256"],
}
def apply_reference_deduplication(root: str | Path, *, fuzzy_threshold: int = 90) -> dict[str, Any]:
workspace_root = validate_workspace_root(root)
try:
threshold = int(fuzzy_threshold)
except (TypeError, ValueError):
threshold = 90
threshold = max(0, min(100, threshold))
with workspace_connection(workspace_root) as conn:
records = [
dict(row)
for row in conn.execute(
"""
SELECT
r.record_id, r.title, r.authors, r.year, r.doi, r.created_at,
MIN(s.imported_at) AS first_imported_at,
MIN(rs.source_record_index) AS first_source_record_index
FROM records r
LEFT JOIN record_sources rs ON rs.record_id = r.record_id
LEFT JOIN sources s ON s.source_id = rs.source_id
WHERE r.record_origin = ?
GROUP BY r.record_id
ORDER BY
COALESCE(first_imported_at, r.created_at),
COALESCE(first_source_record_index, 0),
r.created_at,
r.record_id
""",
(RECORD_ORIGIN_IMPORTED_REFERENCE,),
).fetchall()
]
duplicate_map: dict[str, dict[str, Any]] = {}
doi_canonicals: dict[str, str] = {}
pass1: list[dict[str, Any]] = []
for record in records:
record_id = record["record_id"]
doi = _dedup_doi(record.get("doi"))
if doi and doi in doi_canonicals:
duplicate_map[record_id] = {
"duplicate_of_record_id": doi_canonicals[doi],
"dedup_method": DEDUP_METHOD_DOI,
"dedup_score": 100.0,
}
continue
if doi:
doi_canonicals[doi] = record_id
pass1.append(record)
kept_for_fuzzy: list[tuple[str, str]] = []
for record in pass1:
record_id = record["record_id"]
title = _dedup_title(record.get("title"))
if not title:
kept_for_fuzzy.append((record_id, title))
continue
best_record_id = ""
best_score = 0.0
for kept_record_id, kept_title in kept_for_fuzzy:
if not kept_title:
continue
score = _dedup_title_score(title, kept_title)
if score > best_score:
best_score = score
best_record_id = kept_record_id
if best_record_id and best_score >= threshold:
duplicate_map[record_id] = {
"duplicate_of_record_id": best_record_id,
"dedup_method": DEDUP_METHOD_FUZZY_TITLE,
"dedup_score": round(best_score, 2),
}
else:
kept_for_fuzzy.append((record_id, title))
now = utc_now()
conn.execute(
"""
UPDATE records
SET is_active_for_screening = 1,
duplicate_of_record_id = NULL,
dedup_method = '',
dedup_score = NULL,
updated_at = ?
WHERE record_origin = ?
""",
(now, RECORD_ORIGIN_IMPORTED_REFERENCE),
)
conn.execute(
"""
UPDATE record_sources
SET dedup_status = ?,
duplicate_of_record_id = NULL,
dedup_method = '',
dedup_score = NULL
WHERE record_id IN (
SELECT record_id FROM records WHERE record_origin = ?
)
""",
(DEDUP_STATUS_UNIQUE, RECORD_ORIGIN_IMPORTED_REFERENCE),
)
for duplicate_record_id, evidence in duplicate_map.items():
conn.execute(
"""
UPDATE records
SET is_active_for_screening = 0,
duplicate_of_record_id = ?,
dedup_method = ?,
dedup_score = ?,
updated_at = ?
WHERE record_id = ?
""",
(
evidence["duplicate_of_record_id"],
evidence["dedup_method"],
evidence["dedup_score"],
now,
duplicate_record_id,
),
)
conn.execute(
"""
UPDATE record_sources
SET dedup_status = ?,
duplicate_of_record_id = ?,
dedup_method = ?,
dedup_score = ?
WHERE record_id = ?
""",
(
DEDUP_STATUS_DUPLICATE,
evidence["duplicate_of_record_id"],
evidence["dedup_method"],
evidence["dedup_score"],
duplicate_record_id,
),
)
canonical_rows = [
dict(row)
for row in conn.execute(
"""
SELECT record_id, doi
FROM records
WHERE record_origin = ? AND is_active_for_screening = 1
""",
(RECORD_ORIGIN_IMPORTED_REFERENCE,),
).fetchall()
]
for record in canonical_rows:
source_rows = conn.execute(
"""
SELECT record_id, source_id, source_record_index
FROM record_sources
WHERE record_id = ?
ORDER BY created_at, source_id, source_record_index
""",
(record["record_id"],),
).fetchall()
if len(source_rows) <= 1:
continue
method = DEDUP_METHOD_DOI if _dedup_doi(record.get("doi")) else DEDUP_METHOD_OTHER
for source_row in source_rows[1:]:
conn.execute(
"""
UPDATE record_sources
SET dedup_status = ?,
duplicate_of_record_id = ?,
dedup_method = ?,
dedup_score = ?
WHERE record_id = ? AND source_id = ? AND source_record_index = ?
""",
(
DEDUP_STATUS_DUPLICATE,
record["record_id"],
method,
100.0,
source_row["record_id"],
source_row["source_id"],
source_row["source_record_index"],
),
)
stats = _dedup_stats(conn)
workspace_id_row = conn.execute(
"SELECT value FROM workspace_meta WHERE key = ?",
("workspace_id",),
).fetchone()
_insert_audit_event(
conn,
event_type="reference_deduplicated",
entity_type="workspace",
entity_id=workspace_id_row["value"] if workspace_id_row else "",
summary=(
f"Deduplicated references: {stats['total_after']} active unique "
f"of {stats['total_before']} imported records"
),
metadata={
"fuzzy_threshold": threshold,
"duplicate_record_ids": sorted(duplicate_map),
"stats": stats,
},
)
return {
"stats": stats,
"duplicates": [
{"record_id": record_id, **evidence}
for record_id, evidence in sorted(duplicate_map.items())
],
}
def copy_file_into_workspace(
root: str | Path,
source_path: str | Path,
subdir: str,
*,
original_filename: str | None = None,
allowed_exts: Iterable[str] | None = None,
max_size: int | None = None,
) -> dict[str, Any]:
workspace_root = validate_workspace_root(root)
if subdir not in WORKSPACE_SUBDIRS:
raise UnsafeWorkspacePath("Unsupported workspace subfolder")
source = Path(source_path).resolve()
if not source.is_file():
raise FileNotFoundError("Source file not found")
original = _validate_filename(original_filename or source.name, allowed_exts=allowed_exts)
size = source.stat().st_size
if max_size is not None and size > max_size:
raise WorkspaceError(f"File is too large; limit is {max_size} bytes")
stored_filename = unique_stored_filename(original)
dest_dir = workspace_root / subdir
dest_dir.mkdir(parents=True, exist_ok=True)
dest = (dest_dir / stored_filename).resolve()
try:
dest.relative_to(dest_dir.resolve())
except ValueError as exc:
raise UnsafeWorkspacePath("Copy destination is outside the workspace") from exc
shutil.copy2(source, dest)
relative_path = dest.relative_to(workspace_root.resolve()).as_posix()
return {
"relative_path": relative_path,
"stored_filename": stored_filename,
"original_filename": original,
"size": dest.stat().st_size,
"sha256": sha256_file(dest),
}
def register_pdf(
root: str | Path,
relative_path: str,
*,
original_filename: str,
display_name: str | None = None,
record_id: str | None = None,
metadata: dict[str, Any] | None = None,
) -> dict[str, Any]:
workspace_root = validate_workspace_root(root)
target = resolve_workspace_relative_path(
workspace_root,
relative_path,
subdir="pdfs",
must_exist=True,
require_file=True,
)
if target.suffix.lower() != ".pdf":
raise UnsafeWorkspacePath("PDF metadata path must point to a PDF")
pdf_id = uuid.uuid4().hex
uploaded_at = utc_now()
relative = target.relative_to(workspace_root.resolve()).as_posix()
size = target.stat().st_size
digest = sha256_file(target)
with workspace_connection(workspace_root) as conn:
conn.execute(
"""
INSERT INTO pdfs(
pdf_id, relative_path, original_filename, display_name,
file_size, sha256, record_id, uploaded_at, metadata_json
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
pdf_id,
relative,
original_filename,
display_name or original_filename,
size,
digest,
record_id,
uploaded_at,
json_dumps(_sanitize_metadata(metadata or {})),
),
)
_insert_audit_event(
conn,
event_type="pdf_uploaded",
entity_type="pdf",
entity_id=pdf_id,
summary=f"Uploaded PDF {display_name or original_filename}",
metadata={"file_size": size, "sha256": digest},
)
return {
"pdf_id": pdf_id,
"relative_path": relative,
"original_filename": original_filename,
"display_name": display_name or original_filename,
"size": size,
"sha256": digest,
}
def list_pdf_metadata(root: str | Path) -> list[dict[str, Any]]:
with workspace_connection(root) as conn:
rows = conn.execute(
"""
SELECT pdf_id, relative_path, original_filename, display_name,
file_size, sha256, record_id, uploaded_at
FROM pdfs
ORDER BY display_name COLLATE NOCASE, relative_path COLLATE NOCASE
"""
).fetchall()
return [dict(row) for row in rows]
def delete_pdf(root: str | Path, relative_path: str) -> int:
workspace_root = validate_workspace_root(root)
target = resolve_workspace_relative_path(
workspace_root,
relative_path,
subdir="pdfs",
must_exist=True,
require_file=True,
)
relative = target.relative_to(workspace_root.resolve()).as_posix()
with workspace_connection(workspace_root) as conn:
row = conn.execute(
"SELECT pdf_id, record_id FROM pdfs WHERE relative_path = ?",
(relative,),
).fetchone()
conn.execute("DELETE FROM pdfs WHERE relative_path = ?", (relative,))
if row:
if row["record_id"]:
record = conn.execute(
"SELECT record_origin FROM records WHERE record_id = ?",
(row["record_id"],),
).fetchone()
if record and record["record_origin"] == RECORD_ORIGIN_PDF_ONLY:
conn.execute(
"""
UPDATE records
SET is_active_for_screening = 0,
updated_at = ?
WHERE record_id = ?
""",
(utc_now(), row["record_id"]),
)
_insert_audit_event(
conn,
event_type="pdf_deleted",
entity_type="pdf",
entity_id=row["pdf_id"],
summary="Deleted PDF",
metadata={"relative_path": relative, "record_id": row["record_id"]},
)
remaining = conn.execute("SELECT COUNT(*) AS count FROM pdfs").fetchone()["count"]
target.unlink(missing_ok=True)
return int(remaining)
def clear_pdfs(root: str | Path) -> None:
workspace_root = validate_workspace_root(root)
for row in list_pdf_metadata(workspace_root):
try:
target = resolve_workspace_relative_path(
workspace_root,
row["relative_path"],
subdir="pdfs",
must_exist=True,
require_file=True,
)
target.unlink(missing_ok=True)
except (FileNotFoundError, UnsafeWorkspacePath):
pass
with workspace_connection(workspace_root) as conn:
conn.execute(
"""
UPDATE records
SET is_active_for_screening = 0,
updated_at = ?
WHERE record_origin = ?
AND record_id IN (
SELECT record_id FROM pdfs WHERE record_id IS NOT NULL
)
""",
(utc_now(), RECORD_ORIGIN_PDF_ONLY),
)
conn.execute("DELETE FROM pdfs")
_insert_audit_event(
conn,
event_type="pdfs_cleared",
entity_type="workspace",
entity_id=get_meta(workspace_root, "workspace_id") or "",
summary="Cleared workspace PDFs",
metadata={},
)
def load_records(root: str | Path, *, include_inactive: bool = False) -> list[dict[str, Any]]:
where_sql = "" if include_inactive else "WHERE is_active_for_screening = 1"
with workspace_connection(root) as conn:
rows = conn.execute(
f"""
SELECT record_id, title, abstract, authors, year, journal, doi,
keywords, source_file, record_origin, is_active_for_screening,
duplicate_of_record_id, dedup_method, dedup_score
FROM records
{where_sql}
ORDER BY title COLLATE NOCASE, record_id
"""
).fetchall()
return [dict(row) | {"decision": "", "rationale": "", "human_override": False} for row in rows]
def get_workspace_summary(root: str | Path) -> dict[str, Any]:
workspace_root = validate_workspace_root(root)
metadata = _load_workspace_json(workspace_root)
with workspace_connection(workspace_root) as conn: