diff --git a/CONTEXT.md b/CONTEXT.md new file mode 100644 index 0000000..b99c16d --- /dev/null +++ b/CONTEXT.md @@ -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. diff --git a/README.md b/README.md index 109191d..1404d45 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/docs/SHARED_CONTRACT_ADAPTER.md b/docs/SHARED_CONTRACT_ADAPTER.md new file mode 100644 index 0000000..b09da5f --- /dev/null +++ b/docs/SHARED_CONTRACT_ADAPTER.md @@ -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 --contract `; +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. diff --git a/runner/shared_contract.py b/runner/shared_contract.py new file mode 100644 index 0000000..f1a56c4 --- /dev/null +++ b/runner/shared_contract.py @@ -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()) diff --git a/tests/fixtures/shared_contract/.gitattributes b/tests/fixtures/shared_contract/.gitattributes new file mode 100644 index 0000000..da6ce1d --- /dev/null +++ b/tests/fixtures/shared_contract/.gitattributes @@ -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 diff --git a/tests/fixtures/shared_contract/artifact_ledger.jsonl b/tests/fixtures/shared_contract/artifact_ledger.jsonl new file mode 100644 index 0000000..db2ccd0 --- /dev/null +++ b/tests/fixtures/shared_contract/artifact_ledger.jsonl @@ -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} diff --git a/tests/fixtures/shared_contract/eval_result.json b/tests/fixtures/shared_contract/eval_result.json new file mode 100644 index 0000000..29886f7 --- /dev/null +++ b/tests/fixtures/shared_contract/eval_result.json @@ -0,0 +1 @@ +{"synthetic":true,"status":"needs_human_approval"} diff --git a/tests/fixtures/shared_contract/memory_checkpoint.json b/tests/fixtures/shared_contract/memory_checkpoint.json new file mode 100644 index 0000000..29886f7 --- /dev/null +++ b/tests/fixtures/shared_contract/memory_checkpoint.json @@ -0,0 +1 @@ +{"synthetic":true,"status":"needs_human_approval"} diff --git a/tests/fixtures/shared_contract/review_packet.md b/tests/fixtures/shared_contract/review_packet.md new file mode 100644 index 0000000..d681989 --- /dev/null +++ b/tests/fixtures/shared_contract/review_packet.md @@ -0,0 +1 @@ +Synthetic review fixture diff --git a/tests/fixtures/shared_contract/run_state.json b/tests/fixtures/shared_contract/run_state.json new file mode 100644 index 0000000..29886f7 --- /dev/null +++ b/tests/fixtures/shared_contract/run_state.json @@ -0,0 +1 @@ +{"synthetic":true,"status":"needs_human_approval"} diff --git a/tests/fixtures/shared_contract/synthetic_contract.py b/tests/fixtures/shared_contract/synthetic_contract.py new file mode 100644 index 0000000..aa09023 --- /dev/null +++ b/tests/fixtures/shared_contract/synthetic_contract.py @@ -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) diff --git a/tests/test_shared_contract.py b/tests/test_shared_contract.py new file mode 100644 index 0000000..b15252b --- /dev/null +++ b/tests/test_shared_contract.py @@ -0,0 +1,182 @@ +from __future__ import annotations +import contextlib +import os +import io +import json +from pathlib import Path +import shutil +import tempfile +import unittest +from runner.ledger import ArtifactLedger, ArtifactLedgerError, LEDGER_RELATIVE_PATH +from runner.shared_contract import load_contract, project_ledger, main + +FIXTURE = Path(__file__).parent / 'fixtures/shared_contract' + +class SharedContractTests(unittest.TestCase): + contract_path = FIXTURE / "synthetic_contract.py" + @classmethod + def setUpClass(cls): + cls.contract = load_contract(cls.contract_path) + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + shutil.copytree(FIXTURE, self.root, dirs_exist_ok=True) + target = self.root / LEDGER_RELATIVE_PATH + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(self.root / 'artifact_ledger.jsonl', target) + self.ledger = ArtifactLedger(self.root) + + def rewrite(self, change): + records = self.ledger.read_records() + change(records) + self.ledger.ledger_path.unlink() + for r in records: + if 'payload' in r: + r.update(self.ledger.logical_record(record_type=r['record_type'], run_id=r['run_id'], recorded_at=r['recorded_at'],payload=r['payload'])) + self.ledger.append_records(records) + + def test_saved_six_records_coverage_alias_and_immutable_source(self): + before = self.ledger.ledger_path.read_bytes() + rows = project_ledger(self.root, self.contract) + self.assertEqual(len(rows), 6) + self.assertTrue(set(self.contract.REQUIRED_DRY_RUN_ARTIFACT_TYPES) <= {r['artifact_type'] for r in rows}) + for source, row in zip(self.ledger.read_records(), rows): + self.assertEqual(json.loads(row['source_record_json']), source) + self.assertEqual(row['artifact_path'], source.get('artifact_path')) + self.assertEqual(rows[-1]['raw_lifecycle_state'], 'needs_human_approval') + self.assertEqual(rows[-1]['lifecycle_state'], 'needs_review') + rows[-1]['lifecycle_state'] = 'approved' + self.assertEqual(project_ledger(self.root,self.contract)[-1]['lifecycle_state'],'needs_review') + self.assertEqual(self.ledger.ledger_path.read_bytes(), before) + + def test_all_shared_aliases(self): + for alias, expected in self.contract.LIFECYCLE_ALIASES.items(): + with self.subTest(alias=alias): + self.rewrite(lambda rs: rs[-1]['payload'].update(to_status=alias)) + row = project_ledger(self.root,self.contract)[-1] + self.assertEqual(row['raw_lifecycle_state'],alias) + self.assertEqual(row['lifecycle_state'],expected) + + def test_invalid_missing_and_mission_states_fail_closed(self): + for state in [None, '', 'bogus', 'completed', 'awaiting_review', 'plan_ready', ' approved']: + with self.subTest(state=state): + self.rewrite(lambda rs: rs[-1]['payload'].update(to_status=state)) + with self.assertRaises(ValueError): project_ledger(self.root,self.contract) + self.rewrite(lambda rs: rs[-1]['payload'].pop('to_status')) + with self.assertRaises(ValueError): project_ledger(self.root,self.contract) + + def test_missing_artifact_state(self): + self.rewrite(lambda rs: rs[1]['metadata'].pop('status')) + with self.assertRaises(ValueError): project_ledger(self.root,self.contract) + + def test_unknown_type(self): + self.rewrite(lambda rs: rs[-1].update(record_type='Unknown')) + with self.assertRaisesRegex(ArtifactLedgerError,'unknown artifact'): project_ledger(self.root,self.contract) + + def test_chain_tamper_precedes_projection(self): + path = self.ledger.ledger_path + path.write_bytes(path.read_bytes().replace(b'needs_human_approval',b'owner_approved',1)) + with self.assertRaisesRegex(ArtifactLedgerError,'hash'): project_ledger(self.root,self.contract) + + def test_artifact_tamper_and_missing_file(self): + path = self.root / 'review_packet.md' + path.write_text('tampered',encoding='utf-8') + with self.assertRaisesRegex(ArtifactLedgerError,'integrity'): project_ledger(self.root,self.contract) + path.unlink() + with self.assertRaises((OSError,ArtifactLedgerError)): project_ledger(self.root,self.contract) + + def test_plan_ready_is_metadata_only(self): + self.rewrite(lambda rs: rs[1].update(record_type='ExecutionPlan',metadata={'status':'plan_ready'})) + row = project_ledger(self.root,self.contract)[1] + self.assertIsNone(row['lifecycle_state']) + self.assertEqual(json.loads(row['source_record_json'])['metadata']['status'],'plan_ready') + + def test_cli_parity_and_error(self): + args = ['--project-root',str(self.root),'--contract',str(self.contract_path)] + with contextlib.redirect_stdout(io.StringIO()) as out: + self.assertEqual(main(args),0) + self.assertEqual(json.loads(out.getvalue()),list(project_ledger(self.root,self.contract))) + self.rewrite(lambda rs: rs[-1]['payload'].update(to_status='completed')) + with contextlib.redirect_stderr(io.StringIO()) as err: + self.assertEqual(main(args),2) + self.assertIn('unsupported lifecycle',err.getvalue()) + + def test_actual_runner_saved_artifacts_project(self): + from runner.harness import GovernedSkillRunner + shutil.copytree(Path(__file__).parents[1] / 'schemas', self.root / 'schemas') + skill = self.root / 'sample_skill.md' + shutil.copyfile(Path(__file__).parent / 'fixtures/runner/sample_skill.md', skill) + self.ledger.ledger_path.unlink() + result = GovernedSkillRunner(self.root).run(skill) + rows = project_ledger(self.root, self.contract) + self.assertEqual(len(rows),6) + self.assertEqual(rows[-1]['lifecycle_state'],'needs_review') + self.assertEqual(rows[1]['artifact_path'],f'runs/{result.run_id}/run_state.json') + + def test_file_backed_records_require_identity(self): + original = self.ledger.read_records() + for kind in ('RunState', 'MemoryCheckpoint', 'EvalResult', 'ReviewPacket'): + for value in ('missing', None): + with self.subTest(kind=kind, value=value): + records = json.loads(json.dumps(original)) + record = next(r for r in records if r['record_type'] == kind) + if value == 'missing': + record.pop('artifact_path') + record.pop('artifact_sha256') + else: + record['artifact_path'] = None + record['artifact_sha256'] = None + self.ledger.ledger_path.unlink() + self.ledger.append_records(records) + with self.assertRaisesRegex(ArtifactLedgerError, 'artifact identity'): + project_ledger(self.root, self.contract) + + def test_ledger_file_cannot_escape_through_symlink(self): + with tempfile.TemporaryDirectory() as outside: + target = Path(outside) / 'ledger.jsonl' + shutil.copyfile(self.ledger.ledger_path, target) + self.ledger.ledger_path.unlink() + self.ledger.ledger_path.symlink_to(target) + with self.assertRaisesRegex(ArtifactLedgerError, 'escapes project root'): + project_ledger(self.root, self.contract) + + def test_ledger_parent_cannot_escape_through_symlink(self): + with tempfile.TemporaryDirectory() as outside: + target = Path(outside) / 'ledger' + shutil.move(str(self.ledger.ledger_path.parent), target) + self.ledger.ledger_path.parent.symlink_to(target, target_is_directory=True) + with self.assertRaisesRegex(ArtifactLedgerError, 'escapes project root'): + project_ledger(self.root, self.contract) + + def test_absent_local_ledger_remains_empty(self): + self.ledger.ledger_path.unlink() + self.assertEqual(project_ledger(self.root, self.contract), ()) + + def test_missing_and_invalid_contract_selection(self): + broken = self.root / 'broken.py' + broken.write_text('def invalid syntax', encoding='utf-8') + for selected in (self.root / 'absent.py', self.root, self.root / 'review_packet.md', broken): + with self.subTest(path=selected), contextlib.redirect_stderr(io.StringIO()), contextlib.redirect_stdout(io.StringIO()) as out: + self.assertEqual(main(['--project-root', str(self.root), '--contract', str(selected)]), 2) + self.assertEqual(out.getvalue(), '') + + def test_entire_chain_validated_before_projection(self): + records = self.ledger.read_records() + records[-1]['prev_record_hash'] = 'broken' + self.ledger.ledger_path.write_text('\n'.join(json.dumps(r) for r in records)+'\n',encoding='utf-8') + with self.assertRaisesRegex(ArtifactLedgerError, 'chain'): + project_ledger(self.root,self.contract) + + +class ExternalContractIntegrationTests(SharedContractTests): + """Repeat behavior checks against an explicitly supplied trusted real contract.""" + + @classmethod + def setUpClass(cls): + selected = os.environ.get("OSINT_FORGE_TEST_CONTRACT") + if not selected: + raise unittest.SkipTest("real-contract integration NOT RUN: set OSINT_FORGE_TEST_CONTRACT to trusted Python contract") + cls.contract_path = Path(selected) + super().setUpClass() # An explicitly selected missing/broken contract fails.