feat(db): mesh data model — meshes, members, invites, audit log

- pgSchema "mesh" with 4 tables isolating the peer mesh domain
- Enums: visibility, transport, tier, role
- audit_log is metadata-only (E2E encryption enforced at broker/client)
- Cascade on mesh delete, soft-delete via archivedAt/revokedAt

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Alejandro Gutiérrez
2026-04-04 21:19:32 +01:00
commit d3163a5bff
1384 changed files with 314925 additions and 0 deletions

View File

@@ -0,0 +1,316 @@
# TCS: AI Agent Methodology Guide
> **Purpose**: Enable AI agents to build any compiler/transformer using Triangulated Compiler Synthesis.
## Core Principle
```mermaid
graph TD
A[Input Format] -->|generate| B[Representation 1]
A -->|generate| C[Representation 2]
A -->|generate| D[Representation 3]
B & C & D -->|compare| E{Agreement?}
E -->|yes| F[Valid Sample]
E -->|no| G[Spec Gap Found]
G -->|evolve| H[Updated Spec]
H -->|rebuild| I[Better Compiler]
```
**Key insight**: When 3 independent representations of the same semantic content disagree, at least one is wrong. This disagreement reveals specification gaps.
## The TCS Loop
```
FOR each iteration:
1. GENERATE samples in parallel (input → 3 representations)
2. TRIANGULATE to find disagreements
3. EVOLVE spec based on findings
4. BUILD/UPDATE compiler modules
5. TEST compiler against validated samples
6. FIX failures through diagnosis
UNTIL convergence (all tests pass, target count reached)
```
## How to Apply TCS to Any Domain
### Step 1: Define Your Triangle
Choose 3 representations that encode the SAME semantic information differently:
| Domain | Rep 1 (Visual) | Rep 2 (Structured) | Rep 3 (Compact) |
|--------|----------------|-------------------|-----------------|
| UI Components | JSX/HTML | Component Schema | DSL |
| Surveys | Flow Diagram | GraphSurvey JSON | LiquidSurvey |
| APIs | OpenAPI Spec | TypeScript Types | Route DSL |
| Database | ERD | Prisma Schema | SQL DDL |
| Forms | Form Builder | JSON Schema | Form DSL |
| Charts | Chart Image | Chart Config | Chart DSL |
### Step 2: Create Initial Spec
Write a minimal DSL specification covering:
```markdown
# [Domain] DSL Spec v0.1
## Node Types
- List all semantic entities
## Syntax
- Define symbols and structure
## Examples
- 3-5 simple examples
## Edge Cases
- Known ambiguities (to be resolved)
```
### Step 3: Generate Sample Pairs
```typescript
// Pseudocode for sample generation
async function generateSample(prompt: string) {
const [rep1, rep2, rep3] = await Promise.all([
agent.generate('representation-1', prompt),
agent.generate('representation-2', prompt),
agent.generate('representation-3', prompt),
]);
return { prompt, rep1, rep2, rep3 };
}
```
### Step 4: Triangulate
```typescript
async function triangulate(sample: Sample) {
const findings = await judge.compare({
rep1: sample.rep1,
rep2: sample.rep2,
rep3: sample.rep3,
});
return {
isConsistent: findings.disagreements.length === 0,
disagreements: findings.disagreements,
specGaps: findings.suggestedSpecChanges,
};
}
```
### Step 5: Evolve Spec
When disagreements found:
```markdown
## Spec Evolution Entry
### Finding
Rep1 used `onClick` but Rep3 used `@click` for the same action.
### Resolution
Standardize on `onClick` pattern. Update DSL:
- `@action``onClick={action}`
### Spec Change
Added to Section 4.2: "Actions use camelCase event handlers"
```
### Step 6: Build Compiler Modules
Standard compiler pipeline:
```mermaid
graph LR
A[Source DSL] -->|scan| B[Tokens]
B -->|parse| C[AST]
C -->|emit| D[Target Format]
```
Build each module to handle the evolved spec:
| Module | Input | Output | Responsibility |
|--------|-------|--------|----------------|
| Scanner | Source string | Token[] | Lexical analysis |
| Parser | Token[] | AST | Syntax tree |
| Emitter | AST | Target | Code generation |
### Step 7: Test & Fix Loop
```typescript
for (const sample of validatedSamples) {
const compiled = compiler.compile(sample.rep3);
const expected = sample.rep2;
if (!deepEqual(compiled, expected)) {
const diagnosis = await reflector.diagnose({
input: sample.rep3,
expected: expected,
actual: compiled,
});
await applyFix(diagnosis);
}
}
```
## Parallel Execution Strategy
Maximize throughput by parallelizing independent operations:
```mermaid
graph TD
subgraph "Parallel Sample Generation"
S1[Sample 1]
S2[Sample 2]
S3[Sample N]
end
subgraph "Parallel Triangulation"
T1[Judge 1]
T2[Judge 2]
T3[Judge N]
end
subgraph "Parallel Module Building"
M1[Scanner]
M2[Parser]
M3[Emitter]
end
S1 & S2 & S3 --> T1 & T2 & T3
T1 & T2 & T3 --> M1 & M2 & M3
```
## Convergence Criteria
TCS converges when:
1. **Test Coverage**: `validatedSamples >= targetCount`
2. **Pass Rate**: `failingTests === 0`
3. **Spec Stability**: `specChanges.lastN(5) === 0`
## Agent Roles
| Agent | Prompt Pattern |
|-------|----------------|
| Generator | "Given this prompt, generate [representation] that captures..." |
| Judge | "Compare these 3 representations. Are they semantically equivalent?" |
| Evolver | "Based on this disagreement, how should the spec change?" |
| Builder | "Implement this compiler module following the spec..." |
| Reflector | "This test failed. Diagnose the root cause..." |
## Example: Building a Chart DSL Compiler
```
Iteration 1:
- Generate 10 chart samples (PNG description, ChartConfig, ChartDSL)
- Find: Bar charts inconsistent on axis labeling
- Evolve: Add "axis.label" to spec
- Build: Scanner handles axis tokens
Iteration 2:
- Generate 10 more samples
- Find: Legends positioned differently
- Evolve: Add "legend.position: top|bottom|left|right"
- Build: Parser handles legend node
Iteration 3:
- All 20 samples pass
- Generate 30 more for coverage
- Minor fixes to edge cases
- CONVERGED at 50 samples
```
## Checkpointing
Save state after each iteration:
```json
{
"iteration": 5,
"spec_version": "0.5",
"validated_samples": 47,
"failing_tests": 2,
"last_findings": ["..."],
"compiler_hash": "abc123"
}
```
Resume with: `--resume` flag
## Anti-Patterns
| Don't | Do Instead |
|-------|------------|
| Skip triangulation | Always validate with 3 reps |
| Ignore small disagreements | Every disagreement reveals spec gap |
| Build entire compiler first | Build incrementally per finding |
| Manual spec editing | Let findings drive evolution |
| Sequential sample generation | Parallelize aggressively |
## Quality Principles (MANDATORY)
These principles ensure production-ready output:
### 1. No Bypassing Issues
```
❌ "Add try-catch to suppress error"
❌ "Use 'any' type to fix compilation"
❌ "Skip edge case for now"
✅ Trace error to spec gap → evolve spec
✅ Define proper types matching semantics
✅ Handle all cases in the grammar
```
**Errors are signals, not noise.** Every failure reveals something about the spec or architecture.
### 2. No Isolated Patches
```
❌ "Add special case for sample #47"
❌ "Hardcode value to pass test"
✅ Find pattern across samples → generalize
✅ Update grammar for all similar constructs
```
If you're adding an `if` statement for one case, you're doing it wrong.
### 3. Production-Ready Code Only
Every module must have:
- `strict: true` TypeScript (no `any`, no implicit)
- Complete error handling with descriptive messages
- Zero TODOs - every feature fully implemented
- Zero debug code - no console.log
- Clean public API with proper exports
### 4. Architecture Changes When Needed
Signs of bad architecture:
- Same bug reappearing in different forms
- Adding features requires many special cases
- Tests are brittle (small changes break many)
**Don't patch bad architecture. Redesign it.**
1. Design new structure
2. Rebuild from scratch
3. Migrate all tests
4. Verify all samples pass
## Success Metrics
Track these per iteration:
- `samples_generated`: Total samples this iteration
- `disagreement_rate`: % samples with inconsistencies
- `spec_changes`: Number of spec modifications
- `test_pass_rate`: % tests passing
- `compilation_time`: Avg compile time
Healthy TCS shows: disagreement_rate ↓, test_pass_rate ↑, spec_changes ↓

627
docs/tcs/TCS-CLAUDE-CODE.md Normal file
View File

@@ -0,0 +1,627 @@
# TCS with Claude Code CLI
> Run Triangulated Compiler Synthesis entirely within Claude Code using multi-agent Task orchestration. No external API calls needed.
## Overview
Claude Code can execute TCS by spawning parallel Task agents that act as the generators, judge, and builder roles. All computation happens within Claude Code's context.
```mermaid
graph TD
U[User] -->|"Run TCS for X"| CC[Claude Code Main]
CC -->|spawn| G1[Task: Generator 1]
CC -->|spawn| G2[Task: Generator 2]
CC -->|spawn| G3[Task: Generator 3]
G1 & G2 & G3 -->|results| CC
CC -->|spawn| J[Task: Judge]
J -->|findings| CC
CC -->|if gaps| E[Task: Evolver]
E -->|new spec| CC
CC -->|spawn parallel| B1[Task: Scanner]
CC -->|spawn parallel| B2[Task: Parser]
CC -->|spawn parallel| B3[Task: Emitter]
B1 & B2 & B3 -->|code| CC
CC -->|write| F[Files]
```
## How It Works
1. **User provides**: Domain, initial spec, target sample count
2. **Claude Code orchestrates**: Spawns Task agents in parallel
3. **No API calls**: All LLM work is done by Claude Code itself via Task tool
4. **Files written**: Spec, compiler code, test samples saved to disk
## Execution Protocol
When asked to run TCS, Claude Code should:
### Step 1: Gather Parameters
Ask the user:
```
To run TCS, I need:
1. Domain name (e.g., "form-builder", "chart-dsl")
2. Path to initial spec (or I can create one)
3. Number of iterations (recommended: 5-10)
4. Samples per iteration (recommended: 5-10)
5. Output directory
```
### Step 2: Initialize
```
Create output structure:
{output}/
├── spec/
│ └── SPEC-v0.md (initial)
├── samples/
│ ├── valid/
│ └── invalid/
├── compiler/
│ ├── scanner.ts
│ ├── parser.ts
│ └── emitter.ts
└── state.json (checkpoint)
```
### Step 3: Run Iteration Loop
For each iteration:
#### 3a. Generate Samples (Parallel Tasks)
Spawn N parallel Task agents with `subagent_type: "general-purpose"`:
```
Task 1: "Generate sample for [domain].
Prompt: 'Create a [random scenario]'
Return JSON:
{
'prompt': '...',
'rep1_visual': '... (description/JSX)',
'rep2_structured': { ... (JSON schema) },
'rep3_dsl': '... (DSL code)'
}
Use this spec: [current spec content]"
Task 2: (same with different random prompt)
Task 3: (same with different random prompt)
...
Task N: (same with different random prompt)
```
#### 3b. Triangulate (Parallel Tasks)
For each sample, spawn a judge Task:
```
Task: "Compare these 3 representations for semantic equivalence:
VISUAL: [rep1]
STRUCTURED: [rep2]
DSL: [rep3]
Return JSON:
{
'equivalent': true/false,
'disagreements': ['...'],
'spec_gaps': ['...']
}"
```
#### 3c. Evolve Spec (Single Task if gaps found)
```
Task: "Based on these findings from triangulation:
[list of spec_gaps]
Current spec:
[spec content]
Return the COMPLETE updated spec with changes marked."
```
Write new spec version to `spec/SPEC-v{N}.md`
#### 3d. Build/Update Compiler (Parallel Tasks)
Spawn 3 parallel Tasks:
```
Task Scanner: "Write a TypeScript scanner for this DSL spec:
[spec content]
Return complete scanner.ts code."
Task Parser: "Write a TypeScript parser for this DSL spec:
[spec content]
Return complete parser.ts code."
Task Emitter: "Write a TypeScript emitter for this DSL spec:
[spec content]
Target output: [structured format]
Return complete emitter.ts code."
```
Write files to `compiler/`
#### 3e. Test (Main Agent)
Claude Code main agent:
- Reads validated samples
- Runs compiler mentally or via Bash if executable
- Compares output to expected
- Records pass/fail
#### 3f. Checkpoint
Write to `state.json`:
```json
{
"iteration": 3,
"spec_version": 3,
"samples_validated": 25,
"samples_invalid": 3,
"pass_rate": 0.92,
"last_findings": ["..."]
}
```
### Step 4: Convergence Check
Stop when:
- `pass_rate >= 0.95` AND
- `last 2 iterations had 0 spec changes` AND
- `samples_validated >= target`
Or max iterations reached.
### Step 5: Final Output
```
TCS Complete!
Results:
- Iterations: 7
- Final spec: spec/SPEC-v7.md
- Validated samples: 52
- Pass rate: 98%
- Compiler: compiler/{scanner,parser,emitter}.ts
Files written to: {output}/
```
## Parallel Task Strategy
**Maximize parallelism** by launching independent tasks together:
```
Iteration N:
├── [PARALLEL] Generate 10 samples (10 Tasks)
│ └── Wait for all
├── [PARALLEL] Triangulate 10 samples (10 Tasks)
│ └── Wait for all
├── [SEQUENTIAL] Evolve spec (1 Task, only if gaps)
├── [PARALLEL] Build compiler (3 Tasks)
│ └── Wait for all
└── [SEQUENTIAL] Test & checkpoint (Main agent)
```
## Sample Task Prompts
### Generator Task Prompt Template
```
You are generating a TCS sample for domain: {domain}
SPEC:
---
{spec_content}
---
USER SCENARIO: {random_prompt}
Generate 3 semantically equivalent representations:
1. VISUAL (description or JSX):
Describe what the user would see/interact with.
2. STRUCTURED (JSON):
The underlying data model.
3. DSL (compact notation):
Using the spec syntax above.
Return as JSON:
{
"prompt": "{random_prompt}",
"rep1_visual": "...",
"rep2_structured": {...},
"rep3_dsl": "..."
}
```
### Judge Task Prompt Template
```
You are a TCS triangulation judge.
Compare these 3 representations for SEMANTIC EQUIVALENCE:
REP1 (Visual):
{rep1}
REP2 (Structured):
{rep2}
REP3 (DSL):
{rep3}
Check:
1. Do all 3 represent the SAME thing?
2. Are there missing fields in any representation?
3. Are there contradictions?
4. Does the DSL follow the spec correctly?
SPEC for reference:
{spec}
Return JSON:
{
"equivalent": true/false,
"disagreements": [
"Rep1 has X but Rep2 missing",
"Rep3 uses Y syntax not in spec"
],
"spec_gaps": [
"Spec doesn't define how to handle X",
"Need syntax for Y"
]
}
```
### Evolver Task Prompt Template
```
You are evolving a DSL specification based on TCS findings.
CURRENT SPEC:
---
{spec}
---
FINDINGS FROM TRIANGULATION:
{findings_list}
Update the spec to address these gaps. Rules:
1. Add missing syntax/semantics
2. Clarify ambiguities
3. Add examples for new features
4. Keep backwards compatible if possible
5. Mark changes with <!-- NEW v{N} -->
Return the COMPLETE updated spec.
```
### Builder Task Prompt Templates
**Scanner:**
```
Write a TypeScript scanner/tokenizer for this DSL:
SPEC:
{spec}
Requirements:
- Export: scan(source: string): Token[]
- Token type: { type: string, value: string, line: number, column: number }
- Handle all syntax in spec
- Good error messages with line/column
Return complete scanner.ts file.
```
**Parser:**
```
Write a TypeScript parser for this DSL:
SPEC:
{spec}
TOKEN TYPES (from scanner):
{token_types}
Requirements:
- Export: parse(tokens: Token[]): AST
- AST should mirror the structured representation
- Handle all syntax in spec
- Good error messages
Return complete parser.ts file.
```
**Emitter:**
```
Write a TypeScript emitter for this DSL:
SPEC:
{spec}
AST TYPE:
{ast_type}
TARGET:
{target_format}
Requirements:
- Export: emit(ast: AST): TargetType
- Handle all node types
- Preserve all semantic information
Return complete emitter.ts file.
```
## Error Handling
If a Task fails:
1. Log the error
2. Retry once with clarified prompt
3. If still fails, mark sample as invalid
4. Continue with other samples
If compiler build fails:
1. Spawn a "Reflector" Task to diagnose
2. Apply suggested fix
3. Retry build
## Usage Example
User says:
> "Run TCS to build a chart DSL compiler. 5 iterations, 8 samples each."
Claude Code responds:
> "Starting TCS for chart-dsl domain.
>
> Configuration:
> - Iterations: 5
> - Samples/iteration: 8
> - Output: ./output/chart-dsl/
>
> Creating initial spec... Do you have an existing spec or should I create one?"
User:
> "Create one"
Claude Code:
> "Created initial spec at ./output/chart-dsl/spec/SPEC-v0.md
>
> Starting iteration 1...
> [Spawns 8 parallel generator Tasks]
> Generated 8 samples.
>
> [Spawns 8 parallel judge Tasks]
> Triangulation complete: 6 valid, 2 with disagreements.
>
> Findings:
> - Axis label syntax undefined
> - Legend position options missing
>
> [Spawns evolver Task]
> Spec updated to v1.
>
> [Spawns 3 parallel builder Tasks]
> Compiler built: scanner.ts, parser.ts, emitter.ts
>
> Testing... 5/6 passing (83%)
>
> Iteration 1 complete. Continuing..."
## Checkpoint & Resume
State file enables resume:
```json
{
"domain": "chart-dsl",
"iteration": 3,
"max_iterations": 5,
"samples_per_iteration": 8,
"spec_version": 3,
"validated_samples": ["s001", "s002", ...],
"invalid_samples": ["s003"],
"compiler_version": 3,
"pass_rate": 0.88
}
```
To resume:
> "Resume TCS from ./output/chart-dsl/"
Claude Code reads state.json and continues from last checkpoint.
## Best Practices
1. **Use `run_in_background: false`** for Tasks - need results immediately
2. **Batch parallel Tasks** in single message for efficiency
3. **Keep spec in memory** during iteration, write to disk at checkpoints
4. **Accumulate samples** across iterations for comprehensive testing
5. **Use Opus** for compiler/spec tasks, **Sonnet** for judge/generator tasks
## Model Selection per Task
Use the best models for critical tasks:
```
| Task Type | Model | Reason |
|------------|----------|-------------------------------------|
| Scanner | opus | Compiler code - highest quality |
| Parser | opus | Compiler code - complex logic |
| Emitter | opus | Compiler code - correctness critical|
| Evolver | opus | Spec design - architecture decisions|
| Architect | opus | Redesign - needs deep reasoning |
| Judge | sonnet | Comparison - thorough but fast |
| Reflector | sonnet | Diagnosis - good reasoning |
| Generator | sonnet | Sample generation - quality matters |
```
**Philosophy**: Use Opus 4.5 for anything that produces code or evolves the spec.
Use Sonnet for validation, comparison, and generation tasks.
Specify in Task call:
```
Task(subagent_type="general-purpose", model="opus", prompt="...") // For compiler/spec
Task(subagent_type="general-purpose", model="sonnet", prompt="...") // For judge/generator
```
## Quality Principles (CRITICAL)
These principles are **non-negotiable** for TCS execution:
### 1. No Bypassing Issues
```
❌ WRONG: "Add a try-catch to suppress the error"
❌ WRONG: "Skip this edge case for now"
❌ WRONG: "Use 'any' type to fix compilation"
✅ RIGHT: "The error reveals a spec gap - evolve the spec"
✅ RIGHT: "This edge case needs proper handling in the parser"
✅ RIGHT: "Define proper types that match the semantic model"
```
When a test fails or error occurs:
1. **Understand the root cause** - Why did it fail?
2. **Trace to spec or architecture** - Is the spec incomplete? Is the design wrong?
3. **Fix at the source** - Update spec, redesign module, or add proper handling
4. **Never suppress** - Errors are signals, not noise
### 2. No Isolated Patches
```
❌ WRONG: "Add special case for this one sample"
❌ WRONG: "Hardcode this value to make test pass"
❌ WRONG: "Add if-statement to handle user X's edge case"
✅ RIGHT: "This pattern appears in 3 samples - generalize the solution"
✅ RIGHT: "Update the grammar to properly handle this construct"
✅ RIGHT: "Refactor to use a consistent approach across all cases"
```
When fixing issues:
1. **Look for patterns** - Is this a one-off or systemic?
2. **Generalize the fix** - Solution should work for all similar cases
3. **Update tests** - Add samples that would catch similar issues
4. **Refactor if needed** - Don't bolt-on, integrate properly
### 3. Production-Ready Code Only
```
❌ WRONG: "// TODO: handle this later"
❌ WRONG: "console.log('debug:', value)"
❌ WRONG: "function parse(x: any): any"
✅ RIGHT: Complete implementation with all cases handled
✅ RIGHT: Proper error types with descriptive messages
✅ RIGHT: Full type safety with strict TypeScript
```
Every compiler module must have:
- **Strict TypeScript** - `strict: true`, `noUncheckedIndexedAccess: true`
- **Complete error handling** - All error paths with useful messages
- **No TODOs** - Every feature fully implemented
- **No debug code** - Clean, production-ready output
- **Proper exports** - Well-defined public API
### 4. Architecture Changes When Needed
```
❌ WRONG: "Add another parameter to this 10-parameter function"
❌ WRONG: "Nest another if-statement in this 200-line function"
❌ WRONG: "Keep the broken design, just work around it"
✅ RIGHT: "The scanner needs a state machine - redesign it"
✅ RIGHT: "Split this into separate passes for clarity"
✅ RIGHT: "The AST structure doesn't match semantics - restructure"
```
Signs you need architecture change:
- **Same bug keeps appearing** in different forms
- **Adding features is painful** - too many special cases
- **Code is hard to understand** - even for the builder agent
- **Tests are brittle** - small changes break many tests
When architecture needs changing:
1. **Spawn Architect Task** to design new structure
2. **Rebuild affected modules** from scratch (don't patch)
3. **Migrate tests** to new structure
4. **Verify all samples** still pass
### Quality Gate Checklist
Before marking an iteration complete:
```
[ ] All compiler code compiles with strict TypeScript
[ ] No 'any' types (except unavoidable external interfaces)
[ ] No suppressed errors or warnings
[ ] No TODO comments
[ ] No console.log/debug statements
[ ] All error paths have descriptive messages
[ ] Code handles all spec-defined constructs
[ ] No isolated patches - all fixes are generalized
[ ] Architecture supports future spec evolution
```
### Reflector Task for Quality Issues
When quality problems are detected, spawn a Reflector:
```
Task: "Review this compiler module for quality issues:
CODE:
{module_code}
SPEC:
{spec}
Check for:
1. Bypassed errors (try-catch hiding issues)
2. Isolated patches (special cases that should be generalized)
3. Missing type safety
4. Incomplete error handling
5. Architecture problems
Return JSON:
{
'quality_score': 0-100,
'issues': [
{
'severity': 'critical|major|minor',
'type': 'bypass|patch|types|errors|architecture',
'location': 'line or function name',
'problem': 'description',
'solution': 'how to fix properly'
}
],
'needs_redesign': true/false,
'redesign_reason': 'why architecture change needed'
}"
```
### Iteration Quality Standards
| Metric | Minimum | Target |
|--------|---------|--------|
| TypeScript strict compliance | 100% | 100% |
| Test pass rate | 90% | 98%+ |
| Code quality score | 80 | 95+ |
| Isolated patches | 0 | 0 |
| Bypassed errors | 0 | 0 |
| TODO comments | 0 | 0 |
**Do not proceed to next iteration if minimums not met.**

208
docs/tcs/TCS-QUICKSTART.md Normal file
View File

@@ -0,0 +1,208 @@
# TCS Quick Start
> Build a compiler in hours, not weeks.
## Prerequisites
- Node.js 18+
- pnpm
- Anthropic API key
## 1. Define Your Triangle (5 min)
Pick 3 representations of the same semantic content:
```
Example: Form Builder
├── Visual: Form UI mockup/description
├── Structured: JSON Schema
└── Compact: FormDSL
```
## 2. Write Initial Spec (15 min)
```markdown
# FormDSL Spec v0.1
## Syntax
form "name"
? field_id "Label" type [validation]
! message "text"
-> next_field
end
## Types
Tx = text, Em = email, Ph = phone, Nm = number
## Example
form "contact"
? name "Your name" Tx [required]
? email "Email" Em [required]
! thanks "Thank you!"
end
```
## 3. Create Sample Generator (10 min)
```typescript
// tcs/generate.ts
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
export async function generateTriangle(prompt: string) {
const [visual, structured, dsl] = await Promise.all([
client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 2000,
messages: [{ role: 'user', content: `Describe this form visually: ${prompt}` }]
}),
client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 2000,
messages: [{ role: 'user', content: `Generate JSON Schema for: ${prompt}` }]
}),
client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 2000,
system: `You write FormDSL. Spec: [paste spec here]`,
messages: [{ role: 'user', content: prompt }]
}),
]);
return { visual, structured, dsl };
}
```
## 4. Create Triangulator (10 min)
```typescript
// tcs/triangulate.ts
export async function triangulate(sample: Triangle) {
const response = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 2000,
messages: [{
role: 'user',
content: `Compare these 3 representations. Are they semantically equivalent?
VISUAL:
${sample.visual}
JSON SCHEMA:
${JSON.stringify(sample.structured, null, 2)}
DSL:
${sample.dsl}
Return JSON: { equivalent: boolean, disagreements: string[], specGaps: string[] }`
}]
});
return JSON.parse(response.content[0].text);
}
```
## 5. Run TCS Loop (iterate)
```typescript
// tcs/iterate.ts
async function tcsIteration(spec: string, sampleCount = 10) {
// Generate samples
const prompts = await generatePrompts(sampleCount);
const samples = await Promise.all(prompts.map(generateTriangle));
// Triangulate
const results = await Promise.all(samples.map(triangulate));
// Collect findings
const findings = results
.filter(r => !r.equivalent)
.flatMap(r => r.specGaps);
// Evolve spec if needed
if (findings.length > 0) {
spec = await evolveSpec(spec, findings);
}
// Build/update compiler
await buildCompiler(spec);
// Test
const testResults = await runTests(samples.filter((_, i) => results[i].equivalent));
return { spec, passRate: testResults.passRate, findings };
}
// Main loop
let spec = readFileSync('spec.md', 'utf-8');
while (true) {
const result = await tcsIteration(spec);
spec = result.spec;
if (result.passRate === 1 && result.findings.length === 0) {
console.log('Converged!');
break;
}
}
```
## 6. Output
After convergence:
```
output/
├── spec-final.md # Evolved specification
├── compiler/
│ ├── scanner.ts # Tokenizer
│ ├── parser.ts # AST builder
│ └── emitter.ts # Code generator
└── tests/
└── samples.json # Validated test cases
```
## Tips
1. **Start small** - 5-10 samples per iteration
2. **Parallelize** - Generate/triangulate concurrently
3. **Trust disagreements** - They reveal real spec gaps
4. **Checkpoint often** - Save state every iteration
5. **Let it converge** - Don't manually fix, let TCS find issues
## Example Run
```bash
$ pnpm tcs:run --spec form-dsl.md --target 50
Iteration 1: 10 samples, 3 disagreements, 2 spec changes
Iteration 2: 10 samples, 1 disagreement, 1 spec change
Iteration 3: 10 samples, 0 disagreements, 0 spec changes
Iteration 4: 20 samples, 0 disagreements, 0 spec changes
✓ Converged at 50 samples, 4 iterations
```
## Quality Rules (Non-Negotiable)
1. **No bypassing** - Errors reveal spec gaps, don't suppress them
2. **No patches** - Generalize fixes, don't add special cases
3. **Production code** - Strict TypeScript, no TODOs, no debug code
4. **Redesign when stuck** - Bad architecture can't be patched
```typescript
// ❌ WRONG
try { parse(input) } catch { return null } // Bypassing
if (sample === 'special') { ... } // Isolated patch
const x: any = ... // Not production
// ✅ RIGHT
const result = parse(input) // Let it fail, fix root cause
handleAllCases(sample) // Generalized solution
const x: ParsedNode = ... // Strict types
```
## Next Steps
- Read [TCS-AI-METHODOLOGY.md](./TCS-AI-METHODOLOGY.md) for full theory
- Read [TCS-CLAUDE-CODE.md](./TCS-CLAUDE-CODE.md) for Claude Code execution
- Check [TCS-ROADMAP.md](./TCS-ROADMAP.md) for liquid package applications

252
docs/tcs/TCS-ROADMAP.md Normal file
View File

@@ -0,0 +1,252 @@
# TCS Roadmap: Liquid Package Development
> Using TCS to build all subcomponents for full rendering capability.
## Current State
```mermaid
graph LR
subgraph "Done"
A[liquid-survey] --> B[GraphSurvey Schema]
C[liquid-code] --> D[LiquidSurvey DSL]
B <-->|compile/parse| D
end
subgraph "Next: Rendering"
E[Survey Runner]
F[React Components]
G[Response Collector]
end
D --> E
E --> F
F --> G
```
## Phase 1: Survey Renderer
**Goal**: LiquidSurvey DSL → Interactive React UI
### Triangle Definition
| Rep 1 (Visual) | Rep 2 (Structured) | Rep 3 (Compact) |
|----------------|-------------------|-----------------|
| React JSX | GraphSurvey + Props | LiquidSurvey DSL |
### Subcomponents to Build
```
liquid-survey-renderer/
├── components/ # TCS-built
│ ├── QuestionText.tsx
│ ├── QuestionChoice.tsx
│ ├── QuestionRating.tsx
│ ├── QuestionMatrix.tsx
│ ├── QuestionNPS.tsx
│ ├── ... (41 types)
│ ├── Navigation.tsx
│ └── Progress.tsx
├── engine/ # TCS-built
│ ├── state-machine.ts # Flow controller
│ ├── condition-eval.ts # Branching logic
│ └── response-store.ts # Answer collection
└── themes/ # TCS-built
├── default.css
└── theme-compiler.ts
```
### TCS Iterations
| Iteration | Focus | Samples |
|-----------|-------|---------|
| 1-3 | Basic question types (text, choice, rating) | 30 |
| 4-6 | Advanced types (matrix, ranking, file) | 30 |
| 7-9 | Navigation & branching | 30 |
| 10-12 | Theming & styling | 20 |
| 13-15 | Edge cases & polish | 40 |
**Target**: 150 validated samples
---
## Phase 2: Survey Builder
**Goal**: Visual editor → LiquidSurvey DSL
### Triangle Definition
| Rep 1 (Visual) | Rep 2 (Structured) | Rep 3 (Compact) |
|----------------|-------------------|-----------------|
| Builder UI State | GraphSurvey JSON | LiquidSurvey DSL |
### Subcomponents to Build
```
liquid-survey-builder/
├── canvas/ # TCS-built
│ ├── DragDrop.tsx
│ ├── NodeEditor.tsx
│ └── ConnectionLine.tsx
├── panels/ # TCS-built
│ ├── QuestionPalette.tsx
│ ├── PropertyEditor.tsx
│ └── LogicBuilder.tsx
├── serializers/ # TCS-built
│ ├── to-graph.ts
│ ├── to-dsl.ts
│ └── from-dsl.ts
└── history/ # TCS-built
├── undo-redo.ts
└── autosave.ts
```
### TCS Iterations
| Iteration | Focus | Samples |
|-----------|-------|---------|
| 1-3 | Basic node CRUD | 30 |
| 4-6 | Connections & flow | 30 |
| 7-9 | Property editing | 30 |
| 10-12 | Logic/condition builder | 30 |
| 13-15 | Import/export | 30 |
**Target**: 150 validated samples
---
## Phase 3: Response Analytics
**Goal**: Responses → Visualizations & Insights
### Triangle Definition
| Rep 1 (Visual) | Rep 2 (Structured) | Rep 3 (Compact) |
|----------------|-------------------|-----------------|
| Chart/Dashboard | Analytics JSON | AnalyticsDSL |
### Subcomponents to Build
```
liquid-survey-analytics/
├── aggregators/ # TCS-built
│ ├── count.ts
│ ├── average.ts
│ ├── distribution.ts
│ └── cross-tab.ts
├── visualizations/ # TCS-built
│ ├── BarChart.tsx
│ ├── PieChart.tsx
│ ├── HeatMap.tsx
│ └── WordCloud.tsx
├── exports/ # TCS-built
│ ├── to-csv.ts
│ ├── to-excel.ts
│ └── to-pdf.ts
└── insights/ # TCS-built
├── sentiment.ts
└── trends.ts
```
---
## Implementation Order
```mermaid
gantt
title TCS Development Phases
dateFormat YYYY-MM-DD
section Phase 1
Survey Renderer :a1, 2024-01-01, 14d
section Phase 2
Survey Builder :a2, after a1, 14d
section Phase 3
Analytics :a3, after a2, 10d
section Integration
Full Stack Test :a4, after a3, 5d
```
## Per-Component TCS Config
```yaml
# tcs-config.yaml
renderer:
triangle:
visual: react-jsx
structured: graph-survey-props
compact: liquid-survey-dsl
target_samples: 150
parallel_batch: 10
checkpoint_interval: 5
builder:
triangle:
visual: builder-state
structured: graph-survey
compact: liquid-survey-dsl
target_samples: 150
parallel_batch: 10
analytics:
triangle:
visual: chart-description
structured: analytics-json
compact: analytics-dsl
target_samples: 100
parallel_batch: 10
```
## Success Criteria
| Phase | Metric | Target |
|-------|--------|--------|
| 1 | All 41 question types render | 100% |
| 1 | Branching logic works | 100% |
| 2 | Round-trip: Builder → DSL → Builder | Lossless |
| 2 | Undo/redo works | 50 operations |
| 3 | Aggregations correct | 99.9% accuracy |
| 3 | Charts render all data types | 100% |
## Quality Standards (All Phases)
Every TCS-built component must follow:
### No Bypassing
- Errors reveal spec gaps → evolve spec
- Never suppress with try-catch
- Never use `any` types
### No Isolated Patches
- Special cases indicate missing grammar
- Generalize all fixes
- If adding `if` for one case, redesign
### Production Code Only
- `strict: true` TypeScript
- Complete error handling
- Zero TODOs
- Zero debug code
### Architecture Over Patches
- Recurring bugs = bad architecture
- Redesign don't patch
- Rebuild modules from scratch when needed
## Getting Started
```bash
# Phase 1: Start with renderer
cd packages/liquid-survey-renderer
pnpm tcs:init --config ../tcs-config.yaml --phase renderer
pnpm tcs:run --target 150
# After convergence
pnpm build
pnpm test
```
## Notes
- Each phase builds on previous
- Shared DSL ensures interoperability
- TCS catches integration bugs early via triangulation
- Parallel development possible after Phase 1 stabilizes