Skip to content
Merged
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
11 changes: 11 additions & 0 deletions CONTEXT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# OSINT Forge domain language

**Mission supervisor**: The existing MissionSupervisor is the single owner of mission orchestration, governance gates, persistence and resumption.

**Mission status**: Operational progress of an OSINT mission. Completed and awaiting_review do not establish kernel approval.

**Kernel lifecycle state**: A review state in the shared execution contract. A normalized alias describes a recorded state; it does not authenticate a reviewer or grant authority.

**Ledger projection**: A read-only interpretation of validated ledger records and artifact bytes, retaining each original record and raw lifecycle alias.

**Plan readiness**: Metadata that a plan exists, separate from a review decision or authorization to execute.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,3 +203,6 @@ Keep GDELT as the only live-capable source until DOC-to-GEO enrichment and real
## License

Licensed under the [Apache License 2.0](LICENSE).

Read-only kernel ledger inspection: see [shared contract adapter](docs/SHARED_CONTRACT_ADAPTER.md)
for the shared human/agent command, synthetic fixture and validation boundaries.
74 changes: 74 additions & 0 deletions docs/SHARED_CONTRACT_ADAPTER.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Shared contract adapter: local candidate

Capability `ledger.project/v1` is a read-only local inspection command. Humans use
`python -m runner.shared_contract --project-root <local-root> --contract <trusted-execution_contract.py>`;
agents invoke that same command or `project_ledger(root, load_contract(path))`.
Both use the same validation and saved ledger. JSON stdout is the projection;
exit 2 and stderr describe invalid input. No partial result is emitted on failure.
## Trusted code boundary

`--contract` explicitly selects trusted executable Python code, not passive JSON.
Only existing `.py` files are accepted. Loading executes that file with the
caller's privileges; no sandbox is provided. Do not select an untrusted source.
There is no machine-specific default or automatic private kernel discovery.

## Validation order

The ledger is `.kernel_runs/ledger/artifact_ledger.jsonl` under the selected root.
Inspection assumes a trusted local root whose ledger paths and artifact files
are not being changed concurrently. Resolved-path checks reject static escapes;
they are not an OS sandbox or an atomic filesystem snapshot.
The entire hash chain is checked before projection. All referenced artifact files
must exist within the root and match their recorded SHA256. `record_type` maps to
`artifact_type`, `artifact_path` remains explicit (null for logical records), and
`StateTransition.payload.to_status` maps through shared normalization. Artifact
review statuses use metadata.status for RunState, MemoryCheckpoint, EvalResult
and ReviewPacket. Missing and unsupported lifecycle states fail closed. Other
artifact types carry no inferred lifecycle; ExecutionPlan's plan_ready remains
source metadata. Original records are retained as immutable JSON strings, and raw
aliases remain separate from canonical values. Returned dictionaries are detached
snapshots; changing one cannot change the ledger or future projections.

The saved synthetic fixture is `tests/fixtures/shared_contract/`: six records plus
four referenced files. Tests copy its exact bytes into disposable local roots,
then exercise the real ledger reader and adapter. No fixture approval is an owner
decision. To inspect manually, copy that directory to a disposable root and copy
artifact_ledger.jsonl into `.kernel_runs/ledger/` there, then run the command above.
Self-contained tests use a deliberately limited toy Python dependency, not an
export of the private shared kernel. These tests prove adapter behavior only.
For real-contract integration, explicitly set `OSINT_FORGE_TEST_CONTRACT` to a
trusted external `.py` file, then run `python -m unittest discover -s tests`.
Without that variable the external suite reports a skip (NOT RUN). If set to a
missing or invalid contract, integration fails rather than falling back.
All aliases supplied by the selected real contract are checked in that suite.

MissionSupervisor remains the single mission orchestrator. It owns governed tool
execution, budget/PII gates, persistence and resumption; HumanReviewGate owns its
existing review boundary. This adapter only inspects evidence and never supervises,
executes or records a review decision. Operational completed/awaiting_review states
are not kernel lifecycle aliases. Vector memory remains a non-production spike;
this change starts no ingestion or production connection.

Feature gates (local candidate):

| Gate | Result and evidence |
|---|---|
| 1 Shared capabilities | PASS: CLI/API parity and matching invalid-state rejection in test_cli_parity_and_error. |
| 2 Shared state | PASS for read-only inspection: same saved bytes, fresh reads and detached snapshots in test_saved_six_records_coverage_alias_and_immutable_source. No writes. |
| 3 Scoped authority | PARTIAL: static resolved-path confinement and saved-file integrity checked; local OS file access is the boundary. No verified application principal, grants or expiry; copied actor/status values convey no authority. |
| 4 Human usability | PASS for local CLI: AI-free command, JSON output, actionable stderr and nonzero error code exercised. Human acceptance NOT RUN. |
| 5-7 Supervision/recovery/receipts | NOT APPLICABLE: inspection causes no user-data writes or external effects. |

Hosted, browser, device and live ingestion evidence: NOT RUN. Owner acceptance remains pending. The prior independent bounded recheck was
reported VERIFIED; these portability edits still require review; no production or release completion claim.

## Local validation

Final portable suite: `python -m unittest discover -s tests` ran 169 tests,
OK with 25 skips (24 existing optional/runtime skips and one external-contract
class skip). Explicit trusted real-contract selection ran 32 adapter tests,
all passing: 16 synthetic and 16 external integration cases. These are local
Python results, not hosted, browser, device or human acceptance.

Fixture attributes preserve artifact bytes on checkout because SHA256 values
bind exact saved bytes, including line endings. The JSONL fixture is synthetic and contains no private paths.
90 changes: 90 additions & 0 deletions runner/shared_contract.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
"""Read-only, fail-closed projection of a validated local ledger into kernel terms."""
from __future__ import annotations

import argparse
import hashlib
import importlib.util
import json
import sys
from pathlib import Path

from runner.ledger import ArtifactLedger, ArtifactLedgerError


def load_contract(path: str | Path):
"""Load the explicitly selected shared contract; never copy or modify it."""
path = Path(path).expanduser().resolve(strict=True)
if not path.is_file() or path.suffix != ".py":
raise ArtifactLedgerError("trusted contract must be a Python .py file")
# WHY: docs/SHARED_CONTRACT_ADAPTER.md#trusted-code-boundary
spec = importlib.util.spec_from_file_location("osint_shared_execution_contract", path)
if spec is None or spec.loader is None:
raise ArtifactLedgerError("shared contract cannot be loaded")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module


def project_ledger(project_root: str | Path, contract) -> tuple[dict, ...]:
"""Validate the entire saved chain before projection; return detached snapshots.

Source JSON is retained as an immutable string. Lifecycle normalization is
descriptive only: a projection never authorizes execution or review.
"""
ledger = ArtifactLedger(project_root)
# WHY: docs/SHARED_CONTRACT_ADAPTER.md#validation-order
# The existing ledger reader validates records, but follows the ledger's
# path directly. Check its resolved target before any ledger bytes are read.
ledger._resolve_project_path(ledger.ledger_path, strict=False)
records = ledger.read_records()
projected = []
for record in records:
kind = record["record_type"]
if kind not in contract.VALID_ARTIFACT_TYPES:
raise ArtifactLedgerError(f"unknown artifact type: {kind}")
path = record.get("artifact_path")
if kind in {"RunState", "MemoryCheckpoint", "EvalResult", "ReviewPacket"}:
# These types attest saved files, unlike logical transition records.
# Rehashing a record must not make its file identity optional.
if not isinstance(path, str) or not path or not isinstance(record.get("artifact_sha256"), str):
raise ArtifactLedgerError(f"missing saved artifact identity: {kind}")
if path is not None:
resolved = ledger._resolve_project_path(Path(path), strict=True)
if not resolved.is_file() or hashlib.sha256(resolved.read_bytes()).hexdigest() != record["artifact_sha256"]:
raise ArtifactLedgerError(f"artifact integrity mismatch: {path}")
raw_state = None
if kind == "StateTransition":
raw_state = record.get("payload", {}).get("to_status")
# Missing states must go through the same strict shared validation.
state = contract.normalize_lifecycle_state(raw_state)
elif kind in {"RunState", "MemoryCheckpoint", "EvalResult", "ReviewPacket"}:
raw_state = record.get("metadata", {}).get("status")
state = contract.normalize_lifecycle_state(raw_state)
else:
state = None
projected.append({
"artifact_type": kind,
"artifact_path": path,
"lifecycle_state": state,
"raw_lifecycle_state": raw_state,
"source_record_json": json.dumps(record, sort_keys=True, separators=(",", ":")),
})
return tuple(projected)


def main(argv=None) -> int:
parser = argparse.ArgumentParser(description="Inspect a local kernel ledger (read only; no approval effects)")
parser.add_argument("--project-root", required=True)
parser.add_argument("--contract", required=True, help="Trusted local execution_contract.py")
args = parser.parse_args(argv)
try:
result = project_ledger(args.project_root, load_contract(args.contract))
except (ValueError, OSError, TypeError, AttributeError, SyntaxError, ImportError) as exc:
print(f"projection error: {exc}", file=sys.stderr)
return 2
print(json.dumps(result, indent=2, sort_keys=True))
return 0


if __name__ == "__main__":
raise SystemExit(main())
5 changes: 5 additions & 0 deletions tests/fixtures/shared_contract/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# These saved artifact hashes bind exact bytes, including line endings.
run_state.json -text whitespace=cr-at-eol
memory_checkpoint.json -text whitespace=cr-at-eol
eval_result.json -text whitespace=cr-at-eol
review_packet.md -text whitespace=cr-at-eol
6 changes: 6 additions & 0 deletions tests/fixtures/shared_contract/artifact_ledger.jsonl
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{"payload": {"live_ingestion_attempted": false, "synthetic": true}, "payload_sha256": "3f682068e467659cd3f97720d80cd18ee5176e52a8ab82b247bf551c87e7040e", "prev_record_hash": "0000000000000000000000000000000000000000000000000000000000000000", "record_hash": "ceb0ea4a014c1e72c06ca4ffa0c254f89126e52f9e2b56d5f0cab70f29a90204", "record_type": "ExecutionContract", "recorded_at": "2026-11-13T00:00:00Z", "run_id": "synthetic", "schema_version": "1.0", "sequence": 1}
{"artifact_path": "run_state.json", "artifact_sha256": "3b8d05ad6bd07d2a5c61ab034a3a230e1fbb6b89f4dfa11167e9b66a6dfc40bd", "metadata": {"status": "needs_human_approval"}, "prev_record_hash": "ceb0ea4a014c1e72c06ca4ffa0c254f89126e52f9e2b56d5f0cab70f29a90204", "record_hash": "cb4631c03083153e00625d9deb6c651ddc06aa3d33a44bf92d55a03b01708932", "record_type": "RunState", "recorded_at": "2026-11-13T00:00:00Z", "run_id": "synthetic", "schema_version": "1.0", "sequence": 2}
{"artifact_path": "memory_checkpoint.json", "artifact_sha256": "3b8d05ad6bd07d2a5c61ab034a3a230e1fbb6b89f4dfa11167e9b66a6dfc40bd", "metadata": {"status": "needs_human_approval"}, "prev_record_hash": "cb4631c03083153e00625d9deb6c651ddc06aa3d33a44bf92d55a03b01708932", "record_hash": "e845e84e6f794b2ae82d8fcffcc0d5e65c3c804948712381055a4fb17c8c933b", "record_type": "MemoryCheckpoint", "recorded_at": "2026-11-13T00:00:00Z", "run_id": "synthetic", "schema_version": "1.0", "sequence": 3}
{"artifact_path": "eval_result.json", "artifact_sha256": "3b8d05ad6bd07d2a5c61ab034a3a230e1fbb6b89f4dfa11167e9b66a6dfc40bd", "metadata": {"status": "needs_human_approval"}, "prev_record_hash": "e845e84e6f794b2ae82d8fcffcc0d5e65c3c804948712381055a4fb17c8c933b", "record_hash": "d04e1f863a39875b21d87f440220c038e28b3b9226a3abb6a64880fb001dddf0", "record_type": "EvalResult", "recorded_at": "2026-11-13T00:00:00Z", "run_id": "synthetic", "schema_version": "1.0", "sequence": 4}
{"artifact_path": "review_packet.md", "artifact_sha256": "87deb04cd2b773d247dbc354aac96e0c9d228d41c38002fc89efc83bf1529a7b", "metadata": {"status": "needs_human_approval"}, "prev_record_hash": "d04e1f863a39875b21d87f440220c038e28b3b9226a3abb6a64880fb001dddf0", "record_hash": "9dface4191c0af0e566c907f91fbc734b42d3a406cb12cf49fced917a3839312", "record_type": "ReviewPacket", "recorded_at": "2026-11-13T00:00:00Z", "run_id": "synthetic", "schema_version": "1.0", "sequence": 5}
{"payload": {"from_status": "none", "to_status": "needs_human_approval"}, "payload_sha256": "ca8df698690157fab90db9284b988fa1c415c0dfd3a72a01a2a3c7219703405d", "prev_record_hash": "9dface4191c0af0e566c907f91fbc734b42d3a406cb12cf49fced917a3839312", "record_hash": "5a1b861671bfe55803ae6823259a5dcb0ea8de2d41ae862e999f1d4488f2d6bf", "record_type": "StateTransition", "recorded_at": "2026-11-13T00:00:00Z", "run_id": "synthetic", "schema_version": "1.0", "sequence": 6}
1 change: 1 addition & 0 deletions tests/fixtures/shared_contract/eval_result.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"synthetic":true,"status":"needs_human_approval"}
1 change: 1 addition & 0 deletions tests/fixtures/shared_contract/memory_checkpoint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"synthetic":true,"status":"needs_human_approval"}
1 change: 1 addition & 0 deletions tests/fixtures/shared_contract/review_packet.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Synthetic review fixture
1 change: 1 addition & 0 deletions tests/fixtures/shared_contract/run_state.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"synthetic":true,"status":"needs_human_approval"}
14 changes: 14 additions & 0 deletions tests/fixtures/shared_contract/synthetic_contract.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"""Toy adapter dependency for isolated tests, NOT the shared execution kernel.

Only the fixture vocabulary is supported. Real conformance requires the separate
explicitly selected external-contract integration suite.
"""
VALID_ARTIFACT_TYPES = frozenset('ExecutionContract RunState MemoryCheckpoint EvalResult ReviewPacket StateTransition ExecutionPlan'.split())
REQUIRED_DRY_RUN_ARTIFACT_TYPES = ('RunState', 'MemoryCheckpoint', 'EvalResult', 'ReviewPacket')
LIFECYCLE_ALIASES = {'needs_human_approval': 'needs_review'}


def normalize_lifecycle_state(state):
if not isinstance(state, str) or state not in ('needs_review', 'needs_human_approval'):
raise ValueError('unsupported lifecycle state in synthetic test dependency')
return LIFECYCLE_ALIASES.get(state, state)
Loading
Loading