-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscaffold.py
More file actions
1650 lines (1267 loc) · 51.1 KB
/
Copy pathscaffold.py
File metadata and controls
1650 lines (1267 loc) · 51.1 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
#!/usr/bin/env python3
"""
Partner OS — Project Scaffold
==============================
Run from the project root directory:
python scaffold.py
Creates the complete Partner OS directory structure and all stub files
with proper docstrings. Does NOT overwrite files that already exist.
"""
import os
import sys
from pathlib import Path
PROJECT_ROOT = Path(__file__).parent.resolve()
print(f"=== Partner OS Scaffold ===")
print(f"Project root: {PROJECT_ROOT}")
print()
created = []
skipped = []
def write_stub(relative_path: str, content: str) -> None:
"""Write a stub file if it does not already exist."""
filepath = PROJECT_ROOT / relative_path
if filepath.exists():
skipped.append(relative_path)
print(f" skipped (exists): {relative_path}")
else:
filepath.parent.mkdir(parents=True, exist_ok=True)
filepath.write_text(content, encoding="utf-8")
created.append(relative_path)
print(f" created: {relative_path}")
# =============================================================================
# DIRECTORIES
# =============================================================================
print("Creating directories...")
dirs = [
"docs",
"knowledge/pinneo",
"knowledge/ccim",
"knowledge/reference",
"knowledge/outcomes",
"staging/inbox/unresolved",
"deals",
"data/chroma",
"src/ui",
"src/agents",
"src/brain",
"src/database",
"src/integrations",
"src/learning",
"src/utils",
"tests",
"logs",
]
for d in dirs:
(PROJECT_ROOT / d).mkdir(parents=True, exist_ok=True)
print(" ✓ Directories created\n")
# =============================================================================
# __init__.py FILES
# =============================================================================
print("Creating __init__.py files...")
packages = [
"src", "src/ui", "src/agents", "src/brain",
"src/database", "src/integrations", "src/learning",
"src/utils", "tests",
]
for pkg in packages:
write_stub(f"{pkg}/__init__.py", '"""Partner OS package."""\n')
print()
# =============================================================================
# src/utils/logger.py
# =============================================================================
print("Creating src/utils/ stubs...")
write_stub("src/utils/logger.py", '''\
"""
Partner OS — Centralised Logging
==================================
Configures and provides the application-wide logger used by all agents
and utilities. All modules import get_logger() from here.
Never use print() anywhere in the codebase. Use logging exclusively.
Usage:
from src.utils.logger import get_logger
log = get_logger(__name__)
log.info("Librarian sweep started.")
"""
import logging
import sys
from pathlib import Path
from config import LOG_DIR, LOG_FORMAT, LOG_DATE_FORMAT, LOG_LEVEL
def get_logger(name: str) -> logging.Logger:
"""
Return a configured logger for the given module name.
Args:
name: The module name, typically passed as __name__.
Returns:
A logging.Logger instance writing to both console and a log file
in the LOG_DIR directory.
"""
raise NotImplementedError("get_logger() is not yet implemented.")
''')
# =============================================================================
# src/utils/firewall.py
# =============================================================================
write_stub("src/utils/firewall.py", '''\
"""
Partner OS — The Firewall (Law 1 Enforcement)
===============================================
Validates all agent-generated output before it is written to disk or
displayed in the UI. Enforces Law 1: Partner OS produces DRAFT-ONLY
outputs. No outbound action language is permitted in any system output.
Any string containing outbound action patterns (send, submit, sign,
execute, call, email, forward, transmit, etc.) is flagged and blocked.
Usage:
from src.utils.firewall import validate_output, FirewallViolation
try:
clean_text = validate_output(agent_output)
except FirewallViolation as e:
log.error("Firewall blocked output: %s", e)
"""
from src.utils.logger import get_logger
log = get_logger(__name__)
class FirewallViolation(Exception):
"""Raised when agent output contains prohibited outbound action language."""
pass
def validate_output(text: str, agent_name: str = "unknown") -> str:
"""
Scan agent output for outbound action language and raise if found.
Args:
text: The raw text output from an agent to validate.
agent_name: Name of the producing agent, used in error messages.
Returns:
The original text unchanged if validation passes.
Raises:
FirewallViolation: If any prohibited patterns are detected.
"""
raise NotImplementedError("validate_output() is not yet implemented.")
''')
print()
# =============================================================================
# src/brain/
# =============================================================================
print("Creating src/brain/ stubs...")
write_stub("src/brain/chroma_client.py", '''\
"""
Partner OS — ChromaDB Connection Management
============================================
Manages the persistent ChromaDB client and provides access to the two
named collections used by Partner OS:
- pinneo_brain: WISDOM (Pinneo transcripts, CCIM, Outcomes)
- reference_library: REFERENCE (Zoning codes, laws, regulations)
All modules that need ChromaDB import from here. This ensures a single
connection is shared and collection names are never magic strings.
Usage:
from src.brain.chroma_client import get_pinneo_collection
collection = get_pinneo_collection()
"""
import chromadb
from chromadb.api.models.Collection import Collection
from config import (
CHROMA_DB_PATH,
COLLECTION_PINNEO_BRAIN,
COLLECTION_REFERENCE_LIBRARY,
)
from src.utils.logger import get_logger
log = get_logger(__name__)
def get_chroma_client() -> chromadb.PersistentClient:
"""
Return a persistent ChromaDB client backed by CHROMA_DB_PATH.
Args:
None
Returns:
A chromadb.PersistentClient instance. Creates the database
directory if it does not exist.
"""
raise NotImplementedError("get_chroma_client() is not yet implemented.")
def get_pinneo_collection() -> Collection:
"""
Return the pinneo_brain ChromaDB collection, creating it if absent.
Args:
None
Returns:
The pinneo_brain Collection instance.
"""
raise NotImplementedError("get_pinneo_collection() is not yet implemented.")
def get_reference_collection() -> Collection:
"""
Return the reference_library ChromaDB collection, creating it if absent.
Args:
None
Returns:
The reference_library Collection instance.
"""
raise NotImplementedError("get_reference_collection() is not yet implemented.")
''')
write_stub("src/brain/embedder.py", '''\
"""
Partner OS — Pinneo Brain Embedder (Sprint 1A)
===============================================
Reads all .md files from the knowledge/ directories, chunks them into
overlapping segments, generates vector embeddings via the Gemini API
(text-embedding-004 model), and stores them in the appropriate
ChromaDB collection.
This script builds the Pinneo Brain. Run it once after knowledge/
directories are populated, and again whenever new files are added.
Collections populated:
- pinneo_brain: knowledge/pinneo/, knowledge/ccim/, knowledge/outcomes/
- reference_library: knowledge/reference/
Usage:
python -m src.brain.embedder
python -m src.brain.embedder --collection pinneo_brain
python -m src.brain.embedder --dry-run
"""
import argparse
from pathlib import Path
from typing import Iterator
from config import (
PINNEO_DIR,
CCIM_DIR,
REFERENCE_DIR,
OUTCOMES_DIR,
CHUNK_SIZE,
CHUNK_OVERLAP,
COLLECTION_PINNEO_BRAIN,
COLLECTION_REFERENCE_LIBRARY,
GEMINI_EMBEDDING_MODEL,
)
from src.brain.chroma_client import get_pinneo_collection, get_reference_collection
from src.utils.logger import get_logger
log = get_logger(__name__)
def chunk_text(text: str, chunk_size: int, overlap: int) -> Iterator[str]:
"""
Split text into overlapping chunks of a maximum character length.
Args:
text: The full source text to chunk.
chunk_size: Maximum number of characters per chunk.
overlap: Number of characters to overlap between adjacent chunks.
Yields:
Individual text chunks as strings.
"""
raise NotImplementedError("chunk_text() is not yet implemented.")
def embed_text(text: str) -> list[float]:
"""
Generate a vector embedding for a text string using the Gemini API.
Args:
text: The text to embed. Should be a single chunk from chunk_text().
Returns:
A list of floats representing the embedding vector.
Raises:
google.api_core.exceptions.GoogleAPIError: On API failure.
"""
raise NotImplementedError("embed_text() is not yet implemented.")
def embed_directory(
directory: Path,
collection_name: str,
dry_run: bool = False,
) -> int:
"""
Embed all .md files in a directory into a ChromaDB collection.
Skips files whose content hash already exists in the collection.
This makes the function safe to re-run after adding new files.
Args:
directory: Path to the directory containing .md files.
collection_name: Name of the ChromaDB collection to write to.
dry_run: If True, log what would be embedded without writing.
Returns:
Number of new chunks embedded.
"""
raise NotImplementedError("embed_directory() is not yet implemented.")
def main() -> None:
"""
CLI entry point. Parse arguments and run the embedding pipeline.
"""
raise NotImplementedError("main() is not yet implemented.")
if __name__ == "__main__":
main()
''')
write_stub("src/brain/retriever.py", '''\
"""
Partner OS — Pinneo Brain Retriever
=====================================
Provides the semantic query interface used by all agents to retrieve
relevant context from ChromaDB before generating any AI output.
Every agent must call retrieve_pinneo_context() or
retrieve_reference_context() before calling the Gemini API.
This grounds the agent reasoning in the Pinneo Brain rather than
in generic AI training data.
If retrieved chunks fall below LOW_CONFIDENCE_THRESHOLD, the result
is flagged and the calling agent must mark its output LOW_CONFIDENCE.
Usage:
from src.brain.retriever import retrieve_pinneo_context
result = retrieve_pinneo_context(
query="motivated seller holding property 15 years, needs cash flow",
)
# result.chunks -> list of relevant Pinneo text passages
# result.citations -> list of source references
# result.low_confidence -> bool
"""
from dataclasses import dataclass, field
from config import RAG_TOP_K, LOW_CONFIDENCE_THRESHOLD
from src.brain.chroma_client import get_pinneo_collection, get_reference_collection
from src.utils.logger import get_logger
log = get_logger(__name__)
@dataclass
class RetrievalResult:
"""
Structured output from a ChromaDB semantic query.
Attributes:
query: The original query string.
chunks: Retrieved text passages, ordered by relevance.
citations: Source references matching each chunk.
scores: Relevance scores for each chunk (0.0 to 1.0).
low_confidence: True if best score is below LOW_CONFIDENCE_THRESHOLD.
"""
query: str
chunks: list[str] = field(default_factory=list)
citations: list[str] = field(default_factory=list)
scores: list[float] = field(default_factory=list)
low_confidence: bool = False
def retrieve_pinneo_context(
query: str,
top_k: int = RAG_TOP_K,
) -> RetrievalResult:
"""
Query the pinneo_brain collection for context relevant to a deal scenario.
Args:
query: Natural language description of the deal situation.
top_k: Number of chunks to retrieve.
Returns:
A RetrievalResult containing chunks, citations, scores, and
a low_confidence flag per Law 3.
"""
raise NotImplementedError("retrieve_pinneo_context() is not yet implemented.")
def retrieve_reference_context(
query: str,
top_k: int = RAG_TOP_K,
) -> RetrievalResult:
"""
Query the reference_library collection for regulatory context.
Args:
query: Natural language query about regulations or legal requirements.
top_k: Number of chunks to retrieve.
Returns:
A RetrievalResult containing relevant regulatory passages.
"""
raise NotImplementedError("retrieve_reference_context() is not yet implemented.")
''')
print()
# =============================================================================
# src/database/db.py
# =============================================================================
print("Creating src/database/ stubs...")
write_stub("src/database/db.py", '''\
"""
Partner OS — SQLite Database Interface
=======================================
Manages the SQLite connection and provides typed helper functions for
all database operations used across the codebase.
Rules enforced here:
- PRAGMA foreign_keys = ON is set on every connection.
- PRAGMA journal_mode = WAL is set for concurrent read safety.
- All writes use parameterized queries. String formatting is forbidden.
- The schema is initialised from schema.sql on first run.
Usage:
from src.database.db import get_connection, initialise_database
initialise_database() # call once at startup
with get_connection() as conn:
rows = conn.execute(
"SELECT * FROM deals WHERE status = ?", ("INTAKE",)
).fetchall()
"""
import sqlite3
from contextlib import contextmanager
from pathlib import Path
from typing import Generator
from config import DATABASE_PATH, ROOT_DIR
from src.utils.logger import get_logger
log = get_logger(__name__)
SCHEMA_PATH: Path = ROOT_DIR / "src" / "database" / "schema.sql"
def initialise_database() -> None:
"""
Create all tables defined in schema.sql if they do not already exist.
Safe to call on every startup — uses CREATE TABLE IF NOT EXISTS.
Does not drop or alter existing tables.
Args:
None
Returns:
None
Raises:
FileNotFoundError: If schema.sql is not found at SCHEMA_PATH.
sqlite3.Error: On any database error during initialisation.
"""
raise NotImplementedError("initialise_database() is not yet implemented.")
@contextmanager
def get_connection() -> Generator[sqlite3.Connection, None, None]:
"""
Context manager yielding a configured SQLite connection.
Automatically commits on clean exit and rolls back on exception.
Sets foreign_keys=ON and journal_mode=WAL on every connection.
Args:
None
Yields:
sqlite3.Connection: A configured database connection.
Raises:
sqlite3.Error: On connection failure.
Example:
with get_connection() as conn:
rows = conn.execute("SELECT id FROM deals").fetchall()
"""
raise NotImplementedError("get_connection() is not yet implemented.")
''')
print()
# =============================================================================
# src/agents/
# =============================================================================
print("Creating src/agents/ stubs...")
write_stub("src/agents/librarian.py", '''\
"""
Partner OS — The Librarian (Archivist Agent)
=============================================
The Librarian is the sole gatekeeper of all data entering Partner OS.
It is the only agent permitted to move, rename, or reorganise files
anywhere in the filesystem. No other agent performs file move operations.
The Librarian operates in two modes:
Mode 1 — The Sweep:
Reconciles staging/inbox/ and all deals/ directories against
the SQLite file index. Processes all unindexed files: classifies
content, routes to the correct Deal Jacket subdirectory, updates
SQLite, and triggers downstream pipelines (Whisper for audio,
PDF extractor for documents). Runs on startup and on demand.
Mode 2 — UI Upload Handler:
Receives a file already written to staging/inbox/ by the
Streamlit UI and triggers an immediate targeted sweep.
The Librarian is the only component that creates Deal Jacket directories.
Usage:
from src.agents.librarian import LibrarianAgent
librarian = LibrarianAgent()
librarian.run_sweep()
"""
from pathlib import Path
from config import (
STAGING_INBOX_DIR,
STAGING_UNRESOLVED_DIR,
DEALS_DIR,
DealStatus,
FileStatus,
ContentClass,
DealSubdir,
)
from src.database.db import get_connection
from src.utils.logger import get_logger
log = get_logger(__name__)
class LibrarianAgent:
"""
The Archivist. Sole filesystem authority for Partner OS.
"""
def __init__(self) -> None:
"""Initialise the Librarian agent with verified directory paths."""
raise NotImplementedError("LibrarianAgent.__init__() is not yet implemented.")
def run_sweep(self) -> dict:
"""
Execute a full reconciliation sweep of staging/ and deals/.
Scans staging/inbox/ for unprocessed files. Classifies each file,
determines deal association, and routes to the correct Deal Jacket.
Then reconciles all deals/ subdirectories against the SQLite index.
Args:
None
Returns:
Summary dict: {processed: int, routed: int, unresolved: int, failed: int}
"""
raise NotImplementedError("run_sweep() is not yet implemented.")
def classify_file(self, file_path: Path) -> tuple[str, str]:
"""
Determine the file_type and content_class of an ingested file.
Args:
file_path: Absolute path to the file to classify.
Returns:
A tuple of (file_type, content_class) using constants from config.py.
"""
raise NotImplementedError("classify_file() is not yet implemented.")
def determine_deal_association(
self, file_path: Path, content_class: str
) -> int | None:
"""
Attempt to identify which deal a file belongs to.
Checks parent folder naming, filename patterns, and AI-assisted
content classification as a last resort.
Args:
file_path: Absolute path to the file.
content_class: The classified content type of the file.
Returns:
deal_id integer if association is determined, None if ambiguous.
"""
raise NotImplementedError("determine_deal_association() is not yet implemented.")
def route_file(
self, file_path: Path, deal_id: int, content_class: str
) -> Path:
"""
Move a file from staging/ to the correct Deal Jacket subdirectory.
This is the only function in the system that moves files on disk.
Validates that the destination path is inside the authorised deal
directory before executing the move.
Args:
file_path: Current absolute path of the file (in staging/).
deal_id: Database ID of the deal this file belongs to.
content_class: Determines which subdirectory to route to.
Returns:
The new absolute path of the file after routing.
Raises:
ValueError: If the resolved destination path escapes the deal directory.
"""
raise NotImplementedError("route_file() is not yet implemented.")
def create_deal_jacket(self, address: str) -> tuple[int, Path]:
"""
Create a new Deal Jacket directory and register the deal in SQLite.
Creates the full subdirectory structure and an initial jacket.json.
This is the only function that creates new Deal Jacket directories.
Args:
address: Property address, used to generate the deal_code slug.
Returns:
A tuple of (deal_id, jacket_path).
"""
raise NotImplementedError("create_deal_jacket() is not yet implemented.")
def update_jacket_json(self, deal_id: int) -> None:
"""
Rewrite jacket.json for a deal to reflect current SQLite state.
Called after any file routing or deal status change. jacket.json
is the human-readable filesystem manifest for the deal.
Args:
deal_id: Database ID of the deal to update.
Returns:
None
"""
raise NotImplementedError("update_jacket_json() is not yet implemented.")
''')
write_stub("src/agents/cfo.py", '''\
"""
Partner OS — The CFO (Underwriter Agent)
==========================================
The Underwriter executes the three-phase CFO Hallucination Firewall:
Phase 1 — EXTRACT (AI):
Reads financial documents (T12s, OMs, rent rolls) from the deal
documents/ directory. Uses the Gemini API to extract financial
variables into a draft_financials SQLite record (status UNVERIFIED).
Records a source citation for every number extracted.
Advances deal status to AWAITING_VERIFICATION.
Phase 2 — VERIFY (Human gate, enforced by the UI):
The Streamlit UI presents extracted numbers with source citations.
The principal reviews, corrects, and approves. This creates a
verified_financials record and advances status to CFO_CALCULATING.
The CFO agent does not participate in Phase 2.
Phase 3 — CALCULATE (Pure Python, no AI):
Reads verified_financials. Executes deterministic arithmetic only.
Calculates Cap Rate, DSCR, LTV, Cash-on-Cash, IRR. Sets red-line
flags. Then queries Pinneo Brain and calls Gemini to interpret
results and recommend creative structuring options.
WILL NOT RUN without a verified_financials record with status
VERIFIED. This check is enforced at the start of every calculation.
Usage:
from src.agents.cfo import CFOAgent
cfo = CFOAgent()
cfo.run_phase_1(deal_id=42)
cfo.run_phase_3(deal_id=42) # Only after principal verifies in UI
"""
from config import DealStatus, VerificationStatus
from src.database.db import get_connection
from src.brain.retriever import retrieve_pinneo_context
from src.utils.logger import get_logger
from src.utils.firewall import validate_output
log = get_logger(__name__)
class CFOAgent:
"""
The Underwriter. Financial extraction, verification gate, and calculation.
"""
def run_phase_1(self, deal_id: int) -> int:
"""
Phase 1: Extract financial variables from deal documents using AI.
Reads FINANCIAL_DOCUMENT and OFFERING_MEMORANDUM files from the
deal jacket. Calls Gemini API to extract key variables with source
citations. Writes draft_financials record (status UNVERIFIED).
Advances deal status to AWAITING_VERIFICATION.
Args:
deal_id: Database ID of the deal to process.
Returns:
draft_financials record ID.
Raises:
ValueError: If deal is not in an eligible status for Phase 1.
"""
raise NotImplementedError("run_phase_1() is not yet implemented.")
def run_phase_3(self, deal_id: int) -> int:
"""
Phase 3: Execute deterministic financial calculations (pure Python).
WILL NOT EXECUTE without a verified_financials record (status VERIFIED).
This is a hard check, not a convention.
Calculates: Cap Rate, DSCR, LTV, Cash-on-Cash Return, IRR.
Sets red-line flags. Then queries Pinneo Brain and calls Gemini
to interpret results and recommend structuring options.
Args:
deal_id: Database ID of the deal to calculate.
Returns:
financial_analyses record ID.
Raises:
ValueError: If no VERIFIED financials record exists.
ValueError: If deal status is not CFO_CALCULATING.
"""
raise NotImplementedError("run_phase_3() is not yet implemented.")
def _calculate_cap_rate(self, noi: float, purchase_price: float) -> float:
"""
Calculate the Capitalization Rate: NOI / Purchase Price.
Args:
noi: Net Operating Income (annual, dollars).
purchase_price: Property purchase price (dollars).
Returns:
Cap rate as a decimal (e.g. 0.065 for 6.5%).
Raises:
ValueError: If purchase_price is zero.
"""
raise NotImplementedError("_calculate_cap_rate() is not yet implemented.")
def _calculate_dscr(self, noi: float, annual_debt_service: float) -> float:
"""
Calculate the Debt Service Coverage Ratio: NOI / Annual Debt Service.
Red line: DSCR < 1.2 triggers flag_dscr_below_minimum.
Args:
noi: Net Operating Income (annual, dollars).
annual_debt_service: Total annual principal and interest payments.
Returns:
DSCR as a float (e.g. 1.35).
Raises:
ValueError: If annual_debt_service is zero.
"""
raise NotImplementedError("_calculate_dscr() is not yet implemented.")
def _calculate_ltv(self, loan_amount: float, purchase_price: float) -> float:
"""
Calculate the Loan-to-Value ratio: Loan Amount / Purchase Price.
Red line: LTV > 0.75 triggers flag_ltv_above_maximum.
Args:
loan_amount: Total loan amount (dollars).
purchase_price: Property purchase price (dollars).
Returns:
LTV as a decimal (e.g. 0.70 for 70%).
Raises:
ValueError: If purchase_price is zero.
"""
raise NotImplementedError("_calculate_ltv() is not yet implemented.")
''')
write_stub("src/agents/scout.py", '''\
"""
Partner OS — The Scout (Intelligence Officer Agent)
====================================================
Hunts public records and market data for subject properties in
Clark County, WA. Detects motivated seller signals. Flags data
quality issues. Writes a structured scout_reports record to SQLite.
Tooling:
- playwright: Headless Chromium for JavaScript-rendered county sites
- beautifulsoup4: HTML parsing of rendered pages
- pandas: CSV ingestion for manually exported county records
Primary data source: Clark County Assessor portal
https://www.clark.wa.gov/assessor
Motivated seller signals detected (Pinneo doctrine):
- Ownership tenure >= 10 years (Pinneo Equity Screen Rule)
- Tax delinquency
- Expired or withdrawn MLS listings
- Probate or estate indicators in ownership records
- Suspicious rent estimates (flagged for human review)
Usage:
from src.agents.scout import ScoutAgent
scout = ScoutAgent()
scout.run(deal_id=42)
"""
from pathlib import Path
from config import CLARK_COUNTY_ASSESSOR_URL, DealStatus
from src.database.db import get_connection
from src.brain.retriever import retrieve_pinneo_context
from src.utils.logger import get_logger
log = get_logger(__name__)
class ScoutAgent:
"""
The Intelligence Officer. Public records retrieval and signal detection.
"""
def run(self, deal_id: int) -> int:
"""
Execute a full Scout run for a deal.
Fetches property records from Clark County Assessor, detects
motivated seller signals, and writes a scout_reports record.
Advances deal status to PROFILER_RUNNING on completion.
Args:
deal_id: Database ID of the deal to investigate.
Returns:
scout_reports record ID.
Raises:
ValueError: If deal status is not SCOUT_RUNNING.
"""
raise NotImplementedError("run() is not yet implemented.")
def fetch_assessor_data(self, parcel_number: str) -> dict:
"""
Scrape Clark County Assessor portal for a property record.
Uses Playwright to render the site, then BeautifulSoup to parse.
Args:
parcel_number: Clark County parcel number for the subject property.
Returns:
A dict of raw property data fields from the assessor portal.
Raises:
RuntimeError: If the page fails to load or parse.
"""
raise NotImplementedError("fetch_assessor_data() is not yet implemented.")
def ingest_csv(self, csv_path: Path) -> dict:
"""
Parse a manually exported CSV file of county records.
Args:
csv_path: Absolute path to the .csv file to parse.
Returns:
A dict of property data fields extracted from the CSV.
"""
raise NotImplementedError("ingest_csv() is not yet implemented.")
def score_motivated_seller(self, property_data: dict) -> tuple[int, dict]:
"""
Calculate a motivated seller signal score (0-100) and flag dict.
Applies the Pinneo Equity Screen and other signal detection rules.
A score >= 60 is considered a strong motivated seller signal.
Args:
property_data: Raw property data from assessor or CSV ingest.
Returns:
A tuple of (score: int, flags: dict) mapping each signal to bool.
"""
raise NotImplementedError("score_motivated_seller() is not yet implemented.")
''')
write_stub("src/agents/profiler.py", '''\
"""
Partner OS — The Profiler (Psychologist Agent)
================================================
Generates seller psychological archetypes by analysing all available
data about the seller: ownership history, Scout report, field audio
transcriptions, and correspondence found in the deal jacket.
Grounds every profile in retrieved Pinneo Brain context, specifically
the negotiation psychology heuristics and the Script Vault sections
of the Pinneo transcripts.
Output includes:
- Pinneo psychological archetype (e.g. OLD_SCHOOL, ESTATE_HEIR)
- Ordered pain hierarchy (what hurts most to least)
- Leverage triggers (what motivates this seller to act)
- Recommended negotiation approach
- Relevant Pinneo verbatim scripts from the Master Rulebook
- Risk flags (adversarial posture, attorney involvement, etc.)
Also checks seller_history in SQLite for prior deal interactions.
Usage:
from src.agents.profiler import ProfilerAgent
profiler = ProfilerAgent()
profiler.run(deal_id=42)
"""
from config import DealStatus
from src.database.db import get_connection
from src.brain.retriever import retrieve_pinneo_context
from src.utils.logger import get_logger
from src.utils.firewall import validate_output
log = get_logger(__name__)
class ProfilerAgent:
"""
The Psychologist. Seller archetype generation and negotiation strategy.
"""
def run(self, deal_id: int) -> int:
"""
Execute a full Profiler run for a deal.
Gathers all available seller intelligence, queries the Pinneo
Brain for relevant psychology heuristics, generates a
seller_profiles record in SQLite. Advances deal status to
MANAGER_SYNTHESIZING on completion.
Args:
deal_id: Database ID of the deal to profile.
Returns:
seller_profiles record ID.
Raises:
ValueError: If deal status is not PROFILER_RUNNING.
"""
raise NotImplementedError("run() is not yet implemented.")