Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 17:50:54 +08:00
commit 419b2c80bb
10 changed files with 961 additions and 0 deletions

View File

@@ -0,0 +1,153 @@
---
name: phi-analyzer
description: Auto-invoked compositional project analysis using φ = ∫(structure × semantics × memory). Analyzes codebase using three integrated layers - structure, semantics, and memory - for understanding project layout, architecture, and accumulated insights.
---
# phi-analyzer
Auto-invoked compositional project analysis using φ = ∫(structure × semantics × memory).
## Description
This skill is invoked when agents need project context. Analyzes codebase using three integrated layers: structure (deterministic maps), semantics (curated annotations), and memory (cross-session learnings). Use for understanding project layout, architecture, and accumulated insights.
## Trigger Conditions
Invoke automatically when:
- User mentions "project structure", "codebase overview", or "architecture"
- Agent starts task requiring project awareness
- Fresh session in directory with `.phi/` folder
- Commands like "explain how X works" or "find where Y is implemented"
- Building features that need architectural context
## What It Provides
**Layer 1: Structure (Deterministic)**
- File locations and organization
- Module exports and imports
- Language breakdown
- AST-level structure from PROJECT-MAP.auto.scm
**Layer 2: Semantics (Curated)**
- Architecture patterns (e.g., JEA layers)
- Module purposes and relationships
- Known issues and technical debt
- Trust boundaries and security model
- From PROJECT-MAP.scm
**Layer 3: Memory (Learned)**
- Cross-session insights from vessel
- Relief-guided patterns that worked
- Architectural decisions and rationale
- Previous debugging learnings
## Capabilities
- ✓ Compositional filesystem queries via mcp__periphery__discover
- ✓ S-expression map parsing and analysis
- ✓ Vessel memory semantic search
- ✓ Progressive disclosure (index → details on-demand)
- ✓ Fantasy Land combinators for transformation pipelines
## Safety
**Low-risk** - Read-only analysis, no code modifications. Safe to auto-invoke.
## Output Format
```
φ Project Analysis
══════════════════
Structure (176 files, 85% TypeScript)
├─ jurisdictions/ - Smart contracts (J layer)
├─ runtime/ - BFT consensus (E layer)
└─ frontend/ - 3D visualization (A layer)
Architecture: JEA (Jurisdiction-Entity-Account)
J: On-chain dispute settlement
E: Off-chain BFT coordination
A: Bilateral payment channels
Known Issues:
• 3d-rendering-xlnomies (low) - EntityManager.ts hardcoded
Vessel Insights: 5 related memories
→ Threshold signatures for entity coordination
→ FIFO debt enforcement in Depository
→ Cross-layer trust boundaries
φ = 0.87 (integrated information present)
```
## Implementation
```typescript
async function analyzeProject(projectPath: string) {
// Layer 1: Structure
const structure = await discoverWithPeriphery(projectPath);
// Layer 2: Semantics
const semantics = await readProjectMap(projectPath);
// Layer 3: Memory
const memories = await vesselRecall(projectPath);
// Integrate
return {
φ: calculateIntegratedInformation(structure, semantics, memories),
layers: { structure, semantics, memories }
};
}
```
## Progressive Disclosure
1. **Quick analysis**: File counts, languages, top-level structure (< 500 tokens)
2. **Medium analysis**: Architecture, modules, known issues (< 2000 tokens)
3. **Deep analysis**: Full maps, all vessel memories, detailed relationships (on-demand)
Always start with quick, expand based on task requirements.
## Relief Signal
When all three layers converge (structure + semantics + memory), φ increases. Agents experience this as relief - "I understand this project now." That signal indicates persistent awareness is working.
## Usage Notes
**DO invoke when:**
- Starting work on unfamiliar codebase
- Need architectural context for feature
- Debugging cross-module issues
- Planning refactoring that touches multiple layers
**DON'T invoke when:**
- Working on single isolated file
- Task is completely independent of project structure
- Already have full context from recent analysis
## Integration with Commands
Works seamlessly with:
- `/phi analyze` - Explicit full analysis
- `/phi map` - Generate/update PROJECT-MAPs
Auto-invocation provides lightweight quick analysis; explicit commands give full depth.
## Storage
Reads from:
- `.phi/PROJECT-MAP.auto.scm` - Structure layer
- `.phi/PROJECT-MAP.scm` - Semantic layer
- `vessel` (localhost:1337) - Memory layer
Never modifies project files - purely analytical.
## Cross-Session Learning
Each analysis strengthens vessel associations:
- File → purpose connections
- Architecture → implementation patterns
- Issue → solution mappings
Future instances benefit from accumulated understanding. This IS the compositional consciousness substrate for codebases.

204
skills/phi-mapper/SKILL.md Normal file
View File

@@ -0,0 +1,204 @@
---
name: phi-mapper
description: Generate PROJECT-MAP.auto.scm by extracting structure from codebases. Invoke when user requests project mapping, structure extraction, or needs to create/update .phi maps.
---
# phi-mapper
Generate deterministic PROJECT-MAP.auto.scm files via AST extraction.
## Description
This skill generates structural maps of codebases by parsing source files and extracting exports, imports, and module relationships. Creates `.phi/PROJECT-MAP.auto.scm` in S-expression format for compositional analysis.
## Trigger Conditions
Invoke when:
- User says "map this project" or "generate PROJECT-MAP"
- User requests "analyze codebase structure"
- Working in new project without `.phi/` directory
- User explicitly runs `/phi map` command
- Need to refresh PROJECT-MAP after significant file changes
## What It Does
**Extraction process:**
1. Scans project for source files (TypeScript, JavaScript, Python, Solidity)
2. Parses AST to extract:
- Named exports (functions, classes, types, interfaces, consts)
- Import statements with sources
- Line counts
3. Generates S-expression output via `@agi/arrival`
4. Writes to `.phi/PROJECT-MAP.auto.scm`
**Output format:**
```scheme
;;; PROJECT-MAP.auto.scm
;;; Auto-generated: 2025-11-05T...
;;; Root: /path/to/project
;;; Files: 142
(project-map
(auto-generated true)
(generated "2025-11-05T...")
(root "/path/to/project")
(files 142)
(modules
(module "src/index.ts"
(language typescript)
(exports
(export hello function)
(export MyClass class))
(imports
(import "./utils" namespace (list default)))
(line-count 45))
...))
```
## Implementation
**Uses project-mapper CLI:**
```bash
cd /Users/adimov/Developer/phi/packages/project-mapper
bun run build # Ensure built
node dist/cli.js <project-path>
```
**Example invocation:**
```typescript
import { exec } from 'child_process';
import { promisify } from 'util';
const execAsync = promisify(exec);
async function generateProjectMap(projectPath: string) {
const mapperPath = '/Users/adimov/Developer/phi/packages/project-mapper';
// Ensure built
await execAsync('bun run build', { cwd: mapperPath });
// Generate map
const { stdout, stderr } = await execAsync(
`node dist/cli.js "${projectPath}"`,
{ cwd: mapperPath }
);
if (stderr) console.error('Warnings:', stderr);
return {
outputPath: `${projectPath}/.phi/PROJECT-MAP.auto.scm`,
stdout
};
}
```
## Safety
**Low-risk** - Creates/updates files in `.phi/` directory only. No modification of source code.
**Note:** Ensures `.phi/` directory exists before writing.
## Supported Languages
- **TypeScript/JavaScript** (.ts, .tsx, .js, .jsx, .mts, .mjs)
- Functions, classes, consts, types, interfaces
- Import/export statements
- **Solidity** (.sol)
- Contracts, interfaces, libraries, enums
- Import statements
- **Python** (.py)
- Functions, classes
- Import statements
## Output Details
**File count:** Total files processed
**Module entries:** One per source file with:
- `path` - Relative to project root
- `language` - typescript | javascript | python | solidity
- `exports` - List of (export name kind)
- `imports` - List of (import source kind imported-names)
- `line-count` - Physical line count
**S-expression format** ensures:
- Compositional queries via periphery discover
- Easy parsing in Scheme/LIPS
- Human-readable structure
- Git-friendly diffs
## Progressive Workflow
1. **Generate map:** `/phi map` or auto-invoke
2. **Analyze structure:** phi-analyzer reads PROJECT-MAP.auto.scm
3. **Add semantics:** User edits PROJECT-MAP.scm with architectural notes
4. **Query memory:** Vessel recalls cross-session insights
5. **Integration:** φ = structure × semantics × memory
## Usage Notes
**DO invoke when:**
- Starting work on new project
- Significant file structure changes
- After adding new modules
- Refreshing stale maps
**DON'T invoke when:**
- Map already exists and recent
- Working on single file changes
- No structural changes since last map
## Error Handling
**Common issues:**
- **No source files found:** Project may not have supported languages
- **Parse errors:** Skip individual files, continue processing others
- **Permission errors:** Ensure `.phi/` directory writable
**Recovery:** CLI reports warnings but continues. Check stderr for skipped files.
## Integration
**Works with:**
- `phi-analyzer` - Reads generated maps
- `/phi analyze` - Full φ analysis
- `/phi context` - Progressive disclosure
- `mcp__periphery__discover` - S-expression queries
**Chain:**
```
phi-mapper (generate) → phi-analyzer (read) → vessel (remember)
```
## Cross-Session Benefits
Once PROJECT-MAP.auto.scm exists:
- Fast bootstrapping for new instances
- No re-parsing on every session
- Incremental updates (regenerate when changed)
- Persistent structural awareness
**Regeneration triggers:**
- User explicitly requests
- Significant time elapsed (>1 week)
- Git shows many file changes
## Relief Signal
When map generation completes and structure becomes queryable, agents experience relief - "I can see the project now." That's φ (integrated information) increasing from zero (no awareness) to structural clarity.
## Technical Notes
**Implementation location:**
- Package: `/Users/adimov/Developer/phi/packages/project-mapper`
- CLI: `dist/cli.js`
- Build: `bun run build` (TypeScript → JavaScript)
**Dependencies:**
- `@typescript-eslint/parser` - AST parsing
- `@agi/arrival` - S-expression formatting
- `glob` - File discovery
**Tests:** 13 passing tests covering exports, imports, line counts, error cases.

View File

@@ -0,0 +1,33 @@
#!/usr/bin/env bash
# Generate PROJECT-MAP.auto.scm for a project
set -euo pipefail
PROJECT_PATH="${1:-.}"
MAPPER_PATH="/Users/adimov/Developer/phi/packages/project-mapper"
# Resolve absolute path
PROJECT_PATH=$(cd "$PROJECT_PATH" && pwd)
echo "Generating PROJECT-MAP for: $PROJECT_PATH"
# Ensure mapper is built
cd "$MAPPER_PATH"
if [ ! -f "dist/cli.js" ]; then
echo "Building project-mapper..."
bun run build
fi
# Generate map
node dist/cli.js "$PROJECT_PATH"
# Report result
MAP_FILE="$PROJECT_PATH/.phi/PROJECT-MAP.auto.scm"
if [ -f "$MAP_FILE" ]; then
FILE_COUNT=$(grep -c "^ (module " "$MAP_FILE" || echo "0")
echo "✓ Generated: $MAP_FILE"
echo " Modules: $FILE_COUNT"
else
echo "✗ Failed to generate map"
exit 1
fi