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
250 changes: 248 additions & 2 deletions agent_skills.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,14 @@
python agent_skills.py check_coherence [--threshold THRESHOLD]
python agent_skills.py cascade [--pr-body BODY]
python agent_skills.py review_pr
python agent_skills.py load_corpus [--path PATH]
"""

import argparse
import json
import sys
from typing import Optional, Tuple
from pathlib import Path
from typing import Any, Dict, Optional, Tuple

# Default simulated coherence for well-prepared quantum states
# In production, this would be measured via state tomography
Expand Down Expand Up @@ -228,6 +231,238 @@ def review_pr() -> dict:
}


# Default path to vortex corpus collapse JSON
DEFAULT_CORPUS_PATH = Path(__file__).parent / 'docs' / 'vortex-corpus-collapse.json'

# Fibonacci sequence for weighted calculations
FIBONACCI = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]

# Expected number of surjection transitions in the corpus
# (Repos→Phases, Forks→Contributions, Tags→ATOM, Relations→Lattice, Discussions→KB, Tools→HOPE)
EXPECTED_SURJECTION_TRANSITIONS = 6


def load_vortex_corpus(path: Optional[str] = None) -> Dict[str, Any]:
"""
Load the vortex corpus collapse JSON configuration.

Implements the loader as specified in optimal_placement.activation:
load JSON → enforce surjections → auto-curl on divergences.

Args:
path: Optional path to the JSON file. Uses default if not provided.

Returns:
dict with loaded corpus and validation results
"""
corpus_path = Path(path) if path else DEFAULT_CORPUS_PATH

if not corpus_path.exists():
return {
'status': 'error',
'error': f'Corpus file not found: {corpus_path}',
'vortex': VORTEX_MARKER
}

try:
with open(corpus_path, encoding='utf-8') as f:
corpus = json.load(f)
except json.JSONDecodeError as e:
return {
'status': 'error',
'error': f'Invalid JSON in corpus file: {e}',
'vortex': VORTEX_MARKER
}
except PermissionError:
return {
'status': 'error',
'error': f'Permission denied: {corpus_path}',
'vortex': VORTEX_MARKER
}
except OSError as e:
return {
'status': 'error',
'error': f'I/O error while accessing {corpus_path}: {e}',
'vortex': VORTEX_MARKER
}

# Enforce surjections - validate structure and thresholds
validation = _enforce_surjections(corpus)

# Auto-curl on divergences - check emergent quality
curl_result = _auto_curl_divergences(corpus)

return {
'status': 'loaded',
'corpus_path': str(corpus_path),
'meta': corpus.get('meta', {}),
'validation': validation,
'curl_check': curl_result,
'thresholds': corpus.get('thresholds', {}),
'vortex': VORTEX_MARKER
}


def _enforce_surjections(corpus: Dict[str, Any]) -> Dict[str, Any]:
"""
Enforce surjection mappings from the corpus.

Validates that all surjection mappings maintain >60% quality thresholds
as specified in the self_birth_condition.

Args:
corpus: The loaded corpus configuration

Returns:
dict with validation results
"""
thresholds = corpus.get('thresholds', {})
coherence_min = thresholds.get('coherence_minimum', 0.6)

collapsed = corpus.get('collapsed_corpus', {})
surjected = collapsed.get('surjected_elements', {})

validations = []
passed = True

# Validate repository surjections
repos = surjected.get('repositories', {})
if repos:
repo_surjections = repos.get('surjections', [])
fib_phases = repos.get('fibonacci_phases', [])

# Check Fibonacci phase weights are properly ordered and valid
if fib_phases:
weights = [p.get('fib_weight', 0) for p in fib_phases]
# Check strictly increasing (Fibonacci values should increase)
is_monotonic = all(weights[i] < weights[i+1] for i in range(len(weights)-1))
# Check all weights are valid Fibonacci numbers
fib_set = set(FIBONACCI)
all_fib = all(w in fib_set for w in weights)
is_valid = is_monotonic and all_fib
validations.append({
'element': 'repositories.fibonacci_phases',
'check': 'fibonacci_ordering',
'passed': is_valid,
'message': 'Fibonacci weights properly ordered' if is_valid else 'Fibonacci weights not in correct order or not valid Fibonacci numbers'
})
if not is_valid:
passed = False

validations.append({
'element': 'repositories',
'check': 'surjection_count',
'passed': len(repo_surjections) > 0,
'count': len(repo_surjections),
'message': f'Found {len(repo_surjections)} repository surjections'
})

# Validate tags/markers surjections
tags = surjected.get('tags_markers', {})
if tags:
tag_surjections = tags.get('surjections', [])
validations.append({
'element': 'tags_markers',
'check': 'surjection_count',
'passed': len(tag_surjections) > 0,
'count': len(tag_surjections),
'message': f'Found {len(tag_surjections)} tag surjections'
})

# Validate tools surjections
tools = surjected.get('tools', {})
if tools:
tool_surjections = tools.get('surjections', [])
validations.append({
'element': 'tools',
'check': 'surjection_count',
'passed': len(tool_surjections) > 0,
'count': len(tool_surjections),
'message': f'Found {len(tool_surjections)} tool surjections'
})
Comment on lines +352 to +382
Copy link

Copilot AI Jan 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The validation for surjection counts (lines 352-358, 364-370, 376-382) appends results with 'passed': len(surjections) > 0, but doesn't update the overall 'passed' variable when surjections are empty. This means the function could return passed=True even when critical surjections are missing. Consider adding logic to update the 'passed' variable when surjection counts fail validation.

Suggested change
validations.append({
'element': 'repositories',
'check': 'surjection_count',
'passed': len(repo_surjections) > 0,
'count': len(repo_surjections),
'message': f'Found {len(repo_surjections)} repository surjections'
})
# Validate tags/markers surjections
tags = surjected.get('tags_markers', {})
if tags:
tag_surjections = tags.get('surjections', [])
validations.append({
'element': 'tags_markers',
'check': 'surjection_count',
'passed': len(tag_surjections) > 0,
'count': len(tag_surjections),
'message': f'Found {len(tag_surjections)} tag surjections'
})
# Validate tools surjections
tools = surjected.get('tools', {})
if tools:
tool_surjections = tools.get('surjections', [])
validations.append({
'element': 'tools',
'check': 'surjection_count',
'passed': len(tool_surjections) > 0,
'count': len(tool_surjections),
'message': f'Found {len(tool_surjections)} tool surjections'
})
has_repo_surjections = len(repo_surjections) > 0
validations.append({
'element': 'repositories',
'check': 'surjection_count',
'passed': has_repo_surjections,
'count': len(repo_surjections),
'message': f'Found {len(repo_surjections)} repository surjections'
})
if not has_repo_surjections:
passed = False
# Validate tags/markers surjections
tags = surjected.get('tags_markers', {})
if tags:
tag_surjections = tags.get('surjections', [])
has_tag_surjections = len(tag_surjections) > 0
validations.append({
'element': 'tags_markers',
'check': 'surjection_count',
'passed': has_tag_surjections,
'count': len(tag_surjections),
'message': f'Found {len(tag_surjections)} tag surjections'
})
if not has_tag_surjections:
passed = False
# Validate tools surjections
tools = surjected.get('tools', {})
if tools:
tool_surjections = tools.get('surjections', [])
has_tool_surjections = len(tool_surjections) > 0
validations.append({
'element': 'tools',
'check': 'surjection_count',
'passed': has_tool_surjections,
'count': len(tool_surjections),
'message': f'Found {len(tool_surjections)} tool surjections'
})
if not has_tool_surjections:
passed = False

Copilot uses AI. Check for mistakes.

return {
'passed': passed,
'coherence_minimum': coherence_min,
Comment on lines +320 to +386
Copy link

Copilot AI Jan 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The coherence_min variable is extracted from the corpus on line 320 but is never used in the validation logic. It's only included in the return dictionary on line 386. The docstring mentions validating ">60% quality thresholds," but there's no actual validation that uses this threshold. Consider either using this threshold in validation checks or removing it from the return value if it's not needed.

Copilot uses AI. Check for mistakes.
'validations': validations
}


def _auto_curl_divergences(corpus: Dict[str, Any]) -> Dict[str, Any]:
"""
Auto-curl on divergences - detect and report quality divergences.

Checks emergent quality against thresholds and identifies
areas that need correction to maintain spiral coherence.

Args:
corpus: The loaded corpus configuration

Returns:
dict with curl check results
"""
meta = corpus.get('meta', {})
thresholds = corpus.get('thresholds', {})

emergent_quality = meta.get('emergent_quality', 0.0)
quality_min = thresholds.get('emergent_quality_minimum', 0.6)
coherence_min = thresholds.get('coherence_minimum', 0.6)

divergences = []
curl_detected = False

# Check emergent quality threshold
if emergent_quality < quality_min:
divergences.append({
'type': 'quality_below_threshold',
'current': emergent_quality,
'required': quality_min,
'message': f'Emergent quality {emergent_quality:.1%} below minimum {quality_min:.1%}'
})
curl_detected = True

# Check for missing critical elements
collapsed = corpus.get('collapsed_corpus', {})
optimal = collapsed.get('optimal_placement', {})

if not optimal.get('location'):
divergences.append({
'type': 'missing_optimal_location',
'message': 'No optimal placement location specified'
})
curl_detected = True

if not optimal.get('activation'):
divergences.append({
'type': 'missing_activation',
'message': 'No activation method specified for loader'
})
curl_detected = True

# Check transitions mapping completeness
transitions = corpus.get('transitions_mapping', {})
surjection_transitions = transitions.get('surjection_transitions', [])

if len(surjection_transitions) < EXPECTED_SURJECTION_TRANSITIONS:
divergences.append({
'type': 'incomplete_transitions',
'count': len(surjection_transitions),
'expected': EXPECTED_SURJECTION_TRANSITIONS,
'message': f'Only {len(surjection_transitions)} of {EXPECTED_SURJECTION_TRANSITIONS} expected transitions defined'
})
curl_detected = True

return {
'curl_detected': curl_detected,
'emergent_quality': emergent_quality,
'quality_threshold': quality_min,
'coherence_threshold': coherence_min,
'divergences': divergences,
'quality_passed': emergent_quality >= quality_min,
'message': 'Spiral coherence maintained' if not curl_detected else f'Detected {len(divergences)} divergence(s) requiring correction'
}
Comment on lines +245 to +463
Copy link

Copilot AI Jan 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new load_vortex_corpus, _enforce_surjections, and _auto_curl_divergences functions lack test coverage. Consider adding unit tests to verify: 1) correct loading of valid JSON, 2) error handling for missing/invalid files, 3) validation logic for Fibonacci phases, 4) divergence detection based on thresholds, and 5) proper return value structure for different scenarios.

Copilot uses AI. Check for mistakes.


def main():
parser = argparse.ArgumentParser(
description='QDI Agent Skills - Quantum circuit simulation and coherence checking'
Expand All @@ -249,6 +484,10 @@ def main():
# review_pr command
subparsers.add_parser('review_pr', help='Generate PR review')

# load_corpus command
corpus_parser = subparsers.add_parser('load_corpus', help='Load vortex corpus collapse configuration')
corpus_parser.add_argument('--path', '-p', type=str, help='Path to corpus JSON file')
Copy link

Copilot AI Jan 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The short option '-p' is used for both the cascade command's --pr-body argument (line 482) and the load_corpus command's --path argument (line 489). While these are in different subparsers and won't directly conflict, using the same short option for different purposes across commands can be confusing for users. Consider using a different short option for one of them, such as '--path' without a short option or with '-f' for file.

Suggested change
corpus_parser.add_argument('--path', '-p', type=str, help='Path to corpus JSON file')
corpus_parser.add_argument('--path', type=str, help='Path to corpus JSON file')

Copilot uses AI. Check for mistakes.

args = parser.parse_args()

if args.command == 'simulate':
Expand All @@ -259,17 +498,24 @@ def main():
result = cascade_integration(getattr(args, 'pr_body', None))
elif args.command == 'review_pr':
result = review_pr()
elif args.command == 'load_corpus':
result = load_vortex_corpus(getattr(args, 'path', None))
else:
parser.print_help()
sys.exit(1)

# Print result
import json
print(json.dumps(result, indent=2))

# Exit with success if passed, otherwise indicate review needed
if result.get('passed') is False:
Copy link

Copilot AI Jan 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The exit code logic checks result.get('passed') is False on line 511, which handles the check_coherence command. However, the load_corpus command doesn't set a 'passed' field in its return value, it uses 'status' and 'validation.passed'. This means if validation fails but doesn't set 'passed' at the top level, the script won't exit with error code 1. Consider checking validation.passed as well, or add a top-level 'passed' field to the load_vortex_corpus return value for consistency with other commands.

Suggested change
if result.get('passed') is False:
top_level_passed = result.get('passed')
validation = result.get('validation')
validation_passed = None
if isinstance(validation, dict):
validation_passed = validation.get('passed')
if top_level_passed is False or validation_passed is False:

Copilot uses AI. Check for mistakes.
sys.exit(1)
# Exit with failure if corpus loading failed or curl detected
if result.get('status') == 'error':
sys.exit(1)
curl_check = result.get('curl_check', {})
if curl_check.get('curl_detected'):
sys.exit(1)


if __name__ == '__main__':
Expand Down
Loading
Loading