Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ No performance claims yet. The scaffold proves the invariants:
| BeliefBench runner and baselines | `tests/test_beliefbench.py` |
| GDELT and RSS map to observations | `tests/test_gdelt.py`, `tests/test_rss.py` |
| Retries, dead letters, and replay | `tests/test_scheduler.py` |
| Retention deletes only expired rows; redaction is deep and non-mutating | `tests/test_retention.py` |
| Quality checks catch duplicate, future, and stale data | `tests/test_quality.py` |
| Predictions are immutable and settle once | `tests/test_ledger.py` |
| RSI stays bounded; MACD / Bollinger / OBV behave | `tests/test_indicators.py` |
Expand Down
85 changes: 85 additions & 0 deletions core/janus/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@
ModelRegistry,
)
from .memory.migrations import apply_migrations, current_version
from .memory.retention import (
RetentionPolicy,
RetentionRule,
apply_retention,
export_redacted,
)
from .memory.models import ObservationKind
from .memory.store import JanusStore

Expand All @@ -29,9 +35,11 @@
config_app = typer.Typer(help="Inspect and validate local configuration.")
schema_app = typer.Typer(help="Export and verify the domain contract schema.")
model_app = typer.Typer(help="Inspect content-addressed model artifacts.")
retention_app = typer.Typer(help="Apply retention and export redacted data.")
app.add_typer(config_app, name="config")
app.add_typer(schema_app, name="schema")
app.add_typer(model_app, name="model")
app.add_typer(retention_app, name="retention")


@app.command()
Expand Down Expand Up @@ -159,6 +167,83 @@ def schema_check(
raise typer.Exit(code=1)


def _retention_rule(value: str) -> RetentionRule:
parts = value.split(":")
if len(parts) != 3:
raise typer.BadParameter("rules use SOURCE:KIND:DAYS, e.g. rss:news:30")
source, kind, days = parts
try:
return RetentionRule(source=source, kind=kind, max_age_days=int(days))
except ValueError as exc:
raise typer.BadParameter(str(exc)) from exc


@retention_app.command("apply")
def retention_apply(
as_of: str = typer.Option(..., "--as-of", help="Retention cutoff timestamp"),
rule: Optional[list[str]] = typer.Option(
None, "--rule", help="SOURCE:KIND:DAYS (repeatable)"
),
default_days: Optional[int] = typer.Option(
None, "--default-days", help="Fallback max age for unmatched rows"
),
db: Optional[str] = typer.Option(None, "--db", help="SQLite path"),
dry_run: bool = typer.Option(False, "--dry-run", help="Report without deleting"),
as_json: bool = typer.Option(False, "--json", help="Emit JSON"),
) -> None:
"""Delete observations whose retention window has expired."""

try:
stamp = datetime.fromisoformat(as_of)
except ValueError as exc:
raise typer.BadParameter("use an ISO timestamp") from exc
if stamp.tzinfo is None:
stamp = stamp.replace(tzinfo=timezone.utc)
policy = RetentionPolicy(
rules=tuple(_retention_rule(item) for item in (rule or [])),
default_max_age_days=default_days,
)
settings = load_settings()
result = apply_retention(
JanusStore(db or settings.database),
as_of=stamp,
policy=policy,
dry_run=dry_run,
)
if as_json:
typer.echo(json.dumps(result.to_dict(), indent=2, sort_keys=True))
else:
typer.echo(
f"scanned={result.scanned} deleted={result.deleted} kept={result.kept}"
)


@retention_app.command("export")
def retention_export(
entity: str = typer.Argument(..., help="Entity id"),
as_of: str = typer.Option(..., "--as-of", help="Point-in-time timestamp"),
out: Path = typer.Option(..., "--out", help="JSONL output path"),
field: Optional[list[str]] = typer.Option(
None, "--field", help="Field name to redact (repeatable)"
),
db: Optional[str] = typer.Option(None, "--db", help="SQLite path"),
) -> None:
"""Export one entity's as-of observations with selected fields redacted."""

try:
stamp = datetime.fromisoformat(as_of)
except ValueError as exc:
raise typer.BadParameter("use an ISO timestamp") from exc
if stamp.tzinfo is None:
stamp = stamp.replace(tzinfo=timezone.utc)
settings = load_settings()
rows = JanusStore(db or settings.database).query_observations_as_of(
entity, stamp, mode="published"
)
target = export_redacted(rows, out, fields=field or [])
typer.echo(f"wrote {len(rows)} redacted observation(s) to {target}")


@app.command()
def migrate(
db: Optional[str] = typer.Option(None, "--db", help="SQLite path"),
Expand Down
186 changes: 186 additions & 0 deletions core/janus/memory/retention.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
from __future__ import annotations

import json
from dataclasses import asdict, dataclass
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Iterable, Optional, Sequence

from .models import Observation
from .store import JanusStore


@dataclass(frozen=True)
class RetentionRule:
"""One source/kind retention window. ``*`` matches any value."""

source: str = "*"
kind: str = "*"
max_age_days: int = 365

def __post_init__(self) -> None:
if self.max_age_days < 0:
raise ValueError("max_age_days must be non-negative")

def matches(self, observation: Observation) -> bool:
source = str(observation.source)
source_base = source.split(":")[0]
source_ok = self.source in {"*", source, source_base}
kind_ok = self.kind in {"*", observation.kind.value}
return source_ok and kind_ok

def to_dict(self) -> dict[str, Any]:
return asdict(self)


@dataclass(frozen=True)
class RetentionPolicy:
rules: tuple[RetentionRule, ...] = ()
default_max_age_days: Optional[int] = None

def __post_init__(self) -> None:
if self.default_max_age_days is not None and self.default_max_age_days < 0:
raise ValueError("default_max_age_days must be non-negative")

def max_age_for(self, observation: Observation) -> Optional[int]:
for rule in self.rules:
if rule.matches(observation):
return rule.max_age_days
return self.default_max_age_days

def expiration(self, observation: Observation) -> Optional[datetime]:
days = self.max_age_for(observation)
if days is None:
return None
return observation.published_at + timedelta(days=days)

def expired(self, observation: Observation, as_of: datetime) -> bool:
expiration = self.expiration(observation)
return expiration is not None and expiration <= as_of

def to_dict(self) -> dict[str, Any]:
return {
"rules": [rule.to_dict() for rule in self.rules],
"default_max_age_days": self.default_max_age_days,
}

@classmethod
def from_dict(cls, payload: dict[str, Any]) -> "RetentionPolicy":
return cls(
rules=tuple(RetentionRule(**item) for item in payload.get("rules", [])),
default_max_age_days=payload.get("default_max_age_days"),
)


@dataclass(frozen=True)
class RetentionResult:
as_of: str
scanned: int
deleted: int
kept: int
by_source: dict[str, int]
deleted_ids: tuple[str, ...]

def to_dict(self) -> dict[str, Any]:
return asdict(self)


@dataclass(frozen=True)
class RetentionSkip:
observation_id: str
entity_id: str
kind: str
source: str
expiration: Optional[str]


def apply_retention(
store: JanusStore,
*,
as_of: datetime,
policy: RetentionPolicy,
dry_run: bool = False,
) -> RetentionResult:
"""Delete observations whose policy expiration is at or before ``as_of``."""

if as_of.tzinfo is None or as_of.tzinfo.utcoffset(as_of) is None:
raise ValueError("as_of must be timezone-aware")
rows = store.connection.execute(
"SELECT id, entity_id, kind, source, published_at FROM observation"
).fetchall()
expired: list[str] = []
by_source: dict[str, int] = {}
for row in rows:
observation = Observation(
id=row["id"],
entity_id=row["entity_id"],
kind=row["kind"],
source=row["source"],
published_at=datetime.fromisoformat(row["published_at"]),
value={},
raw_hash="",
)
if policy.expired(observation, as_of):
expired.append(observation.id)
by_source[observation.source] = by_source.get(observation.source, 0) + 1
if expired and not dry_run:
placeholders = ",".join("?" for _ in expired)
with store.connection:
store.connection.execute(
f"DELETE FROM observation WHERE id IN ({placeholders})",
expired,
)
return RetentionResult(
as_of=as_of.isoformat(),
scanned=len(rows),
deleted=len(expired),
kept=len(rows) - len(expired),
by_source=dict(sorted(by_source.items())),
deleted_ids=tuple(sorted(expired)),
)


def redact_value(value: Any, fields: Iterable[str]) -> Any:
"""Return a deep copy with the named keys masked."""

names = {str(field).lower() for field in fields}
if isinstance(value, dict):
result = {}
for key, item in value.items():
if str(key).lower() in names:
result[key] = "***"
else:
result[key] = redact_value(item, names)
return result
if isinstance(value, list):
return [redact_value(item, names) for item in value]
return value


def redact_observation(observation: Observation, fields: Iterable[str]) -> dict[str, Any]:
payload = observation.model_dump(mode="json")
payload["value"] = redact_value(payload["value"], fields)
if "raw_uri" in {str(field).lower() for field in fields}:
payload["raw_uri"] = "***"
return payload


def export_redacted(
observations: Sequence[Observation],
path: Path,
*,
fields: Iterable[str],
) -> Path:
target = Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
with target.open("w", encoding="utf-8") as handle:
for observation in observations:
handle.write(
json.dumps(
redact_observation(observation, fields),
sort_keys=True,
default=str,
)
+ "\n"
)
return target
4 changes: 2 additions & 2 deletions docs/BACKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ criteria.

## How to read this

**Current status (2026-11-24):** JAN-001, JAN-002, JAN-003, JAN-005, JAN-007,
**Current status (2026-11-24):** JAN-001, JAN-002, JAN-003, JAN-005, JAN-007, JAN-020,
JAN-008, JAN-009, JAN-010, JAN-015, JAN-016, JAN-019, JAN-023, JAN-024, JAN-025,
JAN-027, JAN-028, JAN-031 (tracker #39 / JAN-074), JAN-033, JAN-034, JAN-035,
JAN-037, JAN-040, JAN-041,
Expand All @@ -25,7 +25,7 @@ DSH UI wiring and cron are deferred to v0.2. See `schemas/janus.schema.json`,
`tests/test_debrief.py`, `tests/test_persona_weighting.py`,
`tests/test_mcp_service.py`, `tests/test_beliefbench.py`,
`tests/test_gdelt.py`, `tests/test_rss.py`, `tests/test_scheduler.py`,
`tests/test_quality.py`, and `tests/test_copy.py`.
`tests/test_quality.py`, `tests/test_retention.py`, and `tests/test_copy.py`.

- **Milestones** are delivery windows, not promises: M0 foundation, M1 data and
memory, M2 analysis, M3 forecast and review, M4 interface, M5 evaluation and
Expand Down
8 changes: 8 additions & 0 deletions docs/DATA_MODEL.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,14 @@ version. Predictions reference an artifact through the existing `model_version`
column using the `version@<artifact_id[:12]>` convention; no table or migration
is added. See `docs/FORECASTING.md` for replay rules.

## Retention and redaction

`core/janus/memory/retention.py` applies source/kind retention windows and
deletes only observations whose expiration is at or before `as_of`; a dry run
reports the same counts without writing. `redact_value` masks named fields at
any depth, and `export_redacted` writes JSONL without mutating stored facts.
The CLI exposes `janus retention apply` and `janus retention export`.

## As-of semantics

There are two questions, and two modes:
Expand Down
Loading
Loading