feat(learning): S9 — D7 læringssløyfe: verdict-inbox, fail-closed promoteringsgate, artefakt-sourced persona
- inbox.py (§4.2+§5): VerdictDocument med verbatim-id-regel; write_verdict
authoring-primitiv (deterministisk JSON); load_inbox tolerant (skip, aldri
raise; sortert på filnavn); merge_inbox_into_store first-write-wins,
idempotent, skriver aldri (rolle-splitt §3 steg 7)
- promotion.py (§6): promote fail-closed mot {approved,
approved_with_adjustment}; eksplisitt påkrevd timestamp; minimal frontmatter
(rationale → description, aldri strukturerte læringsfelt); path-safe token
med content-hash-fallback; idempotent index-lenking med fast nøytral label
- persona.py (§4.3): load_persona_example fail-fast (run-path-vokabular,
marker ⊆ rationale); drop_persona_verdict artefakt-sourced ved kalltid mot
delt shared/-artefakt
- experience.py (kirurgisk): seeding leser verdict_id VERBATIM fra frontmatter
— re-minting ville kollidert distinkte promoterte kandidater
- 43 nye load-bearing tester (step7/step8/persona), 164/164 uten API-nøkkel;
to-runs-bevis med fersk store + tom-inbox-kontroll; fire detach-bevis kjørt
røde og revertert grønne
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QdSfQdND84oeq2mbjueLTS
This commit is contained in:
parent
9a4caeb419
commit
22bfc80dda
7 changed files with 947 additions and 2 deletions
132
src/portfolio_optimiser_claude/inbox.py
Normal file
132
src/portfolio_optimiser_claude/inbox.py
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
"""The verdict file and the inbox folder contract (method-spec §4.2, §5).
|
||||
|
||||
The long feedback loop's folder interface: an expert (or, in simulation, the
|
||||
persona) drops one verdict per ``{id}.json`` file into an inbox folder; a
|
||||
separate, later run picks it up — fully resumable, no live-session assumption.
|
||||
Role split (§3 Step 7, unwaivable): the system READS the inbox (tolerant load,
|
||||
merge into the store); writing is the authoring primitive's job, used only by
|
||||
the expert/persona side — a run never persists its own captured verdict back.
|
||||
|
||||
Decision vocabulary at this layer: the file carries the expert decision as a
|
||||
plain string — the run-path feedback contract (§4.1) and the promotion gate's
|
||||
accepted set (§6) are where the vocabulary is policed, not the raw file layer.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import BaseModel, Field, ValidationError
|
||||
|
||||
from portfolio_optimiser_claude.experience import (
|
||||
CandidateFeatures,
|
||||
VerdictRecord,
|
||||
VerdictStore,
|
||||
mint_verdict_id,
|
||||
)
|
||||
|
||||
|
||||
class ProposalFeatures(BaseModel):
|
||||
"""§4.2 ``proposal_features``: the structural features of the judged candidate.
|
||||
|
||||
``description`` is surface text — deliberately excluded from both
|
||||
similarity ranking and id minting.
|
||||
"""
|
||||
|
||||
affected_codes: list[str]
|
||||
measure_type: str
|
||||
claimed_saving_nok: float
|
||||
description: str
|
||||
|
||||
|
||||
class VerdictDocument(BaseModel):
|
||||
"""One verdict file (§4.2). A LOADED ``id`` is kept verbatim — never re-minted."""
|
||||
|
||||
id: str = Field(min_length=1)
|
||||
decision: str = Field(min_length=1)
|
||||
rationale: str = Field(min_length=1)
|
||||
proposal_features: ProposalFeatures
|
||||
|
||||
@classmethod
|
||||
def from_candidate(
|
||||
cls,
|
||||
features: CandidateFeatures,
|
||||
*,
|
||||
decision: str,
|
||||
rationale: str,
|
||||
description: str,
|
||||
) -> VerdictDocument:
|
||||
"""Author a verdict for a candidate — the id is minted per §4.2."""
|
||||
return cls(
|
||||
id=mint_verdict_id(features),
|
||||
decision=decision,
|
||||
rationale=rationale,
|
||||
proposal_features=ProposalFeatures(
|
||||
affected_codes=sorted(features.affected_codes),
|
||||
measure_type=features.measure_type,
|
||||
claimed_saving_nok=features.claimed_saving_nok,
|
||||
description=description,
|
||||
),
|
||||
)
|
||||
|
||||
def features(self) -> CandidateFeatures:
|
||||
return CandidateFeatures(
|
||||
affected_codes=frozenset(self.proposal_features.affected_codes),
|
||||
measure_type=self.proposal_features.measure_type,
|
||||
claimed_saving_nok=self.proposal_features.claimed_saving_nok,
|
||||
)
|
||||
|
||||
def to_record(self) -> VerdictRecord:
|
||||
return VerdictRecord(
|
||||
verdict_id=self.id, # verbatim (§4.2) — raw number formatting could diverge
|
||||
decision=self.decision,
|
||||
rationale=self.rationale,
|
||||
features=self.features(),
|
||||
)
|
||||
|
||||
|
||||
def write_verdict(inbox_dir: Path, verdict: VerdictDocument) -> Path:
|
||||
"""The authoring primitive (§5): ``{id}.json``, written deterministically.
|
||||
|
||||
Creates the directory if needed; sorted keys, 2-space indent. The disk
|
||||
layer is LAST-write-wins per file (§4.2).
|
||||
"""
|
||||
inbox_dir.mkdir(parents=True, exist_ok=True)
|
||||
path = inbox_dir / f"{verdict.id}.json"
|
||||
payload = json.dumps(verdict.model_dump(), sort_keys=True, indent=2)
|
||||
path.write_text(payload, encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def load_inbox(inbox_dir: Path) -> list[VerdictDocument]:
|
||||
"""Tolerant load (§5): the raw layer is written out of band — skip, never raise.
|
||||
|
||||
A missing folder yields zero verdicts; files that are not ``.json``, fail
|
||||
to parse, or lack a required top-level key are SKIPPED. Deterministic
|
||||
order: sorted by filename.
|
||||
"""
|
||||
if not inbox_dir.is_dir():
|
||||
return []
|
||||
verdicts: list[VerdictDocument] = []
|
||||
for path in sorted(inbox_dir.iterdir(), key=lambda p: p.name):
|
||||
if path.suffix != ".json" or not path.is_file():
|
||||
continue
|
||||
try:
|
||||
verdicts.append(VerdictDocument.model_validate(json.loads(path.read_text("utf-8"))))
|
||||
except (OSError, ValueError, ValidationError):
|
||||
continue
|
||||
return verdicts
|
||||
|
||||
|
||||
def merge_inbox_into_store(store: VerdictStore, inbox_dir: Path) -> int:
|
||||
"""Merge, never replace (§5): per-verdict add, first-write-wins per id.
|
||||
|
||||
Runs BEFORE the Step-1 fold, so a passed-in store's existing verdicts
|
||||
survive (cross-project threading) and repeated merges are idempotent.
|
||||
Returns the number of inbox verdicts ingested; never writes anything.
|
||||
"""
|
||||
verdicts = load_inbox(inbox_dir)
|
||||
for verdict in verdicts:
|
||||
store.add(verdict.to_record())
|
||||
return len(verdicts)
|
||||
Loading…
Add table
Add a link
Reference in a new issue