-
Notifications
You must be signed in to change notification settings - Fork 0
[codex] Add loop decision memory export #31
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
Binary file not shown.
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1 @@ | ||
| {"claim_count":4601,"claim_extracted_at":"2026-07-01T02:48:05Z","concept_count":875,"context_pack_count":0,"edge_count":1899,"enrichment_run_count":2,"eval_case_count":53,"eval_result_count":53,"insight_decision_count":3,"insight_label_count":3,"insight_policy_version":"agent_core_insight_v1","learning_event_count":4,"learning_ledger_version":"learning_ledger_v1","learning_review_count":0,"observation_count":2,"policy_decision_count":0,"policy_version":"knowledge_policy_v1","quality_finding_count":42,"retrieval_version":"retrieval_v1","run_id":"local-20260701024805","source_ref_count":1020,"source_shas":{}} | ||
| {"claim_count":4601,"claim_extracted_at":"2026-07-02T21:26:39Z","concept_count":875,"context_pack_count":0,"edge_count":1899,"enrichment_run_count":2,"eval_case_count":53,"eval_result_count":53,"insight_decision_count":3,"insight_label_count":3,"insight_policy_version":"agent_core_insight_v1","learning_event_count":4,"learning_ledger_version":"learning_ledger_v1","learning_review_count":0,"loop_decision_envelope_count":0,"loop_decision_memory_version":"agent_core_loop_decision_v1","observation_count":2,"policy_decision_count":0,"policy_version":"knowledge_policy_v1","quality_finding_count":42,"retrieval_version":"retrieval_v1","run_id":"local-20260702212639","source_ref_count":1020,"source_shas":{}} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| """Shared memory helpers for loop decision envelopes.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import sqlite3 | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| from agent_core.arbiter import arbitrate_cross_loop_event | ||
| from agent_core.contracts import LoopDecisionEnvelope | ||
|
|
||
| from .learning_ledger import _forbidden_payload_findings | ||
|
|
||
| DEFAULT_LOOP_DECISION_PATHS = (Path("reports/loop-decision-envelopes.jsonl"),) | ||
|
|
||
|
|
||
| class LoopDecisionMemoryError(ValueError): | ||
| """Raised when imported loop decision records are malformed or unsafe.""" | ||
|
|
||
|
|
||
| def load_loop_decision_envelopes(paths: list[Path] | None = None) -> list[dict[str, Any]]: | ||
| rows: list[dict[str, Any]] = [] | ||
| for path in paths or list(DEFAULT_LOOP_DECISION_PATHS): | ||
| for row in _read_rows(path): | ||
| if not isinstance(row, dict): | ||
| raise LoopDecisionMemoryError(f"loop decision row must be an object: {path}") | ||
| if not row.get("created_at"): | ||
| raise LoopDecisionMemoryError(f"loop decision row must include created_at for deterministic export: {path}") | ||
| findings = _forbidden_payload_findings(row) | ||
| if findings: | ||
| raise LoopDecisionMemoryError(f"unsafe loop decision row in {path}: {'; '.join(findings)}") | ||
| rows.append(LoopDecisionEnvelope.model_validate(row).model_dump(mode="json")) | ||
| return sorted(rows, key=lambda row: (str(row.get("fingerprint") or ""), str(row.get("envelope_id") or ""))) | ||
|
|
||
|
|
||
| def query_loop_decision_envelopes( | ||
| db_path: Path, | ||
| *, | ||
| fingerprint: str | None = None, | ||
| loop: str | None = None, | ||
| limit: int = 50, | ||
| ) -> list[dict[str, Any]]: | ||
| clauses: list[str] = [] | ||
| params: list[Any] = [] | ||
| if fingerprint: | ||
| clauses.append("fingerprint = ?") | ||
| params.append(fingerprint) | ||
| if loop: | ||
| clauses.append("loop = ?") | ||
| params.append(loop) | ||
| where = f" WHERE {' AND '.join(clauses)}" if clauses else "" | ||
| params.append(max(1, min(limit, 500))) | ||
| conn = sqlite3.connect(db_path) | ||
| conn.row_factory = sqlite3.Row | ||
| try: | ||
| rows = conn.execute( | ||
| f""" | ||
| SELECT envelope_id, loop, created_at, fingerprint, decision, insight_id, | ||
| case_id, meta_case_id, evidence_refs_json, proposed_action_json, | ||
| human_outcome_json, governance_json, body_json | ||
| FROM loop_decision_envelopes | ||
| {where} | ||
| ORDER BY created_at DESC, envelope_id ASC | ||
| LIMIT ? | ||
| """, | ||
| params, | ||
| ).fetchall() | ||
| finally: | ||
| conn.close() | ||
| return [_row_json(row) for row in rows] | ||
|
|
||
|
|
||
| def shadow_arbitrate_loop_decisions( | ||
| db_path: Path, | ||
| *, | ||
| fingerprint: str, | ||
| limit: int = 50, | ||
| ) -> dict[str, Any]: | ||
| rows = query_loop_decision_envelopes(db_path, fingerprint=fingerprint, limit=limit) | ||
| candidates = [_arbiter_candidate(row) for row in rows] | ||
| evidence_refs = [] | ||
| for row in rows: | ||
| evidence_refs.extend(row.get("evidence_refs", [])) | ||
| decision = arbitrate_cross_loop_event( | ||
| event_fingerprint=fingerprint, | ||
| candidates=candidates, | ||
| evidence_refs=evidence_refs, | ||
| ) | ||
| return { | ||
| "shadow_mode": True, | ||
| "suppression_applied": False, | ||
| "candidate_count": len(candidates), | ||
| "arbiter_decision": decision.model_dump(mode="json"), | ||
| } | ||
|
|
||
|
|
||
| def _read_rows(path: Path) -> list[Any]: | ||
| if not path.exists(): | ||
| return [] | ||
| text = path.read_text(encoding="utf-8").strip() | ||
| if not text: | ||
| return [] | ||
| if path.suffix == ".json": | ||
| loaded = json.loads(text) | ||
| if isinstance(loaded, list): | ||
| return loaded | ||
| if isinstance(loaded, dict) and isinstance(loaded.get("loop_decision_envelopes"), list): | ||
| return list(loaded["loop_decision_envelopes"]) | ||
| if isinstance(loaded, dict): | ||
| return [loaded] | ||
| return [] | ||
| return [json.loads(line) for line in text.splitlines() if line.strip()] | ||
|
|
||
|
|
||
| def _row_json(row: sqlite3.Row) -> dict[str, Any]: | ||
| result = dict(row) | ||
| for key in ("evidence_refs_json", "proposed_action_json", "human_outcome_json", "governance_json", "body_json"): | ||
| output_key = key.removesuffix("_json") | ||
| result[output_key] = json.loads(str(result.pop(key) or "{}")) | ||
| return result | ||
|
|
||
|
|
||
| def _arbiter_candidate(row: dict[str, Any]) -> dict[str, Any]: | ||
| body = row.get("body") | ||
| candidate = body if isinstance(body, dict) else {} | ||
| proposed = row.get("proposed_action") | ||
| return { | ||
| **candidate, | ||
| "loop": row.get("loop") or candidate.get("loop"), | ||
| "action_selected": row.get("decision") or candidate.get("decision"), | ||
| "case_id": row.get("case_id") or candidate.get("case_id"), | ||
| "meta_case_id": row.get("meta_case_id") or candidate.get("meta_case_id"), | ||
| "candidate_type": candidate.get("candidate_type") or (proposed.get("type") if isinstance(proposed, dict) else None), | ||
| "candidate_source": candidate.get("candidate_source") or candidate.get("policy_version"), | ||
| "proposed_action": proposed, | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When
loop-decisionsorloop-arbiter-shadowis run beforeexports/knowledge.sqliteexists, or with a config pointing at the wrong exports directory,sqlite3.connect(db_path)creates a brand-new empty SQLite file and then the SELECT fails withno such table. That leaves a bogus export DB on disk and breaks the read-only query behavior used elsewhere byKnowledgeStore; check existence and/or open the database with SQLite URImode=roinstead.Useful? React with 👍 / 👎.